Skip to main content

common/
undo_redo.rs

1// Generated by Qleany v1.10.0 from undo_redo.tera
2use crate::event::{Event, EventHub, Origin, UndoRedoEvent};
3use crate::types::EntityId;
4use anyhow::{Result, anyhow};
5use std::any::Any;
6use std::collections::HashMap;
7use std::fmt;
8use std::sync::Arc;
9
10/// The stack id that means **do not record this**.
11///
12/// Some writes must happen and must not appear in the user's history: a buffer
13/// mirrored to the store on a timer, a cache line, an index rebuilt on open.
14/// The generated commands always push — `stack_id: None` resolves to the global
15/// stack `0` rather than opting out — so before this const the only way to keep
16/// such a write out of the history was to push it somewhere and clear that
17/// somewhere afterwards, which nobody remembers to do. Passing this id instead
18/// drops the command at the door: nothing is stored, so there is nothing to
19/// clear, and stack `0` stays empty.
20///
21/// `create_new_stack` counts up from 1, so this value can never collide with a
22/// real stack.
23pub const UNTRACKED_STACK_ID: u64 = u64::MAX;
24
25/// A stable, machine-readable name for what a command did.
26///
27/// Deliberately **not** a localized string. This crate is generated and knows
28/// nothing about locales or about the application's translation catalogue, so
29/// it hands back a key — `("binder_item", "remove")` — and the application
30/// turns that into *"Undo deleting a scene"* in the reader's language.
31#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
32pub struct UndoLabel {
33    /// What was acted on: an entity name, or a feature use case's own name.
34    pub subject: &'static str,
35    /// What was done to it — `"create"`, `"update"`, `"remove"`, … Empty when
36    /// `subject` already names the whole act (a feature use case such as
37    /// `"trash_binder_items"` is not an *action on* something else).
38    pub action: &'static str,
39}
40
41impl UndoLabel {
42    pub const fn new(subject: &'static str, action: &'static str) -> Self {
43        Self { subject, action }
44    }
45
46    /// A whole-act label, for a command whose `subject` is the act itself.
47    pub const fn act(subject: &'static str) -> Self {
48        Self {
49            subject,
50            action: "",
51        }
52    }
53}
54
55/// What [`UndoRedoManager::undo_if_head`] actually did.
56///
57/// The reason this exists: a "take that back" affordance offered *for one
58/// operation* — the Undo button on a toast — cannot use plain `undo()`, which
59/// pops whatever is on top. Anything pushed in the meantime (an autosave, a
60/// second window, a background job) silently becomes the thing that gets undone
61/// instead. Naming the operation and being told it is no longer the head is the
62/// difference between a correct affordance and a data-loss bug.
63#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
64pub enum UndoStatus {
65    /// The named command was on top, and has been undone.
66    Undone,
67    /// Something else has been pushed since; nothing was undone.
68    Superseded,
69    /// The stack is empty; nothing was undone.
70    Empty,
71}
72
73/// Trait for commands that can be undone and redone.
74///
75/// Implementors can optionally support command merging by overriding the
76/// `can_merge` and `merge` methods. This allows the UndoRedoManager to combine
77/// multiple commands of the same type into a single command, which is useful for
78/// operations like continuous typing or dragging.
79pub trait UndoRedoCommand: Send {
80    /// Undoes the command, reverting its effects
81    fn undo(&mut self) -> Result<()>;
82
83    /// Redoes the command, reapplying its effects
84    fn redo(&mut self) -> Result<()>;
85
86    /// Returns true if this command can be merged with the other command.
87    ///
88    /// By default, commands cannot be merged. Override this method to enable
89    /// merging for specific command types.
90    ///
91    /// # Example
92    /// ```test
93    /// fn can_merge(&self, other: &dyn UndoRedoCommand) -> bool {
94    ///     // Check if the other command is of the same type
95    ///     if let Some(_) = other.as_any().downcast_ref::<Self>() {
96    ///         return true;
97    ///     }
98    ///     false
99    /// }
100    /// ```
101    fn can_merge(&self, _other: &dyn UndoRedoCommand) -> bool {
102        false
103    }
104
105    /// Merges this command with the other command.
106    /// Returns true if the merge was successful.
107    ///
108    /// This method is called only if `can_merge` returns true.
109    ///
110    /// # Example
111    /// ```test
112    /// use common::undo_redo::UndoRedoCommand;
113    ///
114    /// fn merge(&mut self, other: &dyn UndoRedoCommand) -> bool {
115    ///     if let Some(other_cmd) = other.as_any().downcast_ref::<Self>() {
116    ///         // Merge the commands
117    ///         self.value += other_cmd.value;
118    ///         return true;
119    ///     }
120    ///     false
121    /// }
122    /// ```
123    fn merge(&mut self, _other: &dyn UndoRedoCommand) -> bool {
124        false
125    }
126
127    /// Returns the type ID of this command for type checking.
128    ///
129    /// This is used for downcasting in the `can_merge` and `merge` methods.
130    ///
131    /// # Example
132    /// ```test
133    /// fn as_any(&self) -> &dyn Any {
134    ///     self
135    /// }
136    /// ```
137    fn as_any(&self) -> &dyn Any;
138
139    /// A stable, machine-readable name for what this command did, for a menu
140    /// that says *"Undo rename"* rather than a bare *"Undo"*.
141    ///
142    /// Defaulted to `None` so an existing implementor compiles unchanged; a
143    /// command that returns `None` simply leaves the row generic.
144    fn label(&self) -> Option<UndoLabel> {
145        None
146    }
147}
148
149/// A composite command that groups multiple commands as one.
150///
151/// This allows treating a sequence of commands as a single unit for undo/redo operations.
152/// When a composite command is undone or redone, all its contained commands are undone
153/// or redone in the appropriate order.
154///
155/// # Example
156/// ```test
157/// use common::undo_redo::CompositeCommand;
158/// let mut composite = CompositeCommand::new();
159/// composite.add_command(Box::new(Command1::new()));
160/// composite.add_command(Box::new(Command2::new()));
161/// // Now composite can be treated as a single command
162/// ```
163pub struct CompositeCommand {
164    label: Option<UndoLabel>,
165    commands: Vec<Box<dyn UndoRedoCommand>>,
166    pub stack_id: u64,
167}
168
169impl fmt::Debug for CompositeCommand {
170    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
171        f.debug_struct("CompositeCommand")
172            .field("commands_len", &self.commands.len())
173            .field("stack_id", &self.stack_id)
174            .finish()
175    }
176}
177
178impl CompositeCommand {
179    /// Creates a new empty composite command.
180    pub fn new(stack_id: Option<u64>) -> Self {
181        Self::labeled(stack_id, None)
182    }
183
184    /// A composite that names itself.
185    ///
186    /// A group's constituent labels are the wrong answer for a menu — a
187    /// three-entity capture would read *"Undo update"* after the least
188    /// interesting of its parts. The caller who opened the group is the only
189    /// one who knows what the group *was*, so it says so here.
190    pub fn labeled(stack_id: Option<u64>, label: Option<UndoLabel>) -> Self {
191        CompositeCommand {
192            label,
193            commands: Vec::new(),
194            stack_id: stack_id.unwrap_or(0),
195        }
196    }
197
198    /// Adds a command to this composite.
199    ///
200    /// Commands are executed, undone, and redone in the order they are added.
201    pub fn add_command(&mut self, command: Box<dyn UndoRedoCommand>) {
202        self.commands.push(command);
203    }
204
205    /// Returns true if this composite contains no commands.
206    pub fn is_empty(&self) -> bool {
207        self.commands.is_empty()
208    }
209
210    /// Name this group after the fact — for a caller that only learns what the
211    /// group was once its parts have run.
212    pub fn set_label(&mut self, label: Option<UndoLabel>) {
213        self.label = label;
214    }
215
216    /// Undo, newest first, the commands added after the first `start`, and drop
217    /// them. The first `start` stay as they are: they belong to an enclosing
218    /// level that is still open. The commands are dropped even when one fails
219    /// to undo, since the level they belonged to is gone either way, so every
220    /// one of them is still offered its undo: stopping at the first failure
221    /// would leave the older ones applied inside a group that goes on to be
222    /// recorded. Returns the first failure.
223    fn cancel_since(&mut self, start: usize) -> Result<()> {
224        let start = start.min(self.commands.len());
225        let mut outcome = Ok(());
226        for command in self.commands[start..].iter_mut().rev() {
227            if let Err(e) = command.undo() {
228                log::error!("Undo failed while cancelling a nested composite: {e}");
229                if outcome.is_ok() {
230                    outcome = Err(e);
231                }
232            }
233        }
234        self.commands.truncate(start);
235        outcome
236    }
237}
238
239impl UndoRedoCommand for CompositeCommand {
240    fn undo(&mut self) -> Result<()> {
241        // Undo commands in reverse order
242        for command in self.commands.iter_mut().rev() {
243            command.undo()?;
244        }
245        Ok(())
246    }
247
248    fn redo(&mut self) -> Result<()> {
249        // Redo commands in original order
250        for command in self.commands.iter_mut() {
251            command.redo()?;
252        }
253        Ok(())
254    }
255
256    fn as_any(&self) -> &dyn Any {
257        self
258    }
259
260    /// The group's own name, never a constituent's — see [`CompositeCommand::labeled`].
261    fn label(&self) -> Option<UndoLabel> {
262        self.label
263    }
264}
265/// Trait for commands that can be executed asynchronously with progress tracking and cancellation.
266///
267/// This trait extends the basic UndoRedoCommand trait with asynchronous capabilities.
268/// Implementors must also implement the UndoRedoCommand trait to ensure compatibility
269/// with the existing undo/redo system.
270pub trait AsyncUndoRedoCommand: UndoRedoCommand {
271    /// Starts the undo operation asynchronously and returns immediately.
272    /// Returns Ok(()) if the operation was successfully started.
273    fn start_undo(&mut self) -> Result<()>;
274
275    /// Starts the redo operation asynchronously and returns immediately.
276    /// Returns Ok(()) if the operation was successfully started.
277    fn start_redo(&mut self) -> Result<()>;
278
279    /// Checks the progress of the current operation.
280    /// Returns a value between 0.0 (not started) and 1.0 (completed).
281    fn check_progress(&self) -> f32;
282
283    /// Attempts to cancel the in-progress operation.
284    /// Returns Ok(()) if cancellation was successful or if no operation is in progress.
285    fn cancel(&mut self) -> Result<()>;
286
287    /// Checks if the current operation is complete.
288    /// Returns true if the operation has finished successfully.
289    fn is_complete(&self) -> bool;
290}
291
292/// One step of history, and the number that names it.
293///
294/// The sequence is what lets a caller say *"undo the thing I just did"* rather
295/// than *"undo whatever is on top"* — see [`UndoStatus`]. It is minted once, at
296/// the push, and travels with the command across the undo/redo boundary, so an
297/// entry keeps its identity however many times it is stepped over.
298struct UndoEntry {
299    command: Box<dyn UndoRedoCommand>,
300    seq: u64,
301    /// Closed to merging — see [`UndoRedoManager::seal_head`].
302    sealed: bool,
303}
304
305/// One open `begin_composite` level, so that cancelling it takes back only
306/// what it added.
307#[derive(Debug, Clone, Copy)]
308struct CompositeLevel {
309    /// How many commands the group held when this level opened.
310    start: usize,
311    /// Whether this level gave the group its name: see
312    /// [`UndoRedoManager::begin_composite_labeled`].
313    named: bool,
314}
315
316#[derive(Default)]
317struct StackData {
318    undo_stack: Vec<UndoEntry>,
319    redo_stack: Vec<UndoEntry>,
320    /// How many commands were recorded on this stack: see
321    /// [`UndoRedoManager::commands_recorded`].
322    commands_recorded: u64,
323}
324
325impl fmt::Debug for StackData {
326    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
327        f.debug_struct("StackData")
328            .field("undo_len", &self.undo_stack.len())
329            .field("redo_len", &self.redo_stack.len())
330            .finish()
331    }
332}
333
334/// Manager for undo and redo operations.
335///
336/// The UndoRedoManager maintains multiple stacks of commands:
337/// - Each stack has an undo stack for commands that can be undone
338/// - Each stack has a redo stack for commands that have been undone and can be redone
339///
340/// It also supports:
341/// - Grouping multiple commands as a single unit using begin_composite/end_composite
342/// - Merging commands of the same type when appropriate
343/// - Switching between different stacks
344#[derive(Debug)]
345pub struct UndoRedoManager {
346    stacks: HashMap<u64, StackData>,
347    next_stack_id: u64,
348    in_progress_composite: Option<CompositeCommand>,
349    /// The open levels of the group, outermost first: as many as there are
350    /// `begin_composite` calls not yet ended or cancelled.
351    composite_levels: Vec<CompositeLevel>,
352    composite_stack_id: Option<u64>,
353    composite_label: Option<UndoLabel>,
354    event_hub: Option<Arc<EventHub>>,
355    /// Monotonic across every stack, so a sequence number is unique in the
356    /// process and a caller never has to say *which* stack it means.
357    next_seq: u64,
358    /// The sequence of the entry the most recent push landed in — a fresh one,
359    /// or the one it merged into. Read it straight after the call that pushed;
360    /// it is how a caller learns the number to hand back to
361    /// [`undo_if_head`](UndoRedoManager::undo_if_head) later.
362    last_pushed_seq: Option<u64>,
363    /// How many entries a stack may hold before the oldest are dropped.
364    /// `None` — the default — is unbounded, which is what a short-lived
365    /// document wants and what a day-long editing session does not.
366    undo_limit: Option<usize>,
367}
368
369impl Default for UndoRedoManager {
370    fn default() -> Self {
371        Self::new()
372    }
373}
374
375impl UndoRedoManager {
376    /// Creates a new empty UndoRedoManager with one default stack (ID 0).
377    pub fn new() -> Self {
378        let mut stacks = HashMap::new();
379        stacks.insert(0, StackData::default());
380        UndoRedoManager {
381            stacks,
382            next_stack_id: 1,
383            in_progress_composite: None,
384            composite_levels: Vec::new(),
385            composite_stack_id: None,
386            composite_label: None,
387            event_hub: None,
388            next_seq: 1,
389            last_pushed_seq: None,
390            undo_limit: None,
391        }
392    }
393
394    /// Emit one undo/redo event, naming the stack it happened on.
395    ///
396    /// The stack id travels in `data` because `ids` means *entity* ids, and a
397    /// process holding one stack per open document needs to tell whose history
398    /// moved — without it every subscriber has to re-poll every stack it knows.
399    fn emit(&self, event: UndoRedoEvent, stack_id: u64) {
400        if let Some(event_hub) = &self.event_hub {
401            event_hub.send_event(Event {
402                origin: Origin::UndoRedo(event),
403                ids: Vec::<EntityId>::new(),
404                data: Some(stack_id.to_string()),
405            });
406        }
407    }
408
409    /// Inject the event hub to allow sending undo/redo related events
410    pub fn set_event_hub(&mut self, event_hub: &Arc<EventHub>) {
411        self.event_hub = Some(Arc::clone(event_hub));
412    }
413
414    /// Undoes the most recent command on the specified stack.
415    /// If `stack_id` is None, the global stack (ID 0) is used.
416    ///
417    /// The undone command is moved to the redo stack.
418    /// Returns Ok(()) if successful or if there are no commands to undo.
419    pub fn undo(&mut self, stack_id: Option<u64>) -> Result<()> {
420        let target_stack_id = stack_id.unwrap_or(0);
421        let stack = self
422            .stacks
423            .get_mut(&target_stack_id)
424            .ok_or_else(|| anyhow!("Stack with ID {} not found", target_stack_id))?;
425
426        let stepped = if let Some(mut entry) = stack.undo_stack.pop() {
427            if let Err(e) = entry.command.undo() {
428                log::error!("Undo failed, re-pushing command to undo stack: {e}");
429                stack.undo_stack.push(entry);
430                return Err(e);
431            }
432            stack.redo_stack.push(entry);
433            true
434        } else {
435            false
436        };
437        if stepped {
438            self.emit(UndoRedoEvent::Undone, target_stack_id);
439        }
440        Ok(())
441    }
442
443    /// Redoes the most recently undone command on the specified stack.
444    /// If `stack_id` is None, the global stack (ID 0) is used.
445    ///
446    /// The redone command is moved back to the undo stack.
447    /// Returns Ok(()) if successful or if there are no commands to redo.
448    pub fn redo(&mut self, stack_id: Option<u64>) -> Result<()> {
449        let target_stack_id = stack_id.unwrap_or(0);
450        let stack = self
451            .stacks
452            .get_mut(&target_stack_id)
453            .ok_or_else(|| anyhow!("Stack with ID {} not found", target_stack_id))?;
454
455        let stepped = if let Some(mut entry) = stack.redo_stack.pop() {
456            if let Err(e) = entry.command.redo() {
457                log::error!("Redo failed, re-pushing command to redo stack: {e}");
458                stack.redo_stack.push(entry);
459                return Err(e);
460            }
461            stack.undo_stack.push(entry);
462            true
463        } else {
464            false
465        };
466        if stepped {
467            self.emit(UndoRedoEvent::Redone, target_stack_id);
468        }
469        Ok(())
470    }
471
472    /// Undo **only if** `seq` still names the top of the stack.
473    ///
474    /// The affordance this exists for is a toast's Undo button: it is offered
475    /// for one specific operation, and between the offer and the click anything
476    /// may have pushed — an autosave, a second window, a background job. Plain
477    /// `undo()` would take back that later thing instead, silently and with the
478    /// user believing they undid what the toast named. Naming the operation
479    /// turns a wrong action into an honest [`UndoStatus::Superseded`].
480    pub fn undo_if_head(&mut self, stack_id: Option<u64>, seq: u64) -> Result<UndoStatus> {
481        let target_stack_id = stack_id.unwrap_or(0);
482        let stack = self
483            .stacks
484            .get(&target_stack_id)
485            .ok_or_else(|| anyhow!("Stack with ID {} not found", target_stack_id))?;
486
487        match stack.undo_stack.last() {
488            None => Ok(UndoStatus::Empty),
489            Some(entry) if entry.seq != seq => Ok(UndoStatus::Superseded),
490            Some(_) => {
491                self.undo(stack_id)?;
492                Ok(UndoStatus::Undone)
493            }
494        }
495    }
496
497    /// Begins a composite command group.
498    ///
499    /// All commands added between begin_composite and end_composite will be treated as a single command.
500    /// This is useful for operations that logically represent a single action but require multiple
501    /// commands to implement.
502    ///
503    /// # Example
504    /// ```test
505    /// let mut manager = UndoRedoManager::new();
506    /// manager.begin_composite();
507    /// manager.add_command(Box::new(Command1::new()));
508    /// manager.add_command(Box::new(Command2::new()));
509    /// manager.end_composite();
510    /// // Now undo() will undo both commands as a single unit
511    /// ```
512    pub fn begin_composite(&mut self, stack_id: Option<u64>) -> Result<()> {
513        self.begin_composite_labeled(stack_id, None)
514    }
515
516    /// [`begin_composite`](Self::begin_composite), naming what the group is.
517    ///
518    /// Worth the extra call: a group's constituent labels describe its parts,
519    /// so a menu built from them reads *"Undo update"* for what the writer
520    /// experienced as *"add a character to the story bible"*. Only the caller
521    /// that opened the group knows the answer.
522    pub fn begin_composite_labeled(
523        &mut self,
524        stack_id: Option<u64>,
525        label: Option<UndoLabel>,
526    ) -> Result<()> {
527        if stack_id == Some(UNTRACKED_STACK_ID) {
528            return Err(anyhow!(
529                "Cannot open a composite on the untracked stack: its commands are \
530                 dropped, so the group could never be undone"
531            ));
532        }
533        if self.composite_stack_id.is_some() && self.composite_stack_id != stack_id {
534            return Err(anyhow!(
535                "Cannot begin a composite on a different stack while another composite is in progress"
536            ));
537        }
538
539        // Set the target stack ID for this composite
540        self.composite_stack_id = stack_id;
541
542        // If there's no composite in progress, create one. A nested
543        // `begin_composite_labeled` may name a group its opener left anonymous,
544        // but never rename one that already has a name: the outermost caller
545        // owns the description.
546        let mut named = false;
547        let start = match &self.in_progress_composite {
548            None => {
549                self.in_progress_composite = Some(CompositeCommand::labeled(stack_id, label));
550                self.composite_label = label;
551                named = label.is_some();
552                0
553            }
554            Some(composite) => {
555                if self.composite_label.is_none() {
556                    self.composite_label = label;
557                    named = label.is_some();
558                }
559                composite.commands.len()
560            }
561        };
562        self.composite_levels.push(CompositeLevel { start, named });
563
564        self.emit(UndoRedoEvent::BeginComposite, stack_id.unwrap_or(0));
565        Ok(())
566    }
567
568    /// Ends the current composite command group and adds it to the specified undo stack.
569    ///
570    /// If no commands were added to the composite, nothing is added to the undo stack.
571    /// If this is a nested composite, only the outermost composite is added to the undo stack.
572    pub fn end_composite(&mut self) {
573        // Close the innermost level
574        self.composite_levels.pop();
575
576        // Only end the composite if we're at the outermost level
577        if self.composite_levels.is_empty() {
578            if let Some(composite) = self.in_progress_composite.take()
579                && !composite.is_empty()
580            {
581                let target_stack_id = self.composite_stack_id.unwrap_or(0);
582                // A missing stack is a caller bug (the stack was dropped
583                // while a composite was open on it), but `end_composite`
584                // returns `()` and is called from a dozen fire-and-forget
585                // UI sites, so it cannot report one. It used to
586                // `.expect("Stack must exist")` — which killed the whole
587                // process, mid-edit, over a lost undo entry.
588                //
589                // Same shape as `database::write_guard`'s `acquire`: loud in
590                // a debug build so the bug is caught in development, and a
591                // degradation in a shipped one — the grouped commands stay
592                // applied, they just aren't undoable as a unit.
593                if self.stacks.contains_key(&target_stack_id) {
594                    let mut composite = composite;
595                    composite.set_label(self.composite_label);
596                    self.push_entry(target_stack_id, Box::new(composite));
597                } else {
598                    // Nothing was recorded, so nothing may be named: leaving
599                    // the register alone would hand the next
600                    // `last_pushed_seq` reader an earlier entry that is
601                    // still the head.
602                    self.last_pushed_seq = None;
603                    debug_assert!(
604                        false,
605                        "end_composite: undo stack {} does not exist — a composite was \
606                             opened on a stack that has since been removed",
607                        target_stack_id
608                    );
609                }
610            } else {
611                // An empty group records nothing either — same reasoning.
612                self.last_pushed_seq = None;
613            }
614            let ended_on = self.composite_stack_id.unwrap_or(0);
615            self.composite_label = None;
616            // Clear the target too, not just the label. `begin_composite`
617            // refuses a stack that differs from the one already open, so a
618            // target left set after the group closed locks every *other* stack
619            // out of compositing for the life of the manager — in a process
620            // holding one stack per open document, the first document to group
621            // anything would be the only one that ever could again.
622            // `cancel_composite` has always cleared it; this path forgot.
623            self.composite_stack_id = None;
624            self.emit(UndoRedoEvent::EndComposite, ended_on);
625        }
626    }
627
628    /// Cancels the innermost open composite level, undoing the commands added
629    /// since that level began.
630    ///
631    /// Inside an enclosing level, only this level's own commands are undone and
632    /// dropped. The enclosing group stays open with everything it held before,
633    /// and still reaches the undo stack when its own `end_composite` comes. It
634    /// used to undo and drop the whole group at any depth: one failed step
635    /// inside an edit block took back the block's earlier edits too, and the
636    /// rest of the block then landed on the stack as separate entries.
637    pub fn cancel_composite(&mut self) {
638        let cancelled_on = self.composite_stack_id.unwrap_or(0);
639
640        if let Some(level) = self.composite_levels.pop()
641            && !self.composite_levels.is_empty()
642        {
643            if let Some(composite) = &mut self.in_progress_composite {
644                let dropped = composite.commands.len().saturating_sub(level.start);
645                let _ = composite.cancel_since(level.start);
646                let stack_id = composite.stack_id;
647                self.forget_recorded(stack_id, dropped);
648            }
649            // A name this level gave the group goes with it.
650            if level.named {
651                self.composite_label = None;
652            }
653            self.last_pushed_seq = None;
654            self.emit(UndoRedoEvent::CancelComposite, cancelled_on);
655            return;
656        }
657
658        // The outermost level: undo any sub-commands that were already executed
659        // in this composite
660        if let Some(ref mut composite) = self.in_progress_composite {
661            let _ = composite.undo();
662            let (stack_id, dropped) = (composite.stack_id, composite.commands.len());
663            self.forget_recorded(stack_id, dropped);
664        }
665
666        self.in_progress_composite = None;
667        self.composite_stack_id = None;
668        self.composite_label = None;
669        // A cancelled group is not history: same reasoning as the record-nothing
670        // paths of `end_composite`.
671        self.last_pushed_seq = None;
672
673        self.emit(UndoRedoEvent::CancelComposite, cancelled_on);
674    }
675
676    /// Take `dropped` commands a cancelled group held off what `stack_id` has recorded (see
677    /// [`commands_recorded`](Self::commands_recorded)).
678    fn forget_recorded(&mut self, stack_id: u64, dropped: usize) {
679        if let Some(stack) = self.stacks.get_mut(&stack_id) {
680            stack.commands_recorded = stack.commands_recorded.wrapping_sub(dropped as u64);
681        }
682    }
683
684    /// Adds a command to the global undo stack (ID 0).
685    pub fn add_command(&mut self, command: Box<dyn UndoRedoCommand>) {
686        let _ = self.add_command_to_stack(command, None);
687    }
688
689    /// Adds a command to the specified undo stack.
690    /// If `stack_id` is None, the global stack (ID 0) is used.
691    ///
692    /// This method handles several cases:
693    /// 1. If a composite command is in progress, the command is added to the composite
694    /// 2. If the command can be merged with the last command on the specified undo stack, they are merged
695    /// 3. Otherwise, the command is added to the specified undo stack as a new entry
696    ///
697    /// In all cases, the redo stack of the stack is cleared when a new command is added.
698    pub fn add_command_to_stack(
699        &mut self,
700        command: Box<dyn UndoRedoCommand>,
701        stack_id: Option<u64>,
702    ) -> Result<()> {
703        // Checked before the composite branch, not after: an untracked write is
704        // untracked whatever else is open. Folding one into a group would make
705        // the group undo something the caller explicitly said was not history.
706        if stack_id == Some(UNTRACKED_STACK_ID) {
707            self.last_pushed_seq = None;
708            return Ok(());
709        }
710
711        // If we have a composite in progress, add the command to it
712        if let Some(composite) = &mut self.in_progress_composite {
713            // ensure that the stack_id is the same as the composite's stack
714            if composite.stack_id != stack_id.unwrap_or(0) {
715                return Err(anyhow!(
716                    "Cannot add command to composite with different stack ID"
717                ));
718            }
719            composite.add_command(command);
720            if let Some(stack) = self.stacks.get_mut(&composite.stack_id) {
721                stack.commands_recorded = stack.commands_recorded.wrapping_add(1);
722            }
723            // The history did not grow: the group is still open, and it is the
724            // group — not this command — that will get a sequence. Clearing the
725            // register is what stops a caller reading `last_pushed_seq` here and
726            // being handed the number of some *earlier*, unrelated entry, which
727            // is still the head and which `undo_if_head` would therefore
728            // cheerfully undo. See `last_pushed_seq`'s own contract.
729            self.last_pushed_seq = None;
730            return Ok(());
731        }
732
733        let target_stack_id = stack_id.unwrap_or(0);
734        let stack = self
735            .stacks
736            .get_mut(&target_stack_id)
737            .ok_or_else(|| anyhow!("Stack with ID {} does not exist", target_stack_id))?;
738
739        // Try to merge with the last command if possible
740        if let Some(last) = stack.undo_stack.last_mut()
741            && !last.sealed
742            && last.command.can_merge(&*command)
743            && last.command.merge(&*command)
744        {
745            // Merged: the history did not grow, so the entry keeps the sequence
746            // it already had. A caller that pushed and then read
747            // `last_pushed_seq` gets the entry its command actually landed in,
748            // which for a burst of coalesced typing is the burst.
749            let seq = last.seq;
750            stack.redo_stack.clear();
751            stack.commands_recorded = stack.commands_recorded.wrapping_add(1);
752            self.last_pushed_seq = Some(seq);
753            self.emit(UndoRedoEvent::StackChanged, target_stack_id);
754            return Ok(());
755        }
756
757        // If we couldn't merge, just add the command normally.
758        stack.commands_recorded = stack.commands_recorded.wrapping_add(1);
759        self.push_entry(target_stack_id, command);
760        Ok(())
761    }
762
763    /// Push one command as a fresh entry: mint its sequence, clear the redo
764    /// branch, trim the stack to [`undo_limit`](Self::set_undo_limit), and
765    /// announce it. The single place history grows.
766    fn push_entry(&mut self, target_stack_id: u64, command: Box<dyn UndoRedoCommand>) {
767        let seq = self.next_seq;
768        self.next_seq = self.next_seq.wrapping_add(1);
769        let limit = self.undo_limit;
770
771        let Some(stack) = self.stacks.get_mut(&target_stack_id) else {
772            // No stack, no entry — so no sequence to hand out and no change to
773            // announce. Reporting one anyway would name an entry that was never
774            // stored.
775            self.last_pushed_seq = None;
776            return;
777        };
778        stack.undo_stack.push(UndoEntry {
779            command,
780            seq,
781            sealed: false,
782        });
783        stack.redo_stack.clear();
784        if let Some(limit) = limit
785            && stack.undo_stack.len() > limit
786        {
787            // Oldest first: the far end of a long session is the part
788            // nobody reaches for, and every entry may be pinning a
789            // snapshot of the store.
790            let excess = stack.undo_stack.len() - limit;
791            stack.undo_stack.drain(0..excess);
792        }
793
794        self.last_pushed_seq = Some(seq);
795        self.emit(UndoRedoEvent::StackChanged, target_stack_id);
796    }
797
798    /// Returns true if there are commands that can be undone on the specified stack.
799    /// If `stack_id` is None, the global stack (ID 0) is used.
800    pub fn can_undo(&self, stack_id: Option<u64>) -> bool {
801        let target_stack_id = stack_id.unwrap_or(0);
802        self.stacks
803            .get(&target_stack_id)
804            .map(|s| !s.undo_stack.is_empty())
805            .unwrap_or(false)
806    }
807
808    /// Returns true if there are commands that can be redone on the specified stack.
809    /// If `stack_id` is None, the global stack (ID 0) is used.
810    pub fn can_redo(&self, stack_id: Option<u64>) -> bool {
811        let target_stack_id = stack_id.unwrap_or(0);
812        self.stacks
813            .get(&target_stack_id)
814            .map(|s| !s.redo_stack.is_empty())
815            .unwrap_or(false)
816    }
817
818    /// Clears the undo and redo history for a specific stack.
819    ///
820    /// This method removes all commands from both the undo and redo stacks of the specified stack.
821    pub fn clear_stack(&mut self, stack_id: u64) {
822        let cleared = if let Some(stack) = self.stacks.get_mut(&stack_id) {
823            stack.undo_stack.clear();
824            stack.redo_stack.clear();
825            true
826        } else {
827            false
828        };
829        if cleared {
830            self.emit(UndoRedoEvent::StackChanged, stack_id);
831        }
832    }
833
834    /// Clears all undo and redo history from all stacks.
835    pub fn clear_all_stacks(&mut self) {
836        for stack in self.stacks.values_mut() {
837            stack.undo_stack.clear();
838            stack.redo_stack.clear();
839        }
840        self.in_progress_composite = None;
841        self.composite_levels.clear();
842        self.composite_label = None;
843        // The target too — same reason `end_composite` clears it: a target left
844        // behind refuses every later group on a different stack.
845        self.composite_stack_id = None;
846        self.last_pushed_seq = None;
847        let ids: Vec<u64> = self.stacks.keys().copied().collect();
848        for id in ids {
849            self.emit(UndoRedoEvent::StackChanged, id);
850        }
851    }
852
853    /// Creates a new undo/redo stack and returns its ID.
854    pub fn create_new_stack(&mut self) -> u64 {
855        let id = self.next_stack_id;
856        self.stacks.insert(id, StackData::default());
857        self.next_stack_id += 1;
858        id
859    }
860
861    /// Deletes an undo/redo stack by its ID.
862    ///
863    /// The default stack (ID 0) cannot be deleted.
864    pub fn delete_stack(&mut self, stack_id: u64) -> Result<()> {
865        if stack_id == 0 {
866            return Err(anyhow!("Cannot delete the default stack"));
867        }
868        if self.stacks.remove(&stack_id).is_some() {
869            Ok(())
870        } else {
871            Err(anyhow!("Stack with ID {} does not exist", stack_id))
872        }
873    }
874
875    /// Gets the size of the undo stack for a specific stack.
876    pub fn get_stack_size(&self, stack_id: u64) -> usize {
877        self.stacks
878            .get(&stack_id)
879            .map(|s| s.undo_stack.len())
880            .unwrap_or(0)
881    }
882
883    /// Gets the size of the redo stack for a specific stack.
884    pub fn get_redo_stack_size(&self, stack_id: u64) -> usize {
885        self.stacks
886            .get(&stack_id)
887            .map(|s| s.redo_stack.len())
888            .unwrap_or(0)
889    }
890
891    /// The sequence number of the entry the most recent push landed in.
892    ///
893    /// Read it immediately after the call that pushed — it is how a caller
894    /// learns the number to hand to [`undo_if_head`](Self::undo_if_head) later,
895    /// and every later push overwrites it. `None` after a push that recorded
896    /// nothing (an untracked stack, or a command folded into an open
897    /// composite).
898    pub fn last_pushed_seq(&self) -> Option<u64> {
899        self.last_pushed_seq
900    }
901
902    /// How many commands have been recorded on a stack: pushed as an entry, merged into
903    /// its head, or added to a group opened on it. Zero for a missing stack.
904    ///
905    /// For a caller to tell whether a call recorded anything: a group's
906    /// [`last_pushed_seq`](Self::last_pushed_seq) is `None` until it ends, and a merge
907    /// keeps the head's sequence, so neither says it. An undo, a redo and the push of a
908    /// group that ends record no command and leave it as it is. A
909    /// [`cancel_composite`](Self::cancel_composite) takes back the commands it drops, so
910    /// a call whose group was cancelled leaves it as it found it: it recorded nothing.
911    pub fn commands_recorded(&self, stack_id: Option<u64>) -> u64 {
912        self.stacks
913            .get(&stack_id.unwrap_or(0))
914            .map_or(0, |s| s.commands_recorded)
915    }
916
917    /// The sequence number now on top of a stack, if any.
918    pub fn head_seq(&self, stack_id: Option<u64>) -> Option<u64> {
919        self.stacks
920            .get(&stack_id.unwrap_or(0))?
921            .undo_stack
922            .last()
923            .map(|e| e.seq)
924    }
925
926    /// What the next undo on this stack would take back, as a machine key for
927    /// the application to translate. `None` when the stack is empty or the
928    /// command declined to name itself.
929    pub fn undo_label(&self, stack_id: Option<u64>) -> Option<UndoLabel> {
930        self.stacks
931            .get(&stack_id.unwrap_or(0))?
932            .undo_stack
933            .last()?
934            .command
935            .label()
936    }
937
938    /// What the next redo on this stack would re-apply. See [`undo_label`](Self::undo_label).
939    pub fn redo_label(&self, stack_id: Option<u64>) -> Option<UndoLabel> {
940        self.stacks
941            .get(&stack_id.unwrap_or(0))?
942            .redo_stack
943            .last()?
944            .command
945            .label()
946    }
947
948    /// Close the top entry to merging, so the next command starts a new one.
949    ///
950    /// Merging exists so a burst of typing is one undo step. It decides purely
951    /// on the *shape* of two commands — adjacent, close in time, same kind —
952    /// and cannot see that something unrelated happened in between. So type,
953    /// rename a chapter from another panel, type again, and the two bursts merge
954    /// **across** the rename: one undo then takes back text entered before an
955    /// event the writer remembers as a dividing line.
956    ///
957    /// A caller that knows such a line was crossed says so here. Idempotent, and
958    /// a no-op on an empty or missing stack.
959    pub fn seal_head(&mut self, stack_id: Option<u64>) {
960        if let Some(stack) = self.stacks.get_mut(&stack_id.unwrap_or(0))
961            && let Some(last) = stack.undo_stack.last_mut()
962        {
963            last.sealed = true;
964        }
965    }
966
967    /// Bound how many entries a stack keeps, dropping the oldest past the
968    /// limit. `None` (the default) is unbounded.
969    ///
970    /// Unbounded is right for a document that lives as long as its window and
971    /// wrong for a session measured in hours: every entry may pin a snapshot of
972    /// the store, so an uncapped stack has no ceiling at all. Applied on the
973    /// next push, not retroactively.
974    pub fn set_undo_limit(&mut self, limit: Option<usize>) {
975        self.undo_limit = limit;
976    }
977
978    /// The current entry limit, if one is set.
979    pub fn undo_limit(&self) -> Option<usize> {
980        self.undo_limit
981    }
982}