From 5b57822605f93d6ba2793085fd3b6eb7fae967f6 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 28 Nov 2026 08:13:12 -0800 Subject: [PATCH] Anchor Inspector: canceling a field edit restores the anchor or the Points per segment count The X, Y, Length and Angle fields ran addon.pathtools.setAnchor with each value as it was typed, outside any undo scope, so Escape left the anchor edited and an angle edit could leave one undo step per keystroke. Each field's gesture now runs in one undo scope (EditPath::Scope): Enter keeps the edit as one undo step, and Escape restores the anchor with no step. While an Angle edit runs, the field shows the handle's angle in the typed value's turn, so a typed 200 is not read back as -160, which the field took as a change made by the app and ended the edit with it kept. Points per segment takes the value its field holds after its events, so a canceled edit leaves the count Add Points uses as it was. --- crates/ui-egui/src/addons/pathtools.rs | 55 +++++++++----- crates/ui-egui/src/addons/pathtools/tests.rs | 77 ++++++++++++++++++++ crates/ui-egui/src/tests/panel_harness.rs | 13 ++++ docs/mcp.md | 4 + docs/ui-parity.md | 1 + 5 files changed, 132 insertions(+), 18 deletions(-) diff --git a/crates/ui-egui/src/addons/pathtools.rs b/crates/ui-egui/src/addons/pathtools.rs index 2b4ba91076..324f907615 100644 --- a/crates/ui-egui/src/addons/pathtools.rs +++ b/crates/ui-egui/src/addons/pathtools.rs @@ -5,7 +5,8 @@ //! [`corner`], and the Shared Edge Merge Tool's, [`shared_edge`]); the Parametric Shape panel //! ([`shape`]); its tools' options dialog (a double-click on the tool); and the Tangent Circle Tool's radius dialog //! ([`tangent_circle_radius`]). Everything acts through `addon.pathtools.*` and `tool.setOption`, except that the radius -//! dialog draws its circle with `shape.circleThroughPoints`. +//! dialog draws its circle with `shape.circleThroughPoints`. Canceling an Anchor Inspector field edit restores its +//! opening value: an anchor edit is one undo step that the cancel takes back. pub mod bridge; pub mod corner; @@ -16,7 +17,7 @@ pub mod shared_edge; pub mod tangent_circle; pub mod tangent_circle_radius; -use craft::behavior::ColumnWidth; +use craft::behavior::{ColumnWidth, EditEvents}; use craft::menu::Node; use craft::ui::buttons::Button; use craft::ui::contract::{Bind, Props as _, Scroll, Show as _, ShowContainer as _, Sizing, clicked}; @@ -35,6 +36,7 @@ use vectorcraft_tools::addons::{anchor_eraser, extend_path, measure_inspect, par use crate::canvas::rulers::general_lengths; use crate::dialogs::host::open_held; +use crate::edits::{EditPath, apply_event}; use crate::menus::{Sep, c, cp}; use crate::panels::empty_state; use crate::{VectorcraftApp, fields}; @@ -73,14 +75,22 @@ const EXTEND_MODES: [(&str, &str); 3] = [("straight", "Straight"), ("bezier", "S pub(crate) struct Inspector { /// How many points Add Points puts on each segment. pub points_per_segment: u32, + /// The In and Out Angle fields' last typed values while their edits run; each field shows its handle's angle in + /// that value's turn, so `200` stays `200` rather than `-160`. + pub angles: [Option; 2], } impl Default for Inspector { fn default() -> Self { - Inspector { points_per_segment: 1 } + Inspector { points_per_segment: 1, angles: [None; 2] } } } +/// `degrees` moved by whole turns to lie nearest `near`; unchanged with no `near`. +fn in_turn_of(degrees: f64, near: Option) -> f64 { + near.map_or(degrees, |near| degrees + 360.0 * ((near - degrees) / 360.0).round()) +} + /// The first selected anchor as the panel shows it: positions less the ruler origin, handles as length and angle. pub(crate) struct AnchorReadout { pub x: f64, @@ -204,36 +214,38 @@ fn show_inspector(app: &mut VectorcraftApp, ui: &mut Ui) { let lengths = general_lengths(app); let origin = app.ruler_origin(); let mut points = app.addon_panels.inspector.points_per_segment; - let mut set: Option = None; + // Each anchor field's edits this pass, as the `addon.pathtools.setAnchor` params they send. + let mut edits: Vec>> = Vec::new(); let mut action: Option<(&str, Value)> = None; match anchor { Some(_) => Text::new(crate::i18n::fmt(tl!("Anchors selected: {count}"), &[("count", &readout.count.to_string())])).show(ui), None => Text::new(tl!("Direct-select anchor points to edit them.")).show(ui), }; let enabled = anchor.is_some(); - let length = |ui: &mut Ui, salt: &'static str, field: NumberField<'static>| typed(field.id_salt(salt).enabled(enabled).show(ui).value()); + // A cleared field sends no params, and its gesture still begins and ends. + let length = |ui: &mut Ui, salt: &'static str, field: NumberField<'static>, to: &dyn Fn(f64) -> Value| { + field.id_salt(salt).enabled(enabled).show(ui).edit.events.map(|v| v.map(to)) + }; + let mut typed_angles = app.addon_panels.inspector.angles; let angle = |ui: &mut Ui, salt: &'static str, v: Option| { let field = NumberField::new(tl!("Angle"), Bind::given(v)).unit_kind(UnitKind::Degrees).fixed_decimals(1); - typed(field.id_salt(salt).enabled(enabled).show(ui).value()) + field.id_salt(salt).enabled(enabled).show(ui).edit.events }; let _ = Grid::new(&COLUMNS).show(ui, |ui, _| { for (label, key, v, o) in [("X", "x", anchor.map(|a| a.x), origin.x), ("Y", "y", anchor.map(|a| a.y), origin.y)] { Text::new(tl!(label)).show(ui); - if let Some(v) = length(ui, key, NumberField::length(tl!(label), Bind::given(v), lengths)) { - set = Some(json!({ key: v + o })); - } + edits.push(length(ui, key, NumberField::length(tl!(label), Bind::given(v), lengths), &|v| json!({ key: v + o }))); } for (label, side, i) in [("In", "in", 0), ("Out", "out", 1)] { Text::new(tl!(label)).show(ui); // A handle's length is a size: `50%` is half of it. let len = fields::size_field(ui, tl!("Length"), anchor.map(|a| a.lengths[i]), lengths); - if let Some(v) = length(ui, if i == 0 { "in-length" } else { "out-length" }, len) { - set = Some(json!({ format!("{side}Length"): v })); - } + edits.push(length(ui, if i == 0 { "in-length" } else { "out-length" }, len, &|v| json!({ format!("{side}Length"): v }))); Text::new("∠").show(ui); - if let Some(v) = angle(ui, if i == 0 { "in-angle" } else { "out-angle" }, anchor.and_then(|a| a.angles[i])) { - set = Some(json!({ format!("{side}Angle"): v })); - } + let shown = anchor.and_then(|a| a.angles[i]).map(|v| in_turn_of(v, typed_angles[i])); + let events = angle(ui, if i == 0 { "in-angle" } else { "out-angle" }, shown); + typed_angles[i] = if events.ended().is_some() { None } else { events.value().copied().flatten().or(typed_angles[i]) }; + edits.push(events.map(|v| v.map(|v| json!({ format!("{side}Angle"): v })))); } }); Divider::horizontal().show(ui); @@ -247,7 +259,8 @@ fn show_inspector(app: &mut VectorcraftApp, ui: &mut Ui) { action = Some(("addon.pathtools.addPoints", json!({ "count": f64::from(points) }))); } let field = NumberField::new(tl!("Points per segment"), Bind::given(Some(f64::from(points)))).range(1.0..=100.0).fixed_decimals(0); - if let Some(v) = typed(field.id_salt("points-per-segment").enabled(selected).show(ui).value()) { + // The value the field holds after its events: a cancel's is the opening value. + if let Some(v) = typed(field.id_salt("points-per-segment").enabled(selected).show(ui).edit.events.landed()) { points = v as u32; } }); @@ -261,8 +274,14 @@ fn show_inspector(app: &mut VectorcraftApp, ui: &mut Ui) { } }); app.addon_panels.inspector.points_per_segment = points; - if let Some(p) = set { - run(app, "addon.pathtools.setAnchor", p); + app.addon_panels.inspector.angles = typed_angles; + // One undo step per gesture; a cancel reverts it. + for event in edits.iter().flatten() { + apply_event(app, event, &EditPath::Scope, &mut |app, p: &Option, _| { + if let Some(p) = p { + run(app, "addon.pathtools.setAnchor", p.clone()); + } + }); } if let Some((id, p)) = action { run(app, id, p); diff --git a/crates/ui-egui/src/addons/pathtools/tests.rs b/crates/ui-egui/src/addons/pathtools/tests.rs index b516412e61..895026b03c 100644 --- a/crates/ui-egui/src/addons/pathtools/tests.rs +++ b/crates/ui-egui/src/addons/pathtools/tests.rs @@ -1,4 +1,6 @@ +use craft::ui::contract::Role; use craft::ui::patterns::form_dialogs::{FieldValue, HostedParamDialog}; +use egui::{Key, Modifiers}; use serde_json::json; use vectorcraft_engine::Session; use vectorcraft_tools::addons::parametric_shape::ShapeKind; @@ -70,6 +72,81 @@ fn a_short_anchor_inspector_scrolls_to_the_selected_anchors_actions() { assert!(anchor.lengths.iter().all(|length| *length > 0.0)); } +/// The Anchor Inspector's anchor fields with what each test types: the field's name, which of the fields with that name +/// it is (In, then Out) and the text typed. +const ANCHOR_TYPED: [(&str, usize, &str); 6] = + [("X", 0, "40"), ("Y", 0, "60"), ("Length", 0, "30"), ("Angle", 0, "45"), ("Length", 1, "25"), ("Angle", 1, "200")]; + +/// An app whose open path's middle anchor is direct-selected and has both handles, from Make Smooth. +fn app_with_smooth_anchor() -> VectorcraftApp { + let mut app = app(); + let r = app.run("path.create", json!({"anchors": [{"x": 10, "y": 10}, {"x": 110, "y": 10}, {"x": 110, "y": 110}], "closed": false})).unwrap(); + let id = vectorcraft_doc::NodeId(r["id"].as_u64().unwrap()); + app.session + .select(|_, sel| { + sel.set([id]); + sel.anchors.insert(id, [(0, 1)].into_iter().collect()); + }) + .unwrap(); + app.run("addon.pathtools.smooth", json!({})).unwrap(); + app +} + +fn undo_len(app: &VectorcraftApp) -> usize { + app.session.active().unwrap().history.undo.len() +} + +#[test] +fn canceling_an_anchor_field_restores_the_anchor_and_enter_is_one_undo_step() { + for (label, nth, text) in ANCHOR_TYPED { + for cancel in [false, true] { + let mut panel = Panel::new(app_with_smooth_anchor(), super::show); + let doc = panel.app().session.active().unwrap().doc.clone(); + let undo = undo_len(&panel.app()); + panel.click_role_nth(label, Role::SPIN_BUTTON, nth); + panel.key(Key::A, Modifiers::COMMAND); + panel.type_text(text); + panel.frame(); + let proposed = panel.app().session.active().unwrap().doc.clone(); + assert_ne!(proposed, doc, "{label} {nth} changes the anchor while typing"); + let shown = readout(&panel.app()).anchor.unwrap(); + panel.key(if cancel { Key::Escape } else { Key::Enter }, Modifiers::NONE); + panel.frame(); + assert!(panel.shows(label), "{label} {nth}: the panel stays open"); + let app = panel.app(); + if cancel { + assert_eq!(app.session.active().unwrap().doc, doc, "{label} {nth} restores the anchor on Escape"); + assert_eq!(undo_len(&app), undo, "{label} {nth}: Escape leaves no undo step"); + } else { + // Enter applies the typed value once more, which can move a handle by a rounding error. + let kept = readout(&app).anchor.unwrap(); + let near = |a: f64, b: f64| (a - b).abs() < 1e-9; + let angles = kept.angles.iter().zip(shown.angles).all(|(a, b)| a.zip(b).is_some_and(|(a, b)| near(a, b))); + let lengths = kept.lengths.iter().zip(shown.lengths).all(|(a, b)| near(*a, b)); + assert!(near(kept.x, shown.x) && near(kept.y, shown.y) && lengths && angles, "{label} {nth}: Enter keeps the edit"); + assert_eq!(undo_len(&app), undo + 1, "{label} {nth}: the edit is one undo step"); + } + } + } +} + +#[test] +fn canceling_points_per_segment_restores_its_value_and_enter_keeps_it() { + for cancel in [false, true] { + let mut panel = Panel::new(app_with_smooth_anchor(), super::show); + let undo = undo_len(&panel.app()); + panel.click_role("Points per segment", Role::SPIN_BUTTON); + panel.key(Key::A, Modifiers::COMMAND); + panel.type_text("5"); + panel.key(if cancel { Key::Escape } else { Key::Enter }, Modifiers::NONE); + panel.frame(); + assert!(panel.shows("Points per segment"), "the panel stays open"); + let kept = if cancel { 1 } else { 5 }; + assert_eq!(panel.app().addon_panels.inspector.points_per_segment, kept, "canceled: {cancel}"); + assert_eq!(undo_len(&panel.app()), undo, "the field adds no undo step"); + } +} + /// Runs `f` on the held options dialog, `None` when none is open. fn held(app: &VectorcraftApp, f: impl FnOnce(Option<&mut HostedParamDialog>) -> R) -> R { app.dialogs().expect("the window's dialogs").with(|h| f(h.get_mut::())) diff --git a/crates/ui-egui/src/tests/panel_harness.rs b/crates/ui-egui/src/tests/panel_harness.rs index f1f58c89ad..7a5dff1202 100644 --- a/crates/ui-egui/src/tests/panel_harness.rs +++ b/crates/ui-egui/src/tests/panel_harness.rs @@ -140,6 +140,19 @@ impl Panel { self.after(); } + /// [`Panel::click_role`] on the zero-based `index`th control of `role` named `name`, where controls of one role share + /// the name (an In and an Out handle's Length). + pub(crate) fn click_role_nth(&mut self, name: &str, role: craft::ui::contract::Role, index: usize) { + self.frame(); + let target = { + let tree = self.fixture.tree(); + self.fixture.by_role(role).into_iter().filter(|t| tree.name_of(t.node) == Some(name)).nth(index) + }; + let target = target.unwrap_or_else(|| panic!("no {role:?} named {name:?} at {index} in {:?}", self.names())); + self.fixture.click(&target); + self.after(); + } + /// The control of `role` named `name` in the latest frame, where nodes of other roles share the name. fn look_role(&self, name: &str, role: craft::ui::contract::Role) -> Target { let tree = self.fixture.tree(); diff --git a/docs/mcp.md b/docs/mcp.md index 8cb939c506..9c04ce0a95 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -15987,6 +15987,10 @@ Commands: at right angles to the bisector of the angle its neighbours make at it, each `ratio` (0.1 to 0.5, 0.3905 by default: the ratio that makes a square's corners a circle) × the nearer neighbour's distance long; an open end aims its handle at its neighbour's. Equalize gives both handles their average length and makes a missing one opposite the other. + In the panel, an edit of X, Y or a handle's Length or Angle runs `addon.pathtools.setAnchor` as it is typed and is + one undo step; canceling it restores the anchor and leaves no undo step. While an Angle edit runs, the field shows + the handle's angle in the typed value's turn (`200` stays `200` rather than `-160`). Canceling a Points per segment + edit restores the count Add Points uses. - `addon.pathtools.removeKeepShape {}` removes the direct-selected anchors, refitting the handles beside each. - `addon.pathtools.addPoints {count?}` splits each selected segment (between two selected anchors, or every segment of a path selected whole) into `count + 1` (1 to 100) pieces of equal length. diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 4884e4672c..76e4ba9040 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -570,6 +570,7 @@ next unit in the order a right-click on a ruler lists them, from Feet back to Po | Document Tools add-on (VectorCraft addition): Object › Plug-ins › Document Tools › New Symbols from Layers makes a symbol of each layer's art named after the layer (the highlighted layers when two or more are, else all); Convert Layers to Symbols also replaces each layer's art with an instance in place; empty layers skipped, one undo step | done | #4927; `addon.document.symbolsFromLayers`, `crates/engine/src/cmd/addons/document.rs`, `crates/ui-egui/src/addons/document.rs` and their tests; not a feature of the reference app, so it is not scored | | Smart Pen add-on (VectorCraft addition): Object › Plug-ins › Smart Pen selects the Smart Pen Tool (also in the Pen tool's group in both shipped toolbars, after the Quick Pen; the All Tools drawer lists it under Draw; a toolbar edited before keeps its saved layout until Reset Toolbar; no shortcut), and opens the Smart Pen panel (next segment straight or curved; Remove Points Keep Shape, Make Smooth, Make Corner, Retract Handles, Close or Join). The tool draws (click: straight or curved segment, a curve after a straight one tangent; drag: smooth anchor, Alt breaks the handle, Shift 45°, Space moves it; Tab switches a segment; rubber band; close, join, continue) and edits without switching tools (click selects a point, drag moves it, Alt-click removes it keeping the shape, Shift+Alt-click deletes it, double-click toggles smooth/corner; handle drags with Shift and Alt; segment drags reshape, Alt-click adds a point) | done | `addon.pen.*`, `crates/tools/src/addons/smart_pen.rs`, `crates/ui-egui/src/addons/pen.rs` and their tests; not a feature of the reference app, so it is not scored | | Path Precision Tools add-on (VectorCraft addition): Object › Plug-ins › Path Precision Tools selects its nine tools (Anchor Eraser Brush, Extend Path, Measure & Inspect, Parametric Shape, Corner Tool, Slide Anchor Along Path, Shared Edge Merge Tool, Tangent Circle Tool, Trim at Crossings Tool), which the All Tools drawer lists under their own heading but neither toolbar shows as shipped (except Trim at Crossings, which both shipped toolbars and the drawer show in the Scissors tool's group), opens the Anchor Inspector panel (the selected anchor's X/Y and handle lengths and angles as fields; Make Smooth, Make Corner, Equalize Handles, Remove Points Keep Shape, Add Points, the three ways to close) and the Parametric Shape panel (kind, count, W/H, rotation, the kind's own values and corner radius of the selected parametric shape, or of the tool's next one), and runs Add Points at / Split at Crossings and Convert to Parametric Shape; the Parametric Shape Tool draws ten re-editable kinds from the centre (↑/↓ and ←/→ change their numbers while dragging) and edits a selected one with handles; the Corner Tool cuts editable corners on any path (hover shows the anchor, a click uses its radius and kind, a drag sizes the corner, Shift whole values; a corner's marker selects it and loads its values, drags to resize, to 0 or double-clicked removes it; never past what fits; Alt-marquee cuts every anchor inside) with a Corners section in the Anchor Inspector (radius, kind, selected count, Apply to Selected Anchors); Slide Anchor Along Path drags an anchor along its curve with the segments beside it refitted, Shift snapping where the tangent is a multiple of 45°; the Shared Edge Merge Tool shows, over two paths touching at two coincident anchors, the two stretches and the edge merging them, a click merges them (half way; Shift the upper path, Alt the lower), and near anchors meet or an anchor one path lacks is added to match (Shift+Alt asks for this inside a stretch), with a Shared Edges section in the Anchor Inspector (brush diameter, coincidence 0 to 3 pt, Keep Shared Points Together, which takes coincident anchors along with the add-on's own anchor moves); a double-click on the brush, Extend Path or Tangent Circle tool opens its options | done | `addon.pathtools.*`, `crates/tools/src/addons/`, `crates/ui-egui/src/addons/pathtools.rs`, `crates/ui-egui/src/addons/pathtools/` and their tests; not a feature of the reference app, so it is not scored | +| Anchor Inspector fields restore canceled edits | done | Canceling an X, Y, handle Length or Angle edit restores the anchor, with no undo step, and canceling a Points per segment edit restores its count. An accepted anchor edit is one undo step. | | Corner and Shared Edge Merge options restore canceled edits | done | Canceling a control gesture restores its opening draft values. Confirmed changes remain available to the tool. | | Path Precision Tools add-on (VectorCraft addition): Object › Plug-ins › Path Precision Tools › Divide into Dashes… (Dash and Gap in any unit, Fit to Corners and Ends, Remove Gaps; Preview) cuts the selected paths, or only their direct-selected segments, into open pieces along the curve, keeping their appearance, one undo step | done | #4950; `addon.pathtools.divideDashes`, `crates/pathops/src/addons/pathtools/dashes.rs`, `crates/ui-egui/src/addons/pathtools/dashes.rs` and their tests; not a feature of the reference app, so it is not scored | | Path Precision Tools add-on (VectorCraft addition): Object › Plug-ins › Path Precision Tools › Set Corners… (also a button in the Anchor Inspector's Corners section: Radius in any unit, Corner kind, Anchors: All, Odd-Numbered or Even-Numbered, counted from each path's first anchor; Angle: from … to …°, only the corners whose sides meet at an angle in that range; Preview) cuts corners on the chosen anchors of every selected path, one undo step | done | #5546, #5545; `addon.pathtools.cornerSet` (`every`, `minAngle`, `maxAngle`), `crates/ui-egui/src/addons/pathtools/set_corners.rs` and their tests; not a feature of the reference app, so it is not scored |