diff --git a/crates/engine/src/cmd/addons/pathtools/shape.rs b/crates/engine/src/cmd/addons/pathtools/shape.rs index fc88442997..6c16893aba 100644 --- a/crates/engine/src/cmd/addons/pathtools/shape.rs +++ b/crates/engine/src/cmd/addons/pathtools/shape.rs @@ -4,13 +4,15 @@ //! (`vectorcraft_tools::addons::parametric_shape`), which SVG export leaves out. use serde_json::{Value, json}; -use vectorcraft_doc::{Node, NodeKind}; +use vectorcraft_doc::{Document, Node, NodeKind}; use vectorcraft_geom::{FillRule, PathData, Point}; use vectorcraft_pathops::addons::pathtools::shapes::{ParametricShape, ShapeKind, recognise}; +use vectorcraft_render::effects; use vectorcraft_tools::addons::parametric_shape::{CREATE, EDIT, KEY, apply, read, stored, to_json}; +use super::super::super::menucmds::whole_or; use super::super::super::{CommandSpec, bad, checked_id, checked_ids_or_selection, cmd, has_doc, has_selection}; -use crate::{EngineError, Result, Session}; +use crate::{EngineError, MAX_COORD, Result, Session}; /// The undo step's name and the command's label. const CONVERT: &str = "Convert to Parametric Shape"; @@ -31,7 +33,7 @@ pub fn specs() -> Vec { "Edit Parametric Shape", [], None, - "{id, kind?, center?, width?, height?, rotation?: degrees clockwise (0: upright), count?, a?, b?, radius?} change a parametric shape's numbers (as addon.pathtools.shape.create takes them; a new kind takes its own defaults for the values not given), as one undo step; with none, or the same ones, nothing changes → {id, shape (its numbers now)}", + "{id, kind?, center?, width?, height?, rotation?: degrees clockwise (0: upright), count?, a?, b?, radius?, reference?: 0..8 (a point on the 9-point grid of the bounding box as object.setBounds measures it, rotated with rotated objects)} change a parametric shape's numbers (as addon.pathtools.shape.create takes them; a new kind takes its own defaults for the values not given), as one undo step; with `reference` and no `center`, that point of the bounding box keeps its place (as the Transform panel's W and H do; snapping to the pixel grid and an attachment to a path apply afterwards), otherwise the center stays; with none, or the same ones, nothing changes → {id, shape (its numbers now; null when snapping to the pixel grid left a plain path)}", has_doc, set ), @@ -95,15 +97,55 @@ fn set(s: &mut Session, p: &Value) -> Result { return Err(bad(C, "the path is locked or hidden")); } let old = d.node(id).and_then(read).ok_or_else(|| bad(C, "the object is not an editable parametric shape"))?; + let reference = match p.get("reference").filter(|v| !v.is_null()) { + Some(_) => match whole_or(p, "reference", 4, C)? { + i @ 0..=8 => Some(i as usize), + _ => return Err(bad(C, "`reference` must be from 0 to 8")), + }, + None => None, + }; let shape = apply(old, p).map_err(|e| bad(C, e))?; if shape != old { + // Without a center, the reference point of the bounding box (as the Transform panel and + // `object.setBounds` measure it; the geometric box where the preview leaves none) keeps + // its place: the new outline moves onto it. The box after the edit is measured the same way + // as the box before it. + let how = s.bounds_measure(); + let geometric = effects::preview::Measure { preview: false, ..how }; + let boxed = |d: &Document, m: effects::preview::Measure| effects::preview::oriented_bounds_with(d, &[id], m).map(|b| (m, b)); + let keep = match reference.filter(|_| p.get("center").is_none_or(Value::is_null)) { + Some(i) => { + let d = &s.doc()?.doc; + let (m, b) = boxed(d, how).or_else(|| boxed(d, geometric)).ok_or_else(|| EngineError::Other("no bounds".into()))?; + Some((i, m, b.reference_point(i))) + } + None => None, + }; let path = outline(&shape, C)?; s.edit(EDIT, |d, sel| { shape_node(d.node_mut(id).ok_or(EngineError::NoNode(id))?, &shape, path); + if let Some((i, m, was)) = keep + && let Some(now) = boxed(d, m).map(|(_, b)| b.reference_point(i)) + && now != was + { + let mut moved = shape; + moved.center += was - now; + let path = outline(&moved, C)?; + shape_node(d.node_mut(id).ok_or(EngineError::NoNode(id))?, &moved, path); + } + // A shape named by `id` and not selected is not checked after the edit: one the edit + // takes past the coordinate limit is an error here, and nothing changes. + if !crate::sanity::objects_in_range(d, &[id]) { + return Err(bad(C, format!("coordinate out of range (limit ±{MAX_COORD} pt)"))); + } sel.anchors.remove(&id); sel.segments.remove(&id); Ok(()) })?; + // The numbers the edit committed (an object attached to a path is put back on it); none + // when snapping to the pixel grid left a plain path. + let committed = s.doc()?.doc.node(id).and_then(read); + return Ok(json!({ "id": id.0, "shape": committed.map_or(Value::Null, |c| to_json(&c)) })); } Ok(json!({ "id": id.0, "shape": to_json(&shape) })) } diff --git a/crates/engine/src/cmd/addons/pathtools/tests.rs b/crates/engine/src/cmd/addons/pathtools/tests.rs index 8cd83bacfd..c474cfae85 100644 --- a/crates/engine/src/cmd/addons/pathtools/tests.rs +++ b/crates/engine/src/cmd/addons/pathtools/tests.rs @@ -476,6 +476,92 @@ fn set_changes_the_numbers_in_one_step_and_nothing_without_a_change() { assert_eq!(path(&s, id).anchor_count(), 16); } +#[test] +fn set_keeps_the_reference_point_of_the_bounding_box_in_place() { + let mut s = session(); + let corner = |s: &Session, id: NodeId, i: usize| s.transform_box(&[id]).unwrap().reference_point(i); + // (kind, its own rotation, a turn with object.rotate, which turns its bounding box too) + for (kind, rotation, turn) in [ + ("rectangle", 0.0, 0.0), + ("rectangle", 30.0, 0.0), + ("rectangle", 180.0, 0.0), + ("rectangle", 0.0, 30.0), + ("star", 0.0, 0.0), + ("heart", 0.0, 0.0), + ] { + let r = s.execute("addon.pathtools.shape.create", &json!({"kind": kind, "center": [200, 150], "rotation": rotation})).unwrap(); + let id = id_of(&r); + if turn != 0.0 { + s.execute("object.rotate", &json!({"angle": turn, "origin": [200, 150]})).unwrap(); + assert!(s.transform_box(&[id]).unwrap().angle != 0.0, "the box turns with the object"); + } + // Each of the 9 points of the box the Transform panel shows stays where it was while the + // width and then the height change, as `object.setBounds` keeps it. + for refi in 0..9 { + for key in ["width", "height"] { + let (before, was) = (shape_of(&s, id).unwrap(), corner(&s, id, refi)); + let grown = if key == "width" { before.width } else { before.height } + 10.0; + s.execute("addon.pathtools.shape.set", &json!({"id": id.0, key: grown, "reference": refi})).unwrap(); + let moved = corner(&s, id, refi).distance(was); + assert!(moved < 1e-6, "{kind} at {rotation}°, reference {refi}, {key}: the point moved {moved} pt"); + let after = shape_of(&s, id).unwrap(); + assert!((if key == "width" { after.width } else { after.height } - grown).abs() < 1e-9, "{kind}, {key}: the new size"); + } + } + // Without a reference point, and with an explicit center, the old rules hold. + s.execute("addon.pathtools.shape.set", &json!({"id": id.0, "width": 80})).unwrap(); + let c = shape_of(&s, id).unwrap().center; + s.execute("addon.pathtools.shape.set", &json!({"id": id.0, "width": 120})).unwrap(); + assert!(shape_of(&s, id).unwrap().center.distance(c) < 1e-9, "the center stays by default"); + s.execute("addon.pathtools.shape.set", &json!({"id": id.0, "width": 60, "center": [10, 20], "reference": 0})).unwrap(); + assert!(shape_of(&s, id).unwrap().center.distance(Point::new(10.0, 20.0)) < 1e-9, "a center given wins"); + } + let id = star(&mut s); + refuses( + &mut s, + "addon.pathtools.shape.set", + &[ + json!({"id": id.0, "width": 50, "reference": -1}), + json!({"id": id.0, "width": 50, "reference": 1.5}), + json!({"id": id.0, "width": 50, "reference": 9}), + json!({"id": id.0, "width": 50, "reference": 9.0}), + ], + ); + // A whole number written with a decimal point picks the same point. + s.execute("addon.pathtools.shape.set", &json!({"id": id.0, "width": 50, "reference": 8.0})).unwrap(); + let written_whole = shape_of(&s, id).unwrap(); + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("addon.pathtools.shape.set", &json!({"id": id.0, "width": 50, "reference": 8})).unwrap(); + assert!(shape_of(&s, id).unwrap().center.distance(written_whole.center) < 1e-9, "`8.0` and `8` pick the same point"); + s.execute("edit.undo", &json!({})).unwrap(); + // With Use Preview Bounds the point is on the box as drawn: a star's stroked tips reach past + // its anchors by more as the star is stretched, so the drawn box and the anchors' box move apart. + s.prefs.use_preview_bounds = true; + let stroked = id_of(&s.execute("addon.pathtools.shape.create", &json!({"kind": "star", "center": [300, 300], "count": 5})).unwrap()); + s.execute("paint.setStroke", &json!({"ids": [stroked.0], "color": "#000000"})).unwrap(); + s.execute("stroke.set", &json!({"ids": [stroked.0], "weight": 12})).unwrap(); + let geometric = |s: &Session, i: usize| s.doc().unwrap().doc.oriented_bounds(&[stroked], false).unwrap().reference_point(i); + for refi in [0, 2, 6, 8] { + let (was, anchors_were) = (corner(&s, stroked, refi), geometric(&s, refi)); + let wide = shape_of(&s, stroked).unwrap().width * 2.5; + s.execute("addon.pathtools.shape.set", &json!({"id": stroked.0, "width": wide, "reference": refi})).unwrap(); + let moved = corner(&s, stroked, refi).distance(was); + assert!(moved < 1e-6, "stroked star, reference {refi}: the drawn box's point moved {moved} pt"); + assert!(geometric(&s, refi).distance(anchors_were) > 1e-3, "reference {refi}: the anchors' box is not the one kept"); + s.execute("edit.undo", &json!({})).unwrap(); + } + s.prefs.use_preview_bounds = false; + // A shape set by id, not selected, that the edit would take past the coordinate limit. + let edge = id_of(&s.execute("addon.pathtools.shape.create", &json!({"kind": "rectangle", "center": [3_999_900, 100]})).unwrap()); + select(&mut s, &[]); + refuses( + &mut s, + "addon.pathtools.shape.set", + &[json!({"id": edge.0, "width": 180, "reference": 0}), json!({"id": edge.0, "center": [3_999_990, 100]})], + ); + s.execute("addon.pathtools.shape.set", &json!({"id": edge.0, "width": 180, "reference": 2})).unwrap(); +} + #[test] fn bad_shape_params_are_refused() { let mut s = session(); diff --git a/crates/ui-egui/src/addons/pathtools/shape.rs b/crates/ui-egui/src/addons/pathtools/shape.rs index e32ece3450..7a666e695e 100644 --- a/crates/ui-egui/src/addons/pathtools/shape.rs +++ b/crates/ui-egui/src/addons/pathtools/shape.rs @@ -70,6 +70,13 @@ pub(super) fn target(app: &VectorcraftApp) -> (Option, ParametricShape) (None, apply(fallback, &app.session.tool_options_of(tool::ID)).unwrap_or(fallback)) } +/// Whether anchors are direct-selected, so that the selection's box is the box around them. +fn anchors_selected(app: &VectorcraftApp) -> bool { + app.session + .active() + .is_some_and(|st| vectorcraft_effects::preview::anchor_bounds_with(&st.selection, &st.doc, app.session.bounds_measure()).is_some()) +} + /// Whether something is selected and none of it is a parametric shape Convert could take. pub(super) fn plain_selected(app: &VectorcraftApp) -> bool { app.session.active().is_some_and(|st| !st.selection.is_empty()) && selected(app).is_none() @@ -143,6 +150,12 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { match (change, id) { (Some(mut p), Some(id)) => { p["id"] = json!(id.0); + // The Transform panel and the Control bar share one reference point locator. W and H + // keep the point of the shape's bounding box chosen there in place. With anchors + // direct-selected the locator shows their box, so the shape keeps its center instead. + if p.get("width").or_else(|| p.get("height")).is_some() && !anchors_selected(app) { + p["reference"] = json!(app.ui.transform_panel.reference_point); + } run(app, "addon.pathtools.shape.set", p); } (Some(values), None) => run(app, "tool.setOption", json!({ "tool": tool::ID, "values": values })), diff --git a/crates/ui-egui/src/addons/pathtools/tests.rs b/crates/ui-egui/src/addons/pathtools/tests.rs index 464ce72f42..6a92443213 100644 --- a/crates/ui-egui/src/addons/pathtools/tests.rs +++ b/crates/ui-egui/src/addons/pathtools/tests.rs @@ -112,6 +112,44 @@ fn the_parametric_shape_panel_edits_the_selected_shape_or_the_tools_next_one() { assert!(id.is_none() && super::shape::plain_selected(&app)); } +/// The panel's W and H keep the point of the selection's box that the Transform panel and the +/// Control bar share in place, as their own W and H do, on upright and turned shapes. +#[test] +fn the_parametric_shape_panels_size_fields_keep_the_shared_reference_point() { + for (refi, rotation) in [(0usize, 0.0), (8, 0.0), (2, 30.0), (0, 180.0)] { + let mut app = app(); + let params = json!({"kind": "rectangle", "center": [150, 150], "width": 100, "height": 60, "rotation": rotation}); + let id = vectorcraft_doc::NodeId(app.run("addon.pathtools.shape.create", params).unwrap()["id"].as_u64().unwrap()); + let shape = + |app: &VectorcraftApp| vectorcraft_tools::addons::parametric_shape::read(app.session.active().unwrap().doc.node(id).unwrap()).unwrap(); + app.ui.transform_panel.reference_point = refi; + let (before, was) = (shape(&app), app.selection_box().unwrap().reference_point(refi)); + let mut panel = Panel::new(app, super::shape::show); + panel.type_into("W", "160"); + panel.type_into("H", "20"); + let mut app = panel.app(); + let after = shape(&app); + assert!(after.width > before.width && after.height < before.height, "reference {refi}: W and H took {after:?}"); + let moved = app.selection_box().unwrap().reference_point(refi).distance(was); + assert!(moved < 1e-6, "reference {refi}, rotation {rotation}: the reference point moved {moved} pt"); + } + // With an anchor direct-selected the locator shows the anchors' box, so W keeps the shape's center. + let mut app = app(); + let params = json!({"kind": "rectangle", "center": [150, 150], "width": 100, "height": 60}); + let id = vectorcraft_doc::NodeId(app.run("addon.pathtools.shape.create", params).unwrap()["id"].as_u64().unwrap()); + app.session + .select(|_, sel| { + sel.anchors.insert(id, [(0, 1)].into_iter().collect()); + }) + .unwrap(); + app.ui.transform_panel.reference_point = 0; + let mut panel = Panel::new(app, super::shape::show); + panel.type_into("W", "160"); + let app = panel.app(); + let after = vectorcraft_tools::addons::parametric_shape::read(app.session.active().unwrap().doc.node(id).unwrap()).unwrap(); + assert!((after.width - 160.0).abs() < 1e-6 && after.center.distance(vectorcraft_geom::Point::new(150.0, 150.0)) < 1e-6, "{after:?}"); +} + /// The Corner Tool and Shared Edge Merge Tool items leave a floating Anchor Inspector showing /// instead of closing it, and in Presentation Mode they choose the tool without failing. #[test] diff --git a/docs/mcp.md b/docs/mcp.md index 97cdbff876..ce305d43bf 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -15178,8 +15178,12 @@ Commands: roundness (0 to 1; 0.4 and 0); gear, tooth height (0.01 to 0.9, 0.2); bubble, the tail's height (0.05 to 0.9, 0.25) and where its tip is across (−1 to 1, −0.4). → `{id, shape}`. - `addon.pathtools.shape.set {id, …}` changes a parametric shape's numbers (the same keys; a new `kind` takes its own - defaults for the values not given) and redraws it in place. With no change it makes no step. → `{id, shape}` (its - numbers now, so `{id}` alone reads them). + defaults for the values not given) and redraws it in place. With `reference` (0 to 8 on the 9-point grid of the + bounding box as `object.setBounds` measures it, rotated with rotated objects) and no `center`, that point of the box + keeps its place, as with the Transform panel's W and H; otherwise the shape's center stays. Snapping to the pixel + grid and an attachment to a path apply after that, as they do for the Transform panel's W and H, and can move the + point. A `reference` outside 0 to 8 is an error. With no change it makes no step. → `{id, shape}` (its numbers now, so `{id}` alone reads them; + `null` when snapping to the pixel grid left a plain path). - `addon.pathtools.shape.convert {ids?}` makes the selected plain closed paths that are rectangles, ellipses or polygons with equal sides and corners (stretched along their own axes at most) parametric shapes with the same outline. → `{ids}` (those converted). diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index a80d4f8f97..da649598bf 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -2876,7 +2876,9 @@ The add-on's Parametric Shape Tool (2026-10-30) draws ten kinds of shape that st ellipse, polygon and star with 3 to 1,000 sides or points, ring, arrow, cross, heart, gear, speech bubble; corner radius limited to the middle of a side): a drag from the centre sizes and turns one, the arrow keys change its count and values while dragging, handles edit a selected one, a double-click places one with the last settings, and its panel edits the -numbers. A shape is a plain path whose numbers and outline fingerprint sit in one object-data entry that SVG export +numbers (its W and H keep the point chosen in the shared reference point locator in place, and the center when anchors +are direct-selected). A shape is a plain path +whose numbers and outline fingerprint sit in one object-data entry that SVG export leaves out; moving, rotating or scaling it keeps it editable, editing its anchors makes it a plain path. Convert to Parametric Shape recognises plain rectangles, ellipses and regular polygons. Geometry in `vectorcraft_pathops::addons::pathtools::shapes`. Tests: `shapes` in `vectorcraft-pathops` (each kind, ranges,