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
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::{Nop, Signal, Slot};
use crate::{Action, At, Entry, Record};
#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};
use std::{
collections::{BTreeMap, VecDeque},
vec,
};
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[derive(Clone, Debug)]
pub struct History<A, S = Nop> {
root: usize,
next: usize,
saved: Option<At>,
pub(crate) record: Record<A, S>,
branches: BTreeMap<usize, Branch<A>>,
}
impl<A> History<A> {
pub fn new() -> History<A> {
History::builder().build()
}
}
impl<A, S> History<A, S> {
pub fn builder() -> Builder<A, S> {
Builder::new()
}
pub fn reserve(&mut self, additional: usize) {
self.record.reserve(additional);
}
pub fn capacity(&self) -> usize {
self.record.capacity()
}
pub fn shrink_to_fit(&mut self) {
self.record.shrink_to_fit();
}
pub fn len(&self) -> usize {
self.record.len()
}
pub fn is_empty(&self) -> bool {
self.record.is_empty()
}
pub fn limit(&self) -> usize {
self.record.limit()
}
pub fn connect(&mut self, slot: S) -> Option<S> {
self.record.connect(slot)
}
pub fn disconnect(&mut self) -> Option<S> {
self.record.disconnect()
}
pub fn is_saved(&self) -> bool {
self.record.is_saved()
}
pub fn can_undo(&self) -> bool {
self.record.can_undo()
}
pub fn can_redo(&self) -> bool {
self.record.can_redo()
}
pub fn branch(&self) -> usize {
self.root
}
pub fn current(&self) -> usize {
self.record.current()
}
pub fn display(&self) -> Display<A, S> {
Display::from(self)
}
pub fn actions(&self) -> impl Iterator<Item = &A> {
self.record.actions()
}
pub fn queue(&mut self) -> Queue<A, S> {
Queue::from(self)
}
pub fn checkpoint(&mut self) -> Checkpoint<A, S> {
Checkpoint::from(self)
}
fn at(&self) -> At {
At::new(self.root, self.current())
}
}
impl<A: Action, S: Slot> History<A, S> {
pub fn apply(&mut self, target: &mut A::Target, action: A) -> A::Output {
let at = self.at();
let saved = self.record.saved.filter(|&saved| saved > at.current);
let (output, merged, tail) = self.record.__apply(target, action);
if !merged && at.current == self.current() {
let root = self.branch();
self.rm_child(root, 0);
self.branches
.values_mut()
.filter(|branch| branch.parent.branch == root)
.for_each(|branch| branch.parent.current -= 1);
}
if !tail.is_empty() {
let new = self.next;
self.next += 1;
self.branches
.insert(at.branch, Branch::new(new, at.current, tail));
self.set_root(new, at.current, saved);
}
output
}
pub fn undo(&mut self, target: &mut A::Target) -> Option<A::Output> {
self.record.undo(target)
}
pub fn redo(&mut self, target: &mut A::Target) -> Option<A::Output> {
self.record.redo(target)
}
pub fn set_saved(&mut self, saved: bool) {
self.saved = None;
self.record.set_saved(saved);
}
pub fn clear(&mut self) {
self.root = 0;
self.next = 1;
self.saved = None;
self.record.clear();
self.branches.clear();
}
pub(crate) fn jump_to(&mut self, root: usize) {
let mut branch = self.branches.remove(&root).unwrap();
debug_assert_eq!(branch.parent, self.at());
let current = self.current();
let saved = self.record.saved.filter(|&saved| saved > current);
let tail = self.record.entries.split_off(current);
self.record.entries.append(&mut branch.entries);
self.branches
.insert(self.root, Branch::new(root, current, tail));
self.set_root(root, current, saved);
}
fn set_root(&mut self, root: usize, current: usize, saved: Option<usize>) {
let old = self.branch();
self.root = root;
debug_assert_ne!(old, root);
self.branches
.values_mut()
.filter(|branch| branch.parent.branch == old && branch.parent.current <= current)
.for_each(|branch| branch.parent.branch = root);
match (self.record.saved, saved, self.saved) {
(Some(_), None, None) | (None, None, Some(_)) => self.swap_saved(root, old, current),
(None, Some(_), None) => {
self.record.saved = saved;
self.swap_saved(old, root, current);
}
(None, None, None) => (),
_ => unreachable!(),
}
}
fn swap_saved(&mut self, old: usize, new: usize, current: usize) {
debug_assert_ne!(old, new);
if let Some(At { current: saved, .. }) = self
.saved
.filter(|at| at.branch == new && at.current <= current)
{
self.saved = None;
self.record.saved = Some(saved);
self.record.socket.emit(Signal::Saved(true));
} else if let Some(saved) = self.record.saved {
self.saved = Some(At::new(old, saved));
self.record.saved = None;
self.record.socket.emit(Signal::Saved(false));
}
}
fn rm_child(&mut self, branch: usize, current: usize) {
let mut dead: Vec<_> = self
.branches
.iter()
.filter(|&(_, child)| child.parent == At::new(branch, current))
.map(|(&id, _)| id)
.collect();
while let Some(parent) = dead.pop() {
self.branches.remove(&parent).unwrap();
self.saved = self.saved.filter(|saved| saved.branch != parent);
dead.extend(
self.branches
.iter()
.filter(|&(_, child)| child.parent.branch == parent)
.map(|(&id, _)| id),
)
}
}
fn mk_path(&mut self, mut to: usize) -> Option<impl Iterator<Item = (usize, Branch<A>)>> {
debug_assert_ne!(self.branch(), to);
let mut dest = self.branches.remove(&to)?;
let mut i = dest.parent.branch;
let mut path = vec![(to, dest)];
while i != self.branch() {
dest = self.branches.remove(&i).unwrap();
to = i;
i = dest.parent.branch;
path.push((to, dest));
}
Some(path.into_iter().rev())
}
pub fn go_to(
&mut self,
target: &mut A::Target,
branch: usize,
current: usize,
) -> Vec<A::Output> {
let root = self.root;
if root == branch {
return self.record.go_to(target, current);
}
let mut outputs = Vec::new();
let Some(path) = self.mk_path(branch) else {
return Vec::new();
};
for (new, branch) in path {
let o = self.record.go_to(target, branch.parent.current);
outputs.extend(o);
for entry in branch.entries {
let current = self.current();
let saved = self.record.saved.filter(|&saved| saved > current);
let (_, _, entries) = self.record.__apply(target, entry.action);
if !entries.is_empty() {
self.branches
.insert(self.root, Branch::new(new, current, entries));
self.set_root(new, current, saved);
}
}
}
let o = self.record.go_to(target, current);
outputs.extend(o);
outputs
}
}
impl<A: ToString, S> History<A, S> {
pub fn undo_string(&self) -> Option<String> {
self.record.undo_string()
}
pub fn redo_string(&self) -> Option<String> {
self.record.redo_string()
}
}
impl<A> Default for History<A> {
fn default() -> History<A> {
History::new()
}
}
impl<A, S> From<Record<A, S>> for History<A, S> {
fn from(record: Record<A, S>) -> Self {
History {
root: 0,
next: 1,
saved: None,
record,
branches: BTreeMap::new(),
}
}
}
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[derive(Clone, Debug, Hash, Eq, PartialEq)]
pub(crate) struct Branch<A> {
pub(crate) parent: At,
pub(crate) entries: VecDeque<Entry<A>>,
}
impl<A> Branch<A> {
fn new(branch: usize, current: usize, entries: VecDeque<Entry<A>>) -> Branch<A> {
Branch {
parent: At::new(branch, current),
entries,
}
}
}
#[cfg(test)]
mod tests {
use crate::*;
struct Push(char);
impl Action for Push {
type Target = String;
type Output = ();
fn apply(&mut self, s: &mut String) {
s.push(self.0);
}
fn undo(&mut self, s: &mut String) {
self.0 = s.pop().unwrap();
}
}
#[test]
fn go_to() {
let mut target = String::new();
let mut history = History::new();
history.apply(&mut target, Push('a'));
history.apply(&mut target, Push('b'));
history.apply(&mut target, Push('c'));
history.apply(&mut target, Push('d'));
history.apply(&mut target, Push('e'));
assert_eq!(target, "abcde");
history.undo(&mut target).unwrap();
history.undo(&mut target).unwrap();
assert_eq!(target, "abc");
let abcde = history.branch();
history.apply(&mut target, Push('f'));
history.apply(&mut target, Push('g'));
assert_eq!(target, "abcfg");
history.undo(&mut target).unwrap();
let abcfg = history.branch();
history.apply(&mut target, Push('h'));
history.apply(&mut target, Push('i'));
history.apply(&mut target, Push('j'));
assert_eq!(target, "abcfhij");
history.undo(&mut target).unwrap();
let abcfhij = history.branch();
history.apply(&mut target, Push('k'));
assert_eq!(target, "abcfhik");
history.undo(&mut target).unwrap();
let abcfhik = history.branch();
history.apply(&mut target, Push('l'));
assert_eq!(target, "abcfhil");
history.apply(&mut target, Push('m'));
assert_eq!(target, "abcfhilm");
let abcfhilm = history.branch();
history.go_to(&mut target, abcde, 2);
history.apply(&mut target, Push('n'));
history.apply(&mut target, Push('o'));
assert_eq!(target, "abno");
history.undo(&mut target).unwrap();
let abno = history.branch();
history.apply(&mut target, Push('p'));
history.apply(&mut target, Push('q'));
assert_eq!(target, "abnpq");
let abnpq = history.branch();
history.go_to(&mut target, abcde, 5);
assert_eq!(target, "abcde");
history.go_to(&mut target, abcfg, 5);
assert_eq!(target, "abcfg");
history.go_to(&mut target, abcfhij, 7);
assert_eq!(target, "abcfhij");
history.go_to(&mut target, abcfhik, 7);
assert_eq!(target, "abcfhik");
history.go_to(&mut target, abcfhilm, 8);
assert_eq!(target, "abcfhilm");
history.go_to(&mut target, abno, 4);
assert_eq!(target, "abno");
history.go_to(&mut target, abnpq, 5);
assert_eq!(target, "abnpq");
}
}