From 24c0f89ff9cd1e66c47f582641f1f8a553a53bc2 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 10:41:36 -0800 Subject: [PATCH] Part of #7840: the Ellipse dialog sets how many anchors the ellipse has A click with the Ellipse tool opens a dialog with a new Anchors field under Height, 4 by default. With 4, OK draws the same live ellipse as before. Any other count from 2 to 1000 draws a closed plain path with that many smooth anchors spaced evenly by angle, from the left one and clockwise, with handles of 4/3*tan(theta/4) scaled along each axis and the path fitted to the typed width and height. The dialog sends the nearest whole number from 2 to 1000 (4 for an empty field or text that is not a number). The count confirmed last is kept as the Ellipse tool's anchors option, and the next Ellipse dialog opens on it. shape.ellipse takes an optional anchors param (default 4). A number that is not a whole number from 2 to 1000 gets one error naming that range, a value that is not a number gets the usual type error, and nothing is drawn. The MCP draw_shape tool lists anchors for ellipses. Docs: params text, docs/mcp.md, docs/target-app-parity.md (Shapes). --- crates/engine/src/cmd/create.rs | 24 +++++- crates/engine/src/tests.rs | 79 ++++++++++++++++++++ crates/engine/src/tests/constrain_new.rs | 19 +++++ crates/engine/src/tests/persp_text.rs | 16 ++++ crates/geom/src/shapes.rs | 55 ++++++++++++++ crates/mcp/src/tools/definitions.rs | 3 +- crates/tools/src/settings.rs | 2 + crates/tools/src/shape.rs | 6 ++ crates/ui-egui/src/dialogs/shapes.rs | 95 +++++++++++++++++++++++- crates/ui-egui/src/dialogs/tools.rs | 6 +- docs/mcp.md | 21 +++++- docs/target-app-parity.md | 1 + 12 files changed, 317 insertions(+), 10 deletions(-) diff --git a/crates/engine/src/cmd/create.rs b/crates/engine/src/cmd/create.rs index 08944940a2..5571d24b28 100644 --- a/crates/engine/src/cmd/create.rs +++ b/crates/engine/src/cmd/create.rs @@ -26,7 +26,7 @@ pub fn specs() -> Vec { "Ellipse", [], None, - "{x, y, width, height, rotation?: deg clockwise about the centre (0: upright)} → {id}", + "{x, y, width, height, rotation?: deg clockwise about the centre (0: upright), anchors=4 (2–1000: smooth anchors spaced evenly by angle; any count but 4 draws a plain path, not a live ellipse)} → {id}", has_doc, ellipse ), @@ -362,10 +362,28 @@ fn rectangle(s: &mut Session, p: &Value) -> Result { add_art_turned(s, label, path_kind(live.to_path(), Some(live)), f64_or(p, "rotation", 0.0)) } +/// The most anchors `shape.ellipse` draws, as many as a polygon's sides. +const MAX_ELLIPSE_ANCHORS: u64 = 1000; + fn ellipse(s: &mut Session, p: &Value) -> Result { let r = rect_of(p, "shape.ellipse")?; - let live = LiveShape::Ellipse { w: r.width(), h: r.height(), pie: (0.0, 360.0), xf: rect_transform(r, p, "shape.ellipse")? }; - add_art_turned(s, "Ellipse", path_kind(live.to_path(), Some(live)), f64_or(p, "rotation", 0.0)) + // One message for every number that is not a whole count in range (a fraction, a negative, + // 0, 1, too many); a value that is not a number gets `number_or`'s. + let (key, min, max) = ("anchors", 2, MAX_ELLIPSE_ANCHORS); + let n = number_or(p, key, 4.0, "shape.ellipse")?; + if n.fract() != 0.0 || !(min as f64..=max as f64).contains(&n) { + return Err(bad("shape.ellipse", format!("`{key}` must be a whole number between {min} and {max} (got {n})"))); + } + let x = n as u64; + let xf = rect_transform(r, p, "shape.ellipse")?; + let rotation = f64_or(p, "rotation", 0.0); + if x != 4 { + // Another count is a plain path: a live ellipse always has 4 anchors. + let path = shapes::ellipse_with_anchors(Rect::new(0.0, 0.0, r.width(), r.height()), x as u32).transformed(xf); + return add_art_turned(s, "Ellipse", path_kind(path, None), rotation); + } + let live = LiveShape::Ellipse { w: r.width(), h: r.height(), pie: (0.0, 360.0), xf }; + add_art_turned(s, "Ellipse", path_kind(live.to_path(), Some(live)), rotation) } /// The whole-number count `p` gives for `key` (`5` or `5.0`), or `default` when it is left out or diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 1b420d7805..64a551e872 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -3310,6 +3310,85 @@ fn flare_ring_seed_moves_only_the_rings() { assert_eq!(s.doc().unwrap().history.undo.len(), undo); } +/// `shape.ellipse` without `anchors`, or with 4, draws the live ellipse it always drew. +#[test] +fn ellipse_with_four_anchors_is_the_live_ellipse() { + let mut s = session(); + let draw = |s: &mut Session, extra: Option| { + let mut p = json!({"x": 40, "y": 30, "width": 120, "height": 80}); + if let Some(n) = extra { + p["anchors"] = json!(n); + } + let id = NodeId(s.execute("shape.ellipse", &p).unwrap()["id"].as_u64().unwrap()); + s.doc().unwrap().doc.node(id).unwrap().clone() + }; + let (plain, four) = (draw(&mut s, None), draw(&mut s, Some(4))); + for n in [&plain, &four] { + assert!(matches!(n.live_shape(), Some(vectorcraft_doc::LiveShape::Ellipse { .. })), "{:?}", n.live_shape()); + assert_eq!(n.path_data().unwrap().anchor_count(), 4); + } + assert_eq!(plain.path_data(), four.path_data()); + assert_eq!(plain.live_shape(), four.live_shape()); +} + +/// Any other count draws a closed plain path of that many smooth anchors on the ellipse, its +/// bounds the typed size, as one undo step. +#[test] +fn ellipse_anchors_draw_that_many_anchors_on_the_ellipse() { + let mut s = session(); + let (x, y, w, h) = (40.0, 30.0, 120.0, 80.0); + let (c, rx, ry) = (Point::new(x + w / 2.0, y + h / 2.0), w / 2.0, h / 2.0); + for n in [2u64, 3, 5, 6, 8] { + let undo = s.doc().unwrap().history.undo.len(); + let id = NodeId(s.execute("shape.ellipse", &json!({"x": x, "y": y, "width": w, "height": h, "anchors": n})).unwrap()["id"].as_u64().unwrap()); + assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1, "{n}: one undo step"); + let node = s.doc().unwrap().doc.node(id).unwrap(); + assert!(node.live_shape().is_none(), "{n}: a plain path"); + let path = node.path_data().unwrap(); + assert_eq!(path.subpaths.len(), 1); + let sp = &path.subpaths[0]; + assert!(sp.closed, "{n}"); + assert_eq!(sp.anchors.len() as u64, n); + for a in &sp.anchors { + assert_eq!(a.kind, vectorcraft_geom::AnchorKind::Smooth, "{n}"); + let on = ((a.p.x - c.x) / rx).powi(2) + ((a.p.y - c.y) / ry).powi(2); + assert!((on - 1.0).abs() < 0.01, "{n}: {:?} is off the ellipse ({on})", a.p); + } + let b = path.bounds().unwrap(); + for (got, want) in [(b.x0, x), (b.y0, y), (b.x1, x + w), (b.y1, y + h)] { + assert!((got - want).abs() < 1e-6, "{n}: bounds {b:?}"); + } + } + // The first anchor is the left one, and they run clockwise on screen, as the live ellipse's do. + let id = NodeId(s.execute("shape.ellipse", &json!({"x": x, "y": y, "width": w, "height": h, "anchors": 8})).unwrap()["id"].as_u64().unwrap()); + let sp = s.doc().unwrap().doc.node(id).unwrap().path_data().unwrap().subpaths[0].clone(); + assert!(sp.anchors[0].p.distance(Point::new(x, c.y)) < 1e-6, "{:?}", sp.anchors[0].p); + assert!(sp.anchors[2].p.distance(Point::new(c.x, y)) < 1e-6, "{:?}", sp.anchors[2].p); +} + +/// An `anchors` that is not a whole number from 2 to 1000 is refused, and nothing is drawn. +#[test] +fn ellipse_refuses_a_bad_anchor_count() { + let mut s = session(); + let undo = s.doc().unwrap().history.undo.len(); + let range = |got: &str| format!("`anchors` must be a whole number between 2 and 1000 (got {got})"); + for (bad, want) in [ + (json!(0), range("0")), + (json!(1), range("1")), + (json!(2.5), range("2.5")), + (json!(-3), range("-3")), + (json!(1001), range("1001")), + (json!("x"), "`anchors` must be a number, not \"x\"".to_string()), + (json!("6"), "`anchors` must be a number, not \"6\"".to_string()), + (json!(true), "`anchors` must be a number, not true".to_string()), + ] { + let e = s.execute("shape.ellipse", &json!({"x": 0, "y": 0, "width": 50, "height": 50, "anchors": bad})).unwrap_err().to_string(); + assert!(e.contains(&want), "{bad}: {e}"); + } + assert_eq!(s.doc().unwrap().history.undo.len(), undo); + assert!(s.doc().unwrap().doc.layers[0].children().unwrap().is_empty()); +} + /// Through the session, Ctrl/Cmd in the Flare tool's center drag keeps the center's size while the /// drag sizes the halo, and the flare drawn keeps both. #[test] diff --git a/crates/engine/src/tests/constrain_new.rs b/crates/engine/src/tests/constrain_new.rs index 49fd29e94b..50797e35e3 100644 --- a/crates/engine/src/tests/constrain_new.rs +++ b/crates/engine/src/tests/constrain_new.rs @@ -253,6 +253,25 @@ fn constrain_angle_turns_shapes_made_by_a_click() { } } +/// An ellipse of another anchor count made by a click turns along the Constrain Angle like the +/// live ellipse: it keeps its anchors and its box runs along the turned axes from the click. +#[test] +fn constrain_angle_turns_an_ellipse_of_six_anchors_made_by_a_click() { + let mut s = new_doc(); + set_angle(&mut s, 90.0); + let p = json!({"x": 10, "y": 200, "width": 100, "height": 50, "anchors": 6}); + let p = constrain_click(&s, "shape.ellipse", p.clone(), corner(&p)); + assert_eq!(p["anchors"], json!(6)); + let id = NodeId(s.execute("shape.ellipse", &p).unwrap()["id"].as_u64().unwrap()); + let n = s.doc().unwrap().doc.node(id).unwrap().clone(); + assert!(n.live_shape().is_none()); + assert_eq!(n.path_data().unwrap().anchor_count(), 6); + let b = bounds(&s, id); + for (got, want) in [(b.x0, 10.0), (b.y0, 100.0), (b.x1, 60.0), (b.y1, 200.0)] { + assert!(close(got, want), "{b:?}"); + } +} + /// The Line Segment tool's Shift steps of 45° count from the Constrain Angle. #[test] fn constrain_angle_steps_the_line_segment_tool() { diff --git a/crates/engine/src/tests/persp_text.rs b/crates/engine/src/tests/persp_text.rs index b5dc5e7a53..443913a635 100644 --- a/crates/engine/src/tests/persp_text.rs +++ b/crates/engine/src/tests/persp_text.rs @@ -399,6 +399,22 @@ fn click_to_size_dialogs_draw_on_the_active_plane_in_plane_units() { assert!(crate::perspective_click(&s, "shape.rectangle", &json!({}), at).is_none()); } +/// The Ellipse dialog's anchor count reaches the ellipse drawn on the active plane. +#[test] +fn an_ellipse_of_six_anchors_made_by_a_click_draws_on_the_active_plane() { + let (mut s, _) = persp_session(); + s.execute("perspective.grid.show", &json!({"visible": true})).unwrap(); + s.execute("perspective.plane.set", &json!({"plane": "right"})).unwrap(); + let at = Point::new(470.0, 300.0); + let p = json!({"x": at.x, "y": at.y, "width": 50, "height": 30, "anchors": 6}); + let (cmd, p) = crate::perspective_click(&s, "shape.ellipse", &p, at).unwrap(); + let n = undo_len(&s); + let id = NodeId(s.execute(&cmd, &p).unwrap()["id"].as_u64().unwrap()); + assert_eq!(undo_len(&s), n + 1); + assert_eq!(attached(&s, id).map(|a| a.0), Some(Plane::Right)); + assert_eq!(node(&s, id).path_data().unwrap().anchor_count(), 6); +} + #[test] fn the_canvas_draws_type_in_perspective_foreshortened() { let (mut s, rect) = persp_session(); diff --git a/crates/geom/src/shapes.rs b/crates/geom/src/shapes.rs index 0ae8a75190..5bebc07384 100644 --- a/crates/geom/src/shapes.rs +++ b/crates/geom/src/shapes.rs @@ -103,6 +103,38 @@ pub fn ellipse(r: Rect) -> PathData { PathData::single(SubPath::new(anchors, true)) } +/// Ellipse inscribed in `r` with `n` smooth anchors (at least 2) spaced evenly by angle, clockwise +/// on screen from the left one, as [`ellipse`] runs. Each segment is a cubic whose handles are +/// 4/3·tan(θ/4) of the tangent at its ends (θ = 360°/`n`), scaled along each axis; the path is then +/// fitted to `r`, so its bounds are `r` whatever the count. 4 anchors give [`ellipse`]. +pub fn ellipse_with_anchors(r: Rect, n: u32) -> PathData { + let n = n.max(2); + let r = r.abs(); + let c = r.center(); + let (rx, ry) = (r.width() / 2.0, r.height() / 2.0); + let step = TAU / f64::from(n); + let k = 4.0 / 3.0 * (step / 4.0).tan(); + let anchors = (0..n) + .map(|i| { + // From the left anchor (angle π). With y down, sin is negative just past π, so the next + // anchor is above the centre: left, then top, then right, as `ellipse` runs. + let a = PI + step * f64::from(i); + let p = Point::new(c.x + rx * a.cos(), c.y + ry * a.sin()); + let d = Vec2::new(-rx * a.sin(), ry * a.cos()) * k; + Anchor { p, h_in: p - d, h_out: p + d, kind: AnchorKind::Smooth } + }) + .collect(); + let path = PathData::single(SubPath::new(anchors, true)); + // Between anchors a curve can reach a little past the ellipse or stop short of it (0.15% of + // the height with 3 anchors): fit the bounds to `r` along each axis that has a size. + let Some(b) = path.bounds() else { return path }; + let fit = |want: f64, got: f64| if want > 0.0 && got > 0.0 { want / got } else { 1.0 }; + let (sx, sy) = (fit(r.width(), b.width()), fit(r.height(), b.height())); + path.transformed( + kurbo::Affine::translate(r.origin().to_vec2()) * kurbo::Affine::scale_non_uniform(sx, sy) * kurbo::Affine::translate(-b.origin().to_vec2()), + ) +} + /// How an ellipse or shape arc is closed or left open when cut between start and end angles. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] @@ -693,6 +725,29 @@ mod tests { assert!((area - PI * 50.0 * 30.0).abs() / area < 0.001); } + #[test] + fn ellipse_with_four_anchors_is_the_ellipse_and_others_fit_the_box() { + let r = Rect::new(10.0, 20.0, 110.0, 80.0); + let (four, plain) = (ellipse_with_anchors(r, 4), ellipse(r)); + for (a, b) in four.subpaths[0].anchors.iter().zip(&plain.subpaths[0].anchors) { + assert!(a.p.distance(b.p) < 1e-9 && a.h_in.distance(b.h_in) < 1e-9 && a.h_out.distance(b.h_out) < 1e-9, "{a:?} {b:?}"); + } + for n in [2, 3, 5, 7, 9, 1000] { + let p = ellipse_with_anchors(r, n); + assert_eq!(p.anchor_count(), n as usize); + let b = p.bounds().unwrap(); + assert!( + (b.x0 - r.x0).abs() < 1e-9 && (b.y0 - r.y0).abs() < 1e-9 && (b.x1 - r.x1).abs() < 1e-9 && (b.y1 - r.y1).abs() < 1e-9, + "{n}: {b:?}" + ); + let area = p.subpaths[0].area().abs(); + assert!((area - PI * 50.0 * 30.0).abs() / area < if n == 2 { 0.1 } else { 0.01 }, "{n}: {area}"); + } + // A box with no height leaves the path flat rather than dividing by zero. + let flat = ellipse_with_anchors(Rect::new(0.0, 5.0, 40.0, 5.0), 6); + assert!(flat.subpaths[0].anchors.iter().all(|a| a.p.y == 5.0 && a.p.x.is_finite())); + } + #[test] fn rounded_rect_clamps() { let p = rounded_rectangle(Rect::new(0.0, 0.0, 20.0, 10.0), 100.0); diff --git a/crates/mcp/src/tools/definitions.rs b/crates/mcp/src/tools/definitions.rs index 4b55d6aff1..e549c2a362 100644 --- a/crates/mcp/src/tools/definitions.rs +++ b/crates/mcp/src/tools/definitions.rs @@ -244,7 +244,7 @@ pub fn tool_definitions() -> Vec { tool( "draw_shape", "Draw shape", - "Create a live shape and apply optional paint. rectangle/ellipse: x, y, width, height (rectangle: radius = corner radius). polygon: cx, cy, radius, sides. star: cx, cy, radius1, radius2, points. line: x1, y1, x2, y2. Omitted paint fields inherit the current new-art appearance (initially white fill and 1 pt black stroke); lines start with no fill and a visible stroke. For a filled shape without an outline, pass an explicit fill and stroke:\"none\". Stroke dash/cap/join, opacity, name and live effects apply to the new shape as in draw_path. Returns the new object id.", + "Create a live shape and apply optional paint. rectangle/ellipse: x, y, width, height (rectangle: radius = corner radius; ellipse: anchors, default 4, where any other count from 2 to 1000 draws a plain path rather than a live shape). polygon: cx, cy, radius, sides. star: cx, cy, radius1, radius2, points. line: x1, y1, x2, y2. Omitted paint fields inherit the current new-art appearance (initially white fill and 1 pt black stroke); lines start with no fill and a visible stroke. For a filled shape without an outline, pass an explicit fill and stroke:\"none\". Stroke dash/cap/join, opacity, name and live effects apply to the new shape as in draw_path. Returns the new object id.", obj( with_draw_options(json!({ "shape": {"type": "string", "enum": ["rectangle", "ellipse", "polygon", "star", "line"]}, @@ -253,6 +253,7 @@ pub fn tool_definitions() -> Vec { "width": num("Width (rectangle/ellipse)"), "height": num("Height (rectangle/ellipse)"), "radius": num("Corner radius (rectangle) or radius (polygon)"), + "anchors": {"type": "integer", "minimum": 2, "maximum": 1000, "description": "Ellipse anchors, spaced evenly by angle (default 4, a live ellipse; any other count draws a plain path)"}, "cx": num("Centre x (polygon/star)"), "cy": num("Centre y (polygon/star)"), "sides": {"type": "integer", "minimum": 3, "description": "Polygon sides (default 6)"}, diff --git a/crates/tools/src/settings.rs b/crates/tools/src/settings.rs index a5c92b00b0..97e980e3c0 100644 --- a/crates/tools/src/settings.rs +++ b/crates/tools/src/settings.rs @@ -51,6 +51,8 @@ const ROWS: &[Row] = &[ (&["livePaintBucket"], None, &["paintFills", "paintStrokes", "cursorSwatchPreview", "highlight", "color", "width"]), (&["polygon"], None, &["sides"]), (&["star"], None, &["points"]), + // The Ellipse dialog's Anchors. + (&["ellipse"], None, &["anchors"]), (&["freeTransform"], None, &["constrain"]), // Shape Builder Tool Options (`builder::ShapeBuilderOptions`). ( diff --git a/crates/tools/src/shape.rs b/crates/tools/src/shape.rs index 66728b4826..9eda809c03 100644 --- a/crates/tools/src/shape.rs +++ b/crates/tools/src/shape.rs @@ -84,6 +84,9 @@ pub struct ShapeTool { began: bool, pub sides: u32, pub points: u32, + /// The anchors an ellipse made by a click has (the Ellipse dialog opens on it); 4 is a live + /// ellipse. + pub anchors: u32, pub corner_radius: f64, /// Star inner radius as a fraction of the outer radius. pub star_ratio: f64, @@ -146,6 +149,7 @@ impl ShapeTool { began: false, sides: 6, points: 5, + anchors: 4, corner_radius: 12.0, star_ratio: 0.5, inner: None, @@ -787,6 +791,7 @@ impl Tool for ShapeTool { json!({ "sides": self.sides, "points": self.points, + "anchors": self.anchors, "cornerRadius": self.corner_radius, "starRatio": self.star_ratio, "length": self.line_length, @@ -799,6 +804,7 @@ impl Tool for ShapeTool { match key { "sides" => self.sides = v.as_u64().unwrap_or(6).clamp(3, 1000) as u32, "points" => self.points = v.as_u64().unwrap_or(5).clamp(3, 1000) as u32, + "anchors" => self.anchors = v.as_u64().unwrap_or(4).clamp(2, 1000) as u32, "cornerRadius" => self.corner_radius = finite.unwrap_or(12.0).clamp(0.0, MAX_CORNER_RADIUS), "starRatio" => self.star_ratio = v.as_f64().unwrap_or(0.5).clamp(0.01, 1.0), "length" => self.line_length = finite.map_or(self.line_length, |n| n.abs().min(1e6)), diff --git a/crates/ui-egui/src/dialogs/shapes.rs b/crates/ui-egui/src/dialogs/shapes.rs index 392c043f35..b807bc5274 100644 --- a/crates/ui-egui/src/dialogs/shapes.rs +++ b/crates/ui-egui/src/dialogs/shapes.rs @@ -306,6 +306,9 @@ fn linked_size_form(ui: &mut egui::Ui, d: &mut Dialog, unit: Unit) { if d.kind == "roundedRectangle" { form::length_field(ui, d, "radius", &form::humanized("radius"), unit); } + if d.kind == "ellipse" { + form::field(ui, d, "anchors", "Anchors:"); + } }); let Some(rows) = rows else { return }; let on = d.bool(LINK); @@ -358,6 +361,13 @@ fn follow_link(d: &mut Dialog, typed: &str) { } } +/// The Ellipse dialog's Anchors: the nearest whole number from 2 to 1000 (4, a live ellipse, when +/// left empty or not a number). +fn ellipse_anchors(d: &Dialog) -> u64 { + let n = d.f64("anchors", 4.0); + if n.is_finite() { n.round().clamp(2.0, 1000.0) as u64 } else { 4 } +} + /// The top-left corner of a rectangle or ellipse: the click itself, or with Alt held (draw from centre) the click minus half the size. fn box_origin(d: &Dialog) -> (f64, f64) { let (x, y) = (d.f64("x", 0.0), d.f64("y", 0.0)); @@ -386,11 +396,15 @@ fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { values[key] = json!(d.f64(key, default).clamp(min, 1000.0) as u64); values }) + .or_else(|| (d.kind == "ellipse").then(|| json!({"anchors": ellipse_anchors(d)}))) .or_else(|| OPTION_TOOLS.contains(&d.kind.as_str()).then(|| tool_options(d))); let (x, y) = (d.f64("x", 0.0), d.f64("y", 0.0)); let (bx, by) = box_origin(d); let (id, params) = match d.kind.as_str() { - "ellipse" => ("shape.ellipse", json!({"x": bx, "y": by, "width": d.f64("width", 100.0), "height": d.f64("height", 100.0)})), + "ellipse" => ( + "shape.ellipse", + json!({"x": bx, "y": by, "width": d.f64("width", 100.0), "height": d.f64("height", 100.0), "anchors": ellipse_anchors(d)}), + ), "polygon" => ("shape.polygon", json!({"cx": x, "cy": y, "radius": d.f64("radius", 50.0), "sides": d.f64("sides", 6.0) as u64})), "star" => ( "shape.star", @@ -649,6 +663,85 @@ mod tests { assert!((b.width() - 80.0).abs() < 1e-6 && (b.height() - 40.0).abs() < 1e-6, "{b:?}"); } + /// The Ellipse dialog opens with Anchors 4, which draws a live ellipse; OK with 6 draws a plain + /// path of 6 anchors, and the next Ellipse dialog opens on 6. + #[test] + fn the_ellipse_dialog_draws_and_keeps_its_anchor_count() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 300, "height": 300})).unwrap(); + app.run("tool.select", json!({"tool": "ellipse"})).unwrap(); + let last = |app: &VectorcraftApp| { + let doc = &app.session.doc().unwrap().doc; + doc.layers[0].children().unwrap().last().cloned().expect("an ellipse") + }; + + super::super::open_tool_dialog(&mut app, "ellipse", json!({"x": 10.0, "y": 10.0})); + assert_eq!(app.ui.dialog.as_ref().unwrap().f64("anchors", 0.0), 4.0); + super::super::confirm(&mut app).unwrap(); + let n = last(&app); + assert!(matches!(n.live_shape(), Some(vectorcraft_doc::LiveShape::Ellipse { .. })), "{:?}", n.live_shape()); + + super::super::open_tool_dialog(&mut app, "ellipse", json!({"x": 150.0, "y": 150.0})); + app.ui.dialog.as_mut().unwrap().fields.insert("anchors".into(), json!("6")); + super::super::confirm(&mut app).unwrap(); + let n = last(&app); + assert!(n.live_shape().is_none()); + assert_eq!(n.path_data().unwrap().anchor_count(), 6); + let b = n.geometric_bounds().unwrap(); + assert!((b.width() - 100.0).abs() < 1e-6 && (b.height() - 100.0).abs() < 1e-6, "{b:?}"); + + // Kept as the Ellipse tool's `anchors` option for the next click, after another tool too. + assert_eq!(app.session.tool_options_of("ellipse")["anchors"], json!(6)); + app.run("tool.select", json!({"tool": "rectangle"})).unwrap(); + app.run("tool.select", json!({"tool": "ellipse"})).unwrap(); + super::super::open_tool_dialog(&mut app, "ellipse", json!({"x": 10.0, "y": 150.0})); + assert_eq!(app.ui.dialog.as_ref().unwrap().f64("anchors", 0.0), 6.0); + app.ui.dialog = None; + // `tool.setOption` keeps it from 2 to 1000, and the dialog opens on what it keeps. + for (set, want) in [(json!(1), 2.0), (json!(2000), 1000.0), (json!(7), 7.0)] { + app.run("tool.setOption", json!({"tool": "ellipse", "values": {"anchors": set}})).unwrap(); + super::super::open_tool_dialog(&mut app, "ellipse", json!({"x": 10.0, "y": 150.0})); + assert_eq!(app.ui.dialog.as_ref().unwrap().f64("anchors", 0.0), want, "{set}"); + app.ui.dialog = None; + } + } + + /// The dialog's Anchors field is named, under Height, and typing into it sets the count. + #[test] + fn the_ellipse_dialog_shows_an_anchors_field() { + use egui::accesskit::Role; + use egui_kittest::kittest::Queryable; + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 300, "height": 300})).unwrap(); + super::super::open_tool_dialog(&mut app, "ellipse", json!({"x": 10.0, "y": 10.0})); + let mut fonts = false; + let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(1100.0, 900.0)).build_ui_state( + move |ui, app: &mut VectorcraftApp| { + if !std::mem::replace(&mut fonts, true) { + crate::theme::install_fonts(ui.ctx()); + return; + } + super::super::show(app, ui.ctx()); + }, + app, + ); + h.run_steps(5); + h.check_accessibility(); + let height = h.get_by_role_and_label(Role::TextInput, "Height:").rect(); + let anchors = h.get_by_role_and_label(Role::TextInput, "Anchors:").rect(); + assert!(anchors.center().y > height.center().y, "Anchors is below Height: {anchors:?} {height:?}"); + assert_eq!(ellipse_anchors(h.state().ui.dialog.as_ref().unwrap()), 4); + } + + #[test] + fn ellipse_anchors_take_the_nearest_whole_number_from_2_to_1000() { + let d = |v: Value| Dialog::new("ellipse", json!({ "anchors": v })); + for (v, want) in [(json!(6), 6), (json!("7"), 7), (json!(5.6), 6), (json!(1), 2), (json!(0), 2), (json!(-3), 2), (json!(5000), 1000)] { + assert_eq!(ellipse_anchors(&d(v.clone())), want, "{v}"); + } + assert_eq!(ellipse_anchors(&Dialog::new("ellipse", json!({}))), 4); + } + #[test] fn a_negative_line_length_draws_and_keeps_the_same_direction() { let mut app = VectorcraftApp::new(Session::new(), Default::default()); diff --git a/crates/ui-egui/src/dialogs/tools.rs b/crates/ui-egui/src/dialogs/tools.rs index 3a8cc570d7..bf65dd4894 100644 --- a/crates/ui-egui/src/dialogs/tools.rs +++ b/crates/ui-egui/src/dialogs/tools.rs @@ -13,7 +13,11 @@ pub fn open_tool_dialog(app: &mut VectorcraftApp, kind: &str, p: Value) { let y = p.get("y").and_then(Value::as_f64).unwrap_or(0.0); let alt = p.get("alt").and_then(Value::as_bool).unwrap_or(false); let d = match kind { - "rectangle" | "ellipse" => Dialog::new(kind, json!({"x": x, "y": y, "alt": alt, "width": "100 pt", "height": "100 pt"})), + "rectangle" => Dialog::new(kind, json!({"x": x, "y": y, "alt": alt, "width": "100 pt", "height": "100 pt"})), + "ellipse" => Dialog::new( + kind, + json!({"x": x, "y": y, "alt": alt, "width": "100 pt", "height": "100 pt", "anchors": app.session.tool_options_of(kind)["anchors"]}), + ), "roundedRectangle" => Dialog::new(kind, json!({"x": x, "y": y, "alt": alt, "width": "100 pt", "height": "100 pt", "radius": "12 pt"})), "polygon" => Dialog::new(kind, json!({"x": x, "y": y, "radius": "50 pt", "sides": app.session.tool_options_of(kind)["sides"]})), "star" => { diff --git a/docs/mcp.md b/docs/mcp.md index b7b4905ef4..22b5e7884b 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -667,7 +667,7 @@ sampler. | `pointer_gesture` | `{events:[{kind,x,y,mods?,backquote?,pressure?,tiltX?,tiltY?,rotation?,holdMs?}], tool?, mods?, backquote?}` | `kind` is one of `down`, `drag`, `up`, `move`, `doubleclick`, `tripleclick` (`doubleclick` follows the second click's `up`, and `tripleclick` the third's). `backquote` is the held state for each event; the top-level value supplies its default, and a `backquote` that is not a boolean is an error. Events go through the same path as the mouse. Headless, a `move` replies after the tool's highlight under the pointer is ready, including the Shape Builder's and the Live Paint Bucket's regions of a large selection, which the desktop app finds off the UI thread and highlights after the reply. The release of a Shape Builder click or drag over such a selection replies once the merge is applied, headless and in the desktop app, which computes the merge off the UI thread. In the desktop app, a gesture sent before then is made after the merge, and its reply comes once it is made; a command that can edit, select, save or redraw the documents (a preference, the proof and separations views), sent before then, waits for the merge and runs after it. | | `pointer_gesture` | `{events:[{kind,x,y,mods?,backquote?,pressure?,tiltX?,tiltY?,rotation?,holdMs?}], tool?, mods?, backquote?}` | `kind` is one of `down`, `drag`, `up`, `move`, `doubleclick`, `tripleclick` (`doubleclick` follows the second click's `up`, and `tripleclick` the third's). `backquote` is the held state for each event; the top-level value supplies its default. Events go through the same path as the mouse. Headless, a `move` replies after the tool's highlight under the pointer is ready, including the Shape Builder's and the Live Paint Bucket's regions of a large selection, which the desktop app finds off the UI thread and highlights after the reply. Remote, the events wait until the keys and other input sent before them (`press_key`, `type_text`) have reached the app, so a key pressed between two calls of one drag applies before the release. When that input is dropped because the document, a dialog or the focus changed first, the call fails and its events are not sent. The release of a Shape Builder click or drag over such a selection replies once the merge is applied, headless and in the desktop app, which computes the merge off the UI thread. In the desktop app, a gesture sent before then is made after the merge, and its reply comes once it is made; a command that can edit, select, save or redraw the documents (a preference, the proof and separations views), sent before then, waits for the merge and runs after it. | | `draw_path` | `{points \| d, closed?, fill?, stroke?, strokeWidth?, dash?, cap?, join?, opacity?, name?, effects?}` | `points` is `[[x,y],…]` or `[{x,y,in?,out?,smooth?},…]`. `d` is SVG path data. The options are below. | -| `draw_shape` | `{shape, …geometry, fill?, stroke?, strokeWidth?, dash?, cap?, join?, opacity?, name?, effects?}` | `rectangle`/`ellipse`: `x,y,width,height` (plus `radius` for corners). `polygon`: `cx,cy,radius,sides`. `star`: `cx,cy,radius1,radius2,points`. Polygons and stars take `rotation` in degrees clockwise (0: a corner or point straight up). `line`: `x1,y1,x2,y2`. | +| `draw_shape` | `{shape, …geometry, fill?, stroke?, strokeWidth?, dash?, cap?, join?, opacity?, name?, effects?}` | `rectangle`/`ellipse`: `x,y,width,height` (plus `radius` for corners; an ellipse takes `anchors`, 2–1000, default 4). `polygon`: `cx,cy,radius,sides`. `star`: `cx,cy,radius1,radius2,points`. Polygons and stars take `rotation` in degrees clockwise (0: a corner or point straight up). `line`: `x1,y1,x2,y2`. | | `set_paint` | `{fill?, stroke?, strokeWidth?, ids?}` | Applies to the selection (or `ids`) and becomes the default for new art. Returns `{applied, objects}`: `objects` is the number of objects painted, as the `objects` of the `paint.setFill`, `paint.setStroke` and `stroke.set` replies (the largest of them): a selected group counts the objects inside it. When it is 0, a `note` says that only the paint for new art changed. | | `press_key` | `{key, mods?}` | Remote: a real key event. Headless: runs the command or tool bound to that shortcut, or sends the key to the busy tool (digits too: `5` while dragging with the Perspective Selection tool; `e` while dragging a Selection or Group Selection marquee; `c` and `f` while dragging out an arc; `f`, `v`, `x` and `c` while dragging out a rectangular or polar grid). | | `type_text` | `{text}` | Remote only. | @@ -1187,6 +1187,18 @@ pixels per point, and the file stores the resolution that results, as with `ppi` either one wins over `ppi` and `scale`. A value that is not a positive number is refused. Export for Screens rows keep their own size (`scale: "512w"`). +`shape.ellipse` (and `draw_shape` with `shape: "ellipse"`) takes `anchors`, the number of smooth anchors (default 4). +Without it, or at 4, it draws a live ellipse. Any other count from 2 to 1000 draws a closed plain path with that many +anchors spaced evenly by angle, clockwise from the left one and fitted to `width` × `height`. The Ellipse dialog (a +click with the Ellipse tool) has an Anchors field that sends it, as the nearest whole number from 2 to 1000 (an +empty field, or text that is not a number, sends 4). The count confirmed last is kept as the Ellipse tool's `anchors` +option (`tool.setOption`), and the next Ellipse dialog opens on it. A drag with the Ellipse tool still draws a live +ellipse. + +```json +{"name":"run_command","arguments":{"command":"shape.ellipse","params":{"x":100,"y":100,"width":120,"height":80,"anchors":6}}} +``` + Long-tail commands: ```json @@ -2018,9 +2030,10 @@ and `type.fractionalWidths`; `flip` in `type.dynamicTextPreset`; `remove` and `o `enhanced` in `imageTrace.make` and `imageTrace.makeAndExpand`. A null is read as a key left out. These commands refuse a string or another value that is not a number with `` `radius` must be a number, not "2" ``, -naming the key, and change nothing: `radius` in `shape.rectangle`; `sides` and `rotation` in `shape.polygon`; -`radius2`, `points` and `rotation` in `shape.star`; `diameter`, `opacity`, `brightness`, `growth`, `fuzziness`, -`rays`, `longest`, `rayFuzziness`, `rotation`, `rings`, `largest`, `x2`, `y2`, `direction`, `pathLength`, `seed` and +naming the key, and change nothing: `radius` in `shape.rectangle`; `anchors` in `shape.ellipse` (a number that is +not a whole number from 2 to 1000 gets `` `anchors` must be a whole number between 2 and 1000 (got 2.5) ``); `sides` +and `rotation` in `shape.polygon`; `radius2`, `points` and `rotation` in `shape.star`; `diameter`, `opacity`, +`brightness`, `growth`, `fuzziness`, `rays`, `longest`, `rayFuzziness`, `rotation`, `rings`, `largest`, `x2`, `y2`, `direction`, `pathLength`, `seed` and `ringSeed` in `shape.flare` (`seed` must also be a whole number of at least 0, and `ringSeed` a whole number from 0 to 2^53 - 1); `decay` and `segments` in `shape.spiral`; `rows` and `columns` in `shape.rectangularGrid`; `concentric` and `radial` in `shape.polarGrid`; `size` and the `width`, `height` and `fitMinPercent` of `area` in `text.create`; diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index eed107bf24..a8f561d875 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1166,6 +1166,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur While an arc is dragged out, C switches it between open and closed, F switches its base between the X and Y axes in the same box, and Up/Down raise and lower its slope by 10 within −100…100; each press switches once, and the values stay as the Arc tool's options. The [default keyboard shortcuts](https://web.archive.org/web/20260726060015/https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html) (archived copy) list C, F and Up/Down for an arc being dragged out. F as the base switch, the arrows changing the slope, the step of 10 and one switch per press are our own rules. While a spiral is dragged out, Alt adds or removes whole winds of four segments and Ctrl/Cmd changes the decay. The spiral's inner end keeps the distance from the center it had on the first modified drag event, while the outer end follows the pointer. The [default keyboard shortcuts](https://web.archive.org/web/20260726060015/https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html) (archived copy) list Alt-drag to add or subtract winds and Ctrl-drag to change the decay rate; [Draw spirals](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/draw-shapes/draw-spirals.html) defines four segments per full wind and Decay as the amount each wind decreases. An 80% spiral has 80% of its outer radius after four segments; newly drawn spirals with the same settings wind more broadly than in earlier VectorCraft builds. Rounding the fitted count to whole winds from the count on the first Alt-only drag event, the held inner radius, the ranges (2…1000 segments, 5…99.99 % decay), Ctrl/Cmd taking precedence when both are held, and the new values staying as Spiral tool options are our own rules. Switching back to Alt uses the current count as its new base while keeping the held inner end. Escape while an arc, spiral or grid is dragged out cancels it and puts back the options its keys, Alt and Ctrl/Cmd changed (slope, open or closed, base axis, segments, decay, dividers and skews), so the next drag and the tool's options start from the values before the canceled drag; a drag that is let go keeps them, and an option set with `tool.setOption` during the drag stays. This is VectorCraft's own rule. + VectorCraft's own Anchors field in the Ellipse dialog (a click with the Ellipse tool; `shape.ellipse {anchors}`, part of #7840) sets how many smooth anchors the ellipse has, 4 by default; 4 draws a live ellipse, and any other count from 2 to 1000 draws a plain path with the anchors spaced evenly by angle, fitted to the typed width and height. The count last confirmed stays as the Ellipse tool's `anchors` option, and the next Ellipse dialog opens on it (`ellipse_with_four_anchors_is_the_live_ellipse`, `ellipse_anchors_draw_that_many_anchors_on_the_ellipse`, `ellipse_refuses_a_bad_anchor_count`, `the_ellipse_dialog_draws_and_keeps_its_anchor_count`). - **Cutting:** Eraser, Scissors, Knife, Mirror & Cut, Line Cut and Rectangle Cut (real geometry, compound paths keep their holes). A Scissors cut (`path.split`) leaves one of the two new end points selected and the rest of the path unselected, as [Cut paths](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-paths/split-paths.html) and the "Split a path" section of the [CS3 user guide](https://help.adobe.com/archive/en_US/illustrator/cs3/illustrator_cs3_help.pdf) describe: the two end points lie on top of each other, and a Direct Selection drag from them moves the selected one with its handles and no other anchor. A closed path cut once stays one open path. While Alt is held, the Scissors tool works as the Add Anchor Point tool ([Default keyboard shortcuts](https://web.archive.org/web/20260726060015/https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html)): a click on a segment adds an anchor point without cutting (`path.insertAnchor`), and the pointer shows the Add Anchor Point cursor. When Alt is let go, a click cuts again.