mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-26 12:21:08 +01:00
Parametric Shape: W and H keep the shared reference point in place
The Parametric Shape panel's W and H fields resized a shape about its center whatever point the reference point locator showed, while the Transform panel and the Control bar keep that point in place. - addon.pathtools.shape.set takes `reference` (0 to 8; any other value is an error). With it and no `center`, the point of the bounding box that object.setBounds measures (rotated with rotated objects, and as drawn with Use Preview Bounds) keeps its place. Without it the center stays, as before. - The panel's W and H pass the locator's point. - A shape set by id and not selected that the edit would take past the coordinate limit is refused, as object.setLiveShape refuses one. - The result's `shape` is read back after the edit, and is null when snapping to the pixel grid left a plain path. Docs: docs/mcp.md, docs/target-app-parity.md.
This commit is contained in:
1 parent
9fff48d88f
commit
4cb3b0d5b6
6 files changed
+199
-9
No files matched your search
@@ -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<CommandSpec> {
|
||||
"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), 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,52 @@ fn set(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
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.
|
||||
let how = s.bounds_measure();
|
||||
let boxed = move |d: &Document| {
|
||||
effects::preview::oriented_bounds_with(d, &[id], how)
|
||||
.or_else(|| effects::preview::oriented_bounds_with(d, &[id], effects::preview::Measure { preview: false, ..how }))
|
||||
};
|
||||
let keep = match reference.filter(|_| p.get("center").is_none_or(Value::is_null)) {
|
||||
Some(i) => Some((i, boxed(&s.doc()?.doc).ok_or_else(|| EngineError::Other("no bounds".into()))?.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, was)) = keep
|
||||
&& let Some(now) = boxed(d).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) }))
|
||||
}
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -9,7 +9,7 @@ use vectorcraft_geom::Point;
|
||||
use vectorcraft_tools::addons::parametric_shape::{self as tool, MAX_COUNT, MAX_SIZE, MIN_COUNT, ParametricShape, ShapeKind, apply, read};
|
||||
|
||||
use crate::VectorcraftApp;
|
||||
use crate::panels::empty_state;
|
||||
use crate::panels::{empty_state, transform};
|
||||
use crate::widgets::{self, dim_label};
|
||||
|
||||
/// The panel's id (`window.panel {panel: "parametricShape"}`).
|
||||
@@ -121,6 +121,11 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
|
||||
match (change, selected) {
|
||||
(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.
|
||||
if p.get("width").or_else(|| p.get("height")).is_some() {
|
||||
p["reference"] = json!(transform::reference_index(ui));
|
||||
}
|
||||
run(app, "addon.pathtools.shape.set", p);
|
||||
}
|
||||
(Some(values), None) => run(app, "tool.setOption", json!({ "tool": tool::ID, "values": values })),
|
||||
|
||||
@@ -136,6 +136,62 @@ fn the_parametric_shape_panel_opens_from_the_submenu_and_shows_the_shape() {
|
||||
assert!(!text.contains("Count:"), "a speech bubble has no count: {text}");
|
||||
}
|
||||
|
||||
/// One headless frame of the Parametric Shape panel with input `events`: every text drawn, with its rect.
|
||||
fn shape_panel_frame(ctx: &egui::Context, app: &mut VectorcraftApp, events: Vec<egui::Event>) -> Vec<(String, egui::Rect)> {
|
||||
let mut out = ctx.run_ui(egui::RawInput { events, ..Default::default() }, |ui| super::shape::show(app, ui));
|
||||
out.textures_delta.clear();
|
||||
fn collect(s: &egui::Shape, out: &mut Vec<(String, egui::Rect)>) {
|
||||
match s {
|
||||
egui::Shape::Text(t) => out.push((t.galley.text().to_string(), t.visual_bounding_rect())),
|
||||
egui::Shape::Vec(v) => v.iter().for_each(|s| collect(s, out)),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
let mut texts = vec![];
|
||||
for c in &out.shapes {
|
||||
collect(&c.shape, &mut texts);
|
||||
}
|
||||
texts
|
||||
}
|
||||
|
||||
/// Type `value` into the panel's field that shows `shown`, and press Enter.
|
||||
fn type_into_shape_panel(ctx: &egui::Context, app: &mut VectorcraftApp, shown: &str, value: &str) {
|
||||
let texts = shape_panel_frame(ctx, app, vec![]);
|
||||
let pos = texts.iter().find(|(t, _)| t == shown).unwrap_or_else(|| panic!("`{shown}` not drawn: {texts:?}")).1.center();
|
||||
let button = |pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() };
|
||||
let key = |key, modifiers| egui::Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers };
|
||||
for e in
|
||||
[egui::Event::PointerMoved(pos), button(true), button(false), key(egui::Key::A, egui::Modifiers::COMMAND), egui::Event::Text(value.into())]
|
||||
{
|
||||
shape_panel_frame(ctx, app, vec![e]);
|
||||
}
|
||||
shape_panel_frame(ctx, app, vec![key(egui::Key::Enter, egui::Modifiers::NONE)]);
|
||||
shape_panel_frame(ctx, app, vec![]);
|
||||
}
|
||||
|
||||
/// 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 node = |app: &VectorcraftApp| app.session.active().unwrap().doc.node(id).cloned().unwrap();
|
||||
let shape = |app: &VectorcraftApp| vectorcraft_tools::addons::parametric_shape::read(&node(app)).unwrap();
|
||||
let ctx = egui::Context::default();
|
||||
crate::theme::install_fonts(&ctx);
|
||||
ctx.data_mut(|d| d.insert_temp(egui::Id::unique("refpt"), refi));
|
||||
let (before, was) = (shape(&app), app.selection_box().unwrap().reference_point(refi));
|
||||
type_into_shape_panel(&ctx, &mut app, "100 pt", "160");
|
||||
type_into_shape_panel(&ctx, &mut app, "60 pt", "20");
|
||||
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");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_corner_tool_item_selects_the_tool_and_opens_its_panel_section() {
|
||||
let mut app = app();
|
||||
|
||||
+5
-2
@@ -14749,8 +14749,11 @@ 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. 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).
|
||||
|
||||
@@ -2820,9 +2820,10 @@ 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
|
||||
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
|
||||
numbers (its W and H keep the point chosen in the shared reference point locator in place). 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,
|
||||
recovery after transforms, recognition), `addons::parametric_shape` in `vectorcraft-tools` (drag, keys, handles,
|
||||
stored data), `cmd::addons::pathtools::tests` in `vectorcraft-engine` (each command one undo step, bad params refused,
|
||||
|
||||
Reference in new issue
Block a user