Skip to main content

openbim_ifc_binding_core/
history.rs

1//! Undo and redo for every mutator (#465).
2//!
3//! History is off by default: [`IfcModel::set_history_limit`] turns it on
4//! with a bound on the number of undo entries. While it is on, each public
5//! mutator is one entry: the exact inverse of every primitive write it made,
6//! recorded by `ifc::History::track`. [`IfcModel::undo`] restores the model
7//! to the state before the last entry (entities under their ids, at their
8//! file positions, the header included) and [`IfcModel::redo`] reverses an
9//! undo. A mutator that is refused and changed nothing records nothing; a
10//! dry run records nothing.
11//!
12//! Undoing the creation of an entity frees its id again, so a later call may
13//! reuse it. Undo and redo are new changes: the model revision moves on.
14//!
15//! A change made outside the history (a mutator while the limit was 0, or a
16//! write through the facade) makes the stacks stale: `undo` and `redo` are
17//! refused with `history-stale` and change nothing, and the next recorded
18//! change drops the stale entries. An empty stack is `history-empty`.
19
20use crate::record::{Field, Record, ToRecord};
21use crate::{BindingError, IfcModel};
22
23/// How much history a model holds: [`IfcModel::history`].
24#[derive(Debug, Clone, Copy, PartialEq, Eq)]
25pub struct HistoryState {
26    /// The bound on undo entries; `0` records nothing.
27    pub limit: usize,
28    /// Entries [`IfcModel::undo`] can step back through.
29    pub undo: usize,
30    /// Entries [`IfcModel::redo`] can step forward through.
31    pub redo: usize,
32}
33
34/// What an undo or redo restores (or would restore): ids in order of
35/// first occurrence in the change.
36#[derive(Debug, Clone, PartialEq, Eq)]
37pub struct HistoryChange {
38    /// Entities absent before the application, present after it.
39    pub created: Vec<u64>,
40    /// Entities present before the application, absent after it.
41    pub removed: Vec<u64>,
42    /// Entities present both times whose content changed.
43    pub modified: Vec<u64>,
44    /// Whether the file header changed.
45    pub header: bool,
46}
47
48impl ToRecord for HistoryState {
49    fn to_record(&self) -> Record {
50        Record::new(
51            "HistoryState",
52            vec![
53                ("limit", Field::Count(self.limit)),
54                ("undo", Field::Count(self.undo)),
55                ("redo", Field::Count(self.redo)),
56            ],
57        )
58    }
59}
60
61impl ToRecord for HistoryChange {
62    fn to_record(&self) -> Record {
63        Record::new(
64            "HistoryChange",
65            vec![
66                ("created", Field::ids(self.created.iter().copied())),
67                ("removed", Field::ids(self.removed.iter().copied())),
68                ("modified", Field::ids(self.modified.iter().copied())),
69                ("header", Field::Bool(self.header)),
70            ],
71        )
72    }
73}
74
75impl From<ifc::Restored> for HistoryChange {
76    fn from(restored: ifc::Restored) -> Self {
77        let ids = |ids: Vec<ifc::EntityId>| ids.into_iter().map(|id| id.0).collect();
78        Self {
79            created: ids(restored.created),
80            removed: ids(restored.removed),
81            modified: ids(restored.modified),
82            header: restored.header,
83        }
84    }
85}
86
87fn refused(error: ifc::HistoryError) -> BindingError {
88    match error {
89        ifc::HistoryError::NothingToUndo => BindingError::HistoryEmpty("nothing to undo".into()),
90        ifc::HistoryError::NothingToRedo => BindingError::HistoryEmpty("nothing to redo".into()),
91        ifc::HistoryError::StaleRevision { .. } => BindingError::HistoryStale(error.to_string()),
92        other => BindingError::Unsupported(other.to_string()),
93    }
94}
95
96impl IfcModel {
97    /// Run a mutator so that, when history is on, what it changes becomes
98    /// one entry. Nested calls (`author` inside `create_entity`) join the
99    /// outer entry; a panic drops the history, whose stacks no longer
100    /// describe the model.
101    pub(crate) fn tracked<T>(&mut self, change: impl FnOnce(&mut Self) -> T) -> T {
102        if self.history.limit() == 0 || self.inner.is_recording() {
103            return change(self);
104        }
105        self.inner.begin_recording();
106        let outcome = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| change(&mut *self)));
107        let inverse = self.inner.end_recording();
108        match outcome {
109            Ok(value) => {
110                if let Some(inverse) = inverse {
111                    self.history.push(inverse);
112                }
113                value
114            }
115            Err(panic) => {
116                self.history.clear();
117                std::panic::resume_unwind(panic)
118            }
119        }
120    }
121
122    /// Bound the undo entries kept; `0` turns history off and drops what
123    /// is held. Lowering the limit drops the oldest entries.
124    pub fn set_history_limit(&mut self, limit: usize) {
125        self.history.set_limit(limit);
126        if limit == 0 {
127            self.history.clear();
128        }
129    }
130
131    /// The history bound and how many entries each direction holds.
132    pub fn history(&self) -> HistoryState {
133        HistoryState {
134            limit: self.history.limit(),
135            undo: self.history.undo_len(),
136            redo: self.history.redo_len(),
137        }
138    }
139
140    /// What [`Self::undo`] would change, without changing anything.
141    ///
142    /// Refused with `history-empty` when there is nothing to undo and
143    /// `history-stale` when the model changed outside the history.
144    pub fn peek_undo(&self) -> Result<HistoryChange, BindingError> {
145        self.history
146            .peek_undo(&self.inner)
147            .map(Into::into)
148            .map_err(refused)
149    }
150
151    /// What [`Self::redo`] would change, without changing anything.
152    pub fn peek_redo(&self) -> Result<HistoryChange, BindingError> {
153        self.history
154            .peek_redo(&self.inner)
155            .map(Into::into)
156            .map_err(refused)
157    }
158
159    /// Restore the model to the state before the last recorded change.
160    /// A refusal changes nothing.
161    pub fn undo(&mut self) -> Result<HistoryChange, BindingError> {
162        self.history
163            .undo(&mut self.inner)
164            .map(Into::into)
165            .map_err(refused)
166    }
167
168    /// Reverse the last [`Self::undo`]. A refusal changes nothing.
169    pub fn redo(&mut self) -> Result<HistoryChange, BindingError> {
170        self.history
171            .redo(&mut self.inner)
172            .map(Into::into)
173            .map_err(refused)
174    }
175
176    /// Drop every undo and redo entry, keeping the limit.
177    pub fn clear_history(&mut self) {
178        self.history.clear();
179    }
180}
181
182#[cfg(test)]
183mod tests {
184    use super::*;
185    use crate::value::Tagged;
186
187    #[test]
188    fn a_write_outside_the_history_makes_it_stale() {
189        let mut model = IfcModel::empty();
190        model.set_history_limit(4);
191        let id = model
192            .add("IFCLABEL", vec![Tagged::Text("a".into())])
193            .unwrap();
194        // A write the history did not see: the facade, not a tracked call.
195        model.inner.push(ifc::Entity::new("IFCLABEL", Vec::new()));
196        let stale = model.undo().unwrap_err();
197        assert_eq!(stale.code(), "history-stale");
198        assert_eq!(model.peek_undo().unwrap_err().code(), "history-stale");
199        assert_eq!(model.history().undo, 1, "a refusal keeps the entries");
200        assert!(model.type_of(id).is_ok());
201
202        // The next recorded change drops the stale entries.
203        model
204            .add("IFCLABEL", vec![Tagged::Text("b".into())])
205            .unwrap();
206        assert_eq!(model.history().undo, 1);
207        model.undo().unwrap();
208        assert_eq!(model.undo().unwrap_err().code(), "history-empty");
209    }
210
211    #[test]
212    fn a_panic_drops_the_history() {
213        let mut model = IfcModel::empty();
214        model.set_history_limit(4);
215        model
216            .add("IFCLABEL", vec![Tagged::Text("a".into())])
217            .unwrap();
218        let panicked = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
219            model.tracked(|this| {
220                this.add("IFCLABEL", vec![Tagged::Text("b".into())])
221                    .unwrap();
222                panic!("boom");
223            })
224        }));
225        assert!(panicked.is_err());
226        assert_eq!(model.history().undo, 0);
227        assert!(!model.inner.is_recording());
228    }
229}