/** * Keeps one CodeMirror editor state in step with one engine buffer. * * The engine is the source of truth. Local changes are sent with * `buffer.edit {id, baseVersion, edits}`, at most one call at a time; changes * typed while a call is in flight are composed and sent together next. The * invariant is: local document = unsent(inflight(confirmed)), where * `confirmed` is the engine text at `version`. * * Resync: when the engine rejects an edit with `stale_version`, or reports a * newer version than ours through `bufferChanged` (a reload from disk, an * edit from the control channel), the sync fetches the text with * `buffer.get`, computes the remote change against `confirmed`, rebases the * unsent local changes over it and applies the remote change to the editor. * No local keystroke is lost; the rebased changes are then sent against the * new version. Idea from https://codemirror.net/examples/collab/. */ import { Annotation, ChangeSet, EditorState, Transaction, type Extension, type TransactionSpec, } from "@codemirror/state"; import type { EditorView } from "@codemirror/view"; import { t } from "../../i18n"; import { run, type EngineError, type RunResult } from "../../ipc"; import { diffDocs, EngineText, separatorOf, type EngineEdit } from "./engineText"; /** A buffer as `file.open` and `buffer.get` describe it. */ export interface BufferInfo { /** Buffer id. */ id: number; /** Project-relative path. */ path: string; /** Full text as the engine holds it. */ text: string; /** Current version. */ version: number; /** Whether the buffer has unsaved changes. */ dirty: boolean; /** Line ending the buffer saves with. */ lineEnding: string; } /** Result of `buffer.edit`. */ export interface EditResult { /** Buffer id. */ id: number; /** Version after the edit. */ version: number; /** Whether the buffer is dirty now. */ dirty: boolean; } /** Params of `buffer.edit`. */ export interface EditParams { /** Buffer id. */ id: number; /** Version the edits refer to. */ baseVersion: number; /** The edits, in engine UTF-16 offsets of the text at `baseVersion`. */ edits: EngineEdit[]; } /** How the sync reaches the engine; replaced by a fake in tests. */ export interface SyncTransport { /** Runs `buffer.edit`. */ edit(params: EditParams): Promise>; /** Runs `buffer.get`. */ get(id: number): Promise>; } /** Transport through the engine IPC. */ export const engineTransport: SyncTransport = { edit: (params) => run("buffer.edit", { id: params.id, baseVersion: params.baseVersion, edits: params.edits.map((e) => ({ from: e.from, to: e.to, insert: e.insert })), }), get: (id) => run("buffer.get", { id }), }; /** Marks transactions that carry engine changes, so they are not sent back. */ export const remoteChange = Annotation.define(); /** * Checks that a value looks like a {@link BufferInfo}. * * @param value - an untrusted command result. */ export function isBufferInfo(value: unknown): value is BufferInfo { if (typeof value !== "object" || value === null) { return false; } const v = value as Record; return ( typeof v.id === "number" && typeof v.path === "string" && typeof v.text === "string" && typeof v.version === "number" && typeof v.dirty === "boolean" ); } /** Synchronises one buffer; see the module documentation. */ export class BufferSync { /** Engine buffer id. */ readonly id: number; /** The local editor state, always current. */ private current: EditorState; /** The view showing this buffer, null while another tab is active. */ private view: EditorView | null = null; /** Engine text at {@link version}. */ private confirmed: EngineText; /** Engine version of {@link confirmed}. */ private version: number; /** Highest version the engine reported for this buffer. */ private latestKnown: number; /** Changes sent and not yet answered, relative to {@link confirmed}. */ private inflight: ChangeSet | null = null; /** Local changes not sent yet, relative to `inflight(confirmed)`. */ private unsent: ChangeSet | null = null; /** Whether a `buffer.get` for a resync is running. */ private resyncing = false; /** Line break used for inserted text. */ private separator: string; /** Set once the buffer is closed; nothing is sent afterwards. */ private disposed = false; /** Callbacks waiting for {@link idle}. */ private waiters: (() => void)[] = []; /** Engine transport. */ private readonly transport: SyncTransport; /** Receives errors that are not handled by a resync. */ private readonly onError: (error: EngineError) => void; /** * @param info - the buffer as the engine described it. * @param extensions - editor extensions for the state. * @param transport - how to reach the engine. * @param onError - receives failures (shown by the editor store). */ constructor( info: BufferInfo, extensions: Extension, transport: SyncTransport = engineTransport, onError: (error: EngineError) => void = () => undefined, ) { this.id = info.id; this.confirmed = EngineText.fromEngine(info.text); this.version = info.version; this.latestKnown = info.version; this.separator = separatorOf(info.lineEnding); this.transport = transport; this.onError = onError; this.current = EditorState.create({ doc: this.confirmed.doc, extensions }); } /** The current local editor state. */ get state(): EditorState { return this.current; } /** Engine version the local document is based on. */ get baseVersion(): number { return this.version; } /** Whether local changes have not reached the engine yet. */ get pending(): boolean { return this.inflight !== null || this.unsent !== null || this.resyncing; } /** * Shows this buffer in a view: the view takes over the local state and * receives remote changes from now on. * * @param view - the editor view. */ attach(view: EditorView): void { this.view = view; view.setState(this.current); } /** Stops updating the view (another tab became active). */ detach(): void { this.view = null; } /** Stops syncing; the buffer was closed. */ dispose(): void { this.disposed = true; this.view = null; this.inflight = null; this.unsent = null; this.settle(); } /** * Creates and applies a transaction on the local state, as typing would. * * @param spec - the transaction. */ dispatch(spec: TransactionSpec): void { this.applyTransactions([this.current.update(spec)]); } /** * Applies transactions created from the current state (by the view or by * {@link dispatch}). Local document changes are queued for the engine. * * @param transactions - the transactions, in order. */ applyTransactions(transactions: readonly Transaction[]): void { const last = transactions[transactions.length - 1]; if (!last) { return; } this.current = last.state; for (const tr of transactions) { if (tr.docChanged && tr.annotation(remoteChange) !== true) { this.unsent = this.unsent ? this.unsent.compose(tr.changes) : tr.changes; } } this.view?.update([...transactions]); this.flush(); } /** * Notes a version reported by the engine (`bufferChanged`). A version * newer than the local base starts a resync once nothing is in flight. * * @param version - the reported version. */ notifyVersion(version: number): void { this.latestKnown = Math.max(this.latestKnown, version); if (this.latestKnown > this.version && this.inflight === null) { this.resync(); } } /** Resolves once every local change has reached the engine. */ idle(): Promise { if (!this.pending || this.disposed) { return Promise.resolve(); } return new Promise((resolve) => this.waiters.push(resolve)); } /** * Wakes {@link idle} callers when nothing is pending. * * @param force - wake them even with pending changes (the engine could not * be reached, so waiting longer would hang the caller). */ private settle(force = false): void { if (!force && this.pending && !this.disposed) { return; } const waiters = this.waiters; this.waiters = []; for (const wake of waiters) { wake(); } } /** Sends the unsent changes, unless a call or a resync is running. */ private flush(): void { if (this.disposed || this.inflight !== null || this.resyncing || this.unsent === null) { this.settle(); return; } const changes = this.unsent; this.inflight = changes; this.unsent = null; const params: EditParams = { id: this.id, baseVersion: this.version, edits: this.confirmed.edits(changes, this.separator), }; void this.transport.edit(params).then((result) => { this.onEditResult(changes, result); }); } /** * Handles the answer to a `buffer.edit`. * * @param changes - the changes that were sent. * @param result - the engine's answer. */ private onEditResult(changes: ChangeSet, result: RunResult): void { if (this.disposed || this.inflight !== changes) { return; } this.inflight = null; if (result.ok) { this.confirmed = this.confirmed.apply(changes, this.separator); this.version = result.value.version; this.latestKnown = Math.max(this.latestKnown, this.version); if (this.latestKnown > this.version) { this.resync(); } else { this.flush(); } return; } this.unsent = this.unsent ? changes.compose(this.unsent) : changes; if (result.error.code === "stale_version") { this.resync(); } else { this.onError(result.error); this.resync(true); } } /** * Fetches the engine text and rebases local changes onto it. * * @param dropLocal - discard unsent local changes instead of rebasing them * (after the engine refused them for a reason other than a stale base). */ private resync(dropLocal = false): void { if (this.disposed || this.resyncing || this.inflight !== null) { return; } this.resyncing = true; void this.transport.get(this.id).then((result) => { this.resyncing = false; if (this.disposed) { return; } if (!result.ok || !isBufferInfo(result.value)) { this.onError( result.ok ? { code: "ipc", message: t("common.error.unexpectedResult", { command: "buffer.get" }) } : result.error, ); this.settle(true); return; } this.rebase(result.value, dropLocal); }); } /** * Moves the local document onto fresh engine text. * * @param info - the engine's current buffer. * @param dropLocal - see {@link resync}. */ private rebase(info: BufferInfo, dropLocal: boolean): void { const fresh = EngineText.fromEngine(info.text); const remote = diffDocs(this.confirmed.doc, fresh.doc); const local = this.unsent; let toLocal: ChangeSet; if (local === null) { toLocal = remote; } else if (dropLocal) { toLocal = local.invert(this.confirmed.doc).compose(remote); this.unsent = null; } else { toLocal = remote.map(local, true); this.unsent = local.map(remote); if (this.unsent.empty) { this.unsent = null; } } this.confirmed = fresh; this.version = info.version; this.latestKnown = Math.max(this.latestKnown, info.version); this.separator = separatorOf(info.lineEnding); if (!toLocal.empty) { this.applyTransactions([ this.current.update({ changes: toLocal, annotations: [remoteChange.of(true), Transaction.addToHistory.of(false)], }), ]); } if (this.latestKnown > this.version) { this.resync(); } else { this.flush(); } } }