Skip to main content

text_document/
events.rs

1//! Document event types and subscription handle.
2
3use std::sync::Arc;
4use std::sync::atomic::AtomicBool;
5
6use parking_lot::Mutex;
7
8use crate::inner::{CallbackEntry, TextDocumentInner};
9
10/// Events emitted by a [`TextDocument`](crate::TextDocument).
11///
12/// Subscribe via [`TextDocument::on_change`](crate::TextDocument::on_change) (callback-based)
13/// or poll via [`TextDocument::poll_events`](crate::TextDocument::poll_events) (frame-loop).
14///
15/// These events carry enough information for a UI to do incremental updates —
16/// repaint only the affected region, not the entire document.
17/// Which channel some text arrived through.
18///
19/// A **fact about how the characters reached the document**, and nothing more.
20/// It says who typed, pasted or dictated nothing at all: an application can only
21/// report the channel it was called through, and the inference from a channel to
22/// an author is not one any of this can make.
23///
24/// ## Why the default is `Unspecified` and not `Programmatic`
25///
26/// Every insertion method has a plain form and a `_with_origin` sibling. The
27/// plain form reports [`Unspecified`](Self::Unspecified), which means *the
28/// caller did not say* — deliberately **not** [`Programmatic`](Self::Programmatic),
29/// which would assert that the application inserted the text itself. Those are
30/// different claims, and a consumer counting them apart is entitled to know
31/// which one it has.
32///
33/// The same distinction as an absent field versus a zero: an unspecified origin
34/// is missing information, and a wrong one is a wrong fact.
35#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
36pub enum InsertionOrigin {
37    /// The caller did not say. The default for every plain insertion method.
38    #[default]
39    Unspecified,
40    /// Entered a key at a time.
41    Typed,
42    /// Committed by an input method — the multi-keystroke path that produces
43    /// one character. Kept apart from [`Typed`](Self::Typed) because a consumer
44    /// counting keystrokes and one counting characters disagree here, and both
45    /// are right.
46    Composed,
47    /// Pasted from a clipboard.
48    Pasted,
49    /// Dropped in from elsewhere.
50    Dropped,
51    /// Brought in by a document import.
52    Imported,
53    /// Re-applied by undo or redo.
54    ///
55    /// Hard-coded at those two paths, which never re-enter the insertion API —
56    /// they snapshot and diff instead — so a replayed edit can never be counted
57    /// twice under its original origin.
58    Replayed,
59    /// Inserted by the application: a template, an expansion, a substitution.
60    Programmatic,
61    /// Arrived through an accessibility channel: dictation, a braille display.
62    ///
63    /// **Never folded into [`Typed`](Self::Typed).** Some people write this way,
64    /// and a record that erased the distinction would be reporting them as
65    /// something they are not.
66    Assistive,
67}
68
69impl InsertionOrigin {
70    /// A stable lower-case token, for anything that has to write one down.
71    ///
72    /// Spelled out rather than derived from the variant name, so renaming a
73    /// variant cannot silently change what a consumer persisted.
74    pub fn token(self) -> &'static str {
75        match self {
76            InsertionOrigin::Unspecified => "unspecified",
77            InsertionOrigin::Typed => "typed",
78            InsertionOrigin::Composed => "composed",
79            InsertionOrigin::Pasted => "pasted",
80            InsertionOrigin::Dropped => "dropped",
81            InsertionOrigin::Imported => "imported",
82            InsertionOrigin::Replayed => "replayed",
83            InsertionOrigin::Programmatic => "programmatic",
84            InsertionOrigin::Assistive => "assistive",
85        }
86    }
87
88    /// Every variant, for a consumer building a table over them.
89    pub const ALL: [InsertionOrigin; 9] = [
90        InsertionOrigin::Unspecified,
91        InsertionOrigin::Typed,
92        InsertionOrigin::Composed,
93        InsertionOrigin::Pasted,
94        InsertionOrigin::Dropped,
95        InsertionOrigin::Imported,
96        InsertionOrigin::Replayed,
97        InsertionOrigin::Programmatic,
98        InsertionOrigin::Assistive,
99    ];
100}
101
102#[derive(Debug, Clone, PartialEq)]
103pub enum DocumentEvent {
104    /// Text content changed at a specific region.
105    ///
106    /// Emitted by every edit that changes what the document contains: the
107    /// text-level ones (`insert_text`, `delete_char`, `delete_previous_char`,
108    /// `remove_selected_text`, `insert_formatted_text`, `insert_block`,
109    /// `insert_html`, `insert_markdown`, `insert_fragment`, `insert_image`), the
110    /// streaming appends, `undo` and `redo`, and every **structural table edit**
111    /// (`insert_table_row`, `insert_table_column`, `remove_table_row`,
112    /// `remove_table_column`, `merge_table_cells`, `split_table_cell`,
113    /// `remove_table`, and the cursor-relative wrappers over them).
114    ///
115    /// ⚠ The list above was wrong in both directions for a long time, and the
116    /// half that mattered was the table edits: they emitted nothing at all, so a
117    /// consumer holding offsets kept them across a row insert and a consumer
118    /// caching on [`TextDocument::content_revision`] never reheated. Nothing
119    /// errored and nothing looked wrong.
120    ///
121    /// ## Two things a consumer should know about the figures
122    ///
123    /// `chars_added` and `chars_removed` are a **net delta for the affected
124    /// region**, not "characters this edit introduced": replacing a selection
125    /// reports both, and a caller wanting to know how much text an edit brought
126    /// in cannot get it from here.
127    ///
128    /// The figures are in the document's own positions, the ones a cursor,
129    /// [`TextDocument::text_at`] and [`TextDocument::to_addressable_text`] use,
130    /// where a table is its `U+FFFC` anchor and the separator after it. Each
131    /// event is a splice of that text: the text before the edit, with
132    /// `chars_removed` characters at `position` replaced by the `chars_added`
133    /// characters at `position` in the text after it, is the text after it.
134    /// `undo`, `redo`, the table edits and inserting a table or a frame work the
135    /// change out by a diff of that text, and report the blocks that changed
136    /// when those hold the whole of it. [`TextDocument::to_plain_text`] is not
137    /// that text when the document contains a table: it leaves the anchors out.
138    ///
139    /// [`TextDocument::content_revision`]: crate::TextDocument::content_revision
140    /// [`TextDocument::to_plain_text`]: crate::TextDocument::to_plain_text
141    /// [`TextDocument::text_at`]: crate::TextDocument::text_at
142    /// [`TextDocument::to_addressable_text`]: crate::TextDocument::to_addressable_text
143    ContentsChanged {
144        position: usize,
145        chars_removed: usize,
146        chars_added: usize,
147        blocks_affected: usize,
148    },
149
150    /// Text arrived, and this is where it came from.
151    ///
152    /// Emitted **alongside** [`ContentsChanged`](Self::ContentsChanged), never
153    /// instead of it, and only when an insertion actually added characters.
154    ///
155    /// ## Why this is not a field on `ContentsChanged`
156    ///
157    /// Because `ContentsChanged` carries the wrong number for the question.
158    /// Its `chars_added` is a **net delta for the affected region**: replacing a
159    /// twelve-character selection with a four-character paste reports both a
160    /// removal and an addition, and neither figure is "how much text this paste
161    /// brought in". Attaching an origin to a net delta would produce an
162    /// attribution that looks precise and is not.
163    ///
164    /// `chars_inserted` here is the other number: **what this insertion
165    /// introduced**, which is the one a consumer attributing text to a channel
166    /// actually wants.
167    ///
168    /// Keeping it a separate event is also what makes it additive — every
169    /// existing consumer of `ContentsChanged` is untouched, and one that does
170    /// not care about origins never has to mention this.
171    TextInserted {
172        position: usize,
173        /// How many characters this insertion introduced. Never a net delta.
174        chars_inserted: usize,
175        origin: InsertionOrigin,
176    },
177
178    /// Formatting changed without text content change.
179    FormatChanged {
180        position: usize,
181        length: usize,
182        /// Distinguishes block-level changes (relayout needed) from
183        /// character-level changes (reshaping only).
184        kind: crate::flow::FormatChangeKind,
185    },
186
187    /// Only paint-level highlight attributes changed (colors, underline
188    /// decorations) on a paint-only highlighter. The shaping input
189    /// (`fragments`) is unchanged, so the layout engine can recolor the
190    /// cached layout without reshaping or reflowing.
191    ///
192    /// `position` / `length` are document-absolute character offsets bounding
193    /// the extent that changed, so a view may recolor just the blocks they
194    /// cover rather than re-snapshotting the whole document.
195    ///
196    /// **A `length` of `0` means "unknown — assume the whole document"**, and
197    /// is what the genuinely document-wide operations send: installing or
198    /// retiring a highlighter, and a full rehighlight. `set_session_ranges`
199    /// knows its own before/after ranges and reports their union exactly.
200    /// A receiver that does not care may keep treating every one of these as
201    /// whole-document; that is the safe reading of both cases.
202    HighlightPaintChanged { position: usize, length: usize },
203
204    /// Block count changed. Carries the new count.
205    BlockCountChanged(usize),
206
207    /// Flow elements were inserted at the given index in the main
208    /// frame's `child_order`.
209    ///
210    /// This is a performance optimization — the layout engine can
211    /// update incrementally instead of re-querying
212    /// [`TextDocument::flow()`](crate::TextDocument::flow).
213    FlowElementsInserted { flow_index: usize, count: usize },
214
215    /// Flow elements were removed starting at the given index in the
216    /// main frame's `child_order`.
217    FlowElementsRemoved { flow_index: usize, count: usize },
218
219    /// The document was completely replaced (import, clear).
220    DocumentReset,
221
222    /// Undo/redo was performed or availability changed.
223    UndoRedoChanged { can_undo: bool, can_redo: bool },
224
225    /// The modified flag changed.
226    ModificationChanged(bool),
227
228    /// A long operation progressed.
229    LongOperationProgress {
230        operation_id: String,
231        percent: f64,
232        message: String,
233    },
234
235    /// A long operation completed or failed.
236    LongOperationFinished {
237        operation_id: String,
238        success: bool,
239        error: Option<String>,
240    },
241}
242
243/// Handle to a document event subscription.
244///
245/// Events are delivered as long as this handle is alive.
246/// Drop it to unsubscribe. No explicit unsubscribe method needed.
247pub struct Subscription {
248    alive: Arc<AtomicBool>,
249}
250
251impl Drop for Subscription {
252    fn drop(&mut self) {
253        self.alive
254            .store(false, std::sync::atomic::Ordering::Relaxed);
255    }
256}
257
258/// Register a callback with the document inner, returning a Subscription handle.
259pub(crate) fn subscribe_inner<F>(inner: &mut TextDocumentInner, callback: F) -> Subscription
260where
261    F: Fn(DocumentEvent) + Send + Sync + 'static,
262{
263    let alive = Arc::new(AtomicBool::new(true));
264    inner.callbacks.push(CallbackEntry {
265        alive: Arc::downgrade(&alive),
266        callback: Arc::new(callback),
267        since: inner.events_queued,
268    });
269    Subscription { alive }
270}
271
272/// Holds back the document's events while it is alive: made by
273/// [`TextDocument::hold_events`](crate::TextDocument::hold_events), and dropping it releases
274/// them.
275///
276/// Owns a handle on the document, so it may be kept in a host's state between the call
277/// that begins a batch and the one that ends it.
278#[must_use = "the events are released as soon as the hold is dropped"]
279pub struct EventHold {
280    pub(crate) doc: Arc<Mutex<TextDocumentInner>>,
281}
282
283impl std::fmt::Debug for EventHold {
284    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
285        f.debug_struct("EventHold").finish_non_exhaustive()
286    }
287}
288
289impl Drop for EventHold {
290    fn drop(&mut self) {
291        crate::inner::release_event_hold(&self.doc);
292    }
293}