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
//! A history tree of edit commands.

mod builder;
mod checkpoint;
mod display;
mod queue;

pub use builder::Builder;
pub use checkpoint::Checkpoint;
pub use display::Display;
pub use queue::Queue;

use crate::socket::Slot;
use crate::{At, Edit, Entry, Event, Record};
use alloc::collections::{BTreeMap, VecDeque};
use alloc::string::String;
use alloc::vec::Vec;
use core::fmt;
#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};

/// A history tree of [`Edit`] commands.
///
/// Unlike [`Record`] which maintains a linear undo history,
/// [`History`] maintains an undo tree containing every edit made to the target.
///
/// See [this](https://github.com/evenorog/undo/blob/master/examples/history.rs)
/// example for an interactive view of the history tree.
///
/// # Examples
/// ```
/// # use undo::{Add, History};
/// let mut target = String::new();
/// let mut history = History::new();
///
/// history.edit(&mut target, Add('a'));
/// history.edit(&mut target, Add('b'));
/// history.edit(&mut target, Add('c'));
/// let abc = history.head();
///
/// history.undo(&mut target);
/// history.undo(&mut target);
/// assert_eq!(target, "a");
///
/// // Instead of discarding 'b' and 'c', a new branch is created.
/// history.edit(&mut target, Add('f'));
/// history.edit(&mut target, Add('g'));
/// assert_eq!(target, "afg");
///
/// // We can now switch back to the original branch.
/// history.go_to(&mut target, abc);
/// assert_eq!(target, "abc");
/// ```
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[derive(Clone, Debug)]
pub struct History<E, S = ()> {
    root: usize,
    next: usize,
    saved: Option<At>,
    record: Record<E, S>,
    branches: BTreeMap<usize, Branch<E>>,
}

impl<E> History<E> {
    /// Returns a new history.
    pub fn new() -> History<E> {
        History::builder().build()
    }
}

impl<E, S> History<E, S> {
    /// Returns a new history builder.
    pub fn builder() -> Builder<E, S> {
        Builder::default()
    }

    /// Reserves capacity for at least `additional` more edits.
    ///
    /// # Panics
    /// Panics if the new capacity overflows usize.
    pub fn reserve(&mut self, additional: usize) {
        self.record.reserve(additional);
    }

    /// Returns the capacity of the history.
    pub fn capacity(&self) -> usize {
        self.record.capacity()
    }

    /// Shrinks the capacity of the history as much as possible.
    pub fn shrink_to_fit(&mut self) {
        self.record.shrink_to_fit();
    }

    /// Returns the number of edits in the current branch of the history.
    pub fn len(&self) -> usize {
        self.record.len()
    }

    /// Returns `true` if the current branch of the history is empty.
    pub fn is_empty(&self) -> bool {
        self.record.is_empty()
    }

    /// Returns the limit of the history.
    pub fn limit(&self) -> usize {
        self.record.limit()
    }

    /// Sets how the event should be handled when the state changes.
    pub fn connect(&mut self, slot: S) -> Option<S> {
        self.record.connect(slot)
    }

    /// Removes and returns the slot if it exists.
    pub fn disconnect(&mut self) -> Option<S> {
        self.record.disconnect()
    }

    /// Returns `true` if the target is in a saved state, `false` otherwise.
    pub fn is_saved(&self) -> bool {
        self.record.is_saved()
    }

    /// Return the position of the saved state.
    pub fn saved(&self) -> Option<At> {
        self.record
            .saved
            .map(|index| At::new(self.root, index))
            .or(self.saved)
    }

    /// Returns `true` if the history can undo.
    pub fn can_undo(&self) -> bool {
        self.record.can_undo()
    }

    /// Returns `true` if the history can redo.
    pub fn can_redo(&self) -> bool {
        self.record.can_redo()
    }

    /// Returns the current position in the history.
    pub fn head(&self) -> At {
        At::new(self.root, self.record.index)
    }

    /// Returns the head of the next branch in the history.
    ///
    /// This will be the first edit that was stored in the branch.
    /// This can be used in combination with [`History::go_to`] to go to the next branch.
    pub fn next_branch_head(&self) -> Option<At> {
        self.branches
            .range(self.root + 1..)
            .next()
            .map(|(&id, branch)| At::new(id, branch.parent.index + 1))
    }

    /// Returns the head of the previous branch in the history.
    ///
    /// This will be the first edit that was stored in the branch.
    /// This can be used in combination with [`History::go_to`] to go to the previous branch.
    pub fn prev_branch_head(&self) -> Option<At> {
        self.branches
            .range(..self.root)
            .next_back()
            .map(|(&id, branch)| At::new(id, branch.parent.index + 1))
    }

    /// Returns the entry at the index in the current root branch.
    ///
    /// Use [History::get_branch] if you want to get entry from other branches.
    pub fn get_entry(&self, index: usize) -> Option<&Entry<E>> {
        self.record.get_entry(index)
    }

    /// Returns an iterator over the entries in the current root branch.
    pub fn entries(&self) -> impl Iterator<Item = &Entry<E>> {
        self.record.entries()
    }

    /// Returns the branch with the given id.
    pub fn get_branch(&self, id: usize) -> Option<&Branch<E>> {
        self.branches.get(&id)
    }

    /// Returns an iterator over the branches in the history.
    ///
    /// This does not include the current root branch.
    pub fn branches(&self) -> impl Iterator<Item = (&usize, &Branch<E>)> {
        self.branches.iter()
    }

    /// Returns a queue.
    pub fn queue(&mut self) -> Queue<E, S> {
        Queue::from(self)
    }

    /// Returns a checkpoint.
    pub fn checkpoint(&mut self) -> Checkpoint<E, S> {
        Checkpoint::from(self)
    }

    /// Returns a structure for configurable formatting of the history.
    pub fn display(&self) -> Display<E, S> {
        Display::from(self)
    }

    fn rm_child_of(&mut self, at: At) {
        // We need to check if any of the branches had the removed node as root.
        let mut dead: Vec<_> = self
            .branches
            .iter()
            .filter(|&(_, child)| child.parent == at)
            .map(|(&id, _)| id)
            .collect();
        while let Some(parent) = dead.pop() {
            // Remove the dead branch.
            self.branches.remove(&parent).unwrap();
            self.saved = self.saved.filter(|saved| saved.root != parent);
            // Add the children of the dead branch so they are removed too.
            dead.extend(
                self.branches
                    .iter()
                    .filter(|&(_, child)| child.parent.root == parent)
                    .map(|(&id, _)| id),
            )
        }
    }

    fn mk_path(&mut self, mut to: usize) -> Option<impl Iterator<Item = (usize, Branch<E>)>> {
        debug_assert_ne!(self.root, to);
        let mut dest = self.branches.remove(&to)?;
        let mut i = dest.parent.root;
        let mut path = alloc::vec![(to, dest)];
        while i != self.root {
            dest = self.branches.remove(&i).unwrap();
            to = i;
            i = dest.parent.root;
            path.push((to, dest));
        }

        Some(path.into_iter().rev())
    }
}

impl<E, S: Slot> History<E, S> {
    /// Marks the target as currently being in a saved or unsaved state.
    pub fn set_saved(&mut self, saved: bool) {
        self.saved = None;
        self.record.set_saved(saved);
    }

    /// Removes all edits from the history without undoing them.
    pub fn clear(&mut self) {
        let old_root = self.root;
        self.root = 0;
        self.next = 1;
        self.saved = None;
        self.record.clear();
        self.branches.clear();
        self.record.socket.emit_if(old_root != 0, || Event::Root(0));
    }

    fn set_root(&mut self, new: At, rm_saved: Option<usize>) {
        debug_assert_ne!(self.root, new.root);

        // Update all branches that are now children of the new root.
        //
        // |           | <- The old root is now a child of the new root.
        // | |         | | <- This branch is still a child of the old root.
        // |/          |/
        // |    ->    /
        // o |       o | <- This branch is now a child of the new root.
        // |/        |/
        // |         |
        //
        // If we split at 'o' all branches that are children of 'o' or below should now
        // be children of the new root. All branches that are above should still be
        // children of the old root.
        self.branches
            .values_mut()
            .filter(|child| child.parent.root == self.root && child.parent.index <= new.index)
            .for_each(|child| child.parent.root = new.root);

        match (self.saved, rm_saved) {
            (Some(saved), None) if saved.root == new.root => {
                self.saved = None;
                self.record.saved = Some(saved.index);
            }
            (None, Some(saved)) => {
                self.saved = Some(At::new(self.root, saved));
            }
            _ => (),
        }

        debug_assert_ne!(self.saved.map(|s| s.root), Some(new.root));

        self.root = new.root;
        self.record.socket.emit(|| Event::Root(new.root));
    }

    fn jump_to(&mut self, root: usize) {
        let mut branch = self.branches.remove(&root).unwrap();
        debug_assert_eq!(branch.parent, self.head());

        let parent = At::new(root, self.record.index);
        let (tail, rm_saved) = self.record.rm_tail();
        self.record.entries.append(&mut branch.entries);
        self.branches.insert(self.root, Branch::new(parent, tail));
        self.set_root(parent, rm_saved);
    }
}

impl<E: Edit, S: Slot> History<E, S> {
    /// Pushes the [`Edit`] to the top of the history and executes its [`Edit::edit`] method.
    pub fn edit(&mut self, target: &mut E::Target, edit: E) -> E::Output {
        let head = self.head();
        let (output, merged, tail, rm_saved) = self.record.edit_and_push(target, edit.into());

        // Check if the limit has been reached.
        if !merged && head.index == self.record.index {
            let root = self.root;
            self.rm_child_of(At::new(root, 0));
            self.branches
                .values_mut()
                .filter(|child| child.parent.root == root)
                .for_each(|child| child.parent.index -= 1);
        }

        // Handle new branch.
        if !tail.is_empty() {
            let new = self.next;
            self.next += 1;
            let parent = At::new(new, head.index);
            self.branches.insert(head.root, Branch::new(parent, tail));
            self.set_root(parent, rm_saved);
        }

        output
    }

    /// Calls the [`Edit::undo`] method for the active edit
    /// and sets the previous one as the new active one.
    pub fn undo(&mut self, target: &mut E::Target) -> Option<E::Output> {
        self.record.undo(target)
    }

    /// Calls the [`Edit::redo`] method for the active edit
    /// and sets the next one as the new active one.
    pub fn redo(&mut self, target: &mut E::Target) -> Option<E::Output> {
        self.record.redo(target)
    }

    /// Repeatedly calls [`Edit::undo`] or [`Edit::redo`] until the edit at `at` is reached.
    pub fn go_to(&mut self, target: &mut E::Target, at: At) -> Vec<E::Output> {
        let root = self.root;
        if root == at.root {
            return self.record.go_to(target, at.index);
        }

        // Walk the path from `root` to `branch`.
        let mut outputs = Vec::new();
        let Some(path) = self.mk_path(at.root) else {
            return Vec::new();
        };

        for (new, branch) in path {
            let mut outs = self.record.go_to(target, branch.parent.index);
            outputs.append(&mut outs);
            // Apply the edits in the branch and move older edits into their own branch.
            for entry in branch.entries {
                let index = self.record.index;
                let (_, _, entries, rm_saved) = self.record.redo_and_push(target, entry);
                if !entries.is_empty() {
                    let parent = At::new(new, index);
                    self.branches
                        .insert(self.root, Branch::new(parent, entries));
                    self.set_root(parent, rm_saved);
                }
            }
        }

        let mut outs = self.record.go_to(target, at.index);
        outputs.append(&mut outs);
        outputs
    }
}

impl<E: fmt::Display, S> History<E, S> {
    /// Returns the string of the edit which will be undone
    /// in the next call to [`History::undo`].
    pub fn undo_string(&self) -> Option<String> {
        self.record.undo_string()
    }

    /// Returns the string of the edit which will be redone
    /// in the next call to [`History::redo`].
    pub fn redo_string(&self) -> Option<String> {
        self.record.redo_string()
    }
}

impl<E> Default for History<E> {
    fn default() -> History<E> {
        History::new()
    }
}

impl<E, S> From<Record<E, S>> for History<E, S> {
    fn from(record: Record<E, S>) -> Self {
        History {
            root: 0,
            next: 1,
            saved: None,
            record,
            branches: BTreeMap::new(),
        }
    }
}

impl<E, F> From<History<E, F>> for Record<E, F> {
    fn from(history: History<E, F>) -> Record<E, F> {
        history.record
    }
}

/// A branch in the history.
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[derive(Clone, Debug)]
pub struct Branch<E> {
    parent: At,
    entries: VecDeque<Entry<E>>,
}

impl<E> Branch<E> {
    fn new(parent: At, entries: VecDeque<Entry<E>>) -> Branch<E> {
        debug_assert!(!entries.is_empty());
        Branch { parent, entries }
    }

    /// Returns the parent edit of the branch.
    pub fn parent(&self) -> At {
        self.parent
    }

    /// Returns the number of edits in the branch.
    #[allow(clippy::len_without_is_empty)]
    pub fn len(&self) -> usize {
        self.entries.len()
    }

    /// Returns the edit at the index.
    pub fn get_entry(&self, index: usize) -> Option<&Entry<E>> {
        self.entries.get(index)
    }

    /// Returns an iterator over the edits in the branch.
    pub fn entries(&self) -> impl Iterator<Item = &Entry<E>> {
        self.entries.iter()
    }
}