Skip to main content

lensbench_core/
history.rs

1//! 元に戻す・やり直すの段。前の状態と段の名前を積む。serve の系の段([`System`](crate::System) の写しと
2//! 変更の記録)と GUI の組合せの段が同じ型を使う。深さを超えたら古い段を捨てる。
3//! 段をまとめる(続けて来た同じ変更を 1 段にする)かは呼ぶ側が決めて [`History::record_or_merge`] に渡す
4
5use std::collections::VecDeque;
6
7/// 元に戻せる段の既定の数
8pub const DEPTH: usize = 100;
9
10/// 元に戻す段(前の状態と、その状態から次への変更の名前 L)と、やり直す段
11#[derive(Debug, Clone)]
12pub struct History<T, L = String> {
13    undo: VecDeque<(T, L)>,
14    redo: VecDeque<(T, L)>,
15    depth: usize,
16}
17
18impl<T, L> Default for History<T, L> {
19    fn default() -> Self {
20        History::new(DEPTH)
21    }
22}
23
24impl<T, L> History<T, L> {
25    /// 深さ depth(1 以上)の空の履歴
26    pub fn new(depth: usize) -> Self {
27        History {
28            undo: VecDeque::new(),
29            redo: VecDeque::new(),
30            depth: depth.max(1),
31        }
32    }
33
34    /// 変更の前の状態 prev を積む(やり直す段は捨てる)
35    pub fn record(&mut self, prev: T, label: L) {
36        self.undo.push_back((prev, label));
37        while self.undo.len() > self.depth {
38            self.undo.pop_front();
39        }
40        self.redo.clear();
41    }
42
43    /// merge なら前の段にまとめて積まない(元に戻す段が無ければ積む)。どちらでもやり直す段は捨てる
44    pub fn record_or_merge(&mut self, prev: T, label: L, merge: bool) {
45        if merge && !self.undo.is_empty() {
46            self.redo.clear();
47        } else {
48            self.record(prev, label);
49        }
50    }
51
52    /// 1 段戻す(back)・やり直す: 今の状態 cur を反対の段に積み、戻した先の状態を返す。段が無ければ None
53    pub fn step(&mut self, cur: T, back: bool) -> Option<T> {
54        let (x, label) = self.pop(back)?;
55        self.pass(back, (cur, label));
56        Some(x)
57    }
58
59    /// 戻す(back)・やり直す段の一番上を取り出す(反対の段には積まない。[`Self::pass`] と組で使う)
60    pub fn pop(&mut self, back: bool) -> Option<(T, L)> {
61        if back {
62            self.undo.pop_back()
63        } else {
64            self.redo.pop_back()
65        }
66    }
67
68    /// [`Self::pop`] で戻した(back)・やり直した段の代わりに、反対の段へ積む(やり直す段は捨てない)
69    pub fn pass(&mut self, back: bool, item: (T, L)) {
70        if back {
71            self.redo.push_back(item);
72        } else {
73            self.undo.push_back(item);
74            while self.undo.len() > self.depth {
75                self.undo.pop_front();
76            }
77        }
78    }
79
80    /// やり直す段を捨てる
81    pub fn clear_redo(&mut self) {
82        self.redo.clear();
83    }
84
85    /// 元に戻せる(back)・やり直せる段の数
86    pub fn len(&self, back: bool) -> usize {
87        if back {
88            self.undo.len()
89        } else {
90            self.redo.len()
91        }
92    }
93
94    /// 元に戻せる(back)・やり直せる段が無い
95    pub fn is_empty(&self, back: bool) -> bool {
96        self.len(back) == 0
97    }
98
99    /// 次に戻す(back)・やり直す段
100    pub fn top(&self, back: bool) -> Option<&(T, L)> {
101        if back {
102            self.undo.back()
103        } else {
104            self.redo.back()
105        }
106    }
107
108    /// 段の名前(元に戻す段は新しい順、やり直す段は次にやり直す順)
109    pub fn labels(&self, back: bool) -> impl Iterator<Item = &L> {
110        let v = if back { &self.undo } else { &self.redo };
111        v.iter().rev().map(|x| &x.1)
112    }
113}
114
115#[cfg(test)]
116mod tests {
117    use super::*;
118
119    #[test]
120    fn record_step_and_depth() {
121        let mut h: History<i32> = History::new(3);
122        for i in 0..5 {
123            h.record(i, format!("to {}", i + 1));
124        }
125        // 深さ 3: 古い段 0・1 は捨てる
126        assert_eq!(h.len(true), 3);
127        assert_eq!(
128            h.labels(true).cloned().collect::<Vec<_>>(),
129            ["to 5", "to 4", "to 3"]
130        );
131        // 今は 5。戻すと 4、3。やり直すと 4
132        assert_eq!(h.step(5, true), Some(4));
133        assert_eq!(h.step(4, true), Some(3));
134        assert_eq!(
135            h.labels(false).cloned().collect::<Vec<_>>(),
136            ["to 4", "to 5"]
137        );
138        assert_eq!(h.step(3, false), Some(4));
139        assert_eq!(h.len(false), 1);
140        // 新しい変更でやり直す段は捨てる
141        h.record(4, "x".into());
142        assert!(h.is_empty(false));
143        assert_eq!(h.step(9, false), None);
144        // まとめる: 段は増えず、やり直す段は捨てる
145        h.step(5, true);
146        h.record_or_merge(4, "y".into(), true);
147        assert_eq!(h.len(true), 2);
148        assert!(h.is_empty(false));
149    }
150}