From 105bfd5a4af03a87bbc58e754041dd4ab830a0d4 Mon Sep 17 00:00:00 2001 From: SteamSmith <341182916+SteamSmith@users.noreply.github.com> Date: Thu, 5 Nov 2026 07:20:50 -0500 Subject: [PATCH] fix(engine): record multi-command gestures as one undo entry Rewiring a dragged link (Disconnect + Connect), dragging a frame (Edit frame + Move nodes) and Import bitmap (import + add node + set param) each made 2-3 history entries. Add Session::begin_group/end_group and Session::group: edits inside a group share one snapshot, an untouched group records nothing, and a failing group() restores everything. The UI uses begin/end_group around those gestures. Co-Authored-By: Claude Sonnet 5.5 --- crates/engine/src/session.rs | 69 ++++++++++++++++++++++ crates/engine/src/session.test.rs | 57 ++++++++++++++++++ crates/ui-egui/src/graph_view.rs | 92 ++++++++++++++++++++++++++---- crates/ui-egui/src/web_files.rs | 8 +-- crates/ui-egui/src/windows.rs | 14 ++--- crates/ui-egui/src/windows.test.rs | 21 +++++++ 6 files changed, 237 insertions(+), 24 deletions(-) create mode 100644 crates/engine/src/session.test.rs create mode 100644 crates/ui-egui/src/windows.test.rs diff --git a/crates/engine/src/session.rs b/crates/engine/src/session.rs index 7dbdeae..9b21f86 100644 --- a/crates/engine/src/session.rs +++ b/crates/engine/src/session.rs @@ -158,6 +158,8 @@ pub struct Session { redo: Vec, /// Edits with the same key coalesce into one undo step (slider drags). merge_key: Option, + /// An open [`Session::begin_group`]: the snapshot taken at its start, and whether any edit ran. + group: Option<(Snapshot, bool)>, decoded: Arc>>, } @@ -183,6 +185,7 @@ impl Session { undo: Vec::new(), redo: Vec::new(), merge_key: None, + group: None, decoded: Arc::new(Mutex::new(HashMap::new())), } } @@ -209,6 +212,9 @@ impl Session { /// Like [`Session::edit`], but consecutive edits with the same `key` (dragging one slider) /// make a single undo step. pub fn edit_merged(&mut self, key: &str, label: &str, f: impl FnOnce(&mut Session) -> Result) -> Result { + if self.group.is_some() { + return self.edit_inner(label, f); + } if self.merge_key.as_deref() == Some(key) && !self.undo.is_empty() { let r = f(self); if r.is_ok() { @@ -223,8 +229,64 @@ impl Session { r } + /// Start grouping: every edit until [`Session::end_group`] becomes one undo entry labelled + /// `label` (a gesture that runs several commands, such as rewiring a link). Nothing is + /// recorded if no edit ran. A group started inside a group is ignored. + pub fn begin_group(&mut self, label: &str) { + if self.group.is_none() { + self.merge_key = None; + self.group = Some((self.snapshot(label), false)); + } + } + + /// Close the group opened by [`Session::begin_group`], recording one undo entry if any edit ran. + pub fn end_group(&mut self) { + if let Some((snap, edited)) = self.group.take() + && edited + { + self.undo.push(snap); + if self.undo.len() > MAX_UNDO { + self.undo.remove(0); + } + self.redo.clear(); + } + } + + /// Run `f` as one undo entry, however many edits it makes. On error everything `f` did is + /// undone and nothing is recorded. + pub fn group(&mut self, label: &str, f: impl FnOnce(&mut Session) -> Result) -> Result { + if self.group.is_some() { + return f(self); + } + self.begin_group(label); + let r = f(self); + match r { + Ok(_) => self.end_group(), + Err(_) => { + if let Some((snap, _)) = self.group.take() { + self.restore(snap); + } + } + } + r + } + fn edit_inner(&mut self, label: &str, f: impl FnOnce(&mut Session) -> Result) -> Result { let snap = self.snapshot(label); + if let Some((_, edited)) = self.group.as_mut() { + // Inside a group: the group's own snapshot is the undo entry. + *edited = true; + return match f(self) { + Ok(v) => { + self.changed(); + Ok(v) + } + Err(e) => { + self.restore(snap); + Err(e) + } + }; + } match f(self) { Ok(v) => { self.undo.push(snap); @@ -268,6 +330,7 @@ impl Session { } pub fn undo(&mut self) -> Option { + self.end_group(); let s = self.undo.pop()?; let label = s.label.clone(); let cur = self.snapshot(&label); @@ -279,6 +342,7 @@ impl Session { } pub fn redo(&mut self) -> Option { + self.end_group(); let s = self.redo.pop()?; let label = s.label.clone(); let cur = self.snapshot(&label); @@ -294,6 +358,7 @@ impl Session { self.undo.clear(); self.redo.clear(); self.merge_key = None; + self.group = None; } /// A decoder for the package's bitmap resources (memoized, shareable with worker threads). @@ -402,3 +467,7 @@ impl Session { } } } + +#[cfg(test)] +#[path = "session.test.rs"] +mod tests; diff --git a/crates/engine/src/session.test.rs b/crates/engine/src/session.test.rs new file mode 100644 index 0000000..6c08584 --- /dev/null +++ b/crates/engine/src/session.test.rs @@ -0,0 +1,57 @@ +#[cfg(test)] +mod group_tests { + use crate::{EngineError, Session, execute}; + use serde_json::json; + + fn two_nodes() -> (Session, u64, u64) { + let mut s = crate::sample_session(); + execute(&mut s, "file.new", &json!({"template": "empty"})).unwrap(); + let a = execute(&mut s, "graph.node.add", &json!({"def": "clouds_1"})).unwrap()["id"].as_u64().unwrap(); + let b = execute(&mut s, "graph.node.add", &json!({"def": "levels"})).unwrap()["id"].as_u64().unwrap(); + (s, a, b) + } + + #[test] + fn a_group_is_one_undo_entry_and_one_undo_reverts_all() { + let (mut s, a, b) = two_nodes(); + let base = s.history().len(); + s.group("Rewire", |s| { + execute(s, "graph.connect", &json!({"from": a, "to": b, "toPort": "input"}))?; + execute(s, "graph.disconnect", &json!({"to": b, "toPort": "input"}))?; + execute(s, "graph.connect", &json!({"from": a, "to": b, "toPort": "input"}))?; + Ok(()) + }) + .unwrap(); + assert_eq!(s.history().len(), base + 1); + assert_eq!(s.history().last().map(String::as_str), Some("Rewire")); + assert_eq!(s.undo().as_deref(), Some("Rewire")); + assert!(s.graph().unwrap().connections.is_empty(), "the single undo removed every step"); + } + + #[test] + fn a_failing_group_restores_everything_and_records_nothing() { + let (mut s, a, b) = two_nodes(); + let base = s.history().len(); + let r: Result<(), EngineError> = s.group("Rewire", |s| { + execute(s, "graph.connect", &json!({"from": a, "to": b, "toPort": "input"}))?; + Err(EngineError::Other("boom".into())) + }); + assert!(r.is_err()); + assert_eq!(s.history().len(), base); + assert!(s.graph().unwrap().connections.is_empty()); + } + + #[test] + fn begin_and_end_group_span_several_calls_and_an_untouched_group_records_nothing() { + let (mut s, a, b) = two_nodes(); + let base = s.history().len(); + s.begin_group("Nothing"); + s.end_group(); + assert_eq!(s.history().len(), base); + s.begin_group("Both"); + execute(&mut s, "graph.connect", &json!({"from": a, "to": b, "toPort": "input"})).unwrap(); + execute(&mut s, "graph.node.param", &json!({"id": b, "param": "in_low", "value": 0.2})).unwrap(); + s.end_group(); + assert_eq!(s.history().len(), base + 1); + } +} diff --git a/crates/ui-egui/src/graph_view.rs b/crates/ui-egui/src/graph_view.rs index ee877da..e362abd 100644 --- a/crates/ui-egui/src/graph_view.rs +++ b/crates/ui-egui/src/graph_view.rs @@ -372,6 +372,47 @@ pub fn add_node_near_selection(app: &mut MaterialCraftApp, def: &str) { app.run("graph.node.add", params); } +/// Add a Bitmap node (wired to the selection when that makes sense) showing `resource`. +pub fn add_bitmap_node(app: &mut MaterialCraftApp, resource: &str) { + add_node_near_selection(app, "bitmap"); + if let Some(id) = app.session.selection.last().copied() { + app.run("graph.node.param", json!({"id": id.0, "param": "resource", "value": resource})); + } +} + +/// File ▸ Import bitmap from a path: import, add the node and bind it, as one undo entry. +#[cfg(not(target_arch = "wasm32"))] +pub fn import_bitmap_file(app: &mut MaterialCraftApp, path: &str) { + app.session.begin_group("Import bitmap"); + if let Some(r) = app.run("file.importBitmap", json!({"path": path})) { + add_bitmap_node(app, r["name"].as_str().unwrap_or_default()); + } + app.session.end_group(); +} + +/// Finish dragging a wire onto input `to_port` of `to`: connect it, first removing the link it +/// was pulled off (`detached`). The gesture is one undo entry. +fn rewire(app: &mut MaterialCraftApp, from: &(NodeId, String), detached: Option<&(NodeId, String)>, to: NodeId, to_port: &str) { + app.session.begin_group("Connect"); + if let Some((n, p)) = detached + && (*n != to || p != to_port) + { + app.run("graph.disconnect", json!({"to": n.0, "toPort": p})); + } + app.run("graph.connect", json!({"from": from.0.0, "fromPort": from.1, "to": to.0, "toPort": to_port})); + app.session.end_group(); +} + +/// Finish dragging a frame: set its rectangle and move the nodes it carries, as one undo entry. +fn move_frame(app: &mut MaterialCraftApp, id: u64, rect: [f32; 4], nodes: &[NodeId], delta: Vec2) { + app.session.begin_group("Move frame"); + app.run("graph.frame.edit", json!({"id": id, "rect": rect})); + if !nodes.is_empty() { + app.run("graph.node.move", json!({"ids": nodes.iter().map(|n| n.0).collect::>(), "by": [delta.x, delta.y]})); + } + app.session.end_group(); +} + /// Frame the graph (or the selection) in the view. fn frame(app: &mut MaterialCraftApp, view: Rect, only_selection: bool) { let thumbs = app.ui.prefs.thumbnails; @@ -916,14 +957,7 @@ fn handle_input( Drag::Wire { from, detached } => { let target = pointer.and_then(|p| nearest_port(&app.graph.ports, p, 12.0)).filter(|h| !h.output).cloned(); match target { - Some(t) => { - if let Some((n, p)) = &detached - && (*n != t.node || *p != t.port) - { - app.run("graph.disconnect", json!({"to": n.0, "toPort": p})); - } - app.run("graph.connect", json!({"from": from.0.0, "fromPort": from.1, "to": t.node.0, "toPort": t.port})); - } + Some(t) => rewire(app, &from, detached.as_ref(), t.node, &t.port), None => { if let Some((n, p)) = &detached { app.run("graph.disconnect", json!({"to": n.0, "toPort": p})); @@ -944,10 +978,7 @@ fn handle_input( } else { [f.rect[0] + delta.x, f.rect[1] + delta.y, f.rect[2], f.rect[3]] }; - app.run("graph.frame.edit", json!({"id": id, "rect": r})); - if !nodes.is_empty() { - app.run("graph.node.move", json!({"ids": nodes.iter().map(|n| n.0).collect::>(), "by": [delta.x, delta.y]})); - } + move_frame(app, id, r, &nodes, delta); } } Drag::Comment { id, delta } => { @@ -1309,6 +1340,43 @@ fn canvas_menu(app: &mut MaterialCraftApp, ui: &mut Ui, at: Pos2) { mod tests { use super::*; + fn empty_app() -> MaterialCraftApp { + let mut app = MaterialCraftApp::headless(materialcraft_engine::sample_session(), crate::UiState::default()); + app.run("file.new", json!({"template": "empty"})); + app + } + + fn add(app: &mut MaterialCraftApp, def: &str) -> NodeId { + NodeId(app.run("graph.node.add", json!({"def": def})).and_then(|v| v["id"].as_u64()).unwrap()) + } + + #[test] + fn rewiring_a_dragged_link_is_one_undo_entry() { + let mut app = empty_app(); + let (a, b, c) = (add(&mut app, "clouds_1"), add(&mut app, "levels"), add(&mut app, "levels")); + app.run("graph.connect", json!({"from": a.0, "fromPort": "output", "to": b.0, "toPort": "input"})); + let base = app.session.history().len(); + rewire(&mut app, &(a, "output".to_string()), Some(&(b, "input".to_string())), c, "input"); + assert_eq!(app.session.history().len(), base + 1, "{:?}", app.session.history()); + let conns = &app.session.graph().unwrap().connections; + assert_eq!(conns.len(), 1); + assert_eq!(conns[0].to, c); + app.session.undo(); + assert_eq!(app.session.graph().unwrap().connections[0].to, b, "one undo restores the old link"); + } + + #[test] + fn dragging_a_frame_with_its_nodes_is_one_undo_entry() { + let mut app = empty_app(); + let n = add(&mut app, "levels"); + let id = app.run("graph.frame.add", json!({"rect": [0, 0, 300, 200]})).and_then(|v| v["id"].as_u64()).unwrap(); + let base = app.session.history().len(); + move_frame(&mut app, id, [10.0, 10.0, 300.0, 200.0], &[n], vec2(10.0, 10.0)); + assert_eq!(app.session.history().len(), base + 1, "{:?}", app.session.history()); + app.session.undo(); + assert_eq!(app.session.graph().unwrap().frames[0].rect, [0.0, 0.0, 300.0, 200.0]); + } + #[test] fn tab_opens_search_in_the_full_workspace() { let mut app = MaterialCraftApp::headless(materialcraft_engine::sample_session(), crate::UiState::default()); diff --git a/crates/ui-egui/src/web_files.rs b/crates/ui-egui/src/web_files.rs index b08a80d..bf1e70b 100644 --- a/crates/ui-egui/src/web_files.rs +++ b/crates/ui-egui/src/web_files.rs @@ -63,16 +63,16 @@ pub fn load(app: &mut MaterialCraftApp, name: &str, bytes: Vec, bitmap: bool return; } if bitmap || materialcraft_engine::formats::IMAGE_EXTENSIONS.contains(&ext.as_str()) { + // Import, add the node and bind it: one undo entry. + app.session.begin_group("Import bitmap"); match materialcraft_engine::file_cmds::add_resource(&mut app.session, name, bytes, None) { Ok(res) => { - crate::graph_view::add_node_near_selection(app, "bitmap"); - if let Some(id) = app.session.selection.last().copied() { - app.run("graph.node.param", serde_json::json!({"id": id.0, "param": "resource", "value": res})); - } + crate::graph_view::add_bitmap_node(app, &res); app.toast(format!("{} {res}", tr("Imported")), false); } Err(e) => app.toast(format!("{} {name}: {e}", tr("Couldn't import")), true), } + app.session.end_group(); return; } match materialcraft_engine::file_cmds::open_bytes(&mut app.session, &bytes, Some(name.to_string())) { diff --git a/crates/ui-egui/src/windows.rs b/crates/ui-egui/src/windows.rs index 00c3e74..839480c 100644 --- a/crates/ui-egui/src/windows.rs +++ b/crates/ui-egui/src/windows.rs @@ -595,14 +595,8 @@ pub fn file_action(app: &mut MaterialCraftApp, ctx: &egui::Context, id: &str) -> true } "file.importBitmap" => { - if let Some(p) = rfd::FileDialog::new().add_filter("Images", materialcraft_engine::formats::IMAGE_EXTENSIONS).pick_file() - && let Some(r) = app.run("file.importBitmap", json!({"path": p.display().to_string()})) - { - let name = r["name"].as_str().unwrap_or_default().to_string(); - crate::graph_view::add_node_near_selection(app, "bitmap"); - if let Some(id) = app.session.selection.last().copied() { - app.run("graph.node.param", json!({"id": id.0, "param": "resource", "value": name})); - } + if let Some(p) = rfd::FileDialog::new().add_filter("Images", materialcraft_engine::formats::IMAGE_EXTENSIONS).pick_file() { + crate::graph_view::import_bitmap_file(app, &p.display().to_string()); } true } @@ -632,3 +626,7 @@ pub fn open_path(app: &mut MaterialCraftApp, path: &str) { after_open(app); } } + +#[cfg(all(test, not(target_arch = "wasm32")))] +#[path = "windows.test.rs"] +mod tests; diff --git a/crates/ui-egui/src/windows.test.rs b/crates/ui-egui/src/windows.test.rs new file mode 100644 index 0000000..04a5c77 --- /dev/null +++ b/crates/ui-egui/src/windows.test.rs @@ -0,0 +1,21 @@ +#[cfg(test)] +mod import_tests { + use crate::{MaterialCraftApp, state::UiState}; + use materialcraft_engine::formats::{Depth, encode}; + use materialcraft_engine::image::{Image, Kind}; + + #[test] + fn importing_a_bitmap_file_is_one_undo_entry() { + let png = encode(&Image::filled(4, 4, Kind::Color, [0.5, 0.2, 0.1, 1.0]), "png", Depth::U8, true).unwrap(); + let path = std::env::temp_dir().join(format!("mc-import-{}.png", std::process::id())); + std::fs::write(&path, png).unwrap(); + let mut app = MaterialCraftApp::headless(materialcraft_engine::sample_session(), UiState::default()); + let base = app.session.history().len(); + crate::graph_view::import_bitmap_file(&mut app, &path.display().to_string()); + std::fs::remove_file(&path).ok(); + assert_eq!(app.session.history().len(), base + 1, "history: {:?}", app.session.history()); + assert_eq!(app.session.history().last().map(String::as_str), Some("Import bitmap")); + app.session.undo(); + assert_eq!(app.session.history().len(), base); + } +}