1use 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
13pub trait IdGenerator {
18 fn next_buffer_id(&mut self) -> BufferId;
20
21 fn next_undo_group_id(&mut self) -> UndoGroupId;
23}
24
25#[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#[derive(Clone)]
41pub struct EngineSnapshot {
42 pub rope: RopeSnapshot,
44 pub selections: Vec<Selection>,
46 pub is_read_only: bool,
48}
49
50pub 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 #[must_use]
66 pub fn new() -> Self {
67 Self::with_id_generator(Box::<SystemIdGenerator>::default())
68 }
69
70 #[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 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 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 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 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 #[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 #[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 #[must_use]
127 pub fn selections(&self, id: BufferId) -> Option<&[Selection]> {
128 self.state.get(id).map(Buffer::selections)
129 }
130
131 #[must_use]
133 pub fn revision(&self, id: BufferId) -> Option<Revision> {
134 self.state.get(id).map(Buffer::revision)
135 }
136
137 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 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 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 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 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 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 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 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 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 #[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 #[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 pub fn drain_events(&mut self) -> Vec<EngineEvent> {
320 std::mem::take(&mut self.events)
321 }
322
323 #[must_use]
325 pub fn state(&self) -> &EngineState {
326 &self.state
327 }
328
329 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}