text-document-common 1.12.1

Shared entities, database, events, and undo/redo infrastructure for text-document
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
// Generated by Qleany v1.10.0 from undo_redo.tera
use crate::event::{Event, EventHub, Origin, UndoRedoEvent};
use crate::types::EntityId;
use anyhow::{Result, anyhow};
use std::any::Any;
use std::collections::HashMap;
use std::fmt;
use std::sync::Arc;

/// The stack id that means **do not record this**.
///
/// Some writes must happen and must not appear in the user's history: a buffer
/// mirrored to the store on a timer, a cache line, an index rebuilt on open.
/// The generated commands always push — `stack_id: None` resolves to the global
/// stack `0` rather than opting out — so before this const the only way to keep
/// such a write out of the history was to push it somewhere and clear that
/// somewhere afterwards, which nobody remembers to do. Passing this id instead
/// drops the command at the door: nothing is stored, so there is nothing to
/// clear, and stack `0` stays empty.
///
/// `create_new_stack` counts up from 1, so this value can never collide with a
/// real stack.
pub const UNTRACKED_STACK_ID: u64 = u64::MAX;

/// A stable, machine-readable name for what a command did.
///
/// Deliberately **not** a localized string. This crate is generated and knows
/// nothing about locales or about the application's translation catalogue, so
/// it hands back a key — `("binder_item", "remove")` — and the application
/// turns that into *"Undo deleting a scene"* in the reader's language.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct UndoLabel {
    /// What was acted on: an entity name, or a feature use case's own name.
    pub subject: &'static str,
    /// What was done to it — `"create"`, `"update"`, `"remove"`, … Empty when
    /// `subject` already names the whole act (a feature use case such as
    /// `"trash_binder_items"` is not an *action on* something else).
    pub action: &'static str,
}

impl UndoLabel {
    pub const fn new(subject: &'static str, action: &'static str) -> Self {
        Self { subject, action }
    }

    /// A whole-act label, for a command whose `subject` is the act itself.
    pub const fn act(subject: &'static str) -> Self {
        Self {
            subject,
            action: "",
        }
    }
}

/// What [`UndoRedoManager::undo_if_head`] actually did.
///
/// The reason this exists: a "take that back" affordance offered *for one
/// operation* — the Undo button on a toast — cannot use plain `undo()`, which
/// pops whatever is on top. Anything pushed in the meantime (an autosave, a
/// second window, a background job) silently becomes the thing that gets undone
/// instead. Naming the operation and being told it is no longer the head is the
/// difference between a correct affordance and a data-loss bug.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum UndoStatus {
    /// The named command was on top, and has been undone.
    Undone,
    /// Something else has been pushed since; nothing was undone.
    Superseded,
    /// The stack is empty; nothing was undone.
    Empty,
}

/// Trait for commands that can be undone and redone.
///
/// Implementors can optionally support command merging by overriding the
/// `can_merge` and `merge` methods. This allows the UndoRedoManager to combine
/// multiple commands of the same type into a single command, which is useful for
/// operations like continuous typing or dragging.
pub trait UndoRedoCommand: Send {
    /// Undoes the command, reverting its effects
    fn undo(&mut self) -> Result<()>;

    /// Redoes the command, reapplying its effects
    fn redo(&mut self) -> Result<()>;

    /// Returns true if this command can be merged with the other command.
    ///
    /// By default, commands cannot be merged. Override this method to enable
    /// merging for specific command types.
    ///
    /// # Example
    /// ```test
    /// fn can_merge(&self, other: &dyn UndoRedoCommand) -> bool {
    ///     // Check if the other command is of the same type
    ///     if let Some(_) = other.as_any().downcast_ref::<Self>() {
    ///         return true;
    ///     }
    ///     false
    /// }
    /// ```
    fn can_merge(&self, _other: &dyn UndoRedoCommand) -> bool {
        false
    }

    /// Merges this command with the other command.
    /// Returns true if the merge was successful.
    ///
    /// This method is called only if `can_merge` returns true.
    ///
    /// # Example
    /// ```test
    /// use common::undo_redo::UndoRedoCommand;
    ///
    /// fn merge(&mut self, other: &dyn UndoRedoCommand) -> bool {
    ///     if let Some(other_cmd) = other.as_any().downcast_ref::<Self>() {
    ///         // Merge the commands
    ///         self.value += other_cmd.value;
    ///         return true;
    ///     }
    ///     false
    /// }
    /// ```
    fn merge(&mut self, _other: &dyn UndoRedoCommand) -> bool {
        false
    }

    /// Returns the type ID of this command for type checking.
    ///
    /// This is used for downcasting in the `can_merge` and `merge` methods.
    ///
    /// # Example
    /// ```test
    /// fn as_any(&self) -> &dyn Any {
    ///     self
    /// }
    /// ```
    fn as_any(&self) -> &dyn Any;

    /// A stable, machine-readable name for what this command did, for a menu
    /// that says *"Undo rename"* rather than a bare *"Undo"*.
    ///
    /// Defaulted to `None` so an existing implementor compiles unchanged; a
    /// command that returns `None` simply leaves the row generic.
    fn label(&self) -> Option<UndoLabel> {
        None
    }
}

/// A composite command that groups multiple commands as one.
///
/// This allows treating a sequence of commands as a single unit for undo/redo operations.
/// When a composite command is undone or redone, all its contained commands are undone
/// or redone in the appropriate order.
///
/// # Example
/// ```test
/// use common::undo_redo::CompositeCommand;
/// let mut composite = CompositeCommand::new();
/// composite.add_command(Box::new(Command1::new()));
/// composite.add_command(Box::new(Command2::new()));
/// // Now composite can be treated as a single command
/// ```
pub struct CompositeCommand {
    label: Option<UndoLabel>,
    commands: Vec<Box<dyn UndoRedoCommand>>,
    pub stack_id: u64,
}

impl fmt::Debug for CompositeCommand {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("CompositeCommand")
            .field("commands_len", &self.commands.len())
            .field("stack_id", &self.stack_id)
            .finish()
    }
}

impl CompositeCommand {
    /// Creates a new empty composite command.
    pub fn new(stack_id: Option<u64>) -> Self {
        Self::labeled(stack_id, None)
    }

    /// A composite that names itself.
    ///
    /// A group's constituent labels are the wrong answer for a menu — a
    /// three-entity capture would read *"Undo update"* after the least
    /// interesting of its parts. The caller who opened the group is the only
    /// one who knows what the group *was*, so it says so here.
    pub fn labeled(stack_id: Option<u64>, label: Option<UndoLabel>) -> Self {
        CompositeCommand {
            label,
            commands: Vec::new(),
            stack_id: stack_id.unwrap_or(0),
        }
    }

    /// Adds a command to this composite.
    ///
    /// Commands are executed, undone, and redone in the order they are added.
    pub fn add_command(&mut self, command: Box<dyn UndoRedoCommand>) {
        self.commands.push(command);
    }

    /// Returns true if this composite contains no commands.
    pub fn is_empty(&self) -> bool {
        self.commands.is_empty()
    }

    /// Name this group after the fact — for a caller that only learns what the
    /// group was once its parts have run.
    pub fn set_label(&mut self, label: Option<UndoLabel>) {
        self.label = label;
    }
}

impl UndoRedoCommand for CompositeCommand {
    fn undo(&mut self) -> Result<()> {
        // Undo commands in reverse order
        for command in self.commands.iter_mut().rev() {
            command.undo()?;
        }
        Ok(())
    }

    fn redo(&mut self) -> Result<()> {
        // Redo commands in original order
        for command in self.commands.iter_mut() {
            command.redo()?;
        }
        Ok(())
    }

    fn as_any(&self) -> &dyn Any {
        self
    }

    /// The group's own name, never a constituent's — see [`CompositeCommand::labeled`].
    fn label(&self) -> Option<UndoLabel> {
        self.label
    }
}
/// Trait for commands that can be executed asynchronously with progress tracking and cancellation.
///
/// This trait extends the basic UndoRedoCommand trait with asynchronous capabilities.
/// Implementors must also implement the UndoRedoCommand trait to ensure compatibility
/// with the existing undo/redo system.
pub trait AsyncUndoRedoCommand: UndoRedoCommand {
    /// Starts the undo operation asynchronously and returns immediately.
    /// Returns Ok(()) if the operation was successfully started.
    fn start_undo(&mut self) -> Result<()>;

    /// Starts the redo operation asynchronously and returns immediately.
    /// Returns Ok(()) if the operation was successfully started.
    fn start_redo(&mut self) -> Result<()>;

    /// Checks the progress of the current operation.
    /// Returns a value between 0.0 (not started) and 1.0 (completed).
    fn check_progress(&self) -> f32;

    /// Attempts to cancel the in-progress operation.
    /// Returns Ok(()) if cancellation was successful or if no operation is in progress.
    fn cancel(&mut self) -> Result<()>;

    /// Checks if the current operation is complete.
    /// Returns true if the operation has finished successfully.
    fn is_complete(&self) -> bool;
}

/// One step of history, and the number that names it.
///
/// The sequence is what lets a caller say *"undo the thing I just did"* rather
/// than *"undo whatever is on top"* — see [`UndoStatus`]. It is minted once, at
/// the push, and travels with the command across the undo/redo boundary, so an
/// entry keeps its identity however many times it is stepped over.
struct UndoEntry {
    command: Box<dyn UndoRedoCommand>,
    seq: u64,
    /// Closed to merging — see [`UndoRedoManager::seal_head`].
    sealed: bool,
}

#[derive(Default)]
struct StackData {
    undo_stack: Vec<UndoEntry>,
    redo_stack: Vec<UndoEntry>,
}

impl fmt::Debug for StackData {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("StackData")
            .field("undo_len", &self.undo_stack.len())
            .field("redo_len", &self.redo_stack.len())
            .finish()
    }
}

/// Manager for undo and redo operations.
///
/// The UndoRedoManager maintains multiple stacks of commands:
/// - Each stack has an undo stack for commands that can be undone
/// - Each stack has a redo stack for commands that have been undone and can be redone
///
/// It also supports:
/// - Grouping multiple commands as a single unit using begin_composite/end_composite
/// - Merging commands of the same type when appropriate
/// - Switching between different stacks
#[derive(Debug)]
pub struct UndoRedoManager {
    stacks: HashMap<u64, StackData>,
    next_stack_id: u64,
    in_progress_composite: Option<CompositeCommand>,
    composite_nesting_level: usize,
    composite_stack_id: Option<u64>,
    composite_label: Option<UndoLabel>,
    event_hub: Option<Arc<EventHub>>,
    /// Monotonic across every stack, so a sequence number is unique in the
    /// process and a caller never has to say *which* stack it means.
    next_seq: u64,
    /// The sequence of the entry the most recent push landed in — a fresh one,
    /// or the one it merged into. Read it straight after the call that pushed;
    /// it is how a caller learns the number to hand back to
    /// [`undo_if_head`](UndoRedoManager::undo_if_head) later.
    last_pushed_seq: Option<u64>,
    /// How many entries a stack may hold before the oldest are dropped.
    /// `None` — the default — is unbounded, which is what a short-lived
    /// document wants and what a day-long editing session does not.
    undo_limit: Option<usize>,
}

impl Default for UndoRedoManager {
    fn default() -> Self {
        Self::new()
    }
}

impl UndoRedoManager {
    /// Creates a new empty UndoRedoManager with one default stack (ID 0).
    pub fn new() -> Self {
        let mut stacks = HashMap::new();
        stacks.insert(0, StackData::default());
        UndoRedoManager {
            stacks,
            next_stack_id: 1,
            in_progress_composite: None,
            composite_nesting_level: 0,
            composite_stack_id: None,
            composite_label: None,
            event_hub: None,
            next_seq: 1,
            last_pushed_seq: None,
            undo_limit: None,
        }
    }

    /// Emit one undo/redo event, naming the stack it happened on.
    ///
    /// The stack id travels in `data` because `ids` means *entity* ids, and a
    /// process holding one stack per open document needs to tell whose history
    /// moved — without it every subscriber has to re-poll every stack it knows.
    fn emit(&self, event: UndoRedoEvent, stack_id: u64) {
        if let Some(event_hub) = &self.event_hub {
            event_hub.send_event(Event {
                origin: Origin::UndoRedo(event),
                ids: Vec::<EntityId>::new(),
                data: Some(stack_id.to_string()),
            });
        }
    }

    /// Inject the event hub to allow sending undo/redo related events
    pub fn set_event_hub(&mut self, event_hub: &Arc<EventHub>) {
        self.event_hub = Some(Arc::clone(event_hub));
    }

    /// Undoes the most recent command on the specified stack.
    /// If `stack_id` is None, the global stack (ID 0) is used.
    ///
    /// The undone command is moved to the redo stack.
    /// Returns Ok(()) if successful or if there are no commands to undo.
    pub fn undo(&mut self, stack_id: Option<u64>) -> Result<()> {
        let target_stack_id = stack_id.unwrap_or(0);
        let stack = self
            .stacks
            .get_mut(&target_stack_id)
            .ok_or_else(|| anyhow!("Stack with ID {} not found", target_stack_id))?;

        let stepped = if let Some(mut entry) = stack.undo_stack.pop() {
            if let Err(e) = entry.command.undo() {
                log::error!("Undo failed, re-pushing command to undo stack: {e}");
                stack.undo_stack.push(entry);
                return Err(e);
            }
            stack.redo_stack.push(entry);
            true
        } else {
            false
        };
        if stepped {
            self.emit(UndoRedoEvent::Undone, target_stack_id);
        }
        Ok(())
    }

    /// Redoes the most recently undone command on the specified stack.
    /// If `stack_id` is None, the global stack (ID 0) is used.
    ///
    /// The redone command is moved back to the undo stack.
    /// Returns Ok(()) if successful or if there are no commands to redo.
    pub fn redo(&mut self, stack_id: Option<u64>) -> Result<()> {
        let target_stack_id = stack_id.unwrap_or(0);
        let stack = self
            .stacks
            .get_mut(&target_stack_id)
            .ok_or_else(|| anyhow!("Stack with ID {} not found", target_stack_id))?;

        let stepped = if let Some(mut entry) = stack.redo_stack.pop() {
            if let Err(e) = entry.command.redo() {
                log::error!("Redo failed, re-pushing command to redo stack: {e}");
                stack.redo_stack.push(entry);
                return Err(e);
            }
            stack.undo_stack.push(entry);
            true
        } else {
            false
        };
        if stepped {
            self.emit(UndoRedoEvent::Redone, target_stack_id);
        }
        Ok(())
    }

    /// Undo **only if** `seq` still names the top of the stack.
    ///
    /// The affordance this exists for is a toast's Undo button: it is offered
    /// for one specific operation, and between the offer and the click anything
    /// may have pushed — an autosave, a second window, a background job. Plain
    /// `undo()` would take back that later thing instead, silently and with the
    /// user believing they undid what the toast named. Naming the operation
    /// turns a wrong action into an honest [`UndoStatus::Superseded`].
    pub fn undo_if_head(&mut self, stack_id: Option<u64>, seq: u64) -> Result<UndoStatus> {
        let target_stack_id = stack_id.unwrap_or(0);
        let stack = self
            .stacks
            .get(&target_stack_id)
            .ok_or_else(|| anyhow!("Stack with ID {} not found", target_stack_id))?;

        match stack.undo_stack.last() {
            None => Ok(UndoStatus::Empty),
            Some(entry) if entry.seq != seq => Ok(UndoStatus::Superseded),
            Some(_) => {
                self.undo(stack_id)?;
                Ok(UndoStatus::Undone)
            }
        }
    }

    /// Begins a composite command group.
    ///
    /// All commands added between begin_composite and end_composite will be treated as a single command.
    /// This is useful for operations that logically represent a single action but require multiple
    /// commands to implement.
    ///
    /// # Example
    /// ```test
    /// let mut manager = UndoRedoManager::new();
    /// manager.begin_composite();
    /// manager.add_command(Box::new(Command1::new()));
    /// manager.add_command(Box::new(Command2::new()));
    /// manager.end_composite();
    /// // Now undo() will undo both commands as a single unit
    /// ```
    pub fn begin_composite(&mut self, stack_id: Option<u64>) -> Result<()> {
        self.begin_composite_labeled(stack_id, None)
    }

    /// [`begin_composite`](Self::begin_composite), naming what the group is.
    ///
    /// Worth the extra call: a group's constituent labels describe its parts,
    /// so a menu built from them reads *"Undo update"* for what the writer
    /// experienced as *"add a character to the story bible"*. Only the caller
    /// that opened the group knows the answer.
    pub fn begin_composite_labeled(
        &mut self,
        stack_id: Option<u64>,
        label: Option<UndoLabel>,
    ) -> Result<()> {
        if stack_id == Some(UNTRACKED_STACK_ID) {
            return Err(anyhow!(
                "Cannot open a composite on the untracked stack: its commands are \
                 dropped, so the group could never be undone"
            ));
        }
        if self.composite_stack_id.is_some() && self.composite_stack_id != stack_id {
            return Err(anyhow!(
                "Cannot begin a composite on a different stack while another composite is in progress"
            ));
        }

        // Set the target stack ID for this composite
        self.composite_stack_id = stack_id;

        // Increment the nesting level
        self.composite_nesting_level += 1;

        // If there's no composite in progress, create one. A nested
        // `begin_composite_labeled` may name a group its opener left anonymous,
        // but never rename one that already has a name: the outermost caller
        // owns the description.
        if self.in_progress_composite.is_none() {
            self.in_progress_composite = Some(CompositeCommand::labeled(stack_id, label));
            self.composite_label = label;
        } else if self.composite_label.is_none() {
            self.composite_label = label;
        }

        self.emit(UndoRedoEvent::BeginComposite, stack_id.unwrap_or(0));
        Ok(())
    }

    /// Ends the current composite command group and adds it to the specified undo stack.
    ///
    /// If no commands were added to the composite, nothing is added to the undo stack.
    /// If this is a nested composite, only the outermost composite is added to the undo stack.
    pub fn end_composite(&mut self) {
        // Decrement the nesting level
        if self.composite_nesting_level > 0 {
            self.composite_nesting_level -= 1;
        }

        // Only end the composite if we're at the outermost level
        if self.composite_nesting_level == 0 {
            if let Some(composite) = self.in_progress_composite.take()
                && !composite.is_empty()
            {
                let target_stack_id = self.composite_stack_id.unwrap_or(0);
                // A missing stack is a caller bug (the stack was dropped
                // while a composite was open on it), but `end_composite`
                // returns `()` and is called from a dozen fire-and-forget
                // UI sites, so it cannot report one. It used to
                // `.expect("Stack must exist")` — which killed the whole
                // process, mid-edit, over a lost undo entry.
                //
                // Same shape as `database::write_guard`'s `acquire`: loud in
                // a debug build so the bug is caught in development, and a
                // degradation in a shipped one — the grouped commands stay
                // applied, they just aren't undoable as a unit.
                if self.stacks.contains_key(&target_stack_id) {
                    let mut composite = composite;
                    composite.set_label(self.composite_label);
                    self.push_entry(target_stack_id, Box::new(composite));
                } else {
                    // Nothing was recorded, so nothing may be named: leaving
                    // the register alone would hand the next
                    // `last_pushed_seq` reader an earlier entry that is
                    // still the head.
                    self.last_pushed_seq = None;
                    debug_assert!(
                        false,
                        "end_composite: undo stack {} does not exist — a composite was \
                             opened on a stack that has since been removed",
                        target_stack_id
                    );
                }
            } else {
                // An empty group records nothing either — same reasoning.
                self.last_pushed_seq = None;
            }
            let ended_on = self.composite_stack_id.unwrap_or(0);
            self.composite_label = None;
            // Clear the target too, not just the label. `begin_composite`
            // refuses a stack that differs from the one already open, so a
            // target left set after the group closed locks every *other* stack
            // out of compositing for the life of the manager — in a process
            // holding one stack per open document, the first document to group
            // anything would be the only one that ever could again.
            // `cancel_composite` has always cleared it; this path forgot.
            self.composite_stack_id = None;
            self.emit(UndoRedoEvent::EndComposite, ended_on);
        }
    }

    pub fn cancel_composite(&mut self) {
        // Decrement the nesting level
        if self.composite_nesting_level > 0 {
            self.composite_nesting_level -= 1;
        }

        // Undo any sub-commands that were already executed in this composite
        if let Some(ref mut composite) = self.in_progress_composite {
            let _ = composite.undo();
        }

        let cancelled_on = self.composite_stack_id.unwrap_or(0);
        self.in_progress_composite = None;
        self.composite_stack_id = None;
        self.composite_label = None;
        // A cancelled group is not history: same reasoning as the record-nothing
        // paths of `end_composite`.
        self.last_pushed_seq = None;

        self.emit(UndoRedoEvent::CancelComposite, cancelled_on);
    }

    /// Adds a command to the global undo stack (ID 0).
    pub fn add_command(&mut self, command: Box<dyn UndoRedoCommand>) {
        let _ = self.add_command_to_stack(command, None);
    }

    /// Adds a command to the specified undo stack.
    /// If `stack_id` is None, the global stack (ID 0) is used.
    ///
    /// This method handles several cases:
    /// 1. If a composite command is in progress, the command is added to the composite
    /// 2. If the command can be merged with the last command on the specified undo stack, they are merged
    /// 3. Otherwise, the command is added to the specified undo stack as a new entry
    ///
    /// In all cases, the redo stack of the stack is cleared when a new command is added.
    pub fn add_command_to_stack(
        &mut self,
        command: Box<dyn UndoRedoCommand>,
        stack_id: Option<u64>,
    ) -> Result<()> {
        // Checked before the composite branch, not after: an untracked write is
        // untracked whatever else is open. Folding one into a group would make
        // the group undo something the caller explicitly said was not history.
        if stack_id == Some(UNTRACKED_STACK_ID) {
            self.last_pushed_seq = None;
            return Ok(());
        }

        // If we have a composite in progress, add the command to it
        if let Some(composite) = &mut self.in_progress_composite {
            // ensure that the stack_id is the same as the composite's stack
            if composite.stack_id != stack_id.unwrap_or(0) {
                return Err(anyhow!(
                    "Cannot add command to composite with different stack ID"
                ));
            }
            composite.add_command(command);
            // The history did not grow: the group is still open, and it is the
            // group — not this command — that will get a sequence. Clearing the
            // register is what stops a caller reading `last_pushed_seq` here and
            // being handed the number of some *earlier*, unrelated entry, which
            // is still the head and which `undo_if_head` would therefore
            // cheerfully undo. See `last_pushed_seq`'s own contract.
            self.last_pushed_seq = None;
            return Ok(());
        }

        let target_stack_id = stack_id.unwrap_or(0);
        let stack = self
            .stacks
            .get_mut(&target_stack_id)
            .ok_or_else(|| anyhow!("Stack with ID {} does not exist", target_stack_id))?;

        // Try to merge with the last command if possible
        if let Some(last) = stack.undo_stack.last_mut()
            && !last.sealed
            && last.command.can_merge(&*command)
            && last.command.merge(&*command)
        {
            // Merged: the history did not grow, so the entry keeps the sequence
            // it already had. A caller that pushed and then read
            // `last_pushed_seq` gets the entry its command actually landed in,
            // which for a burst of coalesced typing is the burst.
            let seq = last.seq;
            stack.redo_stack.clear();
            self.last_pushed_seq = Some(seq);
            self.emit(UndoRedoEvent::StackChanged, target_stack_id);
            return Ok(());
        }

        // If we couldn't merge, just add the command normally.
        self.push_entry(target_stack_id, command);
        Ok(())
    }

    /// Push one command as a fresh entry: mint its sequence, clear the redo
    /// branch, trim the stack to [`undo_limit`](Self::set_undo_limit), and
    /// announce it. The single place history grows.
    fn push_entry(&mut self, target_stack_id: u64, command: Box<dyn UndoRedoCommand>) {
        let seq = self.next_seq;
        self.next_seq = self.next_seq.wrapping_add(1);
        let limit = self.undo_limit;

        let Some(stack) = self.stacks.get_mut(&target_stack_id) else {
            // No stack, no entry — so no sequence to hand out and no change to
            // announce. Reporting one anyway would name an entry that was never
            // stored.
            self.last_pushed_seq = None;
            return;
        };
        stack.undo_stack.push(UndoEntry {
            command,
            seq,
            sealed: false,
        });
        stack.redo_stack.clear();
        if let Some(limit) = limit
            && stack.undo_stack.len() > limit
        {
            // Oldest first: the far end of a long session is the part
            // nobody reaches for, and every entry may be pinning a
            // snapshot of the store.
            let excess = stack.undo_stack.len() - limit;
            stack.undo_stack.drain(0..excess);
        }

        self.last_pushed_seq = Some(seq);
        self.emit(UndoRedoEvent::StackChanged, target_stack_id);
    }

    /// Returns true if there are commands that can be undone on the specified stack.
    /// If `stack_id` is None, the global stack (ID 0) is used.
    pub fn can_undo(&self, stack_id: Option<u64>) -> bool {
        let target_stack_id = stack_id.unwrap_or(0);
        self.stacks
            .get(&target_stack_id)
            .map(|s| !s.undo_stack.is_empty())
            .unwrap_or(false)
    }

    /// Returns true if there are commands that can be redone on the specified stack.
    /// If `stack_id` is None, the global stack (ID 0) is used.
    pub fn can_redo(&self, stack_id: Option<u64>) -> bool {
        let target_stack_id = stack_id.unwrap_or(0);
        self.stacks
            .get(&target_stack_id)
            .map(|s| !s.redo_stack.is_empty())
            .unwrap_or(false)
    }

    /// Clears the undo and redo history for a specific stack.
    ///
    /// This method removes all commands from both the undo and redo stacks of the specified stack.
    pub fn clear_stack(&mut self, stack_id: u64) {
        let cleared = if let Some(stack) = self.stacks.get_mut(&stack_id) {
            stack.undo_stack.clear();
            stack.redo_stack.clear();
            true
        } else {
            false
        };
        if cleared {
            self.emit(UndoRedoEvent::StackChanged, stack_id);
        }
    }

    /// Clears all undo and redo history from all stacks.
    pub fn clear_all_stacks(&mut self) {
        for stack in self.stacks.values_mut() {
            stack.undo_stack.clear();
            stack.redo_stack.clear();
        }
        self.in_progress_composite = None;
        self.composite_nesting_level = 0;
        self.composite_label = None;
        // The target too — same reason `end_composite` clears it: a target left
        // behind refuses every later group on a different stack.
        self.composite_stack_id = None;
        self.last_pushed_seq = None;
        let ids: Vec<u64> = self.stacks.keys().copied().collect();
        for id in ids {
            self.emit(UndoRedoEvent::StackChanged, id);
        }
    }

    /// Creates a new undo/redo stack and returns its ID.
    pub fn create_new_stack(&mut self) -> u64 {
        let id = self.next_stack_id;
        self.stacks.insert(id, StackData::default());
        self.next_stack_id += 1;
        id
    }

    /// Deletes an undo/redo stack by its ID.
    ///
    /// The default stack (ID 0) cannot be deleted.
    pub fn delete_stack(&mut self, stack_id: u64) -> Result<()> {
        if stack_id == 0 {
            return Err(anyhow!("Cannot delete the default stack"));
        }
        if self.stacks.remove(&stack_id).is_some() {
            Ok(())
        } else {
            Err(anyhow!("Stack with ID {} does not exist", stack_id))
        }
    }

    /// Gets the size of the undo stack for a specific stack.
    pub fn get_stack_size(&self, stack_id: u64) -> usize {
        self.stacks
            .get(&stack_id)
            .map(|s| s.undo_stack.len())
            .unwrap_or(0)
    }

    /// Gets the size of the redo stack for a specific stack.
    pub fn get_redo_stack_size(&self, stack_id: u64) -> usize {
        self.stacks
            .get(&stack_id)
            .map(|s| s.redo_stack.len())
            .unwrap_or(0)
    }

    /// The sequence number of the entry the most recent push landed in.
    ///
    /// Read it immediately after the call that pushed — it is how a caller
    /// learns the number to hand to [`undo_if_head`](Self::undo_if_head) later,
    /// and every later push overwrites it. `None` after a push that recorded
    /// nothing (an untracked stack, or a command folded into an open
    /// composite).
    pub fn last_pushed_seq(&self) -> Option<u64> {
        self.last_pushed_seq
    }

    /// The sequence number now on top of a stack, if any.
    pub fn head_seq(&self, stack_id: Option<u64>) -> Option<u64> {
        self.stacks
            .get(&stack_id.unwrap_or(0))?
            .undo_stack
            .last()
            .map(|e| e.seq)
    }

    /// What the next undo on this stack would take back, as a machine key for
    /// the application to translate. `None` when the stack is empty or the
    /// command declined to name itself.
    pub fn undo_label(&self, stack_id: Option<u64>) -> Option<UndoLabel> {
        self.stacks
            .get(&stack_id.unwrap_or(0))?
            .undo_stack
            .last()?
            .command
            .label()
    }

    /// What the next redo on this stack would re-apply. See [`undo_label`](Self::undo_label).
    pub fn redo_label(&self, stack_id: Option<u64>) -> Option<UndoLabel> {
        self.stacks
            .get(&stack_id.unwrap_or(0))?
            .redo_stack
            .last()?
            .command
            .label()
    }

    /// Close the top entry to merging, so the next command starts a new one.
    ///
    /// Merging exists so a burst of typing is one undo step. It decides purely
    /// on the *shape* of two commands — adjacent, close in time, same kind —
    /// and cannot see that something unrelated happened in between. So type,
    /// rename a chapter from another panel, type again, and the two bursts merge
    /// **across** the rename: one undo then takes back text entered before an
    /// event the writer remembers as a dividing line.
    ///
    /// A caller that knows such a line was crossed says so here. Idempotent, and
    /// a no-op on an empty or missing stack.
    pub fn seal_head(&mut self, stack_id: Option<u64>) {
        if let Some(stack) = self.stacks.get_mut(&stack_id.unwrap_or(0))
            && let Some(last) = stack.undo_stack.last_mut()
        {
            last.sealed = true;
        }
    }

    /// Bound how many entries a stack keeps, dropping the oldest past the
    /// limit. `None` (the default) is unbounded.
    ///
    /// Unbounded is right for a document that lives as long as its window and
    /// wrong for a session measured in hours: every entry may pin a snapshot of
    /// the store, so an uncapped stack has no ceiling at all. Applied on the
    /// next push, not retroactively.
    pub fn set_undo_limit(&mut self, limit: Option<usize>) {
        self.undo_limit = limit;
    }

    /// The current entry limit, if one is set.
    pub fn undo_limit(&self) -> Option<usize> {
        self.undo_limit
    }
}