diff --git a/crates/engine/src/cmd/plugin_call.rs b/crates/engine/src/cmd/plugin_call.rs index 3ab02a0719..ab74e4baf7 100644 --- a/crates/engine/src/cmd/plugin_call.rs +++ b/crates/engine/src/cmd/plugin_call.rs @@ -608,13 +608,21 @@ impl Transaction { for st in &mut s.docs { // Past the newest revision the document reached, so the restored one redraws. A // document the transaction left as it was keeps its revision, so a run made - // away from the session on it still applies. + // away from the session on it still applies. Putting back an older snapshot, or + // reopening a document the calls closed, counts as a rollback: an object the calls + // made can lose its node ID to a new one. The count never goes below the highest + // one the document reached. let reached: Vec<_> = open.iter().filter(|d| d.uid == st.uid).collect(); let unchanged = !reached.is_empty() && reached.iter().all(|d| d.revision == st.revision && d.selection == st.selection); if !unchanged { let newest = reached.iter().map(|d| d.revision).max().unwrap_or(st.revision); st.revision = newest.max(st.revision).saturating_add(1); } + let rollbacks = reached.iter().map(|d| d.rollbacks).max().unwrap_or(st.rollbacks); + st.rollbacks = rollbacks.max(st.rollbacks); + if reached.is_empty() || reached.iter().any(|d| !Arc::ptr_eq(&d.doc, &st.doc)) { + st.rollbacks = st.rollbacks.saturating_add(1); + } crate::deselect_hidden(&s.menu, &st.doc, &mut st.selection); } s.active = active; diff --git a/crates/engine/src/cmd/symboledit.rs b/crates/engine/src/cmd/symboledit.rs index 3b5d7cdf48..6b7e314353 100644 --- a/crates/engine/src/cmd/symboledit.rs +++ b/crates/engine/src/cmd/symboledit.rs @@ -231,6 +231,7 @@ pub(crate) fn leave(s: &mut Session, _: &Value) -> Result { st.selection.prune(&st.doc); st.history.redo = Arc::unwrap_or_clone(redo); st.revision += 1; + st.rollbacks += 1; } else { s.edit("Exit Symbol Editing Mode", |d, sel| { finish(d, sel); diff --git a/crates/engine/src/doc_state.rs b/crates/engine/src/doc_state.rs index 501cb6cd53..8dc15f5aac 100644 --- a/crates/engine/src/doc_state.rs +++ b/crates/engine/src/doc_state.rs @@ -121,6 +121,14 @@ pub struct DocState { /// Advances when Undo or Redo restores an older document snapshot. The same node ID can name different objects /// across that boundary. pub history_restores: u64, + /// Advances when a canceled undo group, undo scope or interaction, or Exit Symbol Editing Mode taking + /// back the entering step, puts back an older document snapshot. A canceled plug-in run advances it + /// when its calls changed the document. A preview advances it when it discards an earlier preview + /// that allocated node IDs, or fails after discarding an earlier preview's document change. + /// A command run during a tool interaction advances it when it sets aside a preview that allocated + /// node IDs. + /// The same node ID can name different objects across that boundary. + pub rollbacks: u64, /// Preferences › User Interface › Open Documents As Tabs when the document opened: cleared, /// the UI opens it in a floating window of its own. pub opened_as_tab: bool, @@ -556,6 +564,7 @@ impl DocState { activated: 0, reverts: 0, history_restores: 0, + rollbacks: 0, opened_as_tab: true, mask_view: None, spelling_ignored: Default::default(), @@ -812,6 +821,9 @@ impl DocState { /// End the interaction in progress, undoing what it changed. pub(crate) fn undo_interaction(&mut self) { if let Some(it) = self.interaction.take() { + if !Arc::ptr_eq(&self.doc, &it.doc) { + self.rollbacks += 1; + } self.doc = it.doc; self.selection = Arc::unwrap_or_clone(it.selection); self.sync_new_art(); diff --git a/crates/engine/src/session/edit.rs b/crates/engine/src/session/edit.rs index 604ca822df..2865a74dce 100644 --- a/crates/engine/src/session/edit.rs +++ b/crates/engine/src/session/edit.rs @@ -366,6 +366,9 @@ impl Session { let previewed = !Arc::ptr_eq(&st.doc, &interaction.doc) || st.selection != *interaction.selection; let shown = previewed.then(|| (st.doc.clone(), st.selection.clone())); if previewed { + if st.doc.peek_next_id() > interaction.doc.peek_next_id() { + st.rollbacks += 1; + } st.doc = interaction.doc.clone(); st.selection.clone_from(&interaction.selection); st.revision += 1; @@ -609,7 +612,7 @@ impl Session { // `defaultsOnly: true`, and one after it. let tool_paints = self.tool_paints(false) || self.tool_paints(true); let new_art_basic = self.prefs.new_art_basic; - let (paint, restore_paint, inherited, last_preview_paint) = { + let (paint, restore_paint, inherited, last_preview_paint, discarded_uid, freed_ids, discarded) = { let menu = self.menu.clone(); let st = self.doc_mut()?; let Some(it) = &mut st.interaction else { return Err(EngineError::Other("no interaction in progress".into())) }; @@ -620,6 +623,8 @@ impl Session { st.revision += 1; } let undone = std::mem::replace(&mut st.doc, it.doc.clone()); + let freed_ids = undone.peek_next_id() > it.doc.peek_next_id(); + let discarded = !Arc::ptr_eq(&undone, &it.doc); let isolation = it.isolation; // A batch, or a preview that changed the new-art paints (a pattern rename), started from // the paints the interaction began with. @@ -653,7 +658,7 @@ impl Session { // undone with it. st.restore_isolation(isolation, &undone); cmd::globaledit::follow_history(st); - (paint, restore_paint, inherited, last_preview_paint) + (paint, restore_paint, inherited, last_preview_paint, st.uid, freed_ids, discarded) }; // The paints before the previews that build on each other: a preview that starts from the // interaction's paints (or from the inherited ones) starts a new run of them. A field that @@ -699,6 +704,14 @@ impl Session { } let after_paint = r.is_ok().then(|| (base, self.paint.clone())); let after_item = self.active_appearance_item.clone(); + // A preview advances rollbacks when it discards an earlier preview that allocated node IDs, or + // fails after discarding an earlier preview's document change, even when the command activates + // another document. + if let Some(st) = self.docs.iter_mut().find(|d| d.uid == discarded_uid) + && (freed_ids || (r.is_err() && discarded)) + { + st.rollbacks += 1; + } let st = self.doc_mut()?; if let Some(it) = &mut st.interaction { it.active_appearance_item = diff --git a/crates/engine/src/session/undo.rs b/crates/engine/src/session/undo.rs index bf7b0bf6f7..d51c5ad7d6 100644 --- a/crates/engine/src/session/undo.rs +++ b/crates/engine/src/session/undo.rs @@ -124,6 +124,7 @@ impl Session { cmd::globaledit::follow_history(st); st.drop_stale_variables_highlight(); st.revision += 1; + st.rollbacks += 1; // The journal drops only the canceled groups' own entries and keeps the ones made in other documents meanwhile. journal.extend(g.journal); steps.extend(g.steps); @@ -273,6 +274,7 @@ impl Session { } Some(_) => return, } + let changed = !Arc::ptr_eq(&st.doc, &doc); let undone = std::mem::replace(&mut st.doc, doc); st.selection = selection; st.restore_isolation(scope.isolation, &undone); @@ -281,6 +283,9 @@ impl Session { deselect_hidden(&menu, &st.doc, &mut st.selection); st.history.recost_last(&st.doc); st.revision += 1; + if changed { + st.rollbacks += 1; + } if colors_changed { self.paint = scope.paint; } diff --git a/crates/engine/src/tests/journal.rs b/crates/engine/src/tests/journal.rs index 35f86fa582..1be7fb69b2 100644 --- a/crates/engine/src/tests/journal.rs +++ b/crates/engine/src/tests/journal.rs @@ -829,6 +829,172 @@ fn canceling_undo_groups_in_two_documents_drops_the_edits_of_both_from_the_journ assert_eq!(ids.last(), Some(&"edit.undoGroup.end")); } +/// A canceled undo group puts back an older snapshot, after which a new object can take a removed object's ID, so +/// it advances `rollbacks`; a group that ends without cancel leaves it as it is. Neither changes `history_restores`. +#[test] +fn undo_group_cancellation_advances_rollbacks_only_when_restoring() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + for cancel in [true, false] { + let restores = s.doc().unwrap().history_restores; + let rollbacks = s.doc().unwrap().rollbacks; + let before = s.doc().unwrap().doc.node_count(); + s.execute("edit.undoGroup.begin", &json!({})).unwrap(); + s.execute("shape.rectangle", &rect_step(10)["params"]).unwrap(); + assert!(s.doc().unwrap().doc.node_count() > before); + s.execute("edit.undoGroup.end", &json!({"cancel": cancel})).unwrap(); + assert_eq!(s.doc().unwrap().history_restores, restores); + if cancel { + assert!(s.doc().unwrap().rollbacks > rollbacks, "a canceled group advances the rollback count"); + assert_eq!(s.doc().unwrap().doc.node_count(), before); + } else { + assert_eq!(s.doc().unwrap().rollbacks, rollbacks); + assert!(s.doc().unwrap().doc.node_count() > before); + } + } +} + +/// Exit Symbol Editing Mode with nothing changed takes back the entering step, which puts back an older snapshot, so +/// it advances `rollbacks`; leaving after an edit adds a step and leaves it as it is. +#[test] +fn leaving_symbol_editing_advances_rollbacks_only_when_taking_back_the_entering_step() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + s.execute("shape.rectangle", &rect_step(10)["params"]).unwrap(); + s.execute("symbol.new", &json!({"name": "Box"})).unwrap(); + for edited in [false, true] { + let rollbacks = s.doc().unwrap().rollbacks; + s.execute("symbol.edit", &json!({})).unwrap(); + if edited { + s.execute("object.move", &json!({"dx": 5, "dy": 0})).unwrap(); + } + s.execute("symbol.exitEditing", &json!({})).unwrap(); + if edited { + assert_eq!(s.doc().unwrap().rollbacks, rollbacks, "leaving after an edit keeps the rollback count"); + } else { + assert!(s.doc().unwrap().rollbacks > rollbacks, "taking back the entering step advances the rollback count"); + } + } +} + +/// Canceling an interaction whose preview changed the document advances `rollbacks`; canceling one that changed +/// nothing leaves it as it is. +#[test] +fn interaction_cancellation_advances_rollbacks_only_when_restoring() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + for previewed in [true, false] { + let rollbacks = s.doc().unwrap().rollbacks; + s.begin_interaction("Rectangle").unwrap(); + if previewed { + s.preview("shape.rectangle", &rect_step(10)["params"]).unwrap(); + } + s.cancel_interaction().unwrap(); + if previewed { + assert!(s.doc().unwrap().rollbacks > rollbacks, "a canceled preview advances the rollback count"); + } else { + assert_eq!(s.doc().unwrap().rollbacks, rollbacks, "a cancel with no preview keeps the rollback count"); + } + } +} + +/// A preview advances `rollbacks` when it discards earlier art and frees its node IDs, whether it +/// succeeds or fails. A failed preview also advances it when it discards an earlier document change +/// without freeing IDs. A successful preview that draws the earlier art again also advances the count. +#[test] +fn a_preview_that_discards_earlier_art_and_frees_its_ids_advances_rollbacks() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let rollbacks = s.doc().unwrap().rollbacks; + s.begin_interaction("Rectangle").unwrap(); + s.preview("shape.rectangle", &rect_step(10)["params"]).unwrap(); + assert!(s.preview("unknown.command", &json!({})).is_err(), "an unknown preview command returns an error"); + assert!(s.doc().unwrap().rollbacks > rollbacks, "a failed preview after a drawn preview advances the rollback count"); + s.cancel_interaction().unwrap(); + let rollbacks = s.doc().unwrap().rollbacks; + s.begin_interaction("Rectangle").unwrap(); + assert!(s.preview("unknown.command", &json!({})).is_err(), "an unknown preview command returns an error"); + assert_eq!(s.doc().unwrap().rollbacks, rollbacks, "a failed preview with nothing previewed keeps the rollback count"); + s.cancel_interaction().unwrap(); + let rollbacks = s.doc().unwrap().rollbacks; + s.begin_interaction("Rectangle").unwrap(); + s.preview("shape.rectangle", &rect_step(10)["params"]).unwrap(); + s.preview("shape.rectangle", &rect_step(30)["params"]).unwrap(); + assert_eq!(s.doc().unwrap().rollbacks, rollbacks + 1, "a preview that replaces earlier drawn art advances the rollback count"); + s.cancel_interaction().unwrap(); + let rollbacks = s.doc().unwrap().rollbacks; + let starting_doc = s.doc().unwrap().doc.clone(); + s.begin_interaction("Rectangle").unwrap(); + s.preview("shape.rectangle", &rect_step(10)["params"]).unwrap(); + s.preview("select.set", &json!({"ids": []})).unwrap(); + assert!(std::sync::Arc::ptr_eq(&s.doc().unwrap().doc, &starting_doc), "a selection-only preview leaves the starting document Arc"); + assert_eq!( + s.doc().unwrap().rollbacks, + rollbacks + 1, + "a preview that leaves the starting document after a drawn preview advances the rollback count" + ); + s.cancel_interaction().unwrap(); + let kept = s.execute("shape.rectangle", &rect_step(5)["params"]).unwrap()["id"].clone(); + let rollbacks = s.doc().unwrap().rollbacks; + let starting_doc = s.doc().unwrap().doc.clone(); + s.begin_interaction("Rectangle").unwrap(); + s.preview("shape.rectangle", &rect_step(10)["params"]).unwrap(); + let steps = json!({"commands": [ + {"command": "select.set", "params": {"ids": [kept]}}, + {"command": "object.move", "params": {"dx": 5, "dy": 0}} + ]}); + s.preview("command.batch", &steps).unwrap(); + assert!(!std::sync::Arc::ptr_eq(&s.doc().unwrap().doc, &starting_doc), "the move changes the document"); + assert_eq!(s.doc().unwrap().rollbacks, rollbacks + 1, "a preview that moves art instead of drawing it advances the rollback count"); + s.cancel_interaction().unwrap(); +} + +/// A command run during a tool interaction sets the preview aside and can reuse the node IDs the +/// preview allocated, so it advances `rollbacks`; with no IDs allocated by the preview it does not. +#[test] +fn a_command_outside_a_tool_interaction_advances_rollbacks_only_when_the_preview_allocated_ids() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + s.begin_interaction("Rectangle").unwrap(); + // A tool interaction routes the command through outside_interaction. + s.active_mut().unwrap().interaction.as_mut().unwrap().tool = true; + let preview_id = s.preview("shape.rectangle", &rect_step(10)["params"]).unwrap()["id"].clone(); + let rollbacks = s.doc().unwrap().rollbacks; + let command_id = s.execute("shape.rectangle", &rect_step(30)["params"]).unwrap()["id"].clone(); + assert_eq!(command_id, preview_id, "a command outside a tool interaction reuses the rectangle preview's node ID"); + assert_eq!(s.doc().unwrap().rollbacks, rollbacks + 1, "setting aside a preview that allocated IDs advances the rollback count"); + s.cancel_interaction().unwrap(); + + for previewed in [true, false] { + s.begin_interaction("Rectangle").unwrap(); + s.active_mut().unwrap().interaction.as_mut().unwrap().tool = true; + if previewed { + s.preview("select.none", &json!({})).unwrap(); + } + let rollbacks = s.doc().unwrap().rollbacks; + s.execute("shape.rectangle", &rect_step(50)["params"]).unwrap(); + assert_eq!(s.doc().unwrap().rollbacks, rollbacks, "a command with no preview IDs keeps the rollback count, previewed: {previewed}"); + s.cancel_interaction().unwrap(); + } +} + +/// A preview that activates another document advances rollbacks in the document whose art it discards. +#[test] +fn a_preview_that_activates_another_document_advances_only_the_source_rollbacks() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + s.execute("document.activate", &json!({"index": 0})).unwrap(); + let source_rollbacks = s.documents()[0].rollbacks; + let destination_rollbacks = s.documents()[1].rollbacks; + s.begin_interaction("Rectangle").unwrap(); + s.preview("shape.rectangle", &rect_step(10)["params"]).unwrap(); + s.preview("document.activate", &json!({"index": 1})).unwrap(); + assert_eq!(s.active_index(), Some(1), "the activation preview makes the destination document active"); + assert!(s.documents()[0].rollbacks > source_rollbacks, "discarding the rectangle preview advances the source document's rollback count"); + assert_eq!(s.documents()[1].rollbacks, destination_rollbacks, "the activation preview keeps the destination document's rollback count unchanged"); +} + /// A cancel drops only the canceled groups' own entries from the journal: an edit made in another /// document while a group was open stays in that document and in the journal. #[test] @@ -1283,6 +1449,41 @@ fn an_undo_scope_in_an_open_group_takes_back_only_its_own_edits() { assert_eq!(objects(&s), 0, "one undo takes back the group's edits"); } +/// A canceled undo scope that joined an open group advances `rollbacks` only when it restores an older snapshot; +/// a scope that makes no edit or ends without cancel leaves it as it is. Neither changes `history_restores`. +#[test] +fn joined_undo_scope_cancellation_advances_rollbacks_only_when_restoring() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + s.begin_undo_group(); + for cancel in [true, false] { + let restores = s.doc().unwrap().history_restores; + let rollbacks = s.doc().unwrap().rollbacks; + let before = s.doc().unwrap().doc.node_count(); + let scope = s.begin_undo_scope().unwrap(); + s.execute("shape.rectangle", &rect_step(10)["params"]).unwrap(); + assert!(s.doc().unwrap().doc.node_count() > before); + s.end_undo_scope(scope, cancel); + assert_eq!(s.doc().unwrap().history_restores, restores); + if cancel { + assert!(s.doc().unwrap().rollbacks > rollbacks, "a canceled scope advances the rollback count"); + assert_eq!(s.doc().unwrap().doc.node_count(), before); + } else { + assert_eq!(s.doc().unwrap().rollbacks, rollbacks); + assert!(s.doc().unwrap().doc.node_count() > before); + } + assert!(s.doc().unwrap().undo_group.is_some()); + } + s.execute("shape.rectangle", &rect_step(10)["params"]).unwrap(); + let restores = s.doc().unwrap().history_restores; + let rollbacks = s.doc().unwrap().rollbacks; + let scope = s.begin_undo_scope().unwrap(); + s.end_undo_scope(scope, true); + assert_eq!(s.doc().unwrap().rollbacks, rollbacks, "canceling a scope with no edits preserves the rollback count"); + assert_eq!(s.doc().unwrap().history_restores, restores); + s.end_undo_group(false); +} + /// A canceled undo scope that joined an open group forgets the journal entries it cut: when a command /// in another document takes the same entry number, a later cancel of the group keeps that entry, and /// the journal replays to the same documents. diff --git a/crates/engine/src/tests/plugins.rs b/crates/engine/src/tests/plugins.rs index 42728c7fa6..1652b2ea4e 100644 --- a/crates/engine/src/tests/plugins.rs +++ b/crates/engine/src/tests/plugins.rs @@ -8131,6 +8131,19 @@ fn install_select_all_then_remove(s: &mut Session, id: &str) { run(s, "plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(&wasm), "grant": grant, "replace": true})); } +/// Installs a filter `id` that calls `shape.rectangle` and then returns no objects. +fn install_draw_rectangle_then_remove(s: &mut Session, id: &str) { + let grant = json!(["doc.read", "doc.write", "commands"]); + let manifest = + format!(r#"{{"id":"{id}","name":"Test {id}","kind":"filter","api":2,"permissions":{grant},"commandAllowlist":["shape.rectangle"]}}"#); + let imports = r#"(import "env" "vc_call" (func $vc_call (param i32 i32 i32 i32) (result i32))) + (data (i32.const 0x2000) "shape.rectangle") + (data (i32.const 0x2100) "{\22x\22:0,\22y\22:0,\22width\22:5,\22height\22:5}")"#; + let first = "(drop (call $vc_call (i32.const 0x2000) (i32.const 15) (i32.const 0x2100) (i32.const 34)))"; + let wasm = wat::parse_str(tpl::with_imports(&manifest, imports, first, r#"{"objects":[]}"#)).unwrap(); + run(s, "plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(&wasm), "grant": grant, "replace": true})); +} + /// Runs the job of a run that [`FilterRun::begin_calls`] started as the web build's plug-in worker /// does, making each command call in `s` → its output. fn run_job_away(s: &mut Session, job: &cmd::plugin::FilterJob) -> Vec { @@ -8201,6 +8214,40 @@ fn a_calling_run_made_away_from_the_session_that_ends_changes_nothing() { run(&mut s, "plugin.remove", json!({"id": id})); } +/// A run made away from the session that ends after its calls changed the document advances `rollbacks`. +/// A run whose calls only changed the selection or that ends before any call keeps the rollback count. +#[test] +fn an_ended_calling_run_advances_rollbacks_only_when_its_calls_changed_the_document() { + use cmd::plugin::FilterRun; + let id = "test.engine.callsawayrollback"; + let draw_id = "test.engine.callsawayrollbackdraw"; + let mut s = session(); + install_select_all_then_remove(&mut s, id); + install_draw_rectangle_then_remove(&mut s, draw_id); + let (a, _) = (rect(&mut s, 10.0, "#ff0000"), rect(&mut s, 40.0, "#00ff00")); + for (plugin_id, called, changed_document) in [(draw_id, true, true), (id, true, false), (id, false, false)] { + run(&mut s, "select.set", json!({"ids": [a.0]})); + let rollbacks = s.doc().unwrap().rollbacks; + let job = FilterRun::begin_calls(&mut s, "plugin.run", &json!({"id": plugin_id})).unwrap(); + let doc = s.doc().unwrap().doc.clone(); + if called { + run_job_away(&mut s, &job); + assert_eq!(!std::sync::Arc::ptr_eq(&doc, &s.doc().unwrap().doc), changed_document, "the calls change only the intended state"); + assert_ne!(s.doc().unwrap().selection.objects, vec![a], "the calls change the selection"); + } + s.end_plugin_calls(); + if changed_document { + assert!(s.doc().unwrap().rollbacks > rollbacks, "an ended run whose calls changed the document advances the rollback count"); + } else if called { + assert_eq!(s.doc().unwrap().rollbacks, rollbacks, "an ended run whose calls only changed the selection keeps the rollback count"); + } else { + assert_eq!(s.doc().unwrap().rollbacks, rollbacks, "an ended run with no calls keeps the rollback count"); + } + } + run(&mut s, "plugin.remove", json!({"id": draw_id})); + run(&mut s, "plugin.remove", json!({"id": id})); +} + /// An output handed in for a run that holds the documents is dropped when that run ends: a later /// run with the same input and params is not given it, and `plugin.run` without its own output is /// refused. diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index 3a9142ba89..06bbd705e3 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -180,6 +180,7 @@ impl VectorcraftApp { multi_color: None, global_edit_count: None, shape_angle: None, + shape_edit_target: None, radius_corners: None, selected_rectangles: None, trace_presets: None, diff --git a/crates/ui-egui/src/caches.rs b/crates/ui-egui/src/caches.rs index d7d333402a..058a1099f4 100644 --- a/crates/ui-egui/src/caches.rs +++ b/crates/ui-egui/src/caches.rs @@ -160,6 +160,8 @@ pub struct CanvasCache { pub(crate) global_edit_count: Option<(crate::panels::properties::GlobalEditKey, usize)>, /// The selected live shape's angle, for (document uid, revision, kind of shape). pub shape_angle: Option, + /// The shape-wide edit target, for (document uid, revision). + pub(crate) shape_edit_target: Option<((u64, u64), egui::IdSalt)>, /// The corners a live shape's Corner Radius field sets, as one hash, for (document uid, /// File › Revert count, revision). pub(crate) radius_corners: Option<((u64, u64, u64), u64)>, diff --git a/crates/ui-egui/src/panels/transform/shape.rs b/crates/ui-egui/src/panels/transform/shape.rs index d493cdee9c..89a57e516a 100644 --- a/crates/ui-egui/src/panels/transform/shape.rs +++ b/crates/ui-egui/src/panels/transform/shape.rs @@ -11,7 +11,7 @@ use craft::ui::layout_components::{Row, Stack}; use craft::ui::pickers::Select; use craft::ui::text::{NumberField, link_toggle}; use craft::ui::value_drag::Slider; -use egui::Ui; +use egui::{IdSalt, Ui}; use serde_json::{Value, json}; use vectorcraft_doc::{LiveShape, Node, NodeKind}; use vectorcraft_geom::shapes::CornerKind; @@ -42,14 +42,22 @@ const SIDES_SLIDER: RangeInclusive = 3.0..=20.0; pub(crate) fn live_shape_rows(app: &mut VectorcraftApp, ui: &mut Ui, n: &Node, live: &LiveShape, headed: bool) -> bool { match live { LiveShape::Rectangle { .. } => under_heading(ui, headed.then(|| tl!("Rectangle Properties:")), |ui| { - angle_row(app, ui, live, "rectangleAngle"); + let target = shape_edit_target(app); + angle_row(app, ui, live, "rectangleAngle", target); corner_radius_row(app, ui, n); }), - LiveShape::Polygon { .. } => under_heading(ui, headed.then(|| tl!("Polygon Properties:")), |ui| polygon_rows(app, ui, n, live)), - LiveShape::Star { .. } => under_heading(ui, headed.then(|| tl!("Star Properties:")), |ui| star_rows(app, ui, live)), + LiveShape::Polygon { .. } => under_heading(ui, headed.then(|| tl!("Polygon Properties:")), |ui| { + let target = shape_edit_target(app); + polygon_rows(app, ui, n, live, target); + }), + LiveShape::Star { .. } => under_heading(ui, headed.then(|| tl!("Star Properties:")), |ui| { + let target = shape_edit_target(app); + star_rows(app, ui, live, target); + }), LiveShape::Ellipse { pie, .. } => under_heading(ui, Some(tl!("Ellipse Properties:")), |ui| { - angle_row(app, ui, live, "ellipseAngle"); - pie_rows(app, ui, *pie); + let target = shape_edit_target(app); + angle_row(app, ui, live, "ellipseAngle", target); + pie_rows(app, ui, *pie, target); }), LiveShape::Line { .. } => return line_rows(app, ui, live), _ => return false, @@ -57,6 +65,27 @@ pub(crate) fn live_shape_rows(app: &mut VectorcraftApp, ui: &mut Ui, n: &Node, l true } +/// The edit target of the live shape number fields: the active document, how many times File › Revert replaced its +/// content, how many times Undo or Redo restored an older snapshot, how many times another rollback put one back +/// (`DocState::rollbacks`; after either, the same node ID can name another object), and the selected objects in +/// selection order, which `object.setLiveShape` changes. The first selected object picks the rows, so the same objects +/// in another order can put another property's field in the same place. A field drops a value typed and not yet +/// committed when this changes, even where the newly selected shape shows the same value. Hashed once per (document +/// uid, revision): the panels read it every frame, and Select All can select hundreds of thousands of shapes. The +/// revision is not part of the target, so an edit that leaves the selection as it is keeps the value typed so far. +pub(crate) fn shape_edit_target(app: &mut VectorcraftApp) -> IdSalt { + let Some(st) = app.session.active() else { return IdSalt::new(None::<()>) }; + let key = (st.uid, st.revision); + if let Some((k, target)) = app.canvas.shape_edit_target + && k == key + { + return target; + } + let target = IdSalt::new(Some((st.uid, st.reverts, st.history_restores, st.rollbacks, st.selection.objects.as_slice()))); + app.canvas.shape_edit_target = Some((key, target)); + target +} + /// `rows` under a sub-heading, or bare when there is none. fn under_heading(ui: &mut Ui, heading: Option<&'static str>, mut rows: impl FnMut(&mut Ui)) { match heading { @@ -75,7 +104,16 @@ fn set_live_shape(app: &mut VectorcraftApp, params: Value) { } /// One labelled number field whose edits send `params(number)` to `object.setLiveShape`; a scrub is one undo step. -fn number_row(app: &mut VectorcraftApp, ui: &mut Ui, label: &'static str, value: Option, quantity: Quantity, params: impl Fn(f64) -> Value) { +/// `target` is the field's [`shape_edit_target`]. +fn number_row( + app: &mut VectorcraftApp, + ui: &mut Ui, + label: &'static str, + value: Option, + quantity: Quantity, + target: IdSalt, + params: impl Fn(f64) -> Value, +) { let mut edit = None; Field::new(label).show(ui, |ui, _| { let bind = Bind::given(value); @@ -84,7 +122,7 @@ fn number_row(app: &mut VectorcraftApp, ui: &mut Ui, label: &'static str, value: Quantity::Degrees => NumberField::new(label, bind).unit("°").commit_decimals(1), Quantity::Ratio => NumberField::new(label, bind).range(0.001..=1.0).step(0.001).commit_decimals(3), }; - edit = Some(field.show(ui).edit); + edit = Some(field.edit_target(target).show(ui).edit); }); if let Some(edit) = edit { // `Scope`, not `Preview`: `Preview` names one command, and each field sends its own params. @@ -99,9 +137,9 @@ fn number_row(app: &mut VectorcraftApp, ui: &mut Ui, label: &'static str, value: /// A live rectangle's, ellipse's or polygon's Angle row (counterclockwise): the angle the selected shapes of its /// kind share, blank when they differ. `key` is the `object.setLiveShape` param an edit sets, which turns each of /// them about its own center. -fn angle_row(app: &mut VectorcraftApp, ui: &mut Ui, live: &LiveShape, key: &'static str) { +fn angle_row(app: &mut VectorcraftApp, ui: &mut Ui, live: &LiveShape, key: &'static str, target: IdSalt) { let angle = shared_shape_angle(app, live); - number_row(app, ui, tl!("Angle"), angle, Quantity::Degrees, |a| json!({ key: a })); + number_row(app, ui, tl!("Angle"), angle, Quantity::Degrees, target, |a| json!({ key: a })); } /// The angle ([`LiveShape::shape_angle`]) every selected live shape of `live`'s kind shares, `None` when they @@ -151,9 +189,11 @@ fn line_rows(app: &mut VectorcraftApp, ui: &mut Ui, live: &LiveShape) -> bool { if !only_lines_selected(app) { return false; } + let target = shape_edit_target(app); under_heading(ui, Some(tl!("Line Properties:")), |ui| { - number_row(app, ui, tl!("Line Length"), live.line_length(), Quantity::Length, |l| json!({ "lineLength": l })); - number_row(app, ui, tl!("Line Angle"), Some(live.line_angle().unwrap_or(0.0)), Quantity::Degrees, |a| json!({ "lineAngle": a })); + number_row(app, ui, tl!("Line Length"), live.line_length(), Quantity::Length, target, |l| json!({ "lineLength": l })); + let angle = Some(live.line_angle().unwrap_or(0.0)); + number_row(app, ui, tl!("Line Angle"), angle, Quantity::Degrees, target, |a| json!({ "lineAngle": a })); }); true } @@ -161,13 +201,13 @@ fn line_rows(app: &mut VectorcraftApp, ui: &mut Ui, live: &LiveShape) -> bool { /// An ellipse's Pie Start and End Angle (degrees, counterclockwise from 3 o'clock; 0 to 360 is the whole /// ellipse), the Constrain Pie Angle link beside them, and Invert Pie, which shows the other part of it. With the /// link on, a typed angle moves the other one by as much, so each selected ellipse keeps its span. -fn pie_rows(app: &mut VectorcraftApp, ui: &mut Ui, pie: (f64, f64)) { +fn pie_rows(app: &mut VectorcraftApp, ui: &mut Ui, pie: (f64, f64), target: IdSalt) { let constrain = app.ui.constrain_pie_angle; // The link sits halfway between the two fields, with no bracket drawn to them. Row::new().bracket(Bracket::Unlinked).show(ui, |ui, _| { Stack::new().show(ui, |ui, _| { for (label, key, v) in [(tl!("Pie Start Angle"), "pieStart", pie.0), (tl!("Pie End Angle"), "pieEnd", pie.1)] { - number_row(app, ui, label, Some(v), Quantity::Degrees, |a| { + number_row(app, ui, label, Some(v), Quantity::Degrees, target, |a| { if constrain { json!({ key: a, "constrainPie": true }) } else { json!({ key: a }) } }); } @@ -181,16 +221,16 @@ fn pie_rows(app: &mut VectorcraftApp, ui: &mut Ui, pie: (f64, f64)) { /// A live polygon's Polygon Properties: its side count (a field and a slider), angle (counterclockwise), corner /// type and radius, radius (center to vertex) and side length, and Make Sides Equal, which an uneven scale enables. -fn polygon_rows(app: &mut VectorcraftApp, ui: &mut Ui, n: &Node, live: &LiveShape) { +fn polygon_rows(app: &mut VectorcraftApp, ui: &mut Ui, n: &Node, live: &LiveShape, target: IdSalt) { let LiveShape::Polygon { sides, .. } = live else { return }; let radius = live.polygon_radius(); let side = radius.map(|r| 2.0 * r * (std::f64::consts::PI / f64::from((*sides).max(3))).sin()); - sides_row(app, ui, *sides); - angle_row(app, ui, live, "polygonAngle"); + sides_row(app, ui, *sides, target); + angle_row(app, ui, live, "polygonAngle", target); corner_kind_row(app, ui, corner_style(app, n).1); Field::new(tl!("Corner Radius")).show(ui, |ui, _| corner_radius_field(app, ui, n)); - number_row(app, ui, tl!("Radius"), radius, Quantity::Length, |r| json!({ "polygonRadius": r })); - number_row(app, ui, tl!("Side Length"), side, Quantity::Length, |l| json!({ "sideLength": l })); + number_row(app, ui, tl!("Radius"), radius, Quantity::Length, target, |r| json!({ "polygonRadius": r })); + number_row(app, ui, tl!("Side Length"), side, Quantity::Length, target, |l| json!({ "sideLength": l })); if Button::new(tl!("Make Sides Equal")).enabled(!live.polygon_sides_equal()).show(ui).clicked() { set_live_shape(app, json!({"makeSidesEqual": true})); } @@ -200,18 +240,27 @@ fn polygon_rows(app: &mut VectorcraftApp, ui: &mut Ui, n: &Node, live: &LiveShap /// over [`SIDES_SLIDER`]. A typed count is one undo step. A slider drag previews the count and its release records /// one undo step; Escape during the drag puts the count back. A click on the rail or an arrow key sets the count in /// one undo step. A count above 20 puts the thumb at the rail's right end, and screen readers read the real count. -fn sides_row(app: &mut VectorcraftApp, ui: &mut Ui, sides: u32) { - count_row(app, ui, tl!("Sides"), "sides", sides, 3.0); +fn sides_row(app: &mut VectorcraftApp, ui: &mut Ui, sides: u32, target: IdSalt) { + count_row(app, ui, tl!("Sides"), "sides", sides, 3.0, target); } /// A count row (Polygon Properties' Sides, Star Properties' Points) whose edits set `key`: a field that takes `min` -/// to 1000 and a slider over [`SIDES_SLIDER`], as [`sides_row`] describes. -fn count_row(app: &mut VectorcraftApp, ui: &mut Ui, label: &'static str, key: &'static str, sides: u32, min: f64) { +/// to 1000 and a slider over [`SIDES_SLIDER`], as [`sides_row`] describes. The field drops an unfinished value when +/// `target` changes. +fn count_row(app: &mut VectorcraftApp, ui: &mut Ui, label: &'static str, key: &'static str, sides: u32, min: f64, target: IdSalt) { let count = f64::from(sides); let (mut typed, mut slid) = (None, None); Field::new(label).show(ui, |ui, _| { Row::new().show(ui, |ui, _| { - typed = Some(NumberField::new(label, Bind::given(Some(count))).range(min..=1000.0).fixed_decimals(0).id_salt("field").show(ui).edit); + typed = Some( + NumberField::new(label, Bind::given(Some(count))) + .range(min..=1000.0) + .fixed_decimals(0) + .id_salt("field") + .edit_target(target) + .show(ui) + .edit, + ); let (lo, hi) = (*SIDES_SLIDER.start(), *SIDES_SLIDER.end()); slid = Some( Slider::new(Bind::given(count.clamp(lo, hi)), SIDES_SLIDER) @@ -241,10 +290,10 @@ fn count_row(app: &mut VectorcraftApp, ui: &mut Ui, label: &'static str, key: &' /// A live star's Star Properties: its point count (a field that takes 2 to 1000 and a slider over 3 to 20) and its /// ratio (inner radius over outer radius, 0.001 to 1). Its corners stay with Live Corners and Direct Selection, as any /// path's do. -fn star_rows(app: &mut VectorcraftApp, ui: &mut Ui, live: &LiveShape) { +fn star_rows(app: &mut VectorcraftApp, ui: &mut Ui, live: &LiveShape, target: IdSalt) { let Some(points) = live.star_points() else { return }; - count_row(app, ui, tl!("Points"), "points", points, 2.0); - number_row(app, ui, tl!("Ratio"), live.star_ratio(), Quantity::Ratio, |r| json!({ "ratio": r })); + count_row(app, ui, tl!("Points"), "points", points, 2.0, target); + number_row(app, ui, tl!("Ratio"), live.star_ratio(), Quantity::Ratio, target, |r| json!({ "ratio": r })); } /// The polygon's Corner type select, blank while `kind` is `None` (the corners differ), one number cell wide as the @@ -259,3 +308,6 @@ fn corner_kind_row(app: &mut VectorcraftApp, ui: &mut Ui, kind: Option (VectorcraftApp, Value, Value) { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 400})).unwrap(); + let a = app.run(cmd, a).unwrap()["id"].clone(); + let b = app.run(cmd, b).unwrap()["id"].clone(); + (app, a, b) +} + +/// Selects `a`, types "3+" into field `name` drawn by `draw`, selects `b`, then types "7" and Enter. Returns the +/// field's value just after `b` is selected, after the Enter, and with `a` selected again. +fn type_across_a_selection_change( + app: VectorcraftApp, + draw: fn(&mut VectorcraftApp, &mut Ui), + a: &Value, + b: &Value, + name: &str, +) -> (Option, Option, Option) { + let mut app = app; + app.run("select.set", json!({"ids": [a]})).unwrap(); + let mut p = Panel::new(app, draw); + p.click_role(name, Role::SPIN_BUTTON); + p.key(Key::A, Modifiers::COMMAND); + p.type_text("3+"); + p.app().run("select.set", json!({"ids": [b]})).unwrap(); + p.frame(); + let switched = p.value_role(name, Role::SPIN_BUTTON); + p.type_text("7"); + p.key(Key::Enter, Modifiers::NONE); + p.frame(); + let after = p.value_role(name, Role::SPIN_BUTTON); + p.app().run("select.set", json!({"ids": [a]})).unwrap(); + p.frame(); + (switched, after, p.value_role(name, Role::SPIN_BUTTON)) +} + +/// Checks that a value typed into field `name` for `a` and not finished is dropped when `b`, which shows `shown` +/// there as `a` does, is selected: the field shows `shown`, "7" and Enter then give `b` 7 (`seven`), not 3+7, and +/// `a` keeps `shown`. +fn check_field(app: VectorcraftApp, draw: fn(&mut VectorcraftApp, &mut Ui), a: &Value, b: &Value, name: &str, shown: &str, seven: &str) { + let (switched, after, first) = type_across_a_selection_change(app, draw, a, b, name); + assert_eq!(switched.as_deref(), Some(shown), "{name}: the field shows the newly selected shape's value"); + assert_eq!(after.as_deref(), Some(seven), "{name}: the newly selected shape takes 7, not the unfinished 3+ and 7"); + assert_eq!(first.as_deref(), Some(shown), "{name}: the shape the value was first typed for keeps its value"); +} + +fn pt(v: f64) -> String { + Unit::Points.format(v) +} + +fn rectangles() -> (VectorcraftApp, Value, Value) { + two("shape.rectangle", json!({"x": 0, "y": 0, "width": 30, "height": 30}), json!({"x": 100, "y": 0, "width": 30, "height": 30})) +} + +fn polygons() -> (VectorcraftApp, Value, Value) { + two("shape.polygon", json!({"cx": 60, "cy": 60, "radius": 40, "sides": 5}), json!({"cx": 200, "cy": 60, "radius": 40, "sides": 5})) +} + +fn ellipses() -> (VectorcraftApp, Value, Value) { + two("shape.ellipse", json!({"x": 0, "y": 0, "width": 40, "height": 30}), json!({"x": 100, "y": 0, "width": 40, "height": 30})) +} + +fn lines() -> (VectorcraftApp, Value, Value) { + two("shape.line", json!({"x1": 20, "y1": 20, "x2": 120, "y2": 20}), json!({"x1": 20, "y1": 200, "x2": 120, "y2": 200})) +} + +#[test] +fn an_unfinished_rectangle_angle_does_not_reach_another_rectangle() { + let (app, a, b) = rectangles(); + check_field(app, crate::panels::transform::show, &a, &b, "Angle", "0°", "7°"); + let (app, a, b) = rectangles(); + check_field(app, crate::panels::properties::show, &a, &b, "Angle", "0°", "7°"); +} + +#[test] +fn an_unfinished_polygon_sides_count_does_not_reach_another_polygon() { + let (app, a, b) = polygons(); + check_field(app, crate::panels::transform::show, &a, &b, "Sides", "5", "7"); +} + +#[test] +fn an_unfinished_polygon_angle_radius_or_side_length_does_not_reach_another_polygon() { + let (app, a, b) = polygons(); + check_field(app, crate::panels::transform::show, &a, &b, "Angle", "0°", "7°"); + let (app, a, b) = polygons(); + check_field(app, crate::panels::transform::show, &a, &b, "Radius", &pt(40.0), &pt(7.0)); + let (app, a, b) = polygons(); + let side = pt(2.0 * 40.0 * (std::f64::consts::PI / 5.0).sin()); + check_field(app, crate::panels::transform::show, &a, &b, "Side Length", &side, &pt(7.0)); +} + +/// After Undo removes the shape a value was typed for, a new shape can take its node ID. The value is dropped when +/// that shape is selected, so it does not reach an object it was not typed for. +#[test] +fn an_unfinished_angle_does_not_reach_a_shape_that_takes_an_undone_shapes_id() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 400})).unwrap(); + let rect = app.run("shape.rectangle", json!({"x": 0, "y": 0, "width": 30, "height": 30})).unwrap()["id"].clone(); + app.run("select.set", json!({"ids": [rect]})).unwrap(); + let mut p = Panel::new(app, crate::panels::transform::show); + p.click_role("Angle", Role::SPIN_BUTTON); + p.key(Key::A, Modifiers::COMMAND); + p.type_text("3+"); + p.app().run("edit.undo", json!({})).unwrap(); + let ellipse = p.app().run("shape.ellipse", json!({"x": 100, "y": 0, "width": 40, "height": 30})).unwrap()["id"].clone(); + assert_eq!(ellipse, rect, "the ellipse takes the undone rectangle's node ID"); + p.app().run("select.set", json!({"ids": [ellipse]})).unwrap(); + p.frame(); + assert_eq!(p.value_role("Angle", Role::SPIN_BUTTON).as_deref(), Some("0°"), "the field shows the ellipse's angle"); + p.type_text("7"); + p.key(Key::Enter, Modifiers::NONE); + p.frame(); + assert_eq!(p.value_role("Angle", Role::SPIN_BUTTON).as_deref(), Some("7°"), "the ellipse takes 7°, not the unfinished 3+ and 7"); +} + +/// A canceled undo group removes the shape a value was typed for, and a new shape can take its node ID. The value is +/// dropped when that shape is selected. +#[test] +fn an_unfinished_angle_does_not_reach_a_shape_that_takes_a_canceled_groups_shapes_id() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 400})).unwrap(); + app.run("edit.undoGroup.begin", json!({})).unwrap(); + let rect = app.run("shape.rectangle", json!({"x": 0, "y": 0, "width": 30, "height": 30})).unwrap()["id"].clone(); + app.run("select.set", json!({"ids": [rect]})).unwrap(); + let mut p = Panel::new(app, crate::panels::transform::show); + p.click_role("Angle", Role::SPIN_BUTTON); + p.key(Key::A, Modifiers::COMMAND); + p.type_text("3+"); + p.app().run("edit.undoGroup.end", json!({"cancel": true})).unwrap(); + let ellipse = p.app().run("shape.ellipse", json!({"x": 100, "y": 0, "width": 40, "height": 30})).unwrap()["id"].clone(); + assert_eq!(ellipse, rect, "the ellipse takes the canceled group's rectangle's node ID"); + p.app().run("select.set", json!({"ids": [ellipse]})).unwrap(); + p.frame(); + assert_eq!(p.value_role("Angle", Role::SPIN_BUTTON).as_deref(), Some("0°"), "the field shows the new shape's angle"); + p.type_text("7"); + p.key(Key::Enter, Modifiers::NONE); + p.frame(); + assert_eq!(p.value_role("Angle", Role::SPIN_BUTTON).as_deref(), Some("7°"), "the ellipse takes 7°, not the unfinished 3+ and 7"); +} + +/// Exit Symbol Editing Mode with nothing changed takes back the entering step, which removes the editing copy a value +/// was typed for, and a new shape can take the copy's node ID. The value is dropped when that shape is selected. +#[test] +fn an_unfinished_angle_does_not_reach_a_shape_that_takes_an_unchanged_symbol_copys_id() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 400})).unwrap(); + app.run("shape.rectangle", json!({"x": 0, "y": 0, "width": 30, "height": 30})).unwrap(); + app.run("symbol.new", json!({"name": "Box"})).unwrap(); + app.run("symbol.edit", json!({})).unwrap(); + let copy = app.session.active().map(|st| st.selection.objects.clone()).unwrap_or_default(); + assert_eq!(copy.len(), 1, "symbol editing selects the editing copy"); + let mut p = Panel::new(app, crate::panels::transform::show); + p.click_role("Angle", Role::SPIN_BUTTON); + p.key(Key::A, Modifiers::COMMAND); + p.type_text("3+"); + p.app().run("symbol.exitEditing", json!({})).unwrap(); + p.app().run("shape.rectangle", json!({"x": 100, "y": 0, "width": 40, "height": 30})).unwrap(); + let rect = p.app().run("shape.rectangle", json!({"x": 200, "y": 0, "width": 40, "height": 30})).unwrap()["id"].clone(); + assert_eq!(rect, json!(copy[0].0), "the second new rectangle takes the editing copy's node ID"); + p.app().run("select.set", json!({"ids": [rect]})).unwrap(); + p.frame(); + assert_eq!(p.value_role("Angle", Role::SPIN_BUTTON).as_deref(), Some("0°"), "the field shows the new rectangle's angle"); + p.type_text("7"); + p.key(Key::Enter, Modifiers::NONE); + p.frame(); + assert_eq!(p.value_role("Angle", Role::SPIN_BUTTON).as_deref(), Some("7°"), "the rectangle takes 7°, not the unfinished 3+ and 7"); +} + +/// A canceled interaction removes a shape its preview made and a value was typed for, and a new shape can take that +/// shape's node ID. The value is dropped when that shape is selected. +#[test] +fn an_unfinished_angle_does_not_reach_a_shape_that_takes_a_canceled_previews_shapes_id() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 400})).unwrap(); + app.session.begin_interaction("Rectangle").unwrap(); + let previewed = app.session.preview("shape.rectangle", &json!({"x": 0, "y": 0, "width": 30, "height": 30})).unwrap()["id"].clone(); + let selected = app.session.active().map(|st| st.selection.objects.clone()).unwrap_or_default(); + assert_eq!(json!(selected.iter().map(|id| id.0).collect::>()), json!([previewed]), "the preview selects its rectangle"); + let mut p = Panel::new(app, crate::panels::transform::show); + p.click_role("Angle", Role::SPIN_BUTTON); + p.key(Key::A, Modifiers::COMMAND); + p.type_text("3+"); + p.app().session.cancel_interaction().unwrap(); + let rect = p.app().run("shape.rectangle", json!({"x": 100, "y": 0, "width": 40, "height": 30})).unwrap()["id"].clone(); + assert_eq!(rect, previewed, "the new rectangle takes the canceled preview's rectangle's node ID"); + p.app().run("select.set", json!({"ids": [rect]})).unwrap(); + p.frame(); + assert_eq!(p.value_role("Angle", Role::SPIN_BUTTON).as_deref(), Some("0°"), "the field shows the new rectangle's angle"); + p.type_text("7"); + p.key(Key::Enter, Modifiers::NONE); + p.frame(); + assert_eq!(p.value_role("Angle", Role::SPIN_BUTTON).as_deref(), Some("7°"), "the rectangle takes 7°, not the unfinished 3+ and 7"); +} + +/// A replacement preview reuses the discarded rectangle's node ID and drops its unfinished angle. +/// The replacement rectangle takes the next angle typed into the field. +#[test] +fn an_unfinished_angle_does_not_reach_a_replacement_preview_that_reuses_a_discarded_shapes_id() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 400})).unwrap(); + app.session.begin_interaction("Rectangle").unwrap(); + let previewed = app.session.preview("shape.rectangle", &json!({"x": 0, "y": 0, "width": 30, "height": 30})).unwrap()["id"].clone(); + let mut p = Panel::new(app, crate::panels::transform::show); + p.click_role("Angle", Role::SPIN_BUTTON); + p.key(Key::A, Modifiers::COMMAND); + p.type_text("3+"); + let steps = json!({"commands": [ + {"command": "shape.rectangle", "params": {"x": 100, "y": 10, "width": 40, "height": 30}} + ]}); + let replacement = p.app().session.preview("command.batch", &steps).unwrap(); + let rect = replacement["results"][0]["id"].clone(); + assert_eq!(rect, previewed, "the replacement rectangle reuses the discarded rectangle's node ID"); + let selected = p.app().session.active().map(|st| st.selection.objects.clone()).unwrap_or_default(); + assert_eq!(json!(selected.iter().map(|id| id.0).collect::>()), json!([rect]), "the preview selects the replacement rectangle"); + p.frame(); + assert_eq!(p.value_role("Angle", Role::SPIN_BUTTON).as_deref(), Some("0°"), "the field shows the replacement rectangle's angle"); + p.type_text("7"); + p.key(Key::Enter, Modifiers::NONE); + p.frame(); + assert_eq!(p.value_role("Angle", Role::SPIN_BUTTON).as_deref(), Some("7°"), "the replacement rectangle takes 7°, not the unfinished 3+ and 7"); +} + +#[test] +fn an_unfinished_ellipse_angle_or_pie_angle_does_not_reach_another_ellipse() { + for (name, shown) in [("Angle", "0°"), ("Pie Start Angle", "0°"), ("Pie End Angle", "360°")] { + let (app, a, b) = ellipses(); + check_field(app, crate::panels::transform::show, &a, &b, name, shown, "7°"); + } +} + +#[test] +fn an_unfinished_star_points_or_ratio_does_not_reach_another_star() { + let stars = || { + two( + "shape.star", + json!({"cx": 60, "cy": 60, "radius1": 40, "radius2": 20, "points": 5}), + json!({"cx": 200, "cy": 60, "radius1": 40, "radius2": 20, "points": 5}), + ) + }; + let (app, a, b) = stars(); + check_field(app, crate::panels::transform::show, &a, &b, "Points", "5", "7"); + let (app, a, b) = stars(); + check_field(app, crate::panels::transform::show, &a, &b, "Ratio", "0.5", "1"); +} + +#[test] +fn an_unfinished_line_length_or_angle_does_not_reach_another_line() { + let (app, a, b) = lines(); + check_field(app, crate::panels::transform::show, &a, &b, "Line Length", &pt(100.0), &pt(7.0)); + let (app, a, b) = lines(); + check_field(app, crate::panels::transform::show, &a, &b, "Line Angle", "0°", "7°"); +} + +/// A value typed for a rectangle and not finished is dropped when File Revert replaces the document's content or +/// another document becomes active, even where the selection has the same ids and the same angle. +#[test] +fn an_unfinished_angle_is_dropped_by_file_revert_or_another_document() { + type Change = fn(&mut VectorcraftApp); + let changes: [(&str, Change); 2] = [ + ("File Revert", |app| { + // The same content again, with the same rectangle selected after it. + let st = app.session.active().unwrap(); + let (doc, ids) = ((*st.doc).clone(), st.selection.objects.clone()); + assert!(app.session.replace_document(0, doc)); + app.run("select.set", json!({"ids": ids.iter().map(|id| id.0).collect::>()})).unwrap(); + }), + ("another document became active", |app| { + app.run("document.activate", json!({"index": 1})).unwrap(); + }), + ]; + // The angle of the rectangle in each open document, in whole degrees, and the index of the active document. + let angles = |p: &Panel| -> (Vec>, Option) { + let app = p.app(); + let docs = app.session.documents(); + let angles = docs.iter().map(|st| st.doc.node(st.selection.objects[0]).and_then(|n| n.live_shape()?.shape_angle()).map(|a| a.round() as i64)); + let active = app.session.active().map(|a| a.uid); + (angles.collect(), docs.iter().position(|st| Some(st.uid) == active)) + }; + for (change, apply) in changes { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + for _ in 0..2 { + app.run("file.new", json!({"width": 400, "height": 400})).unwrap(); + let id = app.run("shape.rectangle", json!({"x": 0, "y": 0, "width": 30, "height": 30})).unwrap()["id"].clone(); + app.run("select.set", json!({"ids": [id]})).unwrap(); + } + app.run("document.activate", json!({"index": 0})).unwrap(); + let mut p = Panel::new(app, crate::panels::transform::show); + p.click_role("Angle", Role::SPIN_BUTTON); + p.key(Key::A, Modifiers::COMMAND); + p.type_text("3+"); + apply(&mut p.app()); + p.frame(); + assert_eq!(p.value_role("Angle", Role::SPIN_BUTTON).as_deref(), Some("0°"), "{change}: the field shows the rectangle's angle"); + p.type_text("7"); + p.key(Key::Enter, Modifiers::NONE); + let (got, active) = angles(&p); + let active = active.unwrap(); + let mut want = vec![Some(0), Some(0)]; + want[active] = Some(7); + assert_eq!(got, want, "{change}: the rectangle takes 7°, not the unfinished 3+ and 7"); + } +} + +/// While the selection stays the same, a value typed over several frames is kept and committed whole, also when an +/// edit to an unselected object changes the document in between. +#[test] +fn a_value_typed_with_the_same_selection_is_kept_across_frames() { + let (mut app, a, b) = rectangles(); + app.run("select.set", json!({"ids": [a]})).unwrap(); + let mut p = Panel::new(app, crate::panels::transform::show); + p.click_role("Angle", Role::SPIN_BUTTON); + p.key(Key::A, Modifiers::COMMAND); + p.type_text("3+"); + p.frame(); + let revision = p.app().session.active().unwrap().revision; + p.app().run("stroke.set", json!({"ids": [b], "weight": 4})).unwrap(); + assert_ne!(p.app().session.active().unwrap().revision, revision, "the document changed"); + p.frame(); + p.type_text("7"); + p.key(Key::Enter, Modifiers::NONE); + p.frame(); + assert_eq!(p.value_role("Angle", Role::SPIN_BUTTON).as_deref(), Some("10°"), "3+7 is committed to the same rectangle"); +} + +/// An unfinished Sides value is dropped when selecting the star first replaces Sides with Points. +#[test] +fn an_unfinished_sides_count_does_not_reach_a_star_selected_first() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 400})).unwrap(); + let polygon = app.run("shape.polygon", json!({"cx": 60, "cy": 60, "radius": 40, "sides": 5})).unwrap()["id"].clone(); + let star = app.run("shape.star", json!({"cx": 200, "cy": 60, "radius1": 40, "radius2": 20, "points": 5})).unwrap()["id"].clone(); + app.run("select.set", json!({"ids": [polygon, star]})).unwrap(); + let mut p = Panel::new(app, crate::panels::transform::show); + p.click_role("Sides", Role::SPIN_BUTTON); + p.key(Key::A, Modifiers::COMMAND); + p.type_text("3+"); + p.app().run("select.set", json!({"ids": [star, polygon]})).unwrap(); + p.frame(); + assert_eq!(p.value_role("Points", Role::SPIN_BUTTON).as_deref(), Some("5"), "the field shows the star's points"); + p.type_text("7"); + p.key(Key::Enter, Modifiers::NONE); + p.frame(); + assert_eq!(p.value_role("Points", Role::SPIN_BUTTON).as_deref(), Some("7"), "the star takes 7 points, not the unfinished 3+ and 7"); +} + +/// An Angle value typed across frames is kept when another corner of the same rectangle is Direct-Selected. +#[test] +fn a_value_typed_for_the_same_shape_is_kept_when_direct_selected_anchors_change() { + let (mut app, a, _) = rectangles(); + let id = a.as_u64().unwrap(); + app.run("select.anchors", json!({"id": id, "anchors": [[0, 0]], "mode": "set"})).unwrap(); + let mut p = Panel::new(app, crate::panels::transform::show); + p.click_role("Angle", Role::SPIN_BUTTON); + p.key(Key::A, Modifiers::COMMAND); + p.type_text("3+"); + p.app().run("select.anchors", json!({"id": id, "anchors": [[0, 2]], "mode": "set"})).unwrap(); + p.frame(); + p.type_text("7"); + p.key(Key::Enter, Modifiers::NONE); + p.frame(); + assert_eq!(p.value_role("Angle", Role::SPIN_BUTTON).as_deref(), Some("10°"), "3+7 is committed to the same rectangle"); +}