Skip to main content

continuity_buffer/
buffer.rs

1//! The `Buffer` aggregate.
2//!
3//! Owned exclusively by the caller-selected engine thread. Carries id, rope, revision,
4//! selections, and the undo tree.
5
6mod selection_transform;
7
8use std::sync::Arc;
9
10use continuity_text::{EditOp, Position, Selection};
11use ropey::Rope;
12
13use crate::checksum;
14use crate::selection_clamp::clamp_selection_to_rope;
15#[cfg(not(target_arch = "wasm32"))]
16use crate::FileAssociation;
17use crate::{BufferId, Error, Revision, RopeSnapshot, UndoTree};
18
19use selection_transform::SelectionTransform;
20
21/// A single editable text buffer.
22///
23/// **Thread ownership**: only the caller-selected engine thread mutates a `Buffer`.
24/// All other threads receive [`RopeSnapshot`]s instead.
25#[derive(Debug)]
26pub struct Buffer {
27    id: BufferId,
28    rope: Rope,
29    revision: Revision,
30    selections: Vec<Selection>,
31    undo: UndoTree,
32    #[cfg(not(target_arch = "wasm32"))]
33    file: Option<FileAssociation>,
34    /// Synthetic buffers are never written to persist (no `buffers` row,
35    /// no `buffer_edits`, no `buffer_snapshots`). Used for transient
36    /// read-only surfaces like the tutorial tab — the rope lives only
37    /// in memory for the lifetime of the process.
38    ///
39    /// Construct via [`Buffer::synthetic_read_only`]. Default = `false`.
40    synthetic: bool,
41    /// Read-only buffers reject [`EditOp`] / [`crate::SelectionEdit`]
42    /// application in the core thread before reaching the rope. Pairs
43    /// naturally with `synthetic` for static content (tutorial, release
44    /// notes) but is independent — a persisted buffer could be marked
45    /// read-only without being synthetic.
46    ///
47    /// Default = `false`.
48    read_only: bool,
49    /// FNV-1a 64-bit hash of `rope`'s bytes, kept in sync with each
50    /// [`Self::apply`] via incremental mix/unmix in
51    /// [`crate::checksum::update_for_edit`]. Persisted on every edit
52    /// row as `checksum_after`; full-walk verification reseats it
53    /// periodically (every [`crate::checksum::CHECKSUM_VERIFY_INTERVAL`]
54    /// edits, plus at snapshot boundaries) via
55    /// [`Self::verify_running_checksum`].
56    running_checksum: u64,
57    /// Number of [`Self::apply`] calls since the last full-walk
58    /// verification of [`Self::running_checksum`]. The core thread
59    /// reads this to decide whether to take the verify path on the
60    /// next persisted edit.
61    edits_since_verify: u32,
62}
63
64impl Buffer {
65    /// An empty buffer with a fresh id.
66    #[must_use]
67    pub fn empty() -> Self {
68        Self {
69            id: BufferId::new(),
70            rope: Rope::new(),
71            revision: Revision::INITIAL,
72            selections: vec![Selection::caret_at(Position::ZERO)],
73            undo: UndoTree::new(),
74            #[cfg(not(target_arch = "wasm32"))]
75            file: None,
76            synthetic: false,
77            read_only: false,
78            running_checksum: checksum::FNV_OFFSET_BASIS,
79            edits_since_verify: 0,
80        }
81    }
82
83    /// A buffer pre-populated with `text`.
84    pub fn from_text(text: &str) -> Self {
85        let rope = Rope::from_str(text);
86        let running_checksum = checksum::full_walk_rope(&rope);
87        Self {
88            id: BufferId::new(),
89            rope,
90            revision: Revision::INITIAL,
91            selections: vec![Selection::caret_at(Position::ZERO)],
92            undo: UndoTree::new(),
93            #[cfg(not(target_arch = "wasm32"))]
94            file: None,
95            synthetic: false,
96            read_only: false,
97            running_checksum,
98            edits_since_verify: 0,
99        }
100    }
101
102    /// A synthetic, read-only buffer pre-populated with `text`.
103    ///
104    /// "Synthetic" means the buffer is never persisted: no row in the
105    /// `buffers` table, no `buffer_edits`, no `buffer_snapshots`, never
106    /// surfaced in FTS5 or `find-in-all`. The rope lives only in memory
107    /// for the lifetime of the process. "Read-only" means the core
108    /// thread rejects any [`EditOp`] or [`crate::SelectionEdit`] before
109    /// it reaches the rope.
110    ///
111    /// Used for transient documentation surfaces such as the tutorial
112    /// tab.
113    #[must_use]
114    pub fn synthetic_read_only(text: &str) -> Self {
115        let mut b = Self::from_text(text);
116        b.synthetic = true;
117        b.read_only = true;
118        b
119    }
120
121    /// Reconstruct a buffer with a specific id and revision (for persistence
122    /// recovery). The `revision` should be the revision the snapshot was
123    /// taken at; subsequent [`Self::apply`] calls advance it normally.
124    #[must_use]
125    pub fn from_parts(id: BufferId, text: &str, revision: Revision) -> Self {
126        let rope = Rope::from_str(text);
127        let running_checksum = checksum::full_walk_rope(&rope);
128        Self {
129            id,
130            rope,
131            revision,
132            selections: vec![Selection::caret_at(Position::ZERO)],
133            undo: UndoTree::new(),
134            #[cfg(not(target_arch = "wasm32"))]
135            file: None,
136            synthetic: false,
137            read_only: false,
138            running_checksum,
139            edits_since_verify: 0,
140        }
141    }
142
143    /// Reconstruct a buffer with a specific id, revision, and file
144    /// association.
145    #[cfg(not(target_arch = "wasm32"))]
146    #[must_use]
147    pub fn from_parts_with_file(
148        id: BufferId,
149        text: &str,
150        revision: Revision,
151        file: Option<FileAssociation>,
152    ) -> Self {
153        let mut buffer = Self::from_parts(id, text, revision);
154        buffer.file = file;
155        buffer
156    }
157
158    /// `true` when this buffer is synthetic (never persisted).
159    ///
160    /// Persist clients check this before issuing any write; the core
161    /// thread skips `persist.touch_buffer` / `persist.upsert_buffer` /
162    /// `persist.save_snapshot_async` / `persist.write_edit` for
163    /// synthetic buffers.
164    #[must_use]
165    pub fn is_synthetic(&self) -> bool {
166        self.synthetic
167    }
168
169    /// `true` when this buffer rejects edit application.
170    ///
171    /// The core thread checks this before dispatching to
172    /// `apply_one_edit` / `apply_selection_edit` and returns
173    /// [`Error::ReadOnly`] without touching the rope. Undo / redo
174    /// operations also no-op on read-only buffers.
175    #[must_use]
176    pub fn is_read_only(&self) -> bool {
177        self.read_only
178    }
179
180    /// The buffer's stable id.
181    #[must_use]
182    pub fn id(&self) -> BufferId {
183        self.id
184    }
185
186    /// The current revision number.
187    #[must_use]
188    pub fn revision(&self) -> Revision {
189        self.revision
190    }
191
192    /// Borrow the rope.
193    #[must_use]
194    pub fn rope(&self) -> &Rope {
195        &self.rope
196    }
197
198    /// Borrow the selections.
199    #[must_use]
200    pub fn selections(&self) -> &[Selection] {
201        &self.selections
202    }
203
204    /// Replace the selection set.
205    pub fn set_selections(&mut self, selections: Vec<Selection>) {
206        self.selections = if selections.is_empty() {
207            vec![Selection::caret_at(Position::ZERO)]
208        } else {
209            selections
210                .into_iter()
211                .map(|selection| clamp_selection_to_rope(&self.rope, selection))
212                .collect()
213        };
214    }
215
216    /// Borrow the undo tree.
217    #[must_use]
218    pub fn undo_tree(&self) -> &UndoTree {
219        &self.undo
220    }
221
222    /// Mutable borrow of the undo tree. Used by the engine owner to
223    /// insert groups, append records, and step the current pointer along
224    /// the undo / redo path.
225    pub fn undo_tree_mut(&mut self) -> &mut UndoTree {
226        &mut self.undo
227    }
228
229    /// Borrow the optional filesystem association.
230    #[cfg(not(target_arch = "wasm32"))]
231    #[must_use]
232    pub fn file_association(&self) -> Option<&FileAssociation> {
233        self.file.as_ref()
234    }
235
236    /// Replace the filesystem association.
237    #[cfg(not(target_arch = "wasm32"))]
238    pub fn set_file_association(&mut self, file: Option<FileAssociation>) {
239        self.file = file;
240    }
241
242    /// Capture the substring `op` would remove from the current rope, if
243    /// any. Returns an empty `String` for [`EditOp::Insert`].
244    ///
245    /// # Errors
246    ///
247    /// Returns [`Error::Text`] if the range falls outside the rope.
248    pub fn capture_removed_text(&self, op: &EditOp) -> Result<String, Error> {
249        match op {
250            EditOp::Insert { .. } => Ok(String::new()),
251            EditOp::Delete { range } | EditOp::Replace { range, .. } => {
252                let start = range.start.to_byte_offset(&self.rope)?;
253                let end = range.end.to_byte_offset(&self.rope)?;
254                let lo = start.min(end);
255                let hi = start.max(end);
256                Ok(self.rope.byte_slice(lo..hi).to_string())
257            }
258        }
259    }
260
261    /// Take a cheap, send-able snapshot of the current rope + revision.
262    #[must_use]
263    pub fn snapshot(&self) -> RopeSnapshot {
264        RopeSnapshot::new(Arc::new(self.rope.clone()), self.revision)
265    }
266
267    /// First non-empty trimmed line of the rope, clipped to `max_chars`. An
268    /// empty buffer (or a buffer of pure whitespace) returns `None`.
269    ///
270    /// Used for buffer-switcher labels and the `windows.tabs` table when no
271    /// user-set title exists.
272    #[must_use]
273    pub fn title(&self, max_chars: usize) -> Option<String> {
274        derive_title(&self.rope, max_chars)
275    }
276
277    /// FNV-1a 64-bit hash of the rope's bytes, maintained incrementally
278    /// across [`Self::apply`] calls. The core thread persists this as
279    /// `buffer_edits.checksum_after`; a divergence from a full-walk
280    /// recomputation is surfaced through `event:checksum_drift`. See
281    /// [`crate::checksum`].
282    #[must_use]
283    pub fn running_checksum(&self) -> u64 {
284        self.running_checksum
285    }
286
287    /// Number of [`Self::apply`] calls since the running checksum was
288    /// last cross-checked against a full-walk recomputation.
289    #[must_use]
290    pub fn edits_since_verify(&self) -> u32 {
291        self.edits_since_verify
292    }
293
294    /// Re-run a full-walk FNV-1a over the current rope and reseat the
295    /// running checksum to the freshly-computed value. Returns
296    /// `(observed_before, computed)` — `observed_before` is what the
297    /// running counter held before reseating; equality means no drift.
298    /// Also clears [`Self::edits_since_verify`] so the next verification
299    /// is again `CHECKSUM_VERIFY_INTERVAL` edits away.
300    pub fn verify_running_checksum(&mut self) -> (u64, u64) {
301        let observed = self.running_checksum;
302        let computed = checksum::full_walk_rope(&self.rope);
303        self.running_checksum = computed;
304        self.edits_since_verify = 0;
305        (observed, computed)
306    }
307
308    /// Apply an [`EditOp`], advance the revision, and return the new revision.
309    ///
310    /// # Errors
311    ///
312    /// Returns [`Error::Text`] if any position in `op` falls outside the rope.
313    /// Returns [`Error::ReadOnly`] if the buffer is read-only (e.g. a
314    /// synthetic tutorial buffer); the rope is not touched.
315    pub fn apply(&mut self, op: &EditOp) -> Result<Revision, Error> {
316        if self.read_only {
317            return Err(Error::ReadOnly);
318        }
319        let transform = SelectionTransform::from_op(&self.rope, op)?;
320        // Capture the bytes the op will remove (empty for `Insert`) so
321        // we can unmix them from the running checksum after the rope
322        // has been mutated.
323        let removed_text = self.capture_removed_text(op)?;
324        let old_rope = self.rope.clone();
325        match op {
326            EditOp::Insert { at, text } => {
327                let byte = at.to_byte_offset(&self.rope)?;
328                let char_idx = self.rope.byte_to_char(byte);
329                self.rope.insert(char_idx, text);
330            }
331            EditOp::Delete { range } => {
332                let start_byte = range.start.to_byte_offset(&self.rope)?;
333                let end_byte = range.end.to_byte_offset(&self.rope)?;
334                let start_char = self.rope.byte_to_char(start_byte);
335                let end_char = self.rope.byte_to_char(end_byte);
336                self.rope.remove(start_char..end_char);
337            }
338            EditOp::Replace { range, text } => {
339                let start_byte = range.start.to_byte_offset(&self.rope)?;
340                let end_byte = range.end.to_byte_offset(&self.rope)?;
341                let start_char = self.rope.byte_to_char(start_byte);
342                let end_char = self.rope.byte_to_char(end_byte);
343                self.rope.remove(start_char..end_char);
344                self.rope.insert(start_char, text);
345            }
346        }
347        // If the incremental update ever fails to resolve the op's
348        // positions against the post-apply rope (none of the in-tree
349        // ops do, but the signature returns `Result`), fall back to a
350        // full walk so the running checksum stays bit-for-bit equal to
351        // `hash(rope)` and recovery never sees a drifted edit row.
352        self.running_checksum =
353            match checksum::update_for_edit(self.running_checksum, &self.rope, op, &removed_text) {
354                Ok(state) => state,
355                Err(_) => checksum::full_walk_rope(&self.rope),
356            };
357        self.edits_since_verify = self.edits_since_verify.saturating_add(1);
358        self.selections = transform.apply_all(&old_rope, &self.rope, &self.selections);
359        self.revision = self.revision.next();
360        Ok(self.revision)
361    }
362}
363
364impl Default for Buffer {
365    fn default() -> Self {
366        Self::empty()
367    }
368}
369
370/// First non-empty trimmed line of `rope`, clipped to `max_chars`.
371///
372/// Returns `None` when the rope is empty or only whitespace. The result is
373/// trimmed of leading + trailing whitespace; trailing ellipsis ("…") is
374/// appended only when truncation actually drops characters.
375#[must_use]
376pub fn derive_title(rope: &Rope, max_chars: usize) -> Option<String> {
377    for line_idx in 0..rope.len_lines() {
378        let mut line: String = rope.line(line_idx).to_string();
379        if line.ends_with('\n') {
380            line.pop();
381            if line.ends_with('\r') {
382                line.pop();
383            }
384        }
385        let trimmed = line.trim();
386        if trimmed.is_empty() {
387            continue;
388        }
389        if trimmed.chars().count() <= max_chars {
390            return Some(trimmed.to_string());
391        }
392        let mut s: String = trimmed.chars().take(max_chars.saturating_sub(1)).collect();
393        s.push('…');
394        return Some(s);
395    }
396    None
397}
398
399#[cfg(test)]
400mod tests;