1use crate::comp::{Comp, NodeId};
2use std::collections::VecDeque;
3
4/// Default maximum number of undo steps retained by [`CompHistory`].
5pub const DEFAULT_MAX_HISTORY: usize = 128;
6
7#[derive(Clone, Debug)]
8struct HistoryEntry {
9 label: String,
10 snapshot: Comp,
11 coalesce_key: Option<String>,
12}
13
14/// Snapshot-based undo/redo history stack for [`Comp`] with transaction groups and drag coalescing.
15#[derive(Clone, Debug)]
16pub struct CompHistory {
17 undo_stack: VecDeque<HistoryEntry>,
18 redo_stack: Vec<HistoryEntry>,
19 max_depth: usize,
20 active_group: Option<(String, Comp)>,
21 group_depth: usize,
22 /// Position in `undo_stack` corresponding to the last saved state (`Some(0)` means clean at
23 /// depth 0; `None` means the saved state is no longer reachable via undo/redo).
24 saved_undo_depth: Option<usize>,
25 saved_revision: Option<u64>,
26}
27
28impl Default for CompHistory {
29 fn default() -> Self {
30 Self::new()
31 }
32}
33
34impl CompHistory {
35 pub fn new() -> Self {
36 Self::with_max_depth(DEFAULT_MAX_HISTORY)
37 }
38
39 pub fn with_max_depth(max_depth: usize) -> Self {
40 Self {
41 undo_stack: VecDeque::new(),
42 redo_stack: Vec::new(),
43 max_depth: max_depth.max(1),
44 active_group: None,
45 group_depth: 0,
46 saved_undo_depth: None,
47 saved_revision: None,
48 }
49 }
50
51 pub fn max_depth(&self) -> usize {
52 self.max_depth
53 }
54
55 pub fn can_undo(&self) -> bool {
56 !self.undo_stack.is_empty()
57 }
58
59 pub fn can_redo(&self) -> bool {
60 !self.redo_stack.is_empty()
61 }
62
63 pub fn undo_len(&self) -> usize {
64 self.undo_stack.len()
65 }
66
67 pub fn redo_len(&self) -> usize {
68 self.redo_stack.len()
69 }
70
71 pub fn undo_label(&self) -> Option<&str> {
72 self.undo_stack.back().map(|e| e.label.as_str())
73 }
74
75 pub fn redo_label(&self) -> Option<&str> {
76 self.redo_stack.last().map(|e| e.label.as_str())
77 }
78
79 pub fn in_group(&self) -> bool {
80 self.group_depth > 0
81 }
82
83 /// Clears all undo/redo entries and any active transaction group.
84 pub fn clear(&mut self) {
85 self.undo_stack.clear();
86 self.redo_stack.clear();
87 self.active_group = None;
88 self.group_depth = 0;
89 self.saved_undo_depth = None;
90 self.saved_revision = None;
91 }
92
93 /// Records the current state of `comp` as the clean saved point.
94 pub fn mark_saved(&mut self, comp: &Comp) {
95 self.mark_saved_at(comp.revision);
96 }
97
98 /// Records the state at `comp_revision` as the clean saved point.
99 pub fn mark_saved_at(&mut self, comp_revision: u64) {
100 // Edits after a save must never coalesce into the saved undo entry.
101 self.break_coalescing();
102 self.saved_undo_depth = Some(self.undo_stack.len());
103 self.saved_revision = Some(comp_revision);
104 }
105
106 pub fn saved_revision(&self) -> Option<u64> {
107 self.saved_revision
108 }
109
110 /// Returns `true` if `comp` has unsaved modifications relative to the last [`Self::mark_saved`].
111 pub fn is_dirty(&self, comp: &Comp) -> bool {
112 self.is_dirty_for(comp.revision)
113 }
114
115 /// Returns `true` if a comp at `comp_revision` differs from the last [`Self::mark_saved_at`],
116 /// including mutations that never went through the history.
117 pub fn is_dirty_for(&self, comp_revision: u64) -> bool {
118 self.saved_revision != Some(comp_revision)
119 }
120
121 /// An unrecorded mutation at the saved depth makes the saved state unreachable: any entry
122 /// recorded from here on captures the mutated state, not the saved one.
123 fn forget_diverged_saved_depth(&mut self, depth: usize, state_revision: u64) {
124 if self.saved_undo_depth == Some(depth) && self.saved_revision != Some(state_revision) {
125 self.saved_undo_depth = None;
126 }
127 }
128
129 /// Undo/redo bump `comp.revision` even when they land back on the saved state.
130 fn rebase_saved_revision(&mut self, comp_revision: u64) {
131 if self.saved_undo_depth == Some(self.undo_stack.len()) {
132 self.saved_revision = Some(comp_revision);
133 }
134 }
135
136 /// Pushes a snapshot of `comp` BEFORE applying a discrete mutation.
137 /// No-op if currently inside a [`Self::begin_group`] transaction.
138 pub fn push_snapshot(&mut self, comp: &Comp, label: impl Into<String>) {
139 if self.group_depth > 0 {
140 return;
141 }
142 self.push_entry(HistoryEntry {
143 label: label.into(),
144 snapshot: comp.clone(),
145 coalesce_key: None,
146 });
147 }
148
149 /// Pushes a snapshot of `comp` BEFORE applying a continuous mutation (such as dragging a node
150 /// or scrubbing a parameter slider). Consecutive calls with the same `key` coalesce into a
151 /// single undo step preserving the initial pre-drag snapshot.
152 /// No-op if currently inside a [`Self::begin_group`] transaction.
153 pub fn push_coalesced(
154 &mut self,
155 comp: &Comp,
156 label: impl Into<String>,
157 key: impl Into<String>,
158 ) {
159 if self.group_depth > 0 {
160 return;
161 }
162 let key_str = key.into();
163 let label_str = label.into();
164 if self.redo_stack.is_empty() {
165 if let Some(top) = self.undo_stack.back_mut() {
166 if top.coalesce_key.as_deref() == Some(key_str.as_str()) {
167 top.label = label_str;
168 return;
169 }
170 }
171 }
172 self.push_entry(HistoryEntry {
173 label: label_str,
174 snapshot: comp.clone(),
175 coalesce_key: Some(key_str),
176 });
177 }
178
179 /// Breaks coalescing on the top undo entry so subsequent edits with the same key start a new
180 /// undo step (e.g. on pointer release).
181 pub fn break_coalescing(&mut self) {
182 if let Some(top) = self.undo_stack.back_mut() {
183 top.coalesce_key = None;
184 }
185 }
186
187 /// Begins a transaction group. All mutations until the matching [`Self::commit_group`] collapse
188 /// into a single undo step. Supports nesting.
189 pub fn begin_group(&mut self, comp: &Comp, label: impl Into<String>) {
190 if self.group_depth == 0 {
191 self.active_group = Some((label.into(), comp.clone()));
192 }
193 self.group_depth += 1;
194 }
195
196 /// Commits the current transaction group. When the outermost group closes, pushes one undo
197 /// entry if `comp.revision` changed since `begin_group`. Returns `true` if an entry was added.
198 pub fn commit_group(&mut self, comp: &Comp) -> bool {
199 if self.group_depth == 0 {
200 return false;
201 }
202 self.group_depth -= 1;
203 if self.group_depth > 0 {
204 return false;
205 }
206 let Some((label, snapshot)) = self.active_group.take() else {
207 return false;
208 };
209 if comp.revision == snapshot.revision {
210 return false;
211 }
212 self.push_entry(HistoryEntry {
213 label,
214 snapshot,
215 coalesce_key: None,
216 });
217 true
218 }
219
220 /// Cancels the active transaction group and restores `comp` to its pre-group state.
221 pub fn cancel_group(&mut self, comp: &mut Comp) -> bool {
222 if self.group_depth == 0 {
223 return false;
224 }
225 self.group_depth = 0;
226 let Some((_, snapshot)) = self.active_group.take() else {
227 return false;
228 };
229 let prev_rev = comp.revision;
230 let was_clean = self.saved_revision == Some(snapshot.revision);
231 restore_snapshot(comp, snapshot);
232 if comp.revision != prev_rev {
233 comp.revision = prev_rev.max(comp.revision) + 1;
234 }
235 if was_clean {
236 self.saved_revision = Some(comp.revision);
237 }
238 true
239 }
240
241 /// Undoable [`Comp::paste_fusion_clipboard`]: the whole paste is one undo step, and a failed
242 /// paste leaves both `comp` and the history untouched.
243 pub fn paste_fusion_clipboard(
244 &mut self,
245 comp: &mut Comp,
246 lua_snippet: &str,
247 offset: (f32, f32),
248 ) -> Result<Vec<NodeId>, String> {
249 self.begin_group(comp, "Paste");
250 let pasted = comp.paste_fusion_clipboard(lua_snippet, offset);
251 self.commit_group(comp);
252 pasted
253 }
254
255 /// Undoes the most recent edit, restoring `comp` to the saved snapshot.
256 /// Always advances `comp.revision` monotonically so downstream caches invalidate cleanly.
257 pub fn undo(&mut self, comp: &mut Comp) -> bool {
258 if self.group_depth > 0 {
259 self.group_depth = 1;
260 self.commit_group(comp);
261 }
262 let Some(entry) = self.undo_stack.pop_back() else {
263 return false;
264 };
265 let prev_rev = comp.revision;
266 self.forget_diverged_saved_depth(self.undo_stack.len() + 1, prev_rev);
267 let redo_entry = HistoryEntry {
268 label: entry.label,
269 snapshot: comp.clone(),
270 coalesce_key: None,
271 };
272 self.redo_stack.push(redo_entry);
273 restore_snapshot(comp, entry.snapshot);
274 comp.revision = prev_rev.max(comp.revision) + 1;
275 self.rebase_saved_revision(comp.revision);
276 true
277 }
278
279 /// Redoes the most recently undone edit.
280 /// Always advances `comp.revision` monotonically so downstream caches invalidate cleanly.
281 pub fn redo(&mut self, comp: &mut Comp) -> bool {
282 let Some(entry) = self.redo_stack.pop() else {
283 return false;
284 };
285 let prev_rev = comp.revision;
286 self.forget_diverged_saved_depth(self.undo_stack.len(), prev_rev);
287 let undo_entry = HistoryEntry {
288 label: entry.label,
289 snapshot: comp.clone(),
290 coalesce_key: None,
291 };
292 self.undo_stack.push_back(undo_entry);
293 restore_snapshot(comp, entry.snapshot);
294 comp.revision = prev_rev.max(comp.revision) + 1;
295 self.rebase_saved_revision(comp.revision);
296 true
297 }
298
299 fn push_entry(&mut self, entry: HistoryEntry) {
300 self.forget_diverged_saved_depth(self.undo_stack.len(), entry.snapshot.revision);
301 // Any saved state that lived in the redo branch is now unreachable.
302 if let Some(saved_depth) = self.saved_undo_depth {
303 if saved_depth > self.undo_stack.len() {
304 self.saved_undo_depth = None;
305 }
306 }
307 self.redo_stack.clear();
308 self.undo_stack.push_back(entry);
309 while self.undo_stack.len() > self.max_depth {
310 self.undo_stack.pop_front();
311 self.saved_undo_depth = self.saved_undo_depth.and_then(|d| d.checked_sub(1));
312 }
313 }
314}
315
316/// Replaces `comp` with `snapshot`, keeping the live file identity so a Save As followed by undo
317/// never points Save at the file the snapshot came from.
318fn restore_snapshot(comp: &mut Comp, mut snapshot: Comp) {
319 snapshot.path = comp.path.take();
320 snapshot.name = std::mem::take(&mut comp.name);
321 *comp = snapshot;
322}
323
324
325#[cfg(test)]
326mod tests {
327 use super::*;
328 use crate::comp::ParamValue;
329 use crate::edit::tests::sample_comp;
330 use std::path::Path;
331
332 #[test]
333 fn comp_history_undo_redo_coalescing_groups_and_bounds() {
334 let mut comp = sample_comp();
335 let mut history = CompHistory::with_max_depth(3);
336 history.mark_saved(&comp);
337 assert!(!history.is_dirty(&comp));
338 assert!(!history.can_undo());
339 assert!(!history.can_redo());
340
341 let bg = comp.find_node("BG1").unwrap();
342
343 // 1. Coalesced drag: 120 frames produce ONE undo step
344 for i in 1..=120 {
345 history.push_coalesced(&comp, "Move BG1", format!("drag_node:{}", bg.0));
346 comp.set_node_pos(bg, [100.0 + i as f32, 50.0 + i as f32 * 0.5]);
347 }
348 history.break_coalescing();
349 assert_eq!(history.undo_len(), 1);
350 assert_eq!(history.undo_label(), Some("Move BG1"));
351 assert!(history.is_dirty(&comp));
352 assert_eq!(comp.node(bg).pos, [220.0, 110.0]);
353
354 // Undo restores original pre-drag position and clears dirty flag
355 assert!(history.undo(&mut comp));
356 assert_eq!(comp.node(bg).pos, [100.0, 50.0]);
357 assert!(!history.is_dirty(&comp));
358 assert!(history.can_redo());
359 assert_eq!(history.redo_label(), Some("Move BG1"));
360
361 // Redo restores final dragged position
362 assert!(history.redo(&mut comp));
363 assert_eq!(comp.node(bg).pos, [220.0, 110.0]);
364 assert!(history.is_dirty(&comp));
365
366 // 2. Redo invalidation on new edit after undo
367 assert!(history.undo(&mut comp));
368 assert!(history.can_redo());
369 history.push_snapshot(&comp, "Add Blur");
370 let blur = comp.add_node("Blur", None, [200.0, 100.0]);
371 assert!(!history.can_redo());
372 assert_eq!(history.undo_len(), 1);
373
374 // 3. Transaction group collapses multiple mutations into one undo step
375 history.begin_group(&comp, "Style Blur");
376 comp.set_input_value(blur, "XBlurSize", ParamValue::Number(5.0));
377 history.push_snapshot(&comp, "Ignored inside group");
378 comp.toggle_passthrough(blur);
379 assert!(history.commit_group(&comp));
380 assert_eq!(history.undo_len(), 2);
381 assert_eq!(history.undo_label(), Some("Style Blur"));
382
383 // No-op group doesn't push
384 history.begin_group(&comp, "No-op");
385 assert!(!history.commit_group(&comp));
386 assert_eq!(history.undo_len(), 2);
387
388 // Cancel group restores pre-group state
389 history.begin_group(&comp, "Canceled");
390 comp.set_node_pos(blur, [999.0, 999.0]);
391 assert!(history.cancel_group(&mut comp));
392 assert_eq!(comp.node(blur).pos, [200.0, 100.0]);
393
394 // 4. Bounded history depth (max_depth = 3)
395 history.push_snapshot(&comp, "Edit 3");
396 comp.set_node_pos(blur, [210.0, 100.0]);
397 history.push_snapshot(&comp, "Edit 4");
398 comp.set_node_pos(blur, [220.0, 100.0]);
399 assert_eq!(history.undo_len(), 3);
400
401 history.clear();
402 assert!(!history.can_undo());
403 assert!(!history.can_redo());
404 }
405
406 #[test]
407 fn mark_saved_stops_later_edits_coalescing_into_the_saved_step() {
408 let mut comp = sample_comp();
409 let mut history = CompHistory::new();
410 let bg = comp.find_node("BG1").unwrap();
411
412 history.push_coalesced(&comp, "Drag", "drag");
413 comp.set_node_pos(bg, [1.0, 1.0]);
414 history.mark_saved(&comp);
415 assert!(!history.is_dirty(&comp));
416
417 history.push_coalesced(&comp, "Drag", "drag");
418 comp.set_node_pos(bg, [2.0, 2.0]);
419 assert_eq!(history.undo_len(), 2);
420 assert!(history.is_dirty(&comp));
421 }
422
423 #[test]
424 fn dirty_tracking_sees_edits_made_at_the_saved_depth() {
425 let mut history = CompHistory::new();
426 assert!(history.is_dirty_for(0));
427 history.mark_saved_at(7);
428 assert!(!history.is_dirty_for(7));
429 assert!(history.is_dirty_for(8));
430
431 let mut comp = sample_comp();
432 let bg = comp.find_node("BG1").unwrap();
433 history.mark_saved(&comp);
434 assert_eq!(history.saved_revision(), Some(comp.revision));
435
436 // Mutated without a history entry: undo depth still equals the saved depth.
437 comp.set_node_pos(bg, [5.0, 5.0]);
438 assert_eq!(history.undo_len(), 0);
439 assert!(history.is_dirty(&comp));
440 assert!(history.is_dirty_for(comp.revision));
441
442 // Undo/redo landing back on the saved depth is clean again.
443 history.mark_saved(&comp);
444 history.push_snapshot(&comp, "Move");
445 comp.set_node_pos(bg, [6.0, 6.0]);
446 assert!(history.is_dirty(&comp));
447 assert!(history.undo(&mut comp));
448 assert!(!history.is_dirty(&comp));
449 assert!(history.redo(&mut comp));
450 assert!(history.is_dirty(&comp));
451 assert!(history.undo(&mut comp));
452 assert!(!history.is_dirty(&comp));
453
454 // A cancelled group restores a clean comp to clean.
455 history.begin_group(&comp, "Group");
456 comp.set_node_pos(bg, [7.0, 7.0]);
457 assert!(history.is_dirty(&comp));
458 assert!(history.cancel_group(&mut comp));
459 assert!(!history.is_dirty(&comp));
460 }
461
462 #[test]
463 fn unrecorded_mutation_at_saved_depth_is_never_clean_after_undo_redo() {
464 let mut comp = sample_comp();
465 let mut history = CompHistory::new();
466 let bg = comp.find_node("BG1").unwrap();
467
468 history.push_snapshot(&comp, "Move");
469 comp.set_node_pos(bg, [1.0, 1.0]);
470 history.mark_saved(&comp);
471
472 comp.set_node_pos(bg, [2.0, 2.0]);
473 assert!(history.is_dirty(&comp));
474 assert!(history.undo(&mut comp));
475 assert!(history.redo(&mut comp));
476 assert_eq!(comp.node(bg).pos, [2.0, 2.0]);
477 assert!(history.is_dirty(&comp));
478 }
479
480 #[test]
481 fn unrecorded_mutation_at_saved_depth_is_never_clean_after_push_undo() {
482 let mut comp = sample_comp();
483 let mut history = CompHistory::new();
484 let bg = comp.find_node("BG1").unwrap();
485 history.mark_saved(&comp);
486
487 comp.set_node_pos(bg, [2.0, 2.0]);
488 history.push_snapshot(&comp, "Move");
489 comp.set_node_pos(bg, [3.0, 3.0]);
490 assert!(history.undo(&mut comp));
491 assert_eq!(comp.node(bg).pos, [2.0, 2.0]);
492 assert!(history.is_dirty(&comp));
493 }
494
495 #[test]
496 fn undo_and_redo_keep_the_live_file_identity() {
497 let mut comp = sample_comp();
498 comp.path = Some("/tmp/original.comp".into());
499 comp.name = "original".to_owned();
500 let mut history = CompHistory::new();
501 let bg = comp.find_node("BG1").unwrap();
502
503 history.push_snapshot(&comp, "Move");
504 comp.set_node_pos(bg, [9.0, 9.0]);
505 comp.path = Some("/tmp/save_as.comp".into());
506 comp.name = "save_as".to_owned();
507
508 assert!(history.undo(&mut comp));
509 assert_eq!((comp.path.as_deref(), comp.name.as_str()), (Some(Path::new("/tmp/save_as.comp")), "save_as"));
510 assert!(history.redo(&mut comp));
511 assert_eq!((comp.path.as_deref(), comp.name.as_str()), (Some(Path::new("/tmp/save_as.comp")), "save_as"));
512 }
513}