From 9d8ecd1341de0afde2ff1d12dbcd625324d6932e Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 4 Dec 2026 22:35:37 -0800 Subject: [PATCH] DXF Import: a failed Replace restores the selection after unrelated edits The user's selection came back only while the document revision was unchanged, so a Replace whose rollback raised the revision, or any edit that left the selection alone, kept the swapped object selected. DocState now counts selection changes (`selections`): every Session::select, Undo and Redo, leaving isolation, and any command or batch step that leaves another selection. A failed command that selected its ids first puts the count back with the selection. The selection comes back when the count, the selection, the isolation and the user's objects are unchanged; a symbol part needs the art unchanged. --- crates/engine/src/cmd/edit.rs | 2 + crates/engine/src/cmd/object/arrange.rs | 2 + crates/engine/src/doc_state.rs | 4 + crates/engine/src/session/edit.rs | 1 + crates/engine/src/session/execute.rs | 29 +++- crates/engine/src/session/undo.rs | 2 + crates/ui-egui/src/dialogs/dxf_import.rs | 9 +- crates/ui-egui/src/placing.rs | 26 +++- crates/ui-egui/src/placing/tests.rs | 164 ++++++++++++++++++++++- 9 files changed, 228 insertions(+), 11 deletions(-) diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index 55726c31c9..52330c1dde 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -835,6 +835,7 @@ fn undo(s: &mut Session, _: &Value) -> Result { let doc = std::mem::replace(&mut st.doc, e.doc); keep_unrecorded(&doc, &e.unrecorded, &mut st.doc); let selection = std::mem::replace(&mut st.selection, Arc::unwrap_or_clone(e.selection)); + st.selections = st.selections.wrapping_add(1); let selection = shared_selection(selection, st.history.redo.last()); let mut turned = crate::HistoryEntry::turned(e.label, doc, selection, &st.doc, costs); turned.named = e.named; @@ -873,6 +874,7 @@ fn redo(s: &mut Session, _: &Value) -> Result { let doc = std::mem::replace(&mut st.doc, e.doc); keep_unrecorded(&doc, &e.unrecorded, &mut st.doc); let selection = std::mem::replace(&mut st.selection, Arc::unwrap_or_clone(e.selection)); + st.selections = st.selections.wrapping_add(1); let selection = shared_selection(selection, st.history.undo.last()); let mut turned = crate::HistoryEntry::turned(e.label, doc, selection, &st.doc, costs); turned.named = e.named; diff --git a/crates/engine/src/cmd/object/arrange.rs b/crates/engine/src/cmd/object/arrange.rs index 8ed4656295..f234f4f0b9 100644 --- a/crates/engine/src/cmd/object/arrange.rs +++ b/crates/engine/src/cmd/object/arrange.rs @@ -457,6 +457,7 @@ pub(super) fn exit_isolation(s: &mut Session, p: &Value) -> Result { crate::cmd::distortcmds::finish_edit_text(st, inner); st.isolation = Some(layer); st.selection.set([left]); + st.selections = st.selections.wrapping_add(1); st.revision += 1; return ok(); } @@ -494,6 +495,7 @@ pub(super) fn exit_isolation(s: &mut Session, p: &Value) -> Result { crate::cmd::distortcmds::finish_edit_text(st, i); let target = st.doc.parent_of(left).filter(|p| st.doc.node(*p).is_some_and(|n| n.extras().shaper.is_some())).unwrap_or(left); st.selection.set([target]); + st.selections = st.selections.wrapping_add(1); // A guide path isolated while Lock Guides is on isn't selected (#1534). crate::deselect_hidden(&menu, &st.doc, &mut st.selection); // The art on a locked artboard can't be selected. diff --git a/crates/engine/src/doc_state.rs b/crates/engine/src/doc_state.rs index 501cb6cd53..f31b7f8152 100644 --- a/crates/engine/src/doc_state.rs +++ b/crates/engine/src/doc_state.rs @@ -51,6 +51,9 @@ pub struct DocState { /// Increments on every change (also selection and view-only changes); UIs re-render when it /// moves. Not a dirty flag: see [`DocState::is_dirty`]. pub revision: u64, + /// Increments each time the selection is set through [`crate::Session::select`] and the other + /// selection entries, even when it ends as it was. Not saved, not undoable. + pub selections: u64, /// The document as last saved (or opened). Structural sharing makes "unchanged" a pointer /// comparison, and undoing back to the saved state counts as clean. pub(crate) saved_doc: Arc, @@ -535,6 +538,7 @@ impl DocState { history: History { limit: 500, ..Default::default() }, path, revision: 1, + selections: 0, active_layer, layer_rows: vec![], layers_reveal: None, diff --git a/crates/engine/src/session/edit.rs b/crates/engine/src/session/edit.rs index c299347654..bcb09c0b66 100644 --- a/crates/engine/src/session/edit.rs +++ b/crates/engine/src/session/edit.rs @@ -306,6 +306,7 @@ impl Session { st.layer_rows.clear(); } st.revision += 1; + st.selections = st.selections.wrapping_add(1); // Puppet Warp pins belong to the art they were placed on: another selection starts afresh. if st.doc.puppet.as_ref().is_some_and(|p| p.ids != st.selection.objects) { cmd::distortcmds::drop_puppet_pins(st); diff --git a/crates/engine/src/session/execute.rs b/crates/engine/src/session/execute.rs index 25a9b278b1..fde26a790d 100644 --- a/crates/engine/src/session/execute.rs +++ b/crates/engine/src/session/execute.rs @@ -24,6 +24,16 @@ fn with_settled_warnings(mut r: Value, settled: &[String]) -> Value { r } +/// What [`Session::execute`] compares to tell that a command changed the selection: the counts of +/// what is selected and the first and last object, guide and slice, read in constant time. +type SelectionSummary = ([usize; 5], [Option; 6], bool); + +fn selection_summary(s: &Selection) -> SelectionSummary { + let counts = [s.objects.len(), s.anchors.len(), s.segments.len(), s.guides.len(), s.slices.len()]; + let ends = [s.objects.first(), s.objects.last(), s.guides.first(), s.guides.last(), s.slices.first(), s.slices.last()].map(|id| id.copied()); + (counts, ends, s.symbol_part.is_some()) +} + impl Session { /// Run a command callback and keep warnings from every preview it settles or restores. pub(crate) fn command_with_settled_warnings(&mut self, f: impl FnOnce(&mut Self) -> Result) -> Result { @@ -72,7 +82,19 @@ impl Session { if self.plugins_loading() && crate::waits_for_plugin_loads(id) { self.finish_plugin_loads(); } - self.revealing(|s| s.execute_unwatched(id, params)) + // A command, a step of a batch included, that leaves the active document with another + // selection counts as a selection change ([`crate::DocState::selections`]), whichever way + // it wrote the selection. The selections are compared by a summary that takes constant time. + let before = self.active().map(|st| (st.uid, st.selections, selection_summary(&st.selection))); + let r = self.revealing(|s| s.execute_unwatched(id, params)); + if let Some((uid, selections, summary)) = before + && let Some(st) = self.document_mut(uid) + && st.selections == selections + && selection_summary(&st.selection) != summary + { + st.selections = st.selections.wrapping_add(1); + } + r } /// Run `f`, a top-level entry that changes the active document's rows, current layer or @@ -230,7 +252,7 @@ impl Session { params.get("ids").filter(|v| !v.is_null()).cloned().or_else(|| given.map(|ids| ids.iter().map(|i| i.0).collect::>().into())) }) .flatten(); - let selected_before = select_first.as_ref().and(self.active()).map(|d| (d.uid, d.selection.clone(), d.active_layer)); + let selected_before = select_first.as_ref().and(self.active()).map(|d| (d.uid, d.selection.clone(), d.active_layer, d.selections)); // Only a selection command that changes the selection loads its paints for new art: other // commands, and clicking what is already selected, keep a sampled paint in the proxies. let selection_was = (id.starts_with("select.") || id == "layer.target").then(|| self.active().map(|d| d.selection.clone())).flatten(); @@ -240,11 +262,12 @@ impl Session { } let r = cmd::run_spec(s, spec, run_params); if r.is_err() - && let Some((uid, selection, layer)) = selected_before + && let Some((uid, selection, layer, selections)) = selected_before && let Some(st) = s.docs.iter_mut().find(|d| d.uid == uid) { st.selection = selection; st.active_layer = layer; + st.selections = selections; st.revision += 1; } r diff --git a/crates/engine/src/session/undo.rs b/crates/engine/src/session/undo.rs index bf7b0bf6f7..946af081fa 100644 --- a/crates/engine/src/session/undo.rs +++ b/crates/engine/src/session/undo.rs @@ -118,6 +118,7 @@ impl Session { } let undone = std::mem::replace(&mut st.doc, e.doc); st.selection = Arc::unwrap_or_clone(e.selection); + st.selections = st.selections.wrapping_add(1); deselect_hidden(&self.menu, &st.doc, &mut st.selection); st.restore_isolation(g.isolation, &undone); st.sync_new_art(); @@ -275,6 +276,7 @@ impl Session { } let undone = std::mem::replace(&mut st.doc, doc); st.selection = selection; + st.selections = st.selections.wrapping_add(1); st.restore_isolation(scope.isolation, &undone); cmd::globaledit::follow_history(st); st.drop_stale_variables_highlight(); diff --git a/crates/ui-egui/src/dialogs/dxf_import.rs b/crates/ui-egui/src/dialogs/dxf_import.rs index 737623f09e..55f35d97ff 100644 --- a/crates/ui-egui/src/dialogs/dxf_import.rs +++ b/crates/ui-egui/src/dialogs/dxf_import.rs @@ -516,7 +516,14 @@ fn confirm(app: &mut VectorcraftApp, source: &Source, choices: &DxfChoices) -> R let user = st.selection.clone(); app.session.execute("select.set", &json!({ "ids": [old.0] })).map_err(|e| e.to_string())?; let st = app.session.doc().map_err(|e| e.to_string())?; - user_selection = Some(crate::placing::Reselect { doc: st.uid, revision: st.revision, user }); + user_selection = Some(crate::placing::Reselect { + doc: st.uid, + swapped: st.selection.clone(), + selections: st.selections, + art: st.doc.clone(), + isolation: st.isolation, + user, + }); } } // It goes where new art went when Place started, and what the user changed since is diff --git a/crates/ui-egui/src/placing.rs b/crates/ui-egui/src/placing.rs index 8bb2d58cce..e27bc07b23 100644 --- a/crates/ui-egui/src/placing.rs +++ b/crates/ui-egui/src/placing.rs @@ -193,8 +193,16 @@ pub struct Pending { pub(crate) struct Reselect { /// The document whose selection Replace changed. pub(crate) doc: u64, - /// The document's revision after Replace selected its object. - pub(crate) revision: u64, + /// The selection Replace made: the object it swaps. + pub(crate) swapped: vectorcraft_doc::Selection, + /// The document's selection count ([`vectorcraft_engine::DocState::selections`]) after it. + /// The user's selection comes back only while neither changed, whatever else was edited. + pub(crate) selections: u64, + /// The art then: the user's selection comes back only while each object it holds is as it + /// was, so that its selected anchors and segments still name the same points. + pub(crate) art: std::sync::Arc, + /// The group or layer isolated then: the user's selection comes back only in the same isolation. + pub(crate) isolation: Option, /// The user's selection before it. pub(crate) user: vectorcraft_doc::Selection, } @@ -592,12 +600,20 @@ fn finish(app: &mut VectorcraftApp, p: &Pending, r: Result) { } } -/// Restore the user's selection while the document's revision is unchanged and its objects still exist. -/// The whole selection, guides, slices and new art included, goes through the selection filters as +/// Restore the user's selection while the selection Replace made is unchanged and the user's objects +/// are still there as they were. The whole selection, guides, slices and new art included, goes through the selection filters as /// they are now, and the current layer and active document stay current. pub(crate) fn reselect(app: &mut VectorcraftApp, back: &Reselect) { let Some(st) = app.session.documents().iter().find(|st| st.uid == back.doc) else { return }; - if st.revision != back.revision || !back.user.objects.iter().all(|id| st.doc.node(*id).is_some()) { + let kept = |id: &vectorcraft_doc::NodeId| st.doc.node(*id).is_some_and(|n| back.art.node(*id) == Some(n)); + // A symbol part names a child of the symbol's art, which an edit to the symbol can change. + let part_kept = back.user.symbol_part.is_none() || std::sync::Arc::ptr_eq(&st.doc, &back.art); + if st.selections != back.selections + || st.selection != back.swapped + || st.isolation != back.isolation + || !part_kept + || !back.user.objects.iter().all(kept) + { return; } let layer = st.active_layer; diff --git a/crates/ui-egui/src/placing/tests.rs b/crates/ui-egui/src/placing/tests.rs index 434f47e51e..eef7b0e037 100644 --- a/crates/ui-egui/src/placing/tests.rs +++ b/crates/ui-egui/src/placing/tests.rs @@ -2066,7 +2066,166 @@ fn swapped_out(app: &mut VectorcraftApp, other: NodeId) -> Reselect { let user = app.session.doc().unwrap().selection.clone(); app.run("select.set", json!({"ids": [other.0]})).unwrap(); let st = app.session.doc().unwrap(); - Reselect { doc: st.uid, revision: st.revision, user } + Reselect { doc: st.uid, swapped: st.selection.clone(), selections: st.selections, art: st.doc.clone(), isolation: st.isolation, user } +} + +/// The objects selected before the swap, with two rectangles drawn: the user's and the swapped one. +fn two_rectangles(app: &mut VectorcraftApp) -> (NodeId, NodeId) { + let mut rect = |x| NodeId(app.run("shape.rectangle", json!({"x": x, "y": 10, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap()); + let (mine, other) = (rect(10.0), rect(60.0)); + app.run("select.set", json!({"ids": [mine.0]})).unwrap(); + (mine, other) +} + +#[test] +fn a_raised_revision_alone_does_not_block_the_restore() { + let mut app = app(false); + let (mine, other) = two_rectangles(&mut app); + let back = swapped_out(&mut app, other); + // The rollback of a failed Replace puts the document back as it was and raises its revision + // (`Session::place_read`), which this does alone. + let uid = app.session.doc().unwrap().uid; + app.session.document_mut(uid).unwrap().revision += 1; + reselect(&mut app, &back); + assert_eq!(app.session.doc().unwrap().selection.objects, vec![mine], "the user's selection comes back"); +} + +#[test] +fn a_selection_undo_and_redo_gave_back_is_kept() { + let mut app = app(false); + let (mine, other) = two_rectangles(&mut app); + app.run("select.set", json!({"ids": [other.0]})).unwrap(); + app.run("artboard.setProps", json!({"index": 0, "name": "Front"})).unwrap(); + app.run("select.set", json!({"ids": [mine.0]})).unwrap(); + let back = swapped_out(&mut app, other); + app.run("edit.undo", json!({})).unwrap(); + app.run("edit.redo", json!({})).unwrap(); + assert_eq!(app.session.doc().unwrap().selection.objects, vec![other], "Redo selects the object again"); + reselect(&mut app, &back); + assert_eq!(app.session.doc().unwrap().selection.objects, vec![other], "the selection Redo gave back is kept"); +} + +#[test] +fn a_selection_isolation_gave_back_is_kept() { + let mut app = app(false); + let (mine, other) = two_rectangles(&mut app); + let group = NodeId(app.run("object.group", json!({ "ids": [other.0] })).unwrap()["id"].as_u64().unwrap()); + app.run("select.set", json!({"ids": [mine.0]})).unwrap(); + let back = swapped_out(&mut app, group); + app.run("object.isolate", json!({"id": group.0})).unwrap(); + app.run("object.exitIsolation", json!({})).unwrap(); + assert_eq!(app.session.doc().unwrap().selection.objects, vec![group], "leaving isolation selects the group again"); + reselect(&mut app, &back); + assert_eq!(app.session.doc().unwrap().selection.objects, vec![group], "the selection leaving isolation made is kept"); +} + +#[test] +fn a_selection_a_batch_step_gave_back_is_kept() { + let mut app = app(false); + let (mine, other) = two_rectangles(&mut app); + let group = NodeId(app.run("object.group", json!({ "ids": [other.0] })).unwrap()["id"].as_u64().unwrap()); + app.run("select.set", json!({"ids": [mine.0]})).unwrap(); + let back = swapped_out(&mut app, group); + let steps = json!([{"command": "object.isolate", "params": {"id": group.0}}, {"command": "object.exitIsolation"}]); + app.run("command.batch", json!({"commands": steps})).unwrap(); + assert_eq!(app.session.doc().unwrap().selection.objects, vec![group], "leaving isolation selects the group again"); + reselect(&mut app, &back); + assert_eq!(app.session.doc().unwrap().selection.objects, vec![group], "the selection the batch made is kept"); +} + +#[test] +fn leaving_isolation_onto_the_swapped_group_keeps_it_selected() { + let mut app = app(false); + let (_, other) = two_rectangles(&mut app); + let group = NodeId(app.run("object.group", json!({ "ids": [other.0] })).unwrap()["id"].as_u64().unwrap()); + app.run("object.isolate", json!({"id": group.0})).unwrap(); + app.run("select.set", json!({"ids": [other.0]})).unwrap(); + let back = swapped_out(&mut app, group); + app.run("object.exitIsolation", json!({})).unwrap(); + assert_eq!(app.session.doc().unwrap().selection.objects, vec![group], "leaving isolation selects the group"); + reselect(&mut app, &back); + assert_eq!(app.session.doc().unwrap().selection.objects, vec![group], "the selection leaving isolation made is kept"); +} + +#[test] +fn a_selection_a_lock_and_unlock_batch_gave_back_is_kept() { + let mut app = app(false); + let (mine, other) = two_rectangles(&mut app); + app.run("select.set", json!({"ids": [mine.0]})).unwrap(); + let back = swapped_out(&mut app, other); + let steps = json!([{"command": "object.lock"}, {"command": "object.unlockAll"}]); + app.run("command.batch", json!({"commands": steps})).unwrap(); + assert_eq!(app.session.doc().unwrap().selection.objects, vec![other], "Unlock All selects what it unlocks"); + reselect(&mut app, &back); + assert_eq!(app.session.doc().unwrap().selection.objects, vec![other], "the selection the batch made is kept"); +} + +#[test] +fn a_selection_is_not_restored_into_another_isolation() { + let mut app = app(false); + let (_, other) = two_rectangles(&mut app); + let group = NodeId(app.run("object.group", json!({ "ids": [other.0] })).unwrap()["id"].as_u64().unwrap()); + app.run("select.set", json!({"ids": []})).unwrap(); + let mut back = swapped_out(&mut app, group); + app.run("object.isolate", json!({"id": group.0})).unwrap(); + app.run("select.set", json!({"ids": [group.0]})).unwrap(); + let st = app.session.doc().unwrap(); + (back.swapped, back.selections) = (st.selection.clone(), st.selections); + let selected = st.selection.objects.clone(); + reselect(&mut app, &back); + assert_eq!(app.session.doc().unwrap().selection.objects, selected, "the selection made in isolation is kept"); +} + +#[test] +fn a_command_that_fails_and_puts_the_selection_back_does_not_block_the_restore() { + let mut app = app(false); + let (mine, other) = two_rectangles(&mut app); + let back = swapped_out(&mut app, other); + let far = NodeId(app.run("shape.rectangle", json!({"x": 300, "y": 300, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap()); + app.run("select.set", json!({"ids": [other.0]})).unwrap(); + let mut back = back; + let st = app.session.doc().unwrap(); + (back.swapped, back.selections, back.art) = (st.selection.clone(), st.selections, st.doc.clone()); + assert!(app.run("object.pathfinder.intersect", json!({"ids": [other.0, far.0]})).is_err(), "disjoint shapes have no intersection"); + assert_eq!(app.session.doc().unwrap().selection.objects, vec![other], "the failed command puts the selection back"); + reselect(&mut app, &back); + assert_eq!(app.session.doc().unwrap().selection.objects, vec![mine], "the user's selection comes back"); +} + +#[test] +fn a_symbol_part_is_not_restored_after_an_edit() { + let mut app = app(false); + let (mine, other) = two_rectangles(&mut app); + let mut back = swapped_out(&mut app, other); + back.user.symbol_part = Some(vectorcraft_doc::SymbolPart { instance: mine, path: vec![0] }); + app.run("artboard.setProps", json!({"index": 0, "name": "Front"})).unwrap(); + reselect(&mut app, &back); + assert_eq!(app.session.doc().unwrap().selection.objects, vec![other], "a part of art that may have changed is not restored"); +} + +#[test] +fn selected_anchors_of_a_reversed_path_are_not_restored() { + let mut app = app(false); + let (mine, other) = two_rectangles(&mut app); + app.run("select.anchors", json!({"id": mine.0, "anchors": [[0, 0]], "mode": "set"})).unwrap(); + let back = swapped_out(&mut app, other); + app.run("path.reverse", json!({"ids": [mine.0], "reversed": true})).unwrap(); + assert_eq!(app.session.doc().unwrap().selection.objects, vec![other], "the edit keeps the selection"); + reselect(&mut app, &back); + assert_eq!(app.session.doc().unwrap().selection.objects, vec![other], "anchor numbers of the edited path are not restored"); +} + +#[test] +fn an_edit_that_keeps_the_selection_still_restores_it() { + let mut app = app(false); + let (mine, other) = two_rectangles(&mut app); + let back = swapped_out(&mut app, other); + let revision = app.session.doc().unwrap().revision; + app.run("artboard.setProps", json!({"index": 0, "name": "Front"})).unwrap(); + assert_ne!(app.session.doc().unwrap().revision, revision, "the edit changes the document"); + assert_eq!(app.session.doc().unwrap().selection.objects, vec![other], "the edit keeps the selection"); + reselect(&mut app, &back); + assert_eq!(app.session.doc().unwrap().selection.objects, vec![mine], "the user's selection comes back"); } #[test] @@ -2079,7 +2238,8 @@ fn a_restored_selection_leaves_out_guides_locked_since() { assert_eq!(app.session.doc().unwrap().selection.guides.len(), 1, "the ruler guide is selected"); let mut back = swapped_out(&mut app, other); app.run("view.guides.lock", json!({"locked": true})).unwrap(); - back.revision = app.session.doc().unwrap().revision; + let st = app.session.doc().unwrap(); + (back.swapped, back.selections) = (st.selection.clone(), st.selections); reselect(&mut app, &back); assert!(app.session.doc().unwrap().selection.guides.is_empty(), "the locked guide is not selected again"); }