BlueGit

ict rusty-teams

Files

rusty-teams / vendor / gpui-base / src / input / base / undo_manager.rs

undo_manager.rs

eef6c0a4 History
undo_manager.rs 21.6 KiB Download Raw
1use super::auto_close::AutoClosedPairs;
2use crate::input::change::Change;
3
4use super::cursor::CursorSelection;
5
6const MAX_UNDO_TRANSACTIONS: usize = 1000;
7const MAX_CHANGES_PER_TRANSACTION: usize = 1000;
8
9#[derive(Clone, Copy, Debug, PartialEq, Eq)]
10pub(crate) enum EditIntent {
11 Typing,
12 Backspace,
13 DeleteForward,
14 Atomic,
15}
16
17#[derive(Debug)]
18struct UndoTransaction {
19 intent: EditIntent,
20 changes: Vec<Change>,
21 /// How many changes the most recently appended batch contributed. A batch
22 /// is one logical edit with one change per cursor. Only a following batch
23 /// of the same length can coalesce into this transaction.
24 last_batch_len: usize,
25 /// How many changes were recorded into this transaction. A run of
26 /// single-cursor keystrokes is merged into one change, so this, not
27 /// `changes.len()`, decides when the transaction is full.
28 recorded_changes: usize,
29 /// The cursors as they stood before this transaction, restored on undo.
30 selections_before: Option<Vec<CursorSelection>>,
31 /// The cursors as they stood after it, restored on redo.
32 selections_after: Option<Vec<CursorSelection>>,
33 auto_closed_pairs_before: Option<AutoClosedPairs>,
34 auto_closed_pairs_after: Option<AutoClosedPairs>,
35}
36
37/// A batch of changes being collected between `begin_transaction` and the
38/// matching `commit_transaction`.
39#[derive(Debug)]
40struct PendingTransaction {
41 intent: EditIntent,
42 changes: Vec<Change>,
43 selections_before: Option<Vec<CursorSelection>>,
44 selections_after: Option<Vec<CursorSelection>>,
45 auto_closed_pairs_before: Option<AutoClosedPairs>,
46 auto_closed_pairs_after: Option<AutoClosedPairs>,
47}
48
49/// One transaction handed back to be replayed, with the cursors to restore
50/// once the changes have been applied.
51pub(crate) struct Replay {
52 pub(super) changes: Vec<Change>,
53 pub(super) selections: Option<Vec<CursorSelection>>,
54 pub(super) auto_closed_pairs: Option<AutoClosedPairs>,
55}
56
57/// Coordinates undo and redo as explicit editing transactions.
58///
59/// Each edit first creates a transaction. Compatible adjacent transactions
60/// may then coalesce until an explicit boundary is encountered. Callers that
61/// perform one logical edit through several changes (IME composition, and any
62/// multi-cursor edit) bracket those changes with `begin_transaction` and
63/// `commit_transaction`. The bracket nests, so an outer caller can group
64/// several already-bracketed edits into one undo entry.
65#[derive(Debug)]
66pub(crate) struct UndoManager {
67 undo_transactions: Vec<UndoTransaction>,
68 redo_transactions: Vec<UndoTransaction>,
69 ignoring: bool,
70 transaction_depth: usize,
71 pending: Option<PendingTransaction>,
72 pending_intent: Option<EditIntent>,
73 coalescing_boundary: bool,
74}
75
76impl UndoManager {
77 pub(super) fn new() -> Self {
78 Self {
79 undo_transactions: Vec::new(),
80 redo_transactions: Vec::new(),
81 ignoring: false,
82 transaction_depth: 0,
83 pending: None,
84 pending_intent: None,
85 coalescing_boundary: false,
86 }
87 }
88
89 /// The intent requested for the next recorded change, taken by the edit
90 /// that records it.
91 pub(super) fn take_pending_intent(&mut self) -> Option<EditIntent> {
92 self.pending_intent.take()
93 }
94
95 /// Request the intent to record the next change with.
96 pub(super) fn set_pending_intent(&mut self, intent: EditIntent) {
97 self.pending_intent = Some(intent);
98 }
99
100 pub(super) fn record_transaction(&mut self, change: Change, intent: EditIntent) -> bool {
101 if self.ignoring {
102 return false;
103 }
104 if change.token_delta.is_none()
105 && change.old_range == change.new_range
106 && change.old_text == change.new_text
107 {
108 self.break_transaction_coalescing();
109 return false;
110 }
111
112 match self.pending.as_mut() {
113 Some(pending) => pending.changes.push(change),
114 None => self.push_batch(vec![change], intent),
115 }
116 true
117 }
118
119 /// Open a transaction whose changes commit as one atomic undo entry.
120 pub(super) fn begin_transaction(&mut self) {
121 self.begin_transaction_with(EditIntent::Atomic);
122 }
123
124 /// Open a transaction that commits with `intent`, so a following batch of
125 /// the same intent and shape can coalesce into it. Multi-cursor typing uses
126 /// this to group a burst of keystrokes the way single-cursor typing does.
127 ///
128 /// Only the outermost bracket decides the intent. A nested
129 /// `begin_transaction` merely keeps the batch open.
130 pub(super) fn begin_transaction_with(&mut self, intent: EditIntent) {
131 self.transaction_depth += 1;
132 if self.transaction_depth == 1 {
133 self.pending = Some(PendingTransaction {
134 intent,
135 changes: Vec::new(),
136 selections_before: None,
137 selections_after: None,
138 auto_closed_pairs_before: None,
139 auto_closed_pairs_after: None,
140 });
141 }
142 }
143
144 pub(super) fn commit_transaction(&mut self) {
145 if self.transaction_depth == 0 {
146 return;
147 }
148
149 self.transaction_depth -= 1;
150 if self.transaction_depth > 0 {
151 return;
152 }
153
154 let Some(pending) = self.pending.take() else {
155 return;
156 };
157 // A composition that ends where it started (typed then canceled) leaves
158 // the document untouched and must not become an undo entry.
159 if pending.changes.is_empty() || is_noop_batch(&pending.changes) {
160 return;
161 }
162 self.push_batch(pending.changes, pending.intent);
163 if let Some(before) = pending.selections_before {
164 self.record_selections_before(before);
165 }
166 if let Some(after) = pending.selections_after {
167 self.record_selections_after(after);
168 }
169 // These snapshots were recorded with the edits. Commit them even when
170 // replay has just enabled ignoring to flush an open IME transaction.
171 if let Some(transaction) = self.undo_transactions.last_mut() {
172 if let Some(before) = pending.auto_closed_pairs_before {
173 transaction.auto_closed_pairs_before.get_or_insert(before);
174 }
175 if let Some(after) = pending.auto_closed_pairs_after {
176 transaction.auto_closed_pairs_after = Some(after);
177 }
178 }
179 }
180
181 /// Push one logical edit, which is one or more changes in application
182 /// order, onto the undo stack.
183 fn push_batch(&mut self, changes: Vec<Change>, intent: EditIntent) {
184 if changes.is_empty() {
185 return;
186 }
187
188 self.redo_transactions.clear();
189 let can_coalesce = !self.coalescing_boundary
190 && intent != EditIntent::Atomic
191 && self.undo_transactions.last().is_some_and(|previous| {
192 previous.intent == intent
193 && previous.last_batch_len == changes.len()
194 && previous.recorded_changes + changes.len() <= MAX_CHANGES_PER_TRANSACTION
195 && is_adjacent_batch(intent, previous.trailing_batch(), &changes)
196 });
197
198 if can_coalesce {
199 let previous = self
200 .undo_transactions
201 .last_mut()
202 .expect("coalescing requires a previous transaction");
203 previous.last_batch_len = changes.len();
204 previous.recorded_changes += changes.len();
205 // Adjacent single-cursor keystrokes form one contiguous insertion.
206 // Keep it as one change so undo and redo replay it as a single
207 // edit rather than once per keystroke.
208 if intent == EditIntent::Typing
209 && let [change] = changes.as_slice()
210 && let Some(last) = previous.changes.last_mut()
211 {
212 last.new_text
213 .truncate(change.old_range.start - last.new_range.start);
214 last.new_text.push_str(&change.new_text);
215 last.new_range.end = change.new_range.end;
216 return;
217 }
218 previous.changes.extend(changes);
219 return;
220 }
221
222 if self.undo_transactions.len() >= MAX_UNDO_TRANSACTIONS {
223 self.undo_transactions.remove(0);
224 }
225 self.undo_transactions.push(UndoTransaction {
226 intent,
227 last_batch_len: changes.len(),
228 recorded_changes: changes.len(),
229 changes,
230 selections_before: None,
231 selections_after: None,
232 auto_closed_pairs_before: None,
233 auto_closed_pairs_after: None,
234 });
235 self.coalescing_boundary = intent == EditIntent::Atomic;
236 }
237
238 /// Record the cursors around the transaction being built, or around the
239 /// most recent one when no bracket is open.
240 ///
241 /// A transaction keeps the cursors it was entered with, so a coalescing
242 /// burst of keystrokes still undoes to where the burst began.
243 pub(super) fn record_selections(
244 &mut self,
245 before: Vec<CursorSelection>,
246 after: Vec<CursorSelection>,
247 ) {
248 if self.ignoring {
249 return;
250 }
251 self.record_selections_before(before);
252 self.record_selections_after(after);
253 }
254
255 pub(super) fn record_auto_closed_pairs(
256 &mut self,
257 before: AutoClosedPairs,
258 after: AutoClosedPairs,
259 ) {
260 if self.ignoring {
261 return;
262 }
263 if let Some(pending) = self.pending.as_mut() {
264 pending.auto_closed_pairs_before.get_or_insert(before);
265 } else if let Some(transaction) = self.undo_transactions.last_mut() {
266 transaction.auto_closed_pairs_before.get_or_insert(before);
267 }
268 self.record_auto_closed_pairs_after(after);
269 }
270
271 pub(super) fn record_auto_closed_pairs_after(&mut self, after: AutoClosedPairs) {
272 if self.ignoring {
273 return;
274 }
275 if let Some(pending) = self.pending.as_mut() {
276 pending.auto_closed_pairs_after = Some(after);
277 } else if let Some(transaction) = self.undo_transactions.last_mut() {
278 transaction.auto_closed_pairs_after = Some(after);
279 }
280 }
281
282 fn record_selections_before(&mut self, before: Vec<CursorSelection>) {
283 if let Some(pending) = self.pending.as_mut() {
284 pending.selections_before.get_or_insert(before);
285 } else if let Some(transaction) = self.undo_transactions.last_mut() {
286 transaction.selections_before.get_or_insert(before);
287 }
288 }
289
290 fn record_selections_after(&mut self, after: Vec<CursorSelection>) {
291 if let Some(pending) = self.pending.as_mut() {
292 pending.selections_after = Some(after);
293 } else if let Some(transaction) = self.undo_transactions.last_mut() {
294 transaction.selections_after = Some(after);
295 }
296 }
297
298 /// True while a `begin_transaction` bracket is collecting changes.
299 pub(super) fn has_open_transaction(&self) -> bool {
300 self.transaction_depth > 0
301 }
302
303 pub(super) fn break_transaction_coalescing(&mut self) {
304 // While a batch is open the boundary applies to that batch, so never
305 // close a bracket the caller still owns.
306 if self.transaction_depth == 0 {
307 self.commit_all_transactions();
308 }
309 self.coalescing_boundary = true;
310 }
311
312 /// Close every open bracket, committing whatever they collected.
313 fn commit_all_transactions(&mut self) {
314 if self.transaction_depth == 0 {
315 return;
316 }
317 self.transaction_depth = 1;
318 self.commit_transaction();
319 }
320
321 pub(super) fn is_ignoring(&self) -> bool {
322 self.ignoring
323 }
324
325 pub(super) fn set_ignoring(&mut self, ignoring: bool) {
326 self.ignoring = ignoring;
327 if ignoring {
328 self.commit_all_transactions();
329 }
330 }
331
332 pub(super) fn clear(&mut self) {
333 self.undo_transactions.clear();
334 self.redo_transactions.clear();
335 self.transaction_depth = 0;
336 self.pending = None;
337 self.pending_intent = None;
338 self.coalescing_boundary = false;
339 }
340
341 pub(super) fn undo(&mut self) -> Option<Replay> {
342 self.commit_all_transactions();
343 let transaction = self.undo_transactions.pop()?;
344 let replay = Replay {
345 changes: transaction.changes.iter().rev().cloned().collect(),
346 selections: transaction.selections_before.clone(),
347 auto_closed_pairs: transaction.auto_closed_pairs_before.clone(),
348 };
349 self.redo_transactions.push(transaction);
350 self.coalescing_boundary = true;
351 Some(replay)
352 }
353
354 pub(super) fn redo(&mut self) -> Option<Replay> {
355 self.commit_all_transactions();
356 let transaction = self.redo_transactions.pop()?;
357 let replay = Replay {
358 changes: transaction.changes.clone(),
359 selections: transaction.selections_after.clone(),
360 auto_closed_pairs: transaction.auto_closed_pairs_after.clone(),
361 };
362 self.undo_transactions.push(transaction);
363 self.coalescing_boundary = true;
364 Some(replay)
365 }
366
367 #[cfg(test)]
368 pub(super) fn has_undos(&self) -> bool {
369 !self.undo_transactions.is_empty()
370 }
371
372 #[cfg(test)]
373 pub(super) fn undo_count(&self) -> usize {
374 self.undo_transactions.len()
375 }
376}
377
378impl UndoTransaction {
379 /// The changes contributed by the most recent batch, which are the ones a
380 /// following batch has to be adjacent to.
381 fn trailing_batch(&self) -> &[Change] {
382 &self.changes[self.changes.len() - self.last_batch_len..]
383 }
384}
385
386/// True when a chain of changes that each rewrite the region the previous one
387/// produced leaves the document exactly as it was found.
388///
389/// Changes that do not form such a chain (multi-cursor batches, for one) always
390/// report `false`, so this only ever collapses the single-region case.
391fn is_noop_batch(changes: &[Change]) -> bool {
392 if changes.iter().any(|c| c.token_delta.is_some()) {
393 return false;
394 }
395 let Some(first) = changes.first() else {
396 return true;
397 };
398
399 let mut last = first;
400 for change in &changes[1..] {
401 if last.new_range.start != change.old_range.start
402 || last.new_range.end != change.old_range.end
403 {
404 return false;
405 }
406 last = change;
407 }
408
409 first.old_range.start == last.new_range.start
410 && first.old_range.end == last.new_range.end
411 && first.old_text == last.new_text
412}
413
414/// True when every change in `current` continues the change at the same
415/// position in `previous`, so the two batches are one editing gesture.
416///
417/// A batch applies from the highest offset down, so each of its changes is
418/// still to be shifted by the ones that follow it before the next batch, made
419/// against the settled document, can line up with it.
420fn is_adjacent_batch(intent: EditIntent, previous: &[Change], current: &[Change]) -> bool {
421 if previous.len() != current.len() {
422 return false;
423 }
424
425 let mut shifts = vec![0isize; previous.len()];
426 let mut shift = 0isize;
427 for (index, change) in previous.iter().enumerate().rev() {
428 shifts[index] = shift;
429 shift += change.new_text.len() as isize - change.old_text.len() as isize;
430 }
431
432 previous
433 .iter()
434 .zip(current)
435 .zip(shifts)
436 .all(|((previous, current), shift)| is_adjacent(intent, &previous.shifted(shift), current))
437}
438
439fn is_adjacent(intent: EditIntent, previous: &Change, current: &Change) -> bool {
440 if previous.token_delta.is_some() || current.token_delta.is_some() {
441 return false;
442 }
443 match intent {
444 EditIntent::Typing => {
445 previous.old_range.is_empty()
446 && !previous.new_text.contains(['\n', '\r'])
447 && !current.new_text.contains(['\n', '\r'])
448 && previous.new_range.start <= current.old_range.start
449 && previous.new_range.end == current.old_range.end
450 }
451 EditIntent::Backspace => {
452 previous.new_text.is_empty()
453 && current.new_text.is_empty()
454 && current.old_range.end == previous.old_range.start
455 }
456 EditIntent::DeleteForward => {
457 previous.new_text.is_empty()
458 && current.new_text.is_empty()
459 && current.old_range.start == previous.old_range.start
460 }
461 EditIntent::Atomic => false,
462 }
463}
464
465#[cfg(test)]
466mod tests {
467 use super::*;
468
469 fn typing_change(offset: usize, text: &str) -> Change {
470 let end = offset + text.len();
471 Change::new(offset..offset, "", offset..end, text)
472 }
473
474 #[test]
475 fn adjacent_typing_transactions_coalesce() {
476 let mut manager = UndoManager::new();
477 manager.record_transaction(typing_change(0, "a"), EditIntent::Typing);
478 manager.record_transaction(typing_change(1, "b"), EditIntent::Typing);
479
480 // The run is kept as one insertion, so undo replays a single change.
481 assert_eq!(manager.undo().unwrap().changes, [typing_change(0, "ab")]);
482 assert!(manager.undo().is_none());
483 }
484
485 #[test]
486 fn explicit_transaction_collects_multiple_changes() {
487 let mut manager = UndoManager::new();
488 manager.begin_transaction();
489 manager.record_transaction(typing_change(0, "a"), EditIntent::Typing);
490 manager.record_transaction(typing_change(1, "b"), EditIntent::Typing);
491 manager.commit_transaction();
492
493 // One undo entry that replays its changes in reverse application
494 // order.
495 let transaction = manager.undo().unwrap().changes;
496 assert_eq!(transaction.len(), 2);
497 assert_eq!(transaction[0].new_text, "b");
498 assert_eq!(transaction[1].new_text, "a");
499 assert!(manager.undo().is_none());
500 }
501
502 #[test]
503 fn nested_transactions_commit_as_one_entry() {
504 let mut manager = UndoManager::new();
505 manager.begin_transaction();
506 manager.record_transaction(typing_change(0, "a"), EditIntent::Typing);
507 manager.begin_transaction();
508 manager.record_transaction(typing_change(1, "b"), EditIntent::Typing);
509 manager.commit_transaction();
510 // The inner bracket does not close the transaction.
511 assert!(!manager.has_undos());
512 manager.record_transaction(typing_change(2, "c"), EditIntent::Typing);
513 manager.commit_transaction();
514
515 assert_eq!(manager.undo().unwrap().changes.len(), 3);
516 assert!(manager.undo().is_none());
517 }
518
519 #[test]
520 fn batches_of_the_same_shape_and_intent_coalesce() {
521 let mut manager = UndoManager::new();
522
523 // Two cursors typing "a" then "b", as a multi-cursor keystroke burst.
524 // A batch applies from the highest offset down, and the second burst
525 // sees the offsets the first one left behind.
526 manager.begin_transaction_with(EditIntent::Typing);
527 manager.record_transaction(typing_change(5, "a"), EditIntent::Typing);
528 manager.record_transaction(typing_change(0, "a"), EditIntent::Typing);
529 manager.commit_transaction();
530 manager.begin_transaction_with(EditIntent::Typing);
531 manager.record_transaction(typing_change(7, "b"), EditIntent::Typing);
532 manager.record_transaction(typing_change(1, "b"), EditIntent::Typing);
533 manager.commit_transaction();
534
535 assert_eq!(manager.undo().unwrap().changes.len(), 4);
536 assert!(manager.undo().is_none());
537 }
538
539 #[test]
540 fn a_batch_does_not_coalesce_into_a_differently_shaped_one() {
541 let mut manager = UndoManager::new();
542
543 manager.begin_transaction_with(EditIntent::Typing);
544 manager.record_transaction(typing_change(5, "a"), EditIntent::Typing);
545 manager.record_transaction(typing_change(0, "a"), EditIntent::Typing);
546 manager.commit_transaction();
547 // One cursor left: a single change cannot continue a two-cursor batch.
548 manager.record_transaction(typing_change(1, "b"), EditIntent::Typing);
549
550 assert_eq!(manager.undo().unwrap().changes.len(), 1);
551 assert_eq!(manager.undo().unwrap().changes.len(), 2);
552 }
553
554 #[test]
555 fn an_atomic_batch_never_coalesces() {
556 let mut manager = UndoManager::new();
557
558 manager.begin_transaction();
559 manager.record_transaction(typing_change(0, "a"), EditIntent::Typing);
560 manager.commit_transaction();
561 manager.record_transaction(typing_change(1, "b"), EditIntent::Typing);
562
563 assert_eq!(manager.undo().unwrap().changes.len(), 1);
564 assert_eq!(manager.undo().unwrap().changes.len(), 1);
565 }
566
567 #[test]
568 fn limits_the_number_of_retained_transactions() {
569 let mut manager = UndoManager::new();
570
571 for offset in 0..1_100 {
572 manager.record_transaction(typing_change(offset, "a"), EditIntent::Atomic);
573 }
574
575 for _ in 0..MAX_UNDO_TRANSACTIONS {
576 assert!(manager.undo().is_some());
577 }
578 assert!(manager.undo().is_none());
579 }
580
581 #[test]
582 fn splits_a_coalesced_transaction_before_its_change_list_grows_too_large() {
583 let mut manager = UndoManager::new();
584
585 for offset in 0..1_100 {
586 manager.record_transaction(typing_change(offset, "a"), EditIntent::Typing);
587 }
588
589 // Each run is merged into one insertion, but the split still happens
590 // after the same number of keystrokes.
591 assert_eq!(
592 manager.undo().unwrap().changes,
593 [typing_change(MAX_CHANGES_PER_TRANSACTION, &"a".repeat(100))]
594 );
595 assert_eq!(
596 manager.undo().unwrap().changes,
597 [typing_change(0, &"a".repeat(MAX_CHANGES_PER_TRANSACTION))]
598 );
599 assert!(manager.undo().is_none());
600 }
601}