package com.aranroig.editor; import net.minecraft.core.UUIDUtil; import net.minecraft.network.RegistryFriendlyByteBuf; import net.minecraft.network.codec.ByteBufCodecs; import net.minecraft.network.codec.StreamCodec; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Deque; import java.util.List; import java.util.UUID; /** * A character-level change to a document: a walk over the text saying which * characters to keep ({@link Retain}), which to remove ({@link Delete}) and what * to write ({@link Insert}). Anything the walk does not mention is left alone. * *

Describing a change this way, instead of as one "replace this range with * that text", is what makes shared editing possible. Two players can write * against the same version of a file at the same time; before such a change is * used anywhere other than where it was written it is transformed * against the changes that went in first ({@link #transformAgainst(Edit)}, * {@link #transformPair(Edit, Edit)}), which re-expresses it against the text it * is about to meet. Deleting around somebody else's freshly typed text, typing * inside a selection they are throwing away, both merge instead of one of the * two losing.

* *

{@code author} and {@code seq} survive every transform. They give two * inserts at the same offset a total order, so every player ends up with the * characters in the same sequence, and they tell the server which edits came * from the sender itself (those are already in the buffer the sender typed * into, so the server must not apply them twice).

*/ public record Edit(UUID author, long seq, List components) { /** One step of the walk over a document. */ public sealed interface Component permits Retain, Insert, Delete { } /** Keep {@code count} characters of the document as they are. */ public record Retain(int count) implements Component { } /** Write {@code text} at this point of the document. */ public record Insert(String text) implements Component { } /** Remove {@code count} characters from the document. */ public record Delete(int count) implements Component { } private static final StreamCodec COMPONENT_CODEC = new StreamCodec<>() { @Override public Component decode(RegistryFriendlyByteBuf buf) { return switch (buf.readByte()) { case 1 -> new Insert(ByteBufCodecs.STRING_UTF8.decode(buf)); case 2 -> new Delete(ByteBufCodecs.VAR_INT.decode(buf)); default -> new Retain(ByteBufCodecs.VAR_INT.decode(buf)); }; } @Override public void encode(RegistryFriendlyByteBuf buf, Component component) { if (component instanceof Insert insert) { buf.writeByte(1); ByteBufCodecs.STRING_UTF8.encode(buf, insert.text()); } else if (component instanceof Delete delete) { buf.writeByte(2); ByteBufCodecs.VAR_INT.encode(buf, delete.count()); } else { buf.writeByte(0); ByteBufCodecs.VAR_INT.encode(buf, ((Retain) component).count()); } } }; public static final StreamCodec STREAM_CODEC = StreamCodec.composite( UUIDUtil.STREAM_CODEC, Edit::author, ByteBufCodecs.VAR_LONG, Edit::seq, COMPONENT_CODEC.apply(ByteBufCodecs.list()), Edit::components, Edit::new ); // ── Building edits ──────────────────────────────────────────────────── /** A change that leaves the document as it is. */ public static Edit none(UUID author, long seq) { return new Edit(author, seq, List.of()); } /** {@code text} written at {@code position}, nothing removed. */ public static Edit insertion(UUID author, long seq, int position, String text) { return replace(author, seq, position, 0, text); } /** {@code count} characters removed at {@code position}, nothing written back. */ public static Edit deletion(UUID author, long seq, int position, int count) { return replace(author, seq, position, count, ""); } /** * The shape the text editor produces with every keystroke: remove * {@code deleteLength} characters at {@code position} and write * {@code insert} there. */ public static Edit replace(UUID author, long seq, int position, int deleteLength, String insert) { List components = new ArrayList<>(3); if (position > 0) components.add(new Retain(position)); if (deleteLength > 0) components.add(new Delete(deleteLength)); if (!insert.isEmpty()) components.add(new Insert(insert)); return new Edit(author, seq, components); } public boolean isEmpty() { for (Component component : components) { if (component instanceof Insert || component instanceof Delete) return false; } return true; } /** How many characters of the document this edit reads; 0 for a pure insert. */ public int baseLength() { int total = 0; for (Component component : components) { if (component instanceof Retain retain) total += retain.count(); else if (component instanceof Delete delete) total += delete.count(); } return total; } // ── Applying ────────────────────────────────────────────────────────── /** * Runs this edit over {@code base}. Counts that do not fit the text are * clamped rather than thrown at: a document that stopped matching its * version is repaired by resyncing, not by crashing the editor. */ public String apply(String base) { if (isEmpty()) return base; StringBuilder result = new StringBuilder(base.length()); int index = 0; for (Component component : components) { if (component instanceof Retain retain) { int count = Math.min(retain.count(), base.length() - index); if (count <= 0) break; result.append(base, index, index + count); index += count; } else if (component instanceof Delete delete) { int count = Math.min(delete.count(), base.length() - index); if (count <= 0) break; index += count; } else if (component instanceof Insert insert) { result.append(insert.text()); } } if (index < base.length()) result.append(base, index, base.length()); return result.toString(); } /** * Where a caret at {@code caret} ends up once this edit is applied: text * inserted before it pushes it along, text deleted around it collapses it * onto the deletion point. Text inserted at the caret's own offset goes in * front of it, which is where the editor expects its own typing to land. */ public int shiftPosition(int caret) { int read = 0; // how far into the base document the walk has got int written = 0; for (Component component : components) { if (read >= caret) break; if (component instanceof Retain retain) { int count = Math.min(retain.count(), caret - read); read += count; written += count; } else if (component instanceof Delete delete) { read += Math.min(delete.count(), caret - read); // written does not move: the caret collapses onto the deletion } else if (component instanceof Insert insert) { written += insert.text().length(); } } return written; } // ── Undoing ─────────────────────────────────────────────────────────── /** * The walk that takes this one back: run it over the text this edit * produced and the earlier text comes out again. Removals become writes * of exactly what was removed — which is why the text the edit ran over * has to be at hand — and writes become removals of the same length. * {@code base} is the text this edit was applied to, and counts that do * not fit it are clamped the same way {@link #apply} clamps them. */ public Edit invert(String base) { List inverse = new ArrayList<>(components.size()); int index = 0; for (Component component : components) { if (component instanceof Retain retain) { int count = Math.min(retain.count(), base.length() - index); if (count <= 0) break; add(inverse, new Retain(count)); index += count; } else if (component instanceof Delete delete) { int count = Math.min(delete.count(), base.length() - index); if (count <= 0) break; add(inverse, new Insert(base.substring(index, index + count))); index += count; } else if (component instanceof Insert insert) { add(inverse, new Delete(insert.text().length())); } } return new Edit(author, seq, inverse); } // ── Transforming ────────────────────────────────────────────────────── /** * This edit re-expressed against a document that already contains * {@code other}. Both are assumed to have been written against the same * base document; applying the result after {@code other} has the effect this * edit was meant to have there. */ public Edit transformAgainst(Edit other) { return transformPair(this, other)[0]; } /** * Both edits expressed against each other's result: returns * {@code [this↑other, other↑this]}. Applying {@code this↑other} after * {@code other} gives the same document as applying {@code other↑this} * after {@code this}, which is what every player's copy converging on * rests upon. */ public static Edit[] transformPair(Edit left, Edit right) { List leftResult = new ArrayList<>(); List rightResult = new ArrayList<>(); Deque leftOp = new ArrayDeque<>(left.components()); Deque rightOp = new ArrayDeque<>(right.components()); while (!leftOp.isEmpty() || !rightOp.isEmpty()) { // Whichever edit ran out says nothing about what is left of the // document, which is the same as keeping it. Component l = leftOp.peekFirst(); Component r = rightOp.peekFirst(); boolean lVirtual = l == null; boolean rVirtual = r == null; if (l == null) l = new Retain(remaining(r)); if (r == null) r = new Retain(remaining(l)); if (l instanceof Insert lInsert && !(r instanceof Insert)) { // Our text goes in before whatever the other edit does next. An // insert is never swallowed by a concurrent deletion. add(leftResult, lInsert); add(rightResult, new Retain(lInsert.text().length())); leftOp.pollFirst(); continue; } if (r instanceof Insert rInsert && !(l instanceof Insert)) { add(rightResult, rInsert); add(leftResult, new Retain(rInsert.text().length())); rightOp.pollFirst(); continue; } if (l instanceof Insert lInsert && r instanceof Insert rInsert) { // Two players typed at the same offset: authorship decides who // ends up in front, the same way round in both directions. if (left.precedes(right)) { add(leftResult, lInsert); add(rightResult, new Retain(lInsert.text().length())); leftOp.pollFirst(); } else { add(rightResult, rInsert); add(leftResult, new Retain(rInsert.text().length())); rightOp.pollFirst(); } continue; } // Neither side writes text here: both steps cover the same stretch // of the original document. int count = Math.min(remaining(l), remaining(r)); boolean lDeletes = l instanceof Delete; boolean rDeletes = r instanceof Delete; if (lDeletes && !rDeletes) add(leftResult, new Delete(count)); // they deleted it; we still want it gone else if (rDeletes && !lDeletes) add(rightResult, new Delete(count)); else if (!lDeletes && !rDeletes) { add(leftResult, new Retain(count)); add(rightResult, new Retain(count)); } // Both deleting: the characters are gone either way, nothing to say. consume(leftOp, count, lVirtual); consume(rightOp, count, rVirtual); } return new Edit[]{ new Edit(left.author, left.seq, leftResult), new Edit(right.author, right.seq, rightResult), }; } /** Collects a component, merging it into the previous one where possible. */ private static void add(List components, Component component) { if (component instanceof Retain retain && retain.count() == 0) return; if (component instanceof Delete delete && delete.count() == 0) return; if (component instanceof Insert insert && insert.text().isEmpty()) return; int last = components.size() - 1; if (last >= 0) { Component previous = components.get(last); if (previous instanceof Retain a && component instanceof Retain b) { components.set(last, new Retain(a.count() + b.count())); return; } if (previous instanceof Delete a && component instanceof Delete b) { components.set(last, new Delete(a.count() + b.count())); return; } if (previous instanceof Insert a && component instanceof Insert b) { components.set(last, new Insert(a.text() + b.text())); return; } } components.add(component); } /** Characters a step covers: for inserts, the length of the text written. */ private static int remaining(Component component) { if (component instanceof Retain retain) return retain.count(); if (component instanceof Delete delete) return delete.count(); return ((Insert) component).text().length(); } /** Advances a walk by {@code count} characters, splitting the step it lands in. */ private static void consume(Deque components, int count, boolean virtual) { if (virtual) return; // nothing there to advance; it is re-derived next round Component head = components.pollFirst(); int left = remaining(head) - count; if (left > 0) { components.addFirst(head instanceof Retain ? new Retain(left) : new Delete(left)); } } /** * Total order over two edits, used only to decide which of two inserts at * the same offset comes first. It deliberately ignores positions, so it * still says the same thing after both have been transformed. */ public boolean precedes(Edit other) { int byAuthor = author.compareTo(other.author); if (byAuthor != 0) return byAuthor < 0; return seq < other.seq; } }