diff --git a/crates/ui-egui/src/panels/image_trace.rs b/crates/ui-egui/src/panels/image_trace.rs index afd294a0e5..47aafca31d 100644 --- a/crates/ui-egui/src/panels/image_trace.rs +++ b/crates/ui-egui/src/panels/image_trace.rs @@ -80,6 +80,9 @@ fn color_group<'a>(app: &VectorcraftApp, params: &'a Value) -> Option<&'a str> { rows::known_group(&rows::swatch_groups(app), params) } +/// An object's open document, content generation and node id. +type ObjectKey = (u64, u64, NodeId); + /// Panel state: the preset name, the current parameters, the view and the last result's counts. #[derive(Clone, Debug, Default)] pub(crate) struct TraceUi { @@ -93,13 +96,13 @@ pub(crate) struct TraceUi { /// The selected Image Trace object's stored settings last adopted (so edits in progress /// aren't overwritten until the object changes). synced: Value, - /// The document and object `synced` came from. - object: Option<(u64, NodeId)>, + /// The document contents and object `synced` came from. + object: Option, /// Preview was off at the panel's last frame. preview_off: bool, - /// The settings that wait for objects no longer selected, by document and object: the preset, + /// The settings that wait for objects no longer selected, by document contents and object: the preset, /// the parameters, and the object's stored settings they were changed from. - drafts: std::collections::HashMap<(u64, NodeId), (String, Value, Value)>, + drafts: std::collections::HashMap, } /// The Image Trace panel's run-only state: what it shows, and the view settings of its preset picker. @@ -184,6 +187,8 @@ pub(crate) fn is_trace(n: &Node) -> bool { /// object (wherever it is in the selection). #[derive(Clone, Debug, Default, PartialEq)] pub(crate) struct Target { + /// Present even with nothing selected, so Revert can retire that document's old drafts. + document: Option<(u64, u64)>, /// The active document's uid and the object Trace acts on. object: Option<(u64, NodeId)>, /// The object is an Image Trace object. @@ -195,6 +200,14 @@ pub(crate) struct Target { any_trace: bool, } +impl Target { + fn object_key(&self) -> Option { + let (uid, node) = self.object?; + let (_, reverts) = self.document?; + Some((uid, reverts, node)) + } +} + /// Whether any selected object is an Image Trace object. fn any_trace_selected(app: &VectorcraftApp) -> bool { app.session.active().is_some_and(|st| st.selection.objects.iter().any(|id| st.doc.node(*id).is_some_and(is_trace))) @@ -204,13 +217,15 @@ fn any_trace_selected(app: &VectorcraftApp) -> bool { /// first selected non-traceable object's metadata. Release and Expand keep their own selection scope. fn find_target(app: &VectorcraftApp) -> Target { let Some(st) = app.session.active() else { return Target::default() }; + let document = Some((st.uid, st.reverts)); let any_trace = any_trace_selected(app); let node = vectorcraft_engine::cmd::image_trace_target(&app.session, &Value::Null) .ok() .and_then(|id| st.doc.node(id)) .or_else(|| first_node(app).filter(|n| !is_trace(n) && !matches!(n.kind, NodeKind::Image(_)))); - let Some(n) = node else { return Target { any_trace, ..Target::default() } }; + let Some(n) = node else { return Target { document, any_trace, ..Target::default() } }; Target { + document, object: Some((st.uid, n.id)), is_trace: is_trace(n), is_image: matches!(n.kind, NodeKind::Image(_)), @@ -482,7 +497,7 @@ pub(crate) fn apply_ignore_color_sample(app: &mut VectorcraftApp, p: &Value) { let mut st = std::mem::take(&mut app.ui.image_trace_panel.shown); follow_preset_changes(app, &mut st, &list.presets); let changes: Vec<&TracePresetChange> = app.session.trace_preset_changes_since(0).collect(); - sync_with_object(&mut st, t.stored.clone(), Some((s.doc, s.target)), &list.presets, &changes); + sync_with_object(&mut st, &t, &list.presets, &changes); st.params["ignoreColor"] = json!(color); st.preset = "Custom".into(); let preview = app.ui.image_trace_preview; @@ -624,10 +639,11 @@ fn trace(app: &mut VectorcraftApp, st: &mut TraceUi) { /// the next panel frame must still be recognized as a change, even when it returns to the previous /// settings. fn adopt(st: &mut TraceUi, target: &Target, r: &Value) { + discard_retired_drafts(st, target.document); st.info = Some((r["paths"].as_u64().unwrap_or(0), r["anchors"].as_u64().unwrap_or(0), r["colors"].as_u64().unwrap_or(0))); if let Some(stored) = &target.stored { st.synced = stored.clone(); - st.object = target.object; + st.object = target.object_key(); } } @@ -678,10 +694,22 @@ fn listed_preset(name: &str, params: &Value, all: &[Preset], changes: &[&TracePr found.map_or_else(|| "Custom".into(), |p| p.0.clone()) } -/// Bring the panel's settings `st` in line with the selected object `object`, whose trace settings are `stored`, +/// Drop only drafts for content that Revert replaced in the active document. +fn discard_retired_drafts(st: &mut TraceUi, document: Option<(u64, u64)>) { + let Some((uid, reverts)) = document else { return }; + st.drafts.retain(|(doc, generation, _), _| *doc != uid || *generation == reverts); + if st.object.is_some_and(|(doc, generation, _)| doc == uid && generation != reverts) { + st.object = None; + st.synced = Value::Null; + } +} + +/// Bring the panel's settings `st` in line with the selected object's stored settings, /// with the presets `all` and the saved preset changes `changes` of this session (oldest first); whether the object /// came back with the settings that waited for it. -fn sync_with_object(st: &mut TraceUi, stored: Option, object: Option<(u64, NodeId)>, all: &[Preset], changes: &[&TracePresetChange]) -> bool { +fn sync_with_object(st: &mut TraceUi, target: &Target, all: &[Preset], changes: &[&TracePresetChange]) -> bool { + discard_retired_drafts(st, target.document); + let (stored, object) = (target.stored.clone(), target.object_key()); let same = |a: &Value, b: &Value| a["preset"] == b["preset"] && a["params"] == b["params"]; let mut restored = false; // Another object: the settings that wait for the one left are kept until it is selected again, @@ -796,7 +824,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { follow_preset_changes(app, &mut st, &list.presets); let restored = { let changes: Vec<&TracePresetChange> = app.session.trace_preset_changes_since(0).collect(); - sync_with_object(&mut st, t.stored.clone(), t.object, &list.presets, &changes) + sync_with_object(&mut st, &t, &list.presets, &changes) }; let preview = app.ui.image_trace_preview; let mut actions = (false, false, false); diff --git a/crates/ui-egui/src/panels/image_trace/tests.rs b/crates/ui-egui/src/panels/image_trace/tests.rs index 3935cbe8c2..dd7ff97b78 100644 --- a/crates/ui-egui/src/panels/image_trace/tests.rs +++ b/crates/ui-egui/src/panels/image_trace/tests.rs @@ -99,6 +99,60 @@ fn traced_app_with_ink(ink: u8) -> VectorcraftApp { app } +/// Revert reloads the saved file even when its trace has the same node id and stored settings. +/// A preview-off draft belongs to the discarded source pixels, not the reloaded object. +#[test] +fn native_file_revert_discards_pending_settings_for_reused_trace_ids() { + for frame_without_selection in [false, true] { + let mut app = traced_app_with_ink(0); + let old = find_target(&app); + let id = old.object.unwrap().1; + let old_source = source_image(app.session.active().unwrap().doc.node(id).unwrap()).unwrap().key.clone(); + let dir = vectorcraft_testkit::TempDir::new("trace-native-revert"); + let path = dir.join("saved.vectorcraft"); + app.services.write = Some(Box::new(|path, bytes| std::fs::write(path, bytes).map_err(|e| e.to_string()))); + app.services.read = Some(Box::new(|path| std::fs::read(path).map_err(|e| e.to_string()))); + app.run("file.saveAs", json!({"path": path.to_string_lossy()})).unwrap(); + app.run("object.move", json!({"ids": [id.0], "dx": 1, "dy": 0})).unwrap(); + + // Another saved copy supplies different pixels with the same trace identity and settings. + let mut saved = traced_app_with_ink(100); + let restored = find_target(&saved); + assert_eq!(restored.object.unwrap().1, id); + assert_eq!(old.stored.as_ref().unwrap()["params"], restored.stored.as_ref().unwrap()["params"]); + saved.services.write = Some(Box::new(|path, bytes| std::fs::write(path, bytes).map_err(|e| e.to_string()))); + saved.run("file.saveAs", json!({"path": path.to_string_lossy()})).unwrap(); + + let mut panel = panel_over(app); + panel.click("Preview"); + panel.click("Strokes"); + assert!(!panel.app().ui.image_trace_preview); + assert_eq!(shown(&panel).params["strokes"], json!(true)); + assert_eq!(param(&panel.app(), "strokes"), Some(json!(false)), "the changed setting remains a panel draft"); + let uid = panel.app().session.active().unwrap().uid; + let reverts = panel.app().session.active().unwrap().reverts; + panel.app().run("file.revert", json!({"confirmed": true})).unwrap(); + { + let app = panel.app(); + let st = app.session.active().unwrap(); + assert_eq!(st.uid, uid); + assert_eq!(st.reverts, reverts + 1, "the native Revert replaced the drawing contents"); + assert!(st.selection.objects.is_empty()); + assert_ne!(source_image(st.doc.node(id).unwrap()).unwrap().key, old_source, "Revert read the other saved pixels"); + } + if frame_without_selection { + panel.frame(); + } + select(&mut panel, id); + assert_eq!(shown(&panel).params, restored.stored.unwrap()["params"], "the saved trace's own settings are adopted"); + assert!(shown(&panel).drafts.is_empty(), "the discarded source's draft is gone"); + let before = undo(&panel.app()); + panel.click("Preview"); + assert_eq!(param(&panel.app(), "strokes"), Some(json!(false))); + assert_eq!(undo(&panel.app()), before, "Preview must not apply the discarded source's draft"); + } +} + fn scroll_settings(panel: &mut Panel, dy: f32) { panel.scroll_at(egui::pos2(30.0, 30.0), dy); panel.advance(1.0); @@ -403,7 +457,8 @@ fn settings_that_wait_are_dropped_when_their_object_changed_since() { // A's settings as they were when the change was made, other than its settings now. { let mut app = panel.app(); - let key = (app.session.active().unwrap().uid, a); + let doc = app.session.active().unwrap(); + let key = (doc.uid, doc.reverts, a); let draft = app.ui.image_trace_panel.shown.drafts.get_mut(&key).expect("the change waits for A"); assert_eq!(draft.1["strokes"], json!(true)); draft.2["params"]["threshold"] = json!(1); @@ -1163,7 +1218,7 @@ fn a_trace_off_the_ui_thread_is_adopted_when_it_lands() { assert_eq!(param(&app, "strokes"), Some(json!(true))); let st = &app.ui.image_trace_panel.shown; assert!(st.info.is_some(), "its counts show"); - assert_eq!(st.object, find_target(&app).object); + assert_eq!(st.object, find_target(&app).object_key()); assert!(st.drafts.is_empty(), "nothing waits for the object it replaced"); app.ui.image_trace_preview = true; } @@ -1192,9 +1247,11 @@ fn target_node_sorting_everything(app: &VectorcraftApp) -> Option { /// [`Target`] from [`target_node_sorting_everything`] and a scan of the whole selection for Image /// Trace objects, as the panel read them on every frame before. fn target_sorting_everything(app: &VectorcraftApp) -> Target { + let document = app.session.active().map(|st| (st.uid, st.reverts)); let any_trace = app.session.active().is_some_and(|st| st.selection.objects.iter().any(|id| st.doc.node(*id).is_some_and(is_trace))); - let Some(n) = target_node_sorting_everything(app) else { return Target { any_trace, ..Target::default() } }; + let Some(n) = target_node_sorting_everything(app) else { return Target { document, any_trace, ..Target::default() } }; Target { + document, object: app.session.active().map(|st| (st.uid, n.id)), is_trace: is_trace(&n), is_image: matches!(n.kind, NodeKind::Image(_)), @@ -1347,7 +1404,8 @@ fn the_target_lookup_obeys_canonical_roots_and_explicit_id_validation() { for (parent, child) in [("clip", "clipped"), ("outer", "deep")] { select_as_is(&mut app, &[ids[parent], ids[child]]); let uid = app.session.active().unwrap().uid; - let expected = Target { object: Some((uid, ids[parent])), ..Default::default() }; + let document = app.session.active().map(|st| (st.uid, st.reverts)); + let expected = Target { document, object: Some((uid, ids[parent])), ..Default::default() }; assert_eq!(find_target(&app), expected, "the selected {parent} supplies metadata, not its pruned image"); assert_eq!(*target(&mut app), expected); assert_eq!(*target(&mut app), expected, "the canonical result is also cached");