forge
Explore
Log in

Don't you dare go Hollow

project_note

Clone
★ 0

0 watching0 forksRust3.6 MiBc49f5e7Tahinli1 month ago2 commits

undo.rs1243 lines, 46.0 KiBHistoryRawDownload
1use std::{cell::RefCell, collections::VecDeque, sync::Arc};
2
3use crate::sync::{AtomicU64, Mutex};
4use either::Either;
5use loro_common::{
6 ContainerID, Counter, CounterSpan, HasIdSpan, IdSpan, LoroError, LoroResult, LoroValue, PeerID,
7};
8use parking_lot::lock_api::ReentrantMutex;
9use rustc_hash::{FxHashMap, FxHashSet};
10use tracing::{debug_span, info_span, instrument};
11
12use crate::{
13 change::{get_sys_timestamp, Timestamp},
14 cursor::{AbsolutePosition, Cursor},
15 delta::TreeExternalDiff,
16 event::{Diff, EventTriggerKind, KeptChange},
17 version::Frontiers,
18 ContainerDiff, DiffEvent, DocDiff, LoroDoc, Subscription,
19};
20
21#[cfg(test)]
22mod atomicity_tests;
23pub(crate) mod movable_list;
24
25/// A batch of diffs.
26///
27/// You can use `loroDoc.apply_diff(diff)` to apply the diff to the document.
28#[derive(Debug, Clone, Default)]
29pub struct DiffBatch {
30 pub cid_to_events: FxHashMap<ContainerID, Diff>,
31 pub order: Vec<ContainerID>,
32 /// Set on batches from [`LoroDoc::diff`]: a mergeable child the batch re-activates carries
33 /// its full state (no entry means empty), which `apply_diff` aligns with whatever hidden
34 /// state the target doc keeps at that deterministic cid. Unset batches (local events,
35 /// hand-built ones) are applied incrementally, as a doc that shares the source's hidden
36 /// state needs. Local events must stay unset: a plain re-ensure has no child entry because
37 /// the child is unchanged, which a full-state batch would read as "empty". Import and
38 /// checkout events do carry full states for revived children, so they may be set. See
39 /// context/mergeable-containers.md.
40 pub full_state: bool,
41}
42
43impl DiffBatch {
44 pub fn new(diff: Vec<DocDiff>) -> Self {
45 let mut map: FxHashMap<ContainerID, Diff> = Default::default();
46 let mut order: Vec<ContainerID> = Vec::with_capacity(diff.len());
47 for d in diff.into_iter() {
48 for item in d.diff.into_iter() {
49 let old = map.insert(item.id.clone(), item.diff);
50 assert!(old.is_none(), "Duplicate container ID in diff events");
51 order.push(item.id.clone());
52 }
53 }
54
55 Self {
56 cid_to_events: map,
57 order,
58 full_state: false,
59 }
60 }
61
62 /// Like [`DiffBatch::new`], but a container that kept its state while its event reports a
63 /// full-state revival contributes its actual change. Use it for a batch applied to the doc
64 /// it was computed on (revert, undo). See [`crate::event::KeptChange`].
65 pub(crate) fn from_changes(diff: Vec<DocDiff>) -> Self {
66 let mut map: FxHashMap<ContainerID, Diff> = Default::default();
67 let mut order: Vec<ContainerID> = Vec::with_capacity(diff.len());
68 for d in diff.into_iter() {
69 for item in d.diff.into_iter() {
70 let change = match item.kept {
71 None => item.diff,
72 Some(KeptChange::Unchanged) => continue,
73 Some(KeptChange::Changed(change)) => change,
74 };
75 let old = map.insert(item.id.clone(), change);
76 assert!(old.is_none(), "Duplicate container ID in diff events");
77 order.push(item.id);
78 }
79 }
80
81 Self {
82 cid_to_events: map,
83 order,
84 full_state: false,
85 }
86 }
87
88 /// Composes `other` after `self`.
89 ///
90 /// [`DiffBatch::full_state`] composes as follows. An empty batch is the identity, so
91 /// composing into one adopts `other`'s flag. Two full-state batches stay full-state: a
92 /// mergeable child that `other` re-activates was hidden at the version where the batches
93 /// meet, so `self` has no entry for it, and a child `self` re-activated followed by
94 /// increments is still a full state. Two incremental batches stay incremental. A
95 /// full-state batch and an incremental one cannot be composed: re-activated children would
96 /// mix full states and increments on hidden state, which neither mode can apply.
97 ///
98 /// # Panics
99 ///
100 /// If both batches are non-empty and exactly one of them is full-state.
101 pub fn compose(&mut self, other: &Self) {
102 if other.cid_to_events.is_empty() {
103 return;
104 }
105 if self.cid_to_events.is_empty() {
106 self.full_state = other.full_state;
107 }
108 assert_eq!(
109 self.full_state, other.full_state,
110 "cannot compose a full-state DiffBatch with an incremental one"
111 );
112
113 for (id, diff) in other.iter() {
114 if let Some(this_diff) = self.cid_to_events.get_mut(id) {
115 this_diff.compose_ref(diff);
116 } else {
117 self.cid_to_events.insert(id.clone(), diff.clone());
118 self.order.push(id.clone());
119 }
120 }
121 }
122
123 pub fn transform(&mut self, other: &Self, left_priority: bool) {
124 if other.cid_to_events.is_empty() || self.cid_to_events.is_empty() {
125 return;
126 }
127
128 for (idx, diff) in self.cid_to_events.iter_mut() {
129 if let Some(b_diff) = other.cid_to_events.get(idx) {
130 diff.transform(b_diff, left_priority);
131 }
132 }
133 }
134
135 pub fn clear(&mut self) {
136 self.cid_to_events.clear();
137 self.order.clear();
138 self.full_state = false;
139 }
140
141 pub fn iter(&self) -> impl Iterator<Item = (&ContainerID, &Diff)> + '_ {
142 self.order
143 .iter()
144 .map(|cid| (cid, self.cid_to_events.get(cid).unwrap()))
145 }
146
147 #[allow(clippy::should_implement_trait)]
148 pub fn into_iter(self) -> impl Iterator<Item = (ContainerID, Diff)> {
149 let mut cid_to_events = self.cid_to_events;
150 self.order.into_iter().map(move |cid| {
151 let d = cid_to_events.remove(&cid).unwrap();
152 (cid, d)
153 })
154 }
155}
156
157fn transform_cursor(
158 cursor_with_pos: &mut CursorWithPos,
159 remote_diff: &DiffBatch,
160 doc: &LoroDoc,
161 container_remap: &FxHashMap<ContainerID, ContainerID>,
162) {
163 let mut container_changed = false;
164 let mut cid = &cursor_with_pos.cursor.container;
165 while let Some(new_cid) = container_remap.get(cid) {
166 cid = new_cid;
167 container_changed = true;
168 }
169
170 if cursor_with_pos.cursor.id.is_none() {
171 // We don't need to transform a cursor that always points to the leftmost or rightmost position
172 if container_changed {
173 cursor_with_pos.cursor.container = cid.clone();
174 }
175 return;
176 }
177
178 if let Some(diff) = remote_diff.cid_to_events.get(cid) {
179 let new_pos = diff.transform_cursor(cursor_with_pos.pos.pos, false);
180 cursor_with_pos.pos.pos = new_pos;
181 };
182
183 let new_pos = cursor_with_pos.pos.pos;
184 // Cursors come from the user's `on_push` and may name a missing container
185 let Some(handler) = doc.get_handler(cid.clone()) else {
186 return;
187 };
188 match handler {
189 crate::handler::Handler::Text(h) => {
190 let Some(new_cursor) = h.get_cursor_internal(new_pos, cursor_with_pos.pos.side, false)
191 else {
192 return;
193 };
194
195 cursor_with_pos.cursor = new_cursor;
196 }
197 crate::handler::Handler::List(h) => {
198 let Some(new_cursor) = h.get_cursor(new_pos, cursor_with_pos.pos.side) else {
199 return;
200 };
201
202 cursor_with_pos.cursor = new_cursor;
203 }
204 crate::handler::Handler::MovableList(h) => {
205 let Some(new_cursor) = h.get_cursor(new_pos, cursor_with_pos.pos.side) else {
206 return;
207 };
208
209 cursor_with_pos.cursor = new_cursor;
210 }
211 crate::handler::Handler::Map(_) => {}
212 crate::handler::Handler::Tree(_) => {}
213 crate::handler::Handler::Unknown(_) => {}
214 #[cfg(feature = "counter")]
215 crate::handler::Handler::Counter(_) => {}
216 }
217}
218
219/// UndoManager is responsible for managing undo/redo from the current peer's perspective.
220///
221/// Undo/local is local: it cannot be used to undone the changes made by other peers.
222/// If you want to undo changes made by other peers, you may need to use the time travel feature.
223///
224/// PeerID cannot be changed during the lifetime of the UndoManager
225pub struct UndoManager {
226 peer: Arc<AtomicU64>,
227 container_remap: Arc<Mutex<FxHashMap<ContainerID, ContainerID>>>,
228 element_remap: Mutex<movable_list::ElementRemap>,
229 inner: Arc<parking_lot::ReentrantMutex<RefCell<UndoManagerInner>>>,
230 _peer_id_change_sub: Subscription,
231 _undo_sub: Subscription,
232 doc: LoroDoc,
233}
234
235impl std::fmt::Debug for UndoManager {
236 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
237 f.debug_struct("UndoManager")
238 .field("peer", &self.peer)
239 .field("container_remap", &self.container_remap)
240 .field("inner", &self.inner)
241 .finish()
242 }
243}
244
245#[derive(Debug, Clone, Copy, PartialEq, Eq)]
246pub enum UndoOrRedo {
247 Undo,
248 Redo,
249}
250
251impl UndoOrRedo {
252 fn opposite(&self) -> UndoOrRedo {
253 match self {
254 Self::Undo => Self::Redo,
255 Self::Redo => Self::Undo,
256 }
257 }
258}
259
260/// When a undo/redo item is pushed, the undo manager will call the on_push callback to get the meta data of the undo item.
261/// The returned cursors will be recorded for a new pushed undo item.
262pub type OnPush = Box<
263 dyn for<'a> Fn(UndoOrRedo, CounterSpan, Option<DiffEvent<'a>>) -> UndoItemMeta + Send + Sync,
264>;
265pub type OnPop = Box<dyn Fn(UndoOrRedo, CounterSpan, UndoItemMeta) + Send + Sync>;
266
267struct UndoManagerInner {
268 next_counter: Option<Counter>,
269 undo_stack: Stack,
270 redo_stack: Stack,
271 processing_undo: bool,
272 paused: bool,
273 last_undo_time: i64,
274 merge_interval_in_ms: i64,
275 max_stack_size: usize,
276 exclude_origin_prefixes: Vec<Box<str>>,
277 last_popped_selection: Option<Vec<CursorWithPos>>,
278 on_push: Option<OnPush>,
279 on_pop: Option<OnPop>,
280 group: Option<UndoGroup>,
281}
282
283impl std::fmt::Debug for UndoManagerInner {
284 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
285 f.debug_struct("UndoManagerInner")
286 .field("latest_counter", &self.next_counter)
287 .field("undo_stack", &self.undo_stack)
288 .field("redo_stack", &self.redo_stack)
289 .field("processing_undo", &self.processing_undo)
290 .field("last_undo_time", &self.last_undo_time)
291 .field("merge_interval", &self.merge_interval_in_ms)
292 .field("max_stack_size", &self.max_stack_size)
293 .field("exclude_origin_prefixes", &self.exclude_origin_prefixes)
294 .field("group", &self.group)
295 .finish()
296 }
297}
298
299#[derive(Debug, Clone, Default)]
300struct UndoGroup {
301 start_counter: Counter,
302 affected_cids: FxHashSet<ContainerID>,
303}
304
305impl UndoGroup {
306 pub fn new(start_counter: Counter) -> Self {
307 Self {
308 start_counter,
309 affected_cids: Default::default(),
310 }
311 }
312}
313
314struct ProcessingUndoGuard {
315 inner: Arc<parking_lot::ReentrantMutex<RefCell<UndoManagerInner>>>,
316}
317
318impl Drop for ProcessingUndoGuard {
319 fn drop(&mut self) {
320 self.inner.lock().borrow_mut().processing_undo = false;
321 }
322}
323
324#[derive(Debug)]
325struct Stack {
326 stack: VecDeque<(VecDeque<StackItem>, Arc<Mutex<DiffBatch>>)>,
327 size: usize,
328}
329
330#[derive(Debug, Clone)]
331struct StackItem {
332 span: CounterSpan,
333 meta: UndoItemMeta,
334}
335
336/// The metadata of an undo item.
337///
338/// The cursors inside the metadata will be transformed by remote operations as well.
339/// So that when the item is popped, users can restore the cursors position correctly.
340#[derive(Debug, Default, Clone)]
341pub struct UndoItemMeta {
342 pub value: LoroValue,
343 pub cursors: Vec<CursorWithPos>,
344}
345
346#[derive(Debug, Clone)]
347pub struct CursorWithPos {
348 pub cursor: Cursor,
349 pub pos: AbsolutePosition,
350}
351
352impl UndoItemMeta {
353 pub fn new() -> Self {
354 Self {
355 value: LoroValue::Null,
356 cursors: Default::default(),
357 }
358 }
359
360 /// It's assumed that the cursor is just acquired before the ops that
361 /// need to be undo/redo.
362 ///
363 /// We need to rely on the validity of the original pos value
364 pub fn add_cursor(&mut self, cursor: &Cursor) {
365 self.cursors.push(CursorWithPos {
366 cursor: cursor.clone(),
367 pos: AbsolutePosition {
368 pos: cursor.origin_pos,
369 side: cursor.side,
370 },
371 });
372 }
373
374 pub fn set_value(&mut self, value: LoroValue) {
375 self.value = value;
376 }
377}
378
379impl Stack {
380 pub fn new() -> Self {
381 let mut stack = VecDeque::new();
382 stack.push_back((VecDeque::new(), Arc::new(Mutex::new(Default::default()))));
383 Stack { stack, size: 0 }
384 }
385
386 /// Peek the top-most StackItem's metadata without modifying the stack.
387 ///
388 /// Returns None if the stack is empty.
389 fn peek_top_meta(&self) -> Option<UndoItemMeta> {
390 if self.is_empty() {
391 return None;
392 }
393
394 for (items, _) in self.stack.iter().rev() {
395 if let Some(item) = items.back() {
396 return Some(item.meta.clone());
397 }
398 }
399
400 None
401 }
402
403 pub fn pop(&mut self) -> Option<(StackItem, Arc<Mutex<DiffBatch>>)> {
404 while self.stack.back().unwrap().0.is_empty() && self.stack.len() > 1 {
405 let (_, diff) = self.stack.pop_back().unwrap();
406 let diff = diff.lock();
407 if !diff.cid_to_events.is_empty() {
408 self.stack.back_mut().unwrap().1.lock().compose(&diff);
409 }
410 }
411
412 if self.stack.len() == 1 && self.stack.back().unwrap().0.is_empty() {
413 // If the stack is empty, we need to clear the remote diff
414 self.stack.back_mut().unwrap().1.lock().clear();
415 return None;
416 }
417
418 self.size -= 1;
419 let last = self.stack.back_mut().unwrap();
420 last.0.pop_back().map(|x| (x, last.1.clone()))
421 // If this row in stack is empty, we don't pop it right away
422 // Because we still need the remote diff to be available.
423 // Cursor position transformation relies on the remote diff in the same row.
424 }
425
426 pub fn push(&mut self, span: CounterSpan, meta: UndoItemMeta) {
427 self.push_with_merge(span, meta, false, None)
428 }
429
430 fn restore_popped(&mut self, item: StackItem, remote_diff: &Arc<Mutex<DiffBatch>>) {
431 let last = self.stack.back_mut().unwrap();
432 assert!(
433 Arc::ptr_eq(&last.1, remote_diff),
434 "failed undo lost its remote-diff row"
435 );
436 last.0.push_back(item);
437 self.size += 1;
438 }
439
440 pub fn push_with_merge(
441 &mut self,
442 span: CounterSpan,
443 meta: UndoItemMeta,
444 can_merge: bool,
445 group: Option<&UndoGroup>,
446 ) {
447 let last = self.stack.back_mut().unwrap();
448 let last_remote_diff = last.1.lock();
449
450 // Check if the remote diff is disjoint with the current undo group
451 let is_disjoint_group = group.is_some_and(|g| {
452 g.affected_cids.iter().all(|cid| {
453 last_remote_diff
454 .cid_to_events
455 .get(cid)
456 .is_none_or(|diff| diff.is_empty())
457 })
458 });
459
460 // Can't merge if remote diffs exist and it's not disjoint with the current undo group
461 let should_create_new_entry =
462 !last_remote_diff.cid_to_events.is_empty() && !is_disjoint_group;
463
464 if should_create_new_entry {
465 // Create a new entry in the stack
466 drop(last_remote_diff);
467 let mut v = VecDeque::new();
468 v.push_back(StackItem { span, meta });
469 self.stack
470 .push_back((v, Arc::new(Mutex::new(DiffBatch::default()))));
471 self.size += 1;
472 return;
473 }
474
475 // Try to merge with the previous entry if allowed
476 if can_merge {
477 if let Some(last_span) = last.0.back_mut() {
478 if last_span.span.end == span.start {
479 // Merge spans by extending the end of the last span
480 last_span.span.end = span.end;
481 return;
482 }
483 }
484 }
485
486 // Add as a new item to the existing entry
487 self.size += 1;
488 last.0.push_back(StackItem { span, meta });
489 }
490
491 pub fn compose_remote_event(&mut self, diff: &[&ContainerDiff]) {
492 if self.is_empty() {
493 return;
494 }
495
496 let remote_diff = &mut self.stack.back_mut().unwrap().1;
497 let mut remote_diff = remote_diff.lock();
498 for e in diff {
499 // Transform against what actually changed. A re-activated mergeable child's event
500 // is its full state, but its content (and the undo items' positions in it) stayed.
501 let Some(change) = e.change() else {
502 continue;
503 };
504 if let Some(d) = remote_diff.cid_to_events.get_mut(&e.id) {
505 d.compose_ref(change);
506 } else {
507 remote_diff
508 .cid_to_events
509 .insert(e.id.clone(), change.clone());
510 remote_diff.order.push(e.id.clone());
511 }
512 }
513 }
514
515 pub fn transform_based_on_this_delta(&mut self, diff: &DiffBatch) {
516 if self.is_empty() {
517 return;
518 }
519 let remote_diff = &mut self.stack.back_mut().unwrap().1;
520 remote_diff.lock().transform(diff, false);
521 }
522
523 pub fn clear(&mut self) {
524 self.stack = VecDeque::new();
525 self.stack.push_back((VecDeque::new(), Default::default()));
526 self.size = 0;
527 }
528
529 pub fn is_empty(&self) -> bool {
530 self.size == 0
531 }
532
533 pub fn len(&self) -> usize {
534 self.size
535 }
536
537 fn discard_empty_front_rows(&mut self) {
538 // Undo pop can leave an empty front row that only carries remote diffs.
539 // There is no older stack item for that diff to transform during trimming.
540 while self
541 .stack
542 .front()
543 .is_some_and(|(items, _)| items.is_empty())
544 {
545 self.stack.pop_front();
546 }
547 }
548
549 fn ensure_trailing_empty_row(&mut self) {
550 if self.stack.is_empty() {
551 self.stack
552 .push_back((VecDeque::new(), Arc::new(Mutex::new(Default::default()))));
553 }
554 }
555
556 fn pop_front(&mut self) {
557 if self.is_empty() {
558 return;
559 }
560
561 self.discard_empty_front_rows();
562 self.size -= 1;
563 let first = self.stack.front_mut().unwrap();
564 let f = first.0.pop_front();
565 assert!(f.is_some());
566 if first.0.is_empty() {
567 self.stack.pop_front();
568 }
569
570 self.ensure_trailing_empty_row();
571 }
572
573 fn set_top_meta(&mut self, meta: UndoItemMeta) {
574 let Some(top) = self.stack.back_mut() else {
575 return;
576 };
577 let Some(last) = top.0.back_mut() else {
578 return;
579 };
580 last.meta = meta;
581 }
582}
583
584impl Default for Stack {
585 fn default() -> Self {
586 Stack::new()
587 }
588}
589
590impl UndoManagerInner {
591 fn new(last_counter: Counter) -> Self {
592 Self {
593 next_counter: Some(last_counter),
594 undo_stack: Default::default(),
595 redo_stack: Default::default(),
596 processing_undo: false,
597 paused: false,
598 merge_interval_in_ms: 0,
599 last_undo_time: 0,
600 max_stack_size: usize::MAX,
601 exclude_origin_prefixes: vec![],
602 last_popped_selection: None,
603 on_pop: None,
604 on_push: None,
605 group: None,
606 }
607 }
608
609 /// Returns true if a given container diff is disjoint with the current group.
610 /// They are disjoint if they have no overlap in changed container ids.
611 fn is_disjoint_with_group(&self, diff: &[&ContainerDiff]) -> bool {
612 let Some(group) = &self.group else {
613 return false;
614 };
615
616 diff.iter().all(|d| !group.affected_cids.contains(&d.id))
617 }
618
619 fn record_checkpoint(this: &RefCell<Self>, latest_counter: Counter, event: Option<DiffEvent>) {
620 let previous_counter = this.borrow().next_counter;
621
622 if Some(latest_counter) == this.borrow().next_counter {
623 return;
624 }
625
626 if this.borrow().next_counter.is_none() {
627 this.borrow_mut().next_counter = Some(latest_counter);
628 return;
629 }
630
631 if let Some(group) = &mut this.borrow_mut().group {
632 event.iter().for_each(|e| {
633 e.events.iter().for_each(|e| {
634 group.affected_cids.insert(e.id.clone());
635 })
636 });
637 }
638
639 let now = get_sys_timestamp() as Timestamp;
640 let span = CounterSpan::new(this.borrow().next_counter.unwrap(), latest_counter);
641 let meta = this
642 .borrow()
643 .on_push
644 .as_ref()
645 .map(|x| x(UndoOrRedo::Undo, span, event))
646 .unwrap_or_default();
647
648 let mut this = this.borrow_mut();
649 let this: &mut Self = &mut this;
650 // Wether the change is within the accepted merge interval
651 let in_merge_interval = now - this.last_undo_time < this.merge_interval_in_ms;
652
653 // If group is active, but there is nothing in the group, don't merge
654 // If the group is active and it's not the first push in the group, merge
655 let group_should_merge = this.group.is_some()
656 && match (
657 previous_counter,
658 this.group.as_ref().map(|g| g.start_counter),
659 ) {
660 (Some(previous), Some(active)) => previous != active,
661 _ => true,
662 };
663
664 let should_merge = !this.undo_stack.is_empty() && (in_merge_interval || group_should_merge);
665
666 if should_merge {
667 this.undo_stack
668 .push_with_merge(span, meta, true, this.group.as_ref());
669 } else {
670 this.last_undo_time = now;
671 this.undo_stack.push(span, meta);
672 }
673
674 this.next_counter = Some(latest_counter);
675 this.redo_stack.clear();
676 while this.undo_stack.len() > this.max_stack_size {
677 this.undo_stack.pop_front();
678 }
679 }
680}
681
682fn get_counter_end(doc: &LoroDoc, peer: PeerID) -> Counter {
683 doc.oplog().lock().vv().get(&peer).cloned().unwrap_or(0)
684}
685
686impl UndoManager {
687 pub fn new(doc: &LoroDoc) -> Self {
688 let peer = Arc::new(AtomicU64::new(doc.peer_id()));
689 let peer_clone = peer.clone();
690 let peer_clone2 = peer.clone();
691 let inner = Arc::new(ReentrantMutex::new(RefCell::new(UndoManagerInner::new(
692 get_counter_end(doc, doc.peer_id()),
693 ))));
694 let inner_clone = inner.clone();
695 let inner_clone2 = inner.clone();
696 let remap_containers = Arc::new(Mutex::new(FxHashMap::default()));
697 let remap_containers_clone = remap_containers.clone();
698 let undo_sub = doc.subscribe_root(Arc::new(move |event| match event.event_meta.by {
699 EventTriggerKind::Local => {
700 // TODO: PERF undo can be significantly faster if we can get
701 // the DiffBatch for undo here
702 let lock = inner_clone.lock();
703 if lock.borrow().processing_undo {
704 return;
705 }
706 if let Some(id) = event
707 .event_meta
708 .to
709 .iter()
710 .find(|x| x.peer == peer_clone.load(std::sync::atomic::Ordering::Relaxed))
711 {
712 let is_paused = lock.borrow().paused;
713 let should_exclude = lock
714 .borrow()
715 .exclude_origin_prefixes
716 .iter()
717 .any(|x| event.event_meta.origin.starts_with(&**x));
718 if is_paused || should_exclude {
719 // Paused and excluded-origin edits are not recorded as
720 // undo steps, but their effects must be composed into
721 // both stacks so transforms stay correct, and
722 // next_counter must advance so the next recorded item
723 // does not fold these edits into its span.
724 let mut inner = lock.borrow_mut();
725 inner.undo_stack.compose_remote_event(event.events);
726 inner.redo_stack.compose_remote_event(event.events);
727 inner.next_counter = Some(id.counter + 1);
728 } else {
729 UndoManagerInner::record_checkpoint(&lock, id.counter + 1, Some(event));
730 }
731 }
732 }
733 EventTriggerKind::Import => {
734 let lock = inner_clone.lock();
735 let mut inner = lock.borrow_mut();
736
737 for e in event.events {
738 if let Diff::Tree(tree) = &e.diff {
739 for item in &tree.diff {
740 let target = item.target;
741 if let TreeExternalDiff::Create { .. } = &item.action {
742 // If the concurrent event is a create event, it may bring the deleted tree node back,
743 // so we need to remove it from the remap of the container.
744 remap_containers_clone
745 .lock()
746 .remove(&target.associated_meta_container());
747 }
748 }
749 }
750 }
751
752 let is_import_disjoint = inner.is_disjoint_with_group(event.events);
753
754 inner.undo_stack.compose_remote_event(event.events);
755 inner.redo_stack.compose_remote_event(event.events);
756
757 // If the import is not disjoint, we end the active group
758 // all subsequent changes will be new undo items
759 if !is_import_disjoint {
760 inner.group = None;
761 }
762 }
763 EventTriggerKind::Checkout => {
764 let lock = inner_clone.lock();
765 if lock.borrow().paused {
766 return;
767 }
768 let mut inner = lock.borrow_mut();
769 inner.undo_stack.clear();
770 inner.redo_stack.clear();
771 inner.next_counter = None;
772 }
773 }));
774
775 let sub = doc.subscribe_peer_id_change(Box::new(move |id| {
776 let lock = inner_clone2.lock();
777 let mut inner = lock.borrow_mut();
778 inner.undo_stack.clear();
779 inner.redo_stack.clear();
780 inner.next_counter = Some(id.counter);
781 peer_clone2.store(id.peer, std::sync::atomic::Ordering::Relaxed);
782 true
783 }));
784
785 UndoManager {
786 peer,
787 container_remap: remap_containers,
788 element_remap: Mutex::new(FxHashMap::default()),
789 inner,
790 _peer_id_change_sub: sub,
791 _undo_sub: undo_sub,
792 doc: doc.clone(),
793 }
794 }
795
796 pub fn group_start(&self) -> LoroResult<()> {
797 let lock = self.inner.lock();
798 let mut inner = lock.borrow_mut();
799
800 if inner.group.is_some() {
801 return Err(LoroError::UndoGroupAlreadyStarted);
802 }
803
804 inner.group =
805 Some(UndoGroup::new(inner.next_counter.ok_or_else(|| {
806 LoroError::Unknown("UndoManager is not ready".into())
807 })?));
808
809 Ok(())
810 }
811
812 pub fn group_end(&self) {
813 self.inner.lock().borrow_mut().group = None;
814 }
815
816 pub fn peer(&self) -> PeerID {
817 self.peer.load(std::sync::atomic::Ordering::Relaxed)
818 }
819
820 pub fn set_merge_interval(&self, interval: i64) {
821 self.inner.lock().borrow_mut().merge_interval_in_ms = interval;
822 }
823
824 pub fn set_max_undo_steps(&self, size: usize) {
825 self.inner.lock().borrow_mut().max_stack_size = size;
826 }
827
828 pub fn add_exclude_origin_prefix(&self, prefix: &str) {
829 self.inner
830 .lock()
831 .borrow_mut()
832 .exclude_origin_prefixes
833 .push(prefix.into());
834 }
835
836 pub fn record_new_checkpoint(&self) -> LoroResult<()> {
837 // Use implicit-style barrier to preserve next-commit options across
838 // an empty commit before undo/redo processing.
839 self.doc.with_barrier(|| {});
840 let counter = get_counter_end(&self.doc, self.peer());
841 UndoManagerInner::record_checkpoint(&self.inner.lock(), counter, None);
842 Ok(())
843 }
844
845 /// Consume at most one undo item, even if its transformed inverse is a no-op.
846 /// Returns whether local operations were generated; use `can_undo` to check
847 /// whether history remains after a `false` result.
848 #[instrument(skip_all)]
849 pub fn undo(&self) -> LoroResult<bool> {
850 self.perform(
851 |x| &mut x.undo_stack,
852 |x| &mut x.redo_stack,
853 UndoOrRedo::Undo,
854 )
855 }
856
857 /// Consume at most one redo item, including a no-op. A `false` result means
858 /// no local operations were generated, not necessarily an empty redo stack.
859 #[instrument(skip_all)]
860 pub fn redo(&self) -> LoroResult<bool> {
861 self.perform(
862 |x| &mut x.redo_stack,
863 |x| &mut x.undo_stack,
864 UndoOrRedo::Redo,
865 )
866 }
867
868 fn perform(
869 &self,
870 get_stack: impl Fn(&mut UndoManagerInner) -> &mut Stack,
871 get_opposite: impl Fn(&mut UndoManagerInner) -> &mut Stack,
872 kind: UndoOrRedo,
873 ) -> LoroResult<bool> {
874 if self.inner.lock().borrow().paused {
875 return Ok(false);
876 }
877 let doc = &self.doc.clone();
878 let _exclusive = doc.txn.lock_exclusive();
879 // When in the undo/redo loop, the new undo/redo stack item should restore the selection
880 // to the state it was in before the item that was popped two steps ago from the stack.
881 //
882 // ┌────────────┐
883 // │Selection 1 │
884 // └─────┬──────┘
885 // │ Some
886 // ▼ ops
887 // ┌────────────┐
888 // │Selection 2 │
889 // └─────┬──────┘
890 // │ Some
891 // ▼ ops
892 // ┌────────────┐
893 // │Selection 3 │◁ ─ ─ ─ ─ ─ ─ ─ Restore ─ ─ ─
894 // └─────┬──────┘ │
895 // │
896 // │ │
897 // │ ┌ ─ ─ ─ ─ ─ ─ ─
898 // Enter the │ Undo ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─▶ Push Redo │
899 // undo/redo ─ ─ ─ ▶ ▼ └ ─ ─ ─ ─ ─ ─ ─
900 // loop ┌────────────┐ │
901 // │Selection 2 │◁─ ─ ─ Restore ─
902 // └─────┬──────┘ │ │
903 // │
904 // │ │ │
905 // │ ┌ ─ ─ ─ ─ ─ ─ ─
906 // │ Undo ─ ─ ─ ─ ▶ Push Redo │ │
907 // ▼ └ ─ ─ ─ ─ ─ ─ ─
908 // ┌────────────┐ │ │
909 // │Selection 1 │
910 // └─────┬──────┘ │ │
911 // │ Redo ◀ ─ ─ ─ ─ ─ ─ ─ ─
912 // ▼ │
913 // ┌────────────┐
914 // ┌ Restore ─ ▷│Selection 2 │ │
915 // └─────┬──────┘
916 // │ │ │
917 // ┌ ─ ─ ─ ─ ─ ─ ─ │
918 // Push Undo │◀─ ─ ─ ─ ─ ─ ─ │ Redo ◀ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┘
919 // └ ─ ─ ─ ─ ─ ─ ─ ▼
920 // │ ┌────────────┐
921 // │Selection 3 │
922 // │ └─────┬──────┘
923 // ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ▶ │ Undo
924 // ▼
925 // ┌────────────┐
926 // │Selection 2 │
927 // └────────────┘
928 //
929 // Because users may change the selections during the undo/redo loop, it's
930 // more stable to keep the selection stored in the last stack item
931 // rather than using the current selection directly.
932 self.record_new_checkpoint()?;
933 let end_counter = get_counter_end(doc, self.peer());
934 let top = {
935 let lock = self.inner.lock();
936 let mut inner = lock.borrow_mut();
937 inner.processing_undo = true;
938 get_stack(&mut inner).pop()
939 };
940 let _guard = ProcessingUndoGuard {
941 inner: self.inner.clone(),
942 };
943
944 let mut executed = false;
945 // A no-op still consumes this item. Never cross its history boundary
946 // to undo/redo an unrelated edit in the same call.
947 if let Some((mut span, remote_diff)) = top {
948 let mut next_push_selection = None;
949 {
950 let inner = self.inner.clone();
951 // We need to clone this because otherwise <transform_delta> will be applied to the same remote diff
952 let remote_change_clone = remote_diff.lock().clone();
953 let mut rejected_step = None;
954 let commit = match doc.undo_internal_with(
955 IdSpan {
956 peer: self.peer(),
957 counter: span.span,
958 },
959 &mut self.container_remap.lock(),
960 Some(&remote_change_clone),
961 &mut |diff| {
962 info_span!("transform remote diff").in_scope(|| {
963 let inner = inner.lock();
964 // <transform_delta>
965 get_stack(&mut inner.borrow_mut()).transform_based_on_this_delta(diff);
966 });
967 },
968 &mut rejected_step,
969 &mut self.element_remap.lock(),
970 ) {
971 Ok(c) => c,
972 // Keep the documented unknown-container policy: consume a
973 // prechecked unsupported step and rebase older history.
974 // Application errors, including other ArgErrs, are retried.
975 Err(e @ LoroError::ArgErr(_)) if rejected_step.is_some() => {
976 // Its changes stay in the doc: rebase the steps before
977 // it over them, like over remote changes
978 if let Some(mut changes) = rejected_step {
979 let mut remote = remote_diff.lock();
980 changes.compose(&remote);
981 *remote = changes;
982 }
983 return Err(e);
984 }
985 Err(e) => {
986 get_stack(&mut self.inner.lock().borrow_mut())
987 .restore_popped(span, &remote_diff);
988 return Err(e);
989 }
990 };
991 drop(commit);
992 let inner = self.inner.lock();
993 let mut is_some = false;
994
995 if let Some(on_pop) = inner.borrow().on_pop.as_ref() {
996 is_some = true;
997 for cursor in span.meta.cursors.iter_mut() {
998 // <cursor_transform> We need to transform cursor here.
999 // Note that right now <transform_delta> is already done,
1000 // remote_diff is also transformed by it now (that's what we need).
1001 transform_cursor(
1002 cursor,
1003 &remote_diff.lock(),
1004 doc,
1005 &self.container_remap.lock(),
1006 );
1007 }
1008
1009 on_pop(kind, span.span, span.meta.clone());
1010 }
1011 if is_some {
1012 let take = inner.borrow_mut().last_popped_selection.take();
1013 next_push_selection = take;
1014 inner.borrow_mut().last_popped_selection = Some(span.meta.cursors);
1015 }
1016 }
1017 let new_counter = get_counter_end(doc, self.peer());
1018 if end_counter != new_counter {
1019 let inner = self.inner.lock();
1020 let mut meta = inner
1021 .borrow()
1022 .on_push
1023 .as_ref()
1024 .map(|x| {
1025 x(
1026 kind.opposite(),
1027 CounterSpan::new(end_counter, new_counter),
1028 None,
1029 )
1030 })
1031 .unwrap_or_default();
1032
1033 if matches!(kind, UndoOrRedo::Undo)
1034 && get_opposite(&mut inner.borrow_mut()).is_empty()
1035 {
1036 // If it's the first undo, we use the cursors from the users
1037 } else if let Some(inner) = next_push_selection.take() {
1038 // Otherwise, we use the cursors from the undo/redo loop
1039 meta.cursors = inner;
1040 }
1041
1042 get_opposite(&mut inner.borrow_mut())
1043 .push(CounterSpan::new(end_counter, new_counter), meta);
1044 inner.borrow_mut().next_counter = Some(new_counter);
1045 executed = true;
1046 }
1047 }
1048
1049 Ok(executed)
1050 }
1051
1052 pub fn can_undo(&self) -> bool {
1053 !self.inner.lock().borrow().undo_stack.is_empty()
1054 }
1055
1056 pub fn can_redo(&self) -> bool {
1057 !self.inner.lock().borrow().redo_stack.is_empty()
1058 }
1059
1060 pub fn undo_count(&self) -> usize {
1061 self.inner.lock().borrow().undo_stack.len()
1062 }
1063
1064 pub fn redo_count(&self) -> usize {
1065 self.inner.lock().borrow().redo_stack.len()
1066 }
1067
1068 /// Get the metadata of the top undo stack item, if any.
1069 pub fn top_undo_meta(&self) -> Option<UndoItemMeta> {
1070 self.inner.lock().borrow().undo_stack.peek_top_meta()
1071 }
1072
1073 /// Get the metadata of the top redo stack item, if any.
1074 pub fn top_redo_meta(&self) -> Option<UndoItemMeta> {
1075 self.inner.lock().borrow().redo_stack.peek_top_meta()
1076 }
1077
1078 /// Get the value associated with the top undo stack item, if any.
1079 pub fn top_undo_value(&self) -> Option<LoroValue> {
1080 self.top_undo_meta().map(|m| m.value)
1081 }
1082
1083 /// Get the value associated with the top redo stack item, if any.
1084 pub fn top_redo_value(&self) -> Option<LoroValue> {
1085 self.top_redo_meta().map(|m| m.value)
1086 }
1087
1088 pub fn set_on_push(&self, on_push: Option<OnPush>) {
1089 self.inner.lock().borrow_mut().on_push = on_push;
1090 }
1091
1092 pub fn set_on_pop(&self, on_pop: Option<OnPop>) {
1093 self.inner.lock().borrow_mut().on_pop = on_pop;
1094 }
1095
1096 pub fn clear(&self) {
1097 self.inner.lock().borrow_mut().undo_stack.clear();
1098 self.inner.lock().borrow_mut().redo_stack.clear();
1099 }
1100
1101 /// Clear only the redo stack, preserving the undo stack.
1102 pub fn clear_redo(&self) {
1103 self.inner.lock().borrow_mut().redo_stack.clear();
1104 }
1105
1106 /// Clear only the undo stack, preserving the redo stack.
1107 pub fn clear_undo(&self) {
1108 self.inner.lock().borrow_mut().undo_stack.clear();
1109 }
1110
1111 /// Pause the UndoManager so that local edits and checkout events are ignored.
1112 ///
1113 /// While paused, local edits are not recorded as undo steps and checkout
1114 /// events do not clear the stacks. Import events (remote changes) are still
1115 /// processed so that the stacks remain correctly transformed against
1116 /// concurrent edits.
1117 ///
1118 /// Use this before temporary checkouts (e.g. read-only history preview) that
1119 /// should not disturb the undo/redo history. Close any open group (via
1120 /// [`Self::group_end`]) before pausing.
1121 ///
1122 /// Call [`Self::resume`] after returning the document to its original state.
1123 pub fn pause(&self) {
1124 self.inner.lock().borrow_mut().paused = true;
1125 }
1126
1127 /// Resume the UndoManager after a [`Self::pause`].
1128 pub fn resume(&self) {
1129 self.inner.lock().borrow_mut().paused = false;
1130 }
1131
1132 /// Returns whether the UndoManager is currently paused.
1133 pub fn is_paused(&self) -> bool {
1134 self.inner.lock().borrow().paused
1135 }
1136
1137 pub fn set_top_undo_meta(&self, meta: UndoItemMeta) {
1138 self.inner.lock().borrow_mut().undo_stack.set_top_meta(meta);
1139 }
1140
1141 pub fn set_top_redo_meta(&self, meta: UndoItemMeta) {
1142 self.inner.lock().borrow_mut().redo_stack.set_top_meta(meta);
1143 }
1144}
1145
1146/// Undo the given spans of operations.
1147///
1148/// # Parameters
1149///
1150/// - `spans`: A vector of tuples where each tuple contains an `IdSpan` and its associated `Frontiers`.
1151/// - `IdSpan`: Represents a span of operations identified by an ID.
1152/// - `Frontiers`: Represents the deps of the given id_span
1153/// - `latest_frontiers`: The latest frontiers of the document
1154/// - `calc_diff`: A closure that takes two `Frontiers` and calculates the difference between them, returning a `DiffBatch`.
1155///
1156/// # Returns
1157///
1158/// - `DiffBatch`: Applying this batch on the `latest_frontiers` will undo the ops in the given spans.
1159pub(crate) fn undo(
1160 spans: Vec<(IdSpan, Frontiers)>,
1161 last_frontiers_or_last_bi: Either<&Frontiers, &DiffBatch>,
1162 calc_diff: impl Fn(&Frontiers, &Frontiers) -> DiffBatch,
1163 on_last_event_a: &mut dyn FnMut(&DiffBatch),
1164) -> DiffBatch {
1165 // The process of performing undo is:
1166 //
1167 // 0. Split the span into a series of continuous spans. There is no external dep within each continuous span.
1168 //
1169 // For each continuous span_i:
1170 //
1171 // 1. a. Calculate the event of checkout from id_span.last to id_span.deps, call it Ai. It undo the ops in the current span.
1172 // b. Calculate A'i = Ai + T(Ci-1, Ai) if i > 0, otherwise A'i = Ai.
1173 // NOTE: A'i can undo the ops in the current span and the previous spans, if it's applied on the id_span.last version.
1174 // 2. Calculate the event of checkout from id_span.last to [the next span's last id] or [the latest version], call it Bi.
1175 // 3. Transform event A'i based on Bi, call it Ci
1176 // 4. If span_i is the last span, apply Ci to the current state.
1177
1178 // -------------------------------------------------------
1179 // 0. Split the span into a series of continuous spans
1180 // -------------------------------------------------------
1181
1182 let mut last_ci: Option<DiffBatch> = None;
1183 for i in 0..spans.len() {
1184 debug_span!("Undo", ?i, "Undo span {:?}", &spans[i]).in_scope(|| {
1185 let (this_id_span, this_deps) = &spans[i];
1186 // ---------------------------------------
1187 // 1.a Calc event A_i
1188 // ---------------------------------------
1189 let mut event_a_i = debug_span!("1. Calc event A_i").in_scope(|| {
1190 // Checkout to the last id of the id_span
1191 calc_diff(&this_id_span.id_last().into(), this_deps)
1192 });
1193
1194 // println!("event_a_i: {:?}", event_a_i);
1195
1196 // ---------------------------------------
1197 // 2. Calc event B_i
1198 // ---------------------------------------
1199 let stack_diff_batch;
1200 let event_b_i = 'block: {
1201 let next = if i + 1 < spans.len() {
1202 spans[i + 1].0.id_last().into()
1203 } else {
1204 match last_frontiers_or_last_bi {
1205 Either::Left(last_frontiers) => last_frontiers.clone(),
1206 Either::Right(right) => break 'block right,
1207 }
1208 };
1209 stack_diff_batch = Some(calc_diff(&this_id_span.id_last().into(), &next));
1210 stack_diff_batch.as_ref().unwrap()
1211 };
1212
1213 // println!("event_b_i: {:?}", event_b_i);
1214
1215 // event_a_prime can undo the ops in the current span and the previous spans
1216 let mut event_a_prime = if let Some(mut last_ci) = last_ci.take() {
1217 // ------------------------------------------------------------------------------
1218 // 1.b Transform and apply Ci-1 based on Ai, call it A'i
1219 // ------------------------------------------------------------------------------
1220 last_ci.transform(&event_a_i, true);
1221
1222 event_a_i.compose(&last_ci);
1223 event_a_i
1224 } else {
1225 event_a_i
1226 };
1227 if i == spans.len() - 1 {
1228 on_last_event_a(&event_a_prime);
1229 }
1230 // --------------------------------------------------
1231 // 3. Transform event A'_i based on B_i, call it C_i
1232 // --------------------------------------------------
1233 event_a_prime.transform(event_b_i, true);
1234
1235 // println!("event_a_prime: {:?}", event_a_prime);
1236
1237 let c_i = event_a_prime;
1238 last_ci = Some(c_i);
1239 });
1240 }
1241
1242 last_ci.unwrap()
1243}