Skip to main content

continuity_engine/
engine.rs

1//! Public synchronous editor facade.
2
3use continuity_buffer::{Buffer, BufferId, Revision, RopeSnapshot, UndoGroupId};
4use continuity_text::{EditOp, Position, Range, Selection};
5
6use crate::change::{ChangeBatch, EngineEvent, MutationKind};
7use crate::reconcile_diff::compute_reconcile_splice;
8use crate::selection_coalesce::coalesce_selections;
9use crate::selection_edit::{plan, SelectionEdit};
10use crate::undo::{CoalesceKind, UndoManager};
11use crate::{DeltaHistory, EngineState, Error, RopeEditDeltaWithPoints};
12
13/// Identifier source used for undo groups.
14///
15/// Hosts that need reproducible operation streams can inject a deterministic
16/// implementation with [`Engine::with_id_generator`].
17pub trait IdGenerator {
18    /// Return the next buffer identifier.
19    fn next_buffer_id(&mut self) -> BufferId;
20
21    /// Return the next undo-group identifier.
22    fn next_undo_group_id(&mut self) -> UndoGroupId;
23}
24
25/// UUIDv7 identifier source used by the native application.
26#[derive(Debug, Default)]
27pub struct SystemIdGenerator;
28
29impl IdGenerator for SystemIdGenerator {
30    fn next_buffer_id(&mut self) -> BufferId {
31        BufferId::new()
32    }
33
34    fn next_undo_group_id(&mut self) -> UndoGroupId {
35        UndoGroupId::new()
36    }
37}
38
39/// An immutable rope and selection view captured in one engine call.
40#[derive(Clone)]
41pub struct EngineSnapshot {
42    /// Immutable rope snapshot.
43    pub rope: RopeSnapshot,
44    /// Selections captured at the same revision.
45    pub selections: Vec<Selection>,
46    /// Whether the buffer rejects text mutations.
47    pub is_read_only: bool,
48}
49
50/// Synchronous, storage-neutral editor state machine.
51///
52/// **Thread ownership**: the host chooses the owning thread and must keep all
53/// mutable access on that thread. `Engine` does not create threads or invoke
54/// host callbacks.
55pub struct Engine {
56    state: EngineState,
57    undo: UndoManager,
58    delta_history: DeltaHistory,
59    events: Vec<EngineEvent>,
60    ids: Box<dyn IdGenerator>,
61}
62
63impl Engine {
64    /// Construct an empty engine using UUIDv7 undo-group identifiers.
65    #[must_use]
66    pub fn new() -> Self {
67        Self::with_id_generator(Box::<SystemIdGenerator>::default())
68    }
69
70    /// Construct an empty engine with a host-provided identifier source.
71    #[must_use]
72    pub fn with_id_generator(ids: Box<dyn IdGenerator>) -> Self {
73        Self {
74            state: EngineState::new(),
75            undo: UndoManager::default(),
76            delta_history: DeltaHistory::default(),
77            events: Vec::new(),
78            ids,
79        }
80    }
81
82    /// Open text with a newly generated buffer identifier.
83    pub fn open_buffer(&mut self, text: &str) -> BufferId {
84        let id = self.ids.next_buffer_id();
85        self.adopt_buffer(Buffer::from_parts(id, text, Revision::INITIAL))
86    }
87
88    /// Load text under a host-provided id and revision.
89    pub fn load_buffer(&mut self, id: BufferId, text: &str, revision: Revision) -> BufferId {
90        self.adopt_buffer(Buffer::from_parts(id, text, revision))
91    }
92
93    /// Adopt a prepared buffer without performing persistence or I/O.
94    pub fn adopt_buffer(&mut self, buffer: Buffer) -> BufferId {
95        let id = self.state.insert(buffer);
96        self.events.push(EngineEvent::BufferOpened { id });
97        id
98    }
99
100    /// Remove a buffer and its transient engine state.
101    pub fn close_buffer(&mut self, id: BufferId) -> Option<Buffer> {
102        let buffer = self.state.remove(id)?;
103        self.undo.forget(id);
104        self.delta_history.forget(id);
105        self.events.push(EngineEvent::BufferClosed { id });
106        Some(buffer)
107    }
108
109    /// Capture a buffer snapshot.
110    #[must_use]
111    pub fn snapshot(&self, id: BufferId) -> Option<EngineSnapshot> {
112        self.state.get(id).map(|buffer| EngineSnapshot {
113            rope: buffer.snapshot(),
114            selections: buffer.selections().to_vec(),
115            is_read_only: buffer.is_read_only(),
116        })
117    }
118
119    /// Copy a buffer's current text.
120    #[must_use]
121    pub fn text(&self, id: BufferId) -> Option<String> {
122        self.state.get(id).map(|buffer| buffer.rope().to_string())
123    }
124
125    /// Borrow a buffer's current selections.
126    #[must_use]
127    pub fn selections(&self, id: BufferId) -> Option<&[Selection]> {
128        self.state.get(id).map(Buffer::selections)
129    }
130
131    /// Return a buffer's current revision.
132    #[must_use]
133    pub fn revision(&self, id: BufferId) -> Option<Revision> {
134        self.state.get(id).map(Buffer::revision)
135    }
136
137    /// Replace and normalize a buffer's selections.
138    pub fn set_selections(
139        &mut self,
140        id: BufferId,
141        mut selections: Vec<Selection>,
142    ) -> Result<(), Error> {
143        coalesce_selections(&mut selections);
144        let buffer = self.state.get_mut(id).ok_or(Error::UnknownBuffer)?;
145        buffer.set_selections(selections);
146        self.events.push(EngineEvent::SelectionsChanged { id });
147        Ok(())
148    }
149
150    /// Apply one raw atomic edit as a discrete undo group.
151    pub fn apply_edit(
152        &mut self,
153        id: BufferId,
154        op: EditOp,
155        timestamp_ms: i64,
156    ) -> Result<ChangeBatch, Error> {
157        let batch = self.undo.apply_single(
158            self.state.get_mut(id).ok_or(Error::UnknownBuffer)?,
159            &op,
160            "editor.apply_edit",
161            timestamp_ms,
162            self.ids.as_mut(),
163        )?;
164        self.record_batch(&batch);
165        Ok(batch)
166    }
167
168    /// Apply caller-planned operations as one discrete undo group.
169    pub fn apply_grouped_edit(
170        &mut self,
171        id: BufferId,
172        ops: &[EditOp],
173        selections_after: Vec<Selection>,
174        command: &str,
175        timestamp_ms: i64,
176    ) -> Result<Option<ChangeBatch>, Error> {
177        let buffer = self.state.get_mut(id).ok_or(Error::UnknownBuffer)?;
178        let selections_before = buffer.selections().to_vec();
179        let selections_after = if selections_after.is_empty() {
180            selections_before.clone()
181        } else {
182            selections_after
183        };
184        let batch = self.undo.apply_group(
185            buffer,
186            ops,
187            &selections_before,
188            &selections_after,
189            command,
190            CoalesceKind::Discrete,
191            timestamp_ms,
192            MutationKind::GroupedEdit,
193            self.ids.as_mut(),
194        )?;
195        self.record_optional_batch(batch.as_ref());
196        Ok(batch)
197    }
198
199    /// Plan and apply a selection-aware edit.
200    pub fn apply_selection_edit(
201        &mut self,
202        id: BufferId,
203        edit: &SelectionEdit,
204        timestamp_ms: i64,
205    ) -> Result<Option<ChangeBatch>, Error> {
206        let buffer = self.state.get_mut(id).ok_or(Error::UnknownBuffer)?;
207        let Some(edit_plan) = plan(buffer, edit)? else {
208            return Ok(None);
209        };
210        let batch = self.undo.apply_group(
211            buffer,
212            &edit_plan.ops,
213            &edit_plan.selections_before,
214            &edit_plan.selections_after,
215            command_name_for(edit),
216            coalesce_kind_for(edit),
217            timestamp_ms,
218            MutationKind::SelectionEdit,
219            self.ids.as_mut(),
220        )?;
221        self.record_optional_batch(batch.as_ref());
222        Ok(batch)
223    }
224
225    /// Undo the current group.
226    pub fn undo(&mut self, id: BufferId, timestamp_ms: i64) -> Result<Option<ChangeBatch>, Error> {
227        let batch = self.undo.undo(
228            self.state.get_mut(id).ok_or(Error::UnknownBuffer)?,
229            timestamp_ms,
230        )?;
231        self.record_optional_batch(batch.as_ref());
232        Ok(batch)
233    }
234
235    /// Replay the most-recent redo child.
236    pub fn redo(&mut self, id: BufferId, timestamp_ms: i64) -> Result<Option<ChangeBatch>, Error> {
237        self.redo_inner(id, timestamp_ms, false)
238    }
239
240    /// Replay an alternate redo branch.
241    pub fn redo_alternate(
242        &mut self,
243        id: BufferId,
244        timestamp_ms: i64,
245    ) -> Result<Option<ChangeBatch>, Error> {
246        self.redo_inner(id, timestamp_ms, true)
247    }
248
249    /// Replace the full document only when the caller's revision is current.
250    pub fn replace_text_if_revision(
251        &mut self,
252        id: BufferId,
253        expected: Revision,
254        text: impl Into<String>,
255        timestamp_ms: i64,
256    ) -> Result<ChangeBatch, Error> {
257        let buffer = self.state.get(id).ok_or(Error::UnknownBuffer)?;
258        let actual = buffer.revision();
259        if actual != expected {
260            return Err(Error::RevisionMismatch { expected, actual });
261        }
262        let end = Position::from_byte_offset(buffer.rope(), buffer.rope().len_bytes())?;
263        let op = EditOp::replace(Range::new(Position::ZERO, end), text);
264        self.apply_edit(id, op, timestamp_ms)
265    }
266
267    /// Reconcile a full host document when its expected revision is current.
268    ///
269    /// Returns `None` when the supplied text already matches, so loading or
270    /// reconciling current state never emits a phantom edit. A real difference
271    /// is applied as the minimal single splice (shared prefix and suffix kept),
272    /// so selections and host line mirrors outside the changed range stay put
273    /// instead of collapsing to the document end.
274    pub fn reconcile_text_if_revision(
275        &mut self,
276        id: BufferId,
277        expected: Revision,
278        text: impl Into<String>,
279        timestamp_ms: i64,
280    ) -> Result<Option<ChangeBatch>, Error> {
281        let text = text.into();
282        let buffer = self.state.get(id).ok_or(Error::UnknownBuffer)?;
283        let actual = buffer.revision();
284        if actual != expected {
285            return Err(Error::RevisionMismatch { expected, actual });
286        }
287        if buffer.rope() == text.as_str() {
288            return Ok(None);
289        }
290        let splice = compute_reconcile_splice(buffer.rope(), &text);
291        let start = Position::from_byte_offset(buffer.rope(), splice.start)?;
292        let end = Position::from_byte_offset(buffer.rope(), splice.old_end)?;
293        let replacement = text[splice.start..splice.new_end].to_string();
294        let op = EditOp::replace(Range::new(start, end), replacement);
295        self.apply_edit(id, op, timestamp_ms).map(Some)
296    }
297
298    /// Return byte deltas strictly newer than `since_revision`.
299    #[must_use]
300    pub fn deltas_since(
301        &self,
302        id: BufferId,
303        since_revision: u64,
304    ) -> (Vec<continuity_text::RopeEditDelta>, bool) {
305        self.delta_history.since(id, since_revision)
306    }
307
308    /// Return position-augmented deltas strictly newer than `since_revision`.
309    #[must_use]
310    pub fn deltas_with_points_since(
311        &self,
312        id: BufferId,
313        since_revision: u64,
314    ) -> (Vec<RopeEditDeltaWithPoints>, bool) {
315        self.delta_history.with_points_since(id, since_revision)
316    }
317
318    /// Drain events emitted since the previous call.
319    pub fn drain_events(&mut self) -> Vec<EngineEvent> {
320        std::mem::take(&mut self.events)
321    }
322
323    /// Borrow the lower-level state for native host queries during migration.
324    #[must_use]
325    pub fn state(&self) -> &EngineState {
326        &self.state
327    }
328
329    /// Mutably borrow lower-level state for native host-only metadata changes.
330    pub fn state_mut(&mut self) -> &mut EngineState {
331        &mut self.state
332    }
333
334    fn redo_inner(
335        &mut self,
336        id: BufferId,
337        timestamp_ms: i64,
338        alternate: bool,
339    ) -> Result<Option<ChangeBatch>, Error> {
340        let batch = self.undo.redo(
341            self.state.get_mut(id).ok_or(Error::UnknownBuffer)?,
342            timestamp_ms,
343            alternate,
344        )?;
345        self.record_optional_batch(batch.as_ref());
346        Ok(batch)
347    }
348
349    fn record_optional_batch(&mut self, batch: Option<&ChangeBatch>) {
350        if let Some(batch) = batch {
351            self.record_batch(batch);
352        }
353    }
354
355    fn record_batch(&mut self, batch: &ChangeBatch) {
356        self.delta_history.push(
357            batch.buffer_id,
358            batch.revision_after.get(),
359            batch.deltas.clone(),
360        );
361        self.events.push(EngineEvent::Changed {
362            id: batch.buffer_id,
363            revision: batch.revision_after,
364            kind: batch.kind,
365        });
366    }
367}
368
369impl Default for Engine {
370    fn default() -> Self {
371        Self::new()
372    }
373}
374
375fn coalesce_kind_for(edit: &SelectionEdit) -> CoalesceKind {
376    match edit {
377        SelectionEdit::InsertText(text) if text.chars().count() == 1 && text != "\n" => {
378            CoalesceKind::Typing
379        }
380        SelectionEdit::DeleteBack | SelectionEdit::DeleteForward => CoalesceKind::Typing,
381        _ => CoalesceKind::Discrete,
382    }
383}
384
385fn command_name_for(edit: &SelectionEdit) -> &'static str {
386    match edit {
387        SelectionEdit::InsertText(_) => "editor.insert_text",
388        SelectionEdit::DeleteBack => "editor.delete_back",
389        SelectionEdit::DeleteForward => "editor.delete_forward",
390        _ => "editor.selection_edit",
391    }
392}