ifc_model/mutation/history.rs
1//! A bounded undo and redo history over [`Inverse`]s.
2//!
3//! One entry is one tracked change: a batch of authoring operations, a
4//! property edit, a single `set_attribute`. [`History::track`] runs the
5//! change and keeps its inverse; [`History::undo`] and [`History::redo`]
6//! move entries between the two stacks.
7//!
8//! # Staleness
9//!
10//! The history is valid for one model revision. Anything that changes the
11//! model outside the history (an untracked write) makes [`History::undo`] and
12//! [`History::redo`] return [`HistoryError::StaleRevision`] and change
13//! nothing, because the entries no longer describe the model. The next
14//! [`History::push`] or [`History::track`] whose change began at another
15//! revision clears both stacks first.
16//!
17//! The bound counts entries, not bytes: removed entities stay in memory until
18//! their entry is dropped.
19//!
20//! A [`Model::preview`] is not a change; the history stays valid across it.
21//!
22//! ```
23//! use ifc_model::{Entity, History, Model};
24//!
25//! let mut model = Model::new();
26//! let mut history = History::new(8);
27//! let id = history.track(&mut model, |m| m.push(Entity::new("IFCWALL", vec![])));
28//! assert!(model.contains(id));
29//!
30//! history.undo(&mut model).unwrap();
31//! assert!(model.is_empty());
32//! history.redo(&mut model).unwrap();
33//! assert!(model.contains(id));
34//! ```
35
36use std::collections::VecDeque;
37
38use crate::model::Model;
39use crate::mutation::inverse::{Inverse, Restored};
40
41/// A bounded undo and redo history. See the module docs.
42#[derive(Debug, Clone, Default)]
43pub struct History {
44 undo: VecDeque<Inverse>,
45 redo: Vec<Inverse>,
46 limit: usize,
47 /// The model revision both stacks describe; `Some` exactly when a stack
48 /// is not empty.
49 revision: Option<u64>,
50}
51
52/// Why an undo or redo did not happen.
53#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
54#[non_exhaustive]
55pub enum HistoryError {
56 /// The undo stack is empty.
57 #[error("nothing to undo")]
58 NothingToUndo,
59 /// The redo stack is empty.
60 #[error("nothing to redo")]
61 NothingToRedo,
62 /// The model changed outside the history.
63 #[error("model moved from revision {expected} to {found} outside the history")]
64 StaleRevision {
65 /// The revision the history describes.
66 expected: u64,
67 /// The model's revision.
68 found: u64,
69 },
70}
71
72impl History {
73 /// A history keeping at most `limit` undo entries; 0 disables it.
74 #[must_use]
75 pub fn new(limit: usize) -> Self {
76 Self {
77 limit,
78 ..Self::default()
79 }
80 }
81
82 /// The most undo entries kept.
83 #[must_use]
84 pub fn limit(&self) -> usize {
85 self.limit
86 }
87
88 /// Change the bound, dropping the oldest undo entries and the farthest
89 /// redo entries beyond it.
90 pub fn set_limit(&mut self, limit: usize) {
91 self.limit = limit;
92 self.trim();
93 }
94
95 /// Entries [`History::undo`] can step back through.
96 #[must_use]
97 pub fn undo_len(&self) -> usize {
98 self.undo.len()
99 }
100
101 /// Entries [`History::redo`] can step forward through.
102 #[must_use]
103 pub fn redo_len(&self) -> usize {
104 self.redo.len()
105 }
106
107 /// Whether [`History::undo`] has an entry.
108 #[must_use]
109 pub fn can_undo(&self) -> bool {
110 !self.undo.is_empty()
111 }
112
113 /// Whether [`History::redo`] has an entry.
114 #[must_use]
115 pub fn can_redo(&self) -> bool {
116 !self.redo.is_empty()
117 }
118
119 /// Drop every entry.
120 pub fn clear(&mut self) {
121 self.undo.clear();
122 self.redo.clear();
123 self.revision = None;
124 }
125
126 /// Keep `inverse` as the newest undo entry and clear redo.
127 ///
128 /// Ignored when the history is disabled or the inverse is empty. If the
129 /// inverse began at a revision the history does not describe, the old
130 /// entries are dropped first.
131 pub fn push(&mut self, inverse: Inverse) {
132 if self.limit == 0 || inverse.is_empty() {
133 return;
134 }
135 if self.revision.is_some_and(|r| r != inverse.before()) {
136 self.clear();
137 }
138 self.redo.clear();
139 self.revision = Some(inverse.revision());
140 self.undo.push_back(inverse);
141 self.trim();
142 }
143
144 /// Run `change` on `model` and keep the inverse of what it wrote as one
145 /// entry.
146 ///
147 /// Whatever `change` wrote is kept whether it returned `Ok` or `Err`;
148 /// nothing is rolled back. With a limit of 0 the change runs unrecorded.
149 pub fn track<T>(&mut self, model: &mut Model, change: impl FnOnce(&mut Model) -> T) -> T {
150 if self.limit == 0 {
151 return change(model);
152 }
153 let (value, inverse) = Inverse::record(model, change);
154 self.push(inverse);
155 value
156 }
157
158 /// What [`History::undo`] would change, without changing it.
159 pub fn peek_undo(&self, model: &Model) -> Result<Restored, HistoryError> {
160 let entry = self.undo.back().ok_or(HistoryError::NothingToUndo)?;
161 self.check(model)?;
162 Ok(entry.summary(model))
163 }
164
165 /// What [`History::redo`] would change, without changing it.
166 pub fn peek_redo(&self, model: &Model) -> Result<Restored, HistoryError> {
167 let entry = self.redo.last().ok_or(HistoryError::NothingToRedo)?;
168 self.check(model)?;
169 Ok(entry.summary(model))
170 }
171
172 /// Undo the newest entry.
173 pub fn undo(&mut self, model: &mut Model) -> Result<Restored, HistoryError> {
174 let (restored, redo) = self.step_back(model)?;
175 if !redo.is_empty() {
176 self.redo.push(redo);
177 }
178 self.settle(model);
179 Ok(restored)
180 }
181
182 /// Undo the newest entry and forget it: the model changes exactly as
183 /// [`History::undo`] changes it, with the same revision check and the
184 /// same refusals (the history is unchanged on a refusal), but the entry
185 /// is dropped instead of moved to the redo stack.
186 ///
187 /// For a change that is abandoned, not undone by the user. Redo is
188 /// cleared, as [`History::push`] clears it: the model moved to a state
189 /// the redo entries were not recorded against, so redoing them would
190 /// replay onto the wrong base. In the usual case (the newest entry just
191 /// tracked) redo was empty already and stays empty.
192 pub fn rollback(&mut self, model: &mut Model) -> Result<Restored, HistoryError> {
193 let (restored, _redo) = self.step_back(model)?;
194 self.redo.clear();
195 self.settle(model);
196 Ok(restored)
197 }
198
199 /// Pop the newest undo entry and apply it; return what it restored and
200 /// its inverse. Nothing changes when it refuses.
201 fn step_back(&mut self, model: &mut Model) -> Result<(Restored, Inverse), HistoryError> {
202 if self.undo.is_empty() {
203 return Err(HistoryError::NothingToUndo);
204 }
205 self.check(model)?;
206 let mut entry = self.undo.pop_back().expect("checked non-empty");
207 entry.rebase(model.revision());
208 Ok(entry
209 .apply(model)
210 .expect("the entry was rebased to the current revision"))
211 }
212
213 /// Redo the most recently undone entry.
214 pub fn redo(&mut self, model: &mut Model) -> Result<Restored, HistoryError> {
215 if self.redo.is_empty() {
216 return Err(HistoryError::NothingToRedo);
217 }
218 self.check(model)?;
219 let mut entry = self.redo.pop().expect("checked non-empty");
220 entry.rebase(model.revision());
221 let (restored, undo) = entry
222 .apply(model)
223 .expect("the entry was rebased to the current revision");
224 if !undo.is_empty() {
225 self.undo.push_back(undo);
226 }
227 self.settle(model);
228 Ok(restored)
229 }
230
231 fn check(&self, model: &Model) -> Result<(), HistoryError> {
232 match self.revision {
233 Some(expected) if expected != model.revision() => Err(HistoryError::StaleRevision {
234 expected,
235 found: model.revision(),
236 }),
237 _ => Ok(()),
238 }
239 }
240
241 /// After a move between the stacks: follow the model's new revision.
242 fn settle(&mut self, model: &Model) {
243 self.trim();
244 if self.undo.is_empty() && self.redo.is_empty() {
245 self.revision = None;
246 } else {
247 self.revision = Some(model.revision());
248 }
249 }
250
251 fn trim(&mut self) {
252 while self.undo.len() > self.limit {
253 self.undo.pop_front();
254 }
255 if self.redo.len() > self.limit {
256 let excess = self.redo.len() - self.limit;
257 self.redo.drain(..excess);
258 }
259 if self.undo.is_empty() && self.redo.is_empty() {
260 self.revision = None;
261 }
262 }
263}