package com.aranroig.collab; import com.aranroig.Codecraft; import com.aranroig.SavedProjectData; import com.aranroig.editor.Edit; import com.aranroig.editor.EditorFile; import com.aranroig.editor.EditorPresence; import com.aranroig.payloads.ClientboundDocumentEditPayload; import com.aranroig.payloads.ClientboundDocumentStatePayload; import com.aranroig.payloads.ClientboundEditAckPayload; import com.aranroig.payloads.ClientboundPresencePayload; import com.aranroig.payloads.ClientboundRenameFilePayload; import com.aranroig.payloads.ClientboundSaveCodePayload; import net.fabricmc.fabric.api.event.lifecycle.v1.ServerLifecycleEvents; import net.fabricmc.fabric.api.networking.v1.ServerPlayConnectionEvents; import net.fabricmc.fabric.api.networking.v1.ServerPlayNetworking; import net.minecraft.server.MinecraftServer; import net.minecraft.server.level.ServerPlayer; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.UUID; /** * The server's copy of every document that players have open in the editor, and * the single authority on what they contain. * *

Live editing

* *

A player who opens the editor is put in a session for the file * they are looking at. Every keystroke they make arrives as an * {@link Edit} written against a known version of the document; this class * rebases it onto the current version — transforming it against the edits that * landed in the meantime, and never against the sender's own edits, which are * already in the buffer it was typed into — applies it, and hands it to the * other players in that file. That is what lets several people type in the same * file at once without losing each other's work.

* *

Each applied edit bumps the document's version, so every client can tell * which version it holds. The server keeps the last few edits per document so * an edit that arrives a little late can still be rebased; when one arrives * too late for that, its author is simply sent the authoritative document * again. The same thing happens whenever a client reports (through the ack * hash) that its copy stopped matching.

* *

Carets are tracked per session too, and every session gets the caret * positions of the other players, which is what lets the editor draw them.

* *

Threading

* *

All of this runs on the server thread: payload handlers and the connection * events below are dispatched there, so the maps need no locking.

*/ public final class DocumentManager { /** How many applied edits are kept per document for rebasing stale edits. */ private static final int HISTORY_PER_DOCUMENT = 128; /** Caret colours, picked by player id so a player looks the same everywhere. */ private static final int[] PRESENCE_COLORS = { 0xFF4FC3F7, // light blue 0xFFFF8A65, // orange 0xFFAED581, // green 0xFFF06292, // pink 0xFFBA68C8, // purple 0xFFFFD54F, // amber 0xFF4DB6AC, // teal 0xFFE57373, // red 0xFF90A4AE, // grey 0xFFA1887F, // brown }; private static final Map DOCUMENTS = new HashMap<>(); /** One entry per player with the editor open, keyed by player id. */ private static final Map SESSIONS = new HashMap<>(); private DocumentManager() { } /** * Drops players from their editing sessions when they disconnect and * throws the cached documents away when the world shuts down. Call once * from {@link com.aranroig.Codecraft#onInitialize()}. */ public static void install() { ServerPlayConnectionEvents.DISCONNECT.register((handler, server) -> closeEditor(handler.player)); // Cached text must not outlive the world it came from. ServerLifecycleEvents.SERVER_STOPPING.register(server -> { DOCUMENTS.clear(); SESSIONS.clear(); }); } // ── Sessions ────────────────────────────────────────────────────────── /** * Puts {@code player} in the live session of {@code file} and replies with * its authoritative contents. Their previous file, if any, is dropped. */ public static void openDocument(ServerPlayer player, String file) { MinecraftServer server = server(player); if (server == null) return; Session session = SESSIONS.computeIfAbsent(player.getUUID(), id -> new Session(player)); if (!file.equals(session.file)) { session.file = file; session.cursor = 0; session.anchor = -1; } Document document = document(server, file); ServerPlayNetworking.send(player, new ClientboundDocumentStatePayload(file, document.text, document.version)); broadcastPresence(server, file); sendPresenceSnapshot(player); } /** Ends {@code player}'s editing session: called on close and on disconnect. */ public static void closeEditor(ServerPlayer player) { Session session = SESSIONS.remove(player.getUUID()); if (session == null) return; MinecraftServer server = server(player); if (server != null && session.file != null) { broadcastPresence(server, session.file); } } // ── Document contents ───────────────────────────────────────────────── /** * Applies one of {@code player}'s keystrokes. The edit was written against * version {@code baseVersion}; if the document moved on since then the edit * is rebased onto what happened in between first. */ public static void applyEdit(ServerPlayer player, String file, int baseVersion, Edit edit) { MinecraftServer server = server(player); if (server == null) return; Document document = document(server, file); // Never take the client's word for who wrote an edit: rebasing skips // the sender's own edits, so a spoofed author would apply one twice. Edit applied = new Edit(player.getUUID(), edit.seq(), edit.components()); if (baseVersion > document.version || baseVersion < document.oldestRebaseVersion()) { // Too far behind to rebase this edit without guessing: give the // player the real document and let them retype on top of it. ServerPlayNetworking.send(player, new ClientboundDocumentStatePayload(file, document.text, document.version)); return; } for (int version = baseVersion + 1; version <= document.version; version++) { Edit earlier = document.appliedAt(version); if (earlier == null) break; if (earlier.author().equals(player.getUUID())) continue; applied = applied.transformAgainst(earlier); } document.apply(applied); boolean brandNew = persist(server, file, document.text); ServerPlayNetworking.send(player, new ClientboundEditAckPayload(file, document.version, document.text.hashCode(), document.text.length())); broadcastEdit(server, player.getUUID(), file, document.version, applied); // A file nobody had saved yet came into the project with this keystroke, // and the editors of it are the only ones the edit above reaches: tell // everybody else the project has one more file. if (brandNew) broadcastProjectFile(server, player, file, document.text); } /** * Writes {@code text} over {@code file} as one edit (the explicit Save). * Going through an edit rather than storing the buffer directly is what * keeps the other editors converging instead of being clobbered, and it * trims the parts both versions agree on so the change stays small. */ public static void replaceDocument(ServerPlayer player, String file, String text) { MinecraftServer server = server(player); if (server == null) return; Document document = document(server, file); String current = document.text; if (current.equals(text)) { // Nothing changed, but the player asked to save: the file still // has to exist on disk (a brand-new file is saved before it has // any edits flowing), and confirm the version they are on so they // can check their copy against it. persist(server, file, current); ServerPlayNetworking.send(player, new ClientboundEditAckPayload(file, document.version, current.hashCode(), current.length())); } else { int prefix = commonPrefix(current, text); int suffix = commonSuffix(current, text, prefix); Edit edit = Edit.replace(player.getUUID(), document.nextSequence(), prefix, current.length() - prefix - suffix, text.substring(prefix, text.length() - suffix)); // A whole-file save states what the file should contain, so it is // applied to the server's current text instead of being rebased. document.apply(edit); persist(server, file, document.text); ServerPlayNetworking.send(player, new ClientboundEditAckPayload(file, document.version, document.text.hashCode(), document.text.length())); broadcastEdit(server, player.getUUID(), file, document.version, edit); } // Saving is also how a file says it exists: the other editors add it to // their sidebars, and the ones not looking at it are not left holding a // copy a save behind. broadcastProjectFile(server, player, file, document.text); } /** * Moves {@code oldName} to {@code newName} everywhere the server knows it: * in the saved project, in the cached document and in the sessions of * everyone editing it — and the other editors' file lists are told. A name * the project already holds is refused. */ public static void renameFile(ServerPlayer player, String oldName, String newName) { MinecraftServer server = server(player); if (server == null || oldName.equals(newName)) return; SavedProjectData data = SavedProjectData.getSavedBlockData(server); List files = data.getEditorFiles(); for (EditorFile editorFile : files) { if (editorFile.getName().equals(newName)) return; // the name is taken } boolean onDisk = false; for (EditorFile editorFile : files) { if (editorFile.getName().equals(oldName)) { editorFile.setName(newName); onDisk = true; break; } } if (onDisk) data.markDirty(); // The live document keeps its version history under the new name, so // the editors of the file can carry on without refetching anything. Document document = DOCUMENTS.remove(oldName); if (document != null) DOCUMENTS.put(newName, document); for (Session session : SESSIONS.values()) { if (oldName.equals(session.file)) session.file = newName; } // Nobody is in the old name any more, and the new one holds them all. broadcastPresence(server, oldName); broadcastPresence(server, newName); for (ServerPlayer other : server.getPlayerList().getPlayers()) { if (other != player) { ServerPlayNetworking.send(other, new ClientboundRenameFilePayload(oldName, newName)); } } } // ── Carets ──────────────────────────────────────────────────────────── /** Records where {@code player}'s caret is in {@code file} and tells everyone. */ public static void updateCursor(ServerPlayer player, String file, int cursor, int anchor) { Session session = SESSIONS.get(player.getUUID()); if (session == null || !file.equals(session.file)) return; MinecraftServer server = server(player); if (server == null) return; session.cursor = Math.max(0, cursor); session.anchor = anchor; broadcastPresence(server, file); } // ── Internals ───────────────────────────────────────────────────────── private static Document document(MinecraftServer server, String file) { Document document = DOCUMENTS.get(file); if (document == null) { String text = ""; for (EditorFile editorFile : SavedProjectData.getSavedBlockData(server).getEditorFiles()) { if (editorFile.getName().equals(file)) { text = editorFile.getText(); break; } } document = new Document(text); DOCUMENTS.put(file, document); } return document; } /** * Copies the live text back into the project's saved data, saying whether * that meant the project gained the file. The write itself is throttled by * {@code SavedData}, so marking it dirty per keystroke is cheap and means a * crash loses at most a second of typing. */ private static boolean persist(MinecraftServer server, String file, String text) { SavedProjectData data = SavedProjectData.getSavedBlockData(server); List files = data.getEditorFiles(); for (EditorFile editorFile : files) { if (editorFile.getName().equals(file)) { editorFile.setText(text); data.markDirty(); return false; } } files.add(new EditorFile(file, text)); data.setEditorFiles(files); return true; } /** * Tells every editor but {@code author} that the project holds {@code file} * with {@code text}. It is how one player's new file turns into a row in the * others' sidebars, and what keeps a client that is not looking at the file * from holding a copy a save behind. */ private static void broadcastProjectFile(MinecraftServer server, ServerPlayer author, String file, String text) { for (ServerPlayer other : server.getPlayerList().getPlayers()) { if (other == author) continue; ServerPlayNetworking.send(other, new ClientboundSaveCodePayload(new EditorFile(file, text))); } } private static void broadcastEdit(MinecraftServer server, UUID author, String file, int version, Edit edit) { for (Map.Entry entry : SESSIONS.entrySet()) { if (entry.getKey().equals(author) || !file.equals(entry.getValue().file)) continue; ServerPlayNetworking.send(entry.getValue().player, new ClientboundDocumentEditPayload(file, version, edit)); } } /** Re-sends the carets of everyone in {@code file} to every open editor. */ private static void broadcastPresence(MinecraftServer server, String file) { for (Map.Entry entry : SESSIONS.entrySet()) { if (entry.getValue().file == null) continue; sendPresence(entry.getValue().player, file, presenceIn(file, entry.getKey())); } } /** Brings a player up to date with everywhere somebody is already editing. */ private static void sendPresenceSnapshot(ServerPlayer player) { UUID self = player.getUUID(); List files = new ArrayList<>(); for (Session session : SESSIONS.values()) { if (session.file != null && !files.contains(session.file)) files.add(session.file); } for (String file : files) { sendPresence(player, file, presenceIn(file, self)); } } private static void sendPresence(ServerPlayer to, String file, List editors) { ServerPlayNetworking.send(to, new ClientboundPresencePayload(file, editors)); } private static List presenceIn(String file, UUID exclude) { List editors = new ArrayList<>(); for (Map.Entry entry : SESSIONS.entrySet()) { Session session = entry.getValue(); if (entry.getKey().equals(exclude) || !file.equals(session.file)) continue; editors.add(new EditorPresence(entry.getKey(), session.player.getScoreboardName(), session.color, session.cursor, session.anchor)); } return editors; } private static MinecraftServer server(ServerPlayer player) { return player.level().getServer(); } private static int commonPrefix(String left, String right) { int max = Math.min(left.length(), right.length()); int i = 0; while (i < max && left.charAt(i) == right.charAt(i)) i++; return i; } private static int commonSuffix(String left, String right, int prefix) { int max = Math.min(left.length(), right.length()) - prefix; int i = 0; while (i < max && left.charAt(left.length() - 1 - i) == right.charAt(right.length() - 1 - i)) i++; return i; } // ── State ───────────────────────────────────────────────────────────── /** The server's copy of one document, with the edits that produced it. */ private static final class Document { private String text; private int version; /** Applied edits, oldest first; {@code history.get(0)} is version {@code firstRetainedVersion}. */ private final List history = new ArrayList<>(); private int firstRetainedVersion = 1; private Document(String text) { this.text = text; } private void apply(Edit edit) { text = edit.apply(text); version++; if (history.size() == HISTORY_PER_DOCUMENT) { history.remove(0); firstRetainedVersion++; } history.add(edit); } /** The edit that took the document to {@code targetVersion}, or null once forgotten. */ private Edit appliedAt(int targetVersion) { int index = targetVersion - firstRetainedVersion; if (index < 0 || index >= history.size()) return null; return history.get(index); } /** Oldest base version that can still be rebased onto this document. */ private int oldestRebaseVersion() { return firstRetainedVersion - 1; } private long nextSequence() { return version + 1L; } } /** One player with the editor open, and where they are pointing. */ private static final class Session { private final ServerPlayer player; private final int color; private String file; private int cursor; private int anchor = -1; private Session(ServerPlayer player) { this.player = player; this.color = PRESENCE_COLORS[Math.floorMod(player.getUUID().hashCode(), PRESENCE_COLORS.length)]; } } }