From 1901799b7683c7277f8e801df8ccf106b37c0dc5 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 17 Nov 2026 15:56:21 -0800 Subject: [PATCH 1/6] Shapes: Circle Tool Options set what the Circle tool shows and where its anchors go Double-clicking the Circle tool, or `tool.options {tool: "circle"}`, opens Circle Tool Options. Show Center, Show Radii and Show Diameter switch the center cross, the radius lines and the diameter label the tool shows while a circle is drawn, and Color sets the color of the cross and the lines (red, blue, magenta, green, black or gray). With Anchors at Standard Positions off, the circle's anchors are at the points it was drawn through, plus evenly spaced anchors between them so that no curve turns more than a quarter of the circle. With Third Point by Dragging off, a second click places the second point and a third click draws the circle through the three; a double-click on the second point draws the circle on the two. Every option is on by default, and the options are kept with the preferences. `shape.circleThroughPoints` takes `anchors: "standard"|"points"`. `tool.setOption` rejects a value the Circle tool's options do not take. --- ROADMAP.md | 1 + crates/engine/src/cmd/create.rs | 24 +- crates/engine/src/tests/circle_through.rs | 29 +++ crates/engine/src/tooling.rs | 3 + crates/geom/src/shapes.rs | 80 +++++++ crates/tools/src/circle.rs | 219 +++++++++++++++++-- crates/tools/src/circle/tests.rs | 175 +++++++++++++++ crates/tools/src/settings.rs | 2 + crates/ui-egui/src/dialogs.rs | 2 + crates/ui-egui/src/dialogs/circle_options.rs | 169 ++++++++++++++ crates/ui-egui/src/i18n/bg.tsv | 4 + crates/ui-egui/src/i18n/bs.tsv | 4 + crates/ui-egui/src/i18n/ca.tsv | 4 + crates/ui-egui/src/i18n/cs.tsv | 4 + crates/ui-egui/src/i18n/da.tsv | 4 + crates/ui-egui/src/i18n/de.tsv | 5 + crates/ui-egui/src/i18n/el.tsv | 4 + crates/ui-egui/src/i18n/es.tsv | 4 + crates/ui-egui/src/i18n/fi.tsv | 4 + crates/ui-egui/src/i18n/fr.tsv | 4 + crates/ui-egui/src/i18n/gu.tsv | 5 + crates/ui-egui/src/i18n/hi.tsv | 4 + crates/ui-egui/src/i18n/hu.tsv | 4 + crates/ui-egui/src/i18n/id.tsv | 4 + crates/ui-egui/src/i18n/it.tsv | 5 + crates/ui-egui/src/i18n/ja.tsv | 5 + crates/ui-egui/src/i18n/ka.tsv | 4 + crates/ui-egui/src/i18n/ko.tsv | 5 + crates/ui-egui/src/i18n/nl.tsv | 4 + crates/ui-egui/src/i18n/pl.tsv | 5 + crates/ui-egui/src/i18n/pt-br.tsv | 4 + crates/ui-egui/src/i18n/ru.tsv | 4 + crates/ui-egui/src/i18n/sv.tsv | 4 + crates/ui-egui/src/i18n/tr.tsv | 4 + crates/ui-egui/src/i18n/uk.tsv | 5 + crates/ui-egui/src/i18n/vi.tsv | 5 + crates/ui-egui/src/i18n/zh-hans.tsv | 4 + crates/ui-egui/src/i18n/zh-hant.tsv | 5 + crates/ui-egui/src/menus/ui_commands.rs | 2 +- crates/ui-egui/src/toolbar.rs | 5 +- docs/mcp.md | 28 +++ 41 files changed, 838 insertions(+), 22 deletions(-) create mode 100644 crates/ui-egui/src/dialogs/circle_options.rs diff --git a/ROADMAP.md b/ROADMAP.md index e9d2cc56b5..7f2a055bc4 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -139,6 +139,7 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap - 2026-11-02: Mouse wheel over a closed font-family field in Character, Properties or Control changes selected text through the family list using saved font filters (excluding search text), one undo step per notch, stopping at the ends (#5253). Scores and estimates unchanged. - 2026-11-15: Circle through three points: three Shift-clicks with the Ellipse tool, or `shape.circleThroughPoints` with three points or three selected anchor points, draw the circle whose edge passes through them, with the current paint, in one undo step; after two points the tool previews the circle through the pointer, and two points that are the same or three on one line are refused with a message. Scores and estimates unchanged. - 2026-11-17: Circle tool (after the Ellipse tool in its group): two clicks or a drag draw the circle on that diameter, and a click followed by a drag from a second point to a third draws the circle through the three; Shift keeps the diameter at 45° steps, Alt rounds a two-point circle's diameter to the rulers' ticks at the current zoom, points snap to Smart Guides, and the tool shows the circle, its center, its radii and its diameter until the release, or "Circle too large" for points on one line or a circle past the canvas. `shape.circleThroughPoints` also takes two points or two selected anchor points as the ends of a diameter. One undo step per circle. A VectorCraft addition: headline numbers unchanged. +- 2026-11-17: Circle Tool Options (double-click the Circle tool): Show Center, Show Radii and Show Diameter switch what the tool shows while a circle is drawn, Color sets the color of the center cross and radius lines, Anchors at Standard Positions off puts the circle's anchors at the points it was drawn through (`shape.circleThroughPoints {anchors: "points"}`), and Third Point by Dragging off draws a three-point circle with three clicks and a two-point circle with a double-click on the second point. A VectorCraft addition: headline numbers unchanged. - 2026-10-31: Pattern libraries: Window › Swatch Libraries › Patterns and the Swatches panel's library menu open Geometric Patterns, a built-in library of eleven pattern swatches (dots, stripes, checks, a grid and shapes); clicking one adds its pattern and swatch to the document, once, and applies it to the active fill or stroke (`swatch.library.add`). - 2026-11-11: Pattern libraries: Patterns › Grit Textures, a second built-in pattern library, holds eight seamless black textures (Fine Grain, Coarse Grit, Sand, Speckle, Stipple, Scratches, Sparse Flecks and Dense Flecks) on tiles of 18 to 36 pt, each drawn the same way every time; marks that reach past a tile edge continue on the next tile, so the tiles join without a seam (`swatch.library.add`). Scores and estimates unchanged. - 2026-11-11: Pattern libraries: Patterns › Optical Effects, a third built-in pattern library, of VectorCraft's own designs, holds eight black wave, moiré and op-art tiles (Sine Bands, Ripple Lines, Interference Rings, Offset Rings, Warped Checks, Pinched Stripes, Chevron Pulse and Radiating Lenses) of 32 to 48 pt, each drawn the same way every time; each tile is one period of its design, and art that reaches past a tile edge continues on the next tile, so the tiles join without a seam (`swatch.library.add`). Scores and estimates unchanged. diff --git a/crates/engine/src/cmd/create.rs b/crates/engine/src/cmd/create.rs index e9fcad8883..61b22d12b9 100644 --- a/crates/engine/src/cmd/create.rs +++ b/crates/engine/src/cmd/create.rs @@ -62,7 +62,7 @@ pub fn specs() -> Vec { "Circle Through Points", [], None, - "{points?: [[x, y], [x, y]] or [[x, y], [x, y], [x, y]] (two: the ends of a diameter; left out: the two or three selected anchor points, where a path selected whole counts all its anchors and selected segments' ends do not count)} → {id, cx, cy, radius}: a circle with the current paint whose edge passes through the points, not pixel-aligned even while Align New Objects to Pixel Grid is on; two points that are the same, three on one line, or a circle reaching past the canvas are an error, and nothing is drawn", + "{points?: [[x, y], [x, y]] or [[x, y], [x, y], [x, y]] (two: the ends of a diameter; left out: the two or three selected anchor points, where a path selected whole counts all its anchors and selected segments' ends do not count), anchors?: \"standard\"|\"points\" (default standard: four anchors at 0°, 90°, 180° and 270°; points: an anchor at each point and more between them so that no curve turns more than a quarter)} → {id, cx, cy, radius}: a circle with the current paint whose edge passes through the points, not pixel-aligned even while Align New Objects to Pixel Grid is on; two points that are the same, three on one line, or a circle reaching past the canvas are an error, and nothing is drawn", has_doc, circle_through_points ), @@ -414,20 +414,32 @@ fn ellipse(s: &mut Session, p: &Value) -> Result { } /// A live ellipse whose edge passes through two or three points: `points`, or the two or three -/// selected anchor points ([`selected_anchor_points`]). Two points are the ends of a diameter. One -/// undo step, named as an Ellipse tool drag is. +/// selected anchor points ([`selected_anchor_points`]). Two points are the ends of a diameter. With +/// `anchors: "points"` the circle is a plain path with an anchor at each point +/// ([`shapes::circle_with_anchors_at`]); otherwise it is a live ellipse. One undo step, named as an +/// Ellipse tool drag is. fn circle_through_points(s: &mut Session, p: &Value) -> Result { const C: &str = "shape.circleThroughPoints"; let points = match p.get("points").filter(|v| !v.is_null()) { Some(v) => two_or_three_points(v).ok_or_else(|| bad(C, "`points` must be two or three [x, y] pairs of numbers"))?, None => selected_anchor_points(s)?.ok_or_else(|| bad(C, "direct-select two or three anchor points, or give `points`"))?, }; + let key = "anchors"; + let at_points = match p.get(key).filter(|v| !v.is_null()).map(Value::as_str) { + None | Some(Some("standard")) => false, + Some(Some("points")) => true, + Some(_) => return Err(bad(C, format!("`{key}` must be one of {}", "standard, points"))), + }; let (center, radius) = shapes::circle_through_points(&points) .ok_or_else(|| bad(C, "no circle passes through these points: two are the same or all three lie on one line"))?; - let r = Rect::new(center.x - radius, center.y - radius, center.x + radius, center.y + radius); - let live = LiveShape::Ellipse { w: r.width(), h: r.height(), pie: (0.0, 360.0), xf: Affine::translate(r.origin().to_vec2()) }; // Not pixel-aligned: the circle stays through the points. - let mut out = add_art_unaligned(s, "Ellipse", path_kind(live.to_path(), Some(live)))?; + let mut out = if at_points { + add_art_unaligned(s, "Ellipse", path_kind(shapes::circle_with_anchors_at(center, radius, &points), None))? + } else { + let r = Rect::new(center.x - radius, center.y - radius, center.x + radius, center.y + radius); + let live = LiveShape::Ellipse { w: r.width(), h: r.height(), pie: (0.0, 360.0), xf: Affine::translate(r.origin().to_vec2()) }; + add_art_unaligned(s, "Ellipse", path_kind(live.to_path(), Some(live)))? + }; out["cx"] = json!(center.x); out["cy"] = json!(center.y); out["radius"] = json!(radius); diff --git a/crates/engine/src/tests/circle_through.rs b/crates/engine/src/tests/circle_through.rs index e91c48e76a..a6f69d1bea 100644 --- a/crates/engine/src/tests/circle_through.rs +++ b/crates/engine/src/tests/circle_through.rs @@ -204,6 +204,35 @@ fn the_circle_is_not_moved_onto_the_pixel_grid() { assert!(!node(&s, id).extras().pixel_aligned); } +/// `anchors: "points"` puts an anchor exactly at each point, with one more on each half of a +/// diameter's circle; the circle is a plain path, not pixel-aligned, and one undo step. Any other +/// `anchors` value is an error and draws nothing. +#[test] +fn anchors_at_the_points_puts_an_anchor_at_each_point() { + let mut s = session(); + s.execute("document.setup", &json!({"alignNewObjectsToPixelGrid": true})).unwrap(); + let undo = undo_len(&s); + let points = [Point::new(0.3, 0.2), Point::new(80.6, 0.1), Point::new(0.4, 60.7)]; + let pairs: Vec = points.iter().map(|p| json!([p.x, p.y])).collect(); + let id = id_of(&s.execute(C, &json!({ "points": pairs, "anchors": "points" })).unwrap()); + let n = node(&s, id); + let anchors: Vec = n.path_data().unwrap().subpaths[0].anchors.iter().map(|a| a.p).collect(); + assert!(points.iter().all(|p| anchors.contains(p)), "{anchors:?}"); + assert!(matches!(n.kind, NodeKind::Path { live: None, .. }), "{:?}", n.kind); + assert!(!n.extras().pixel_aligned); + assert_eq!(undo_len(&s), undo + 1); + let id = id_of(&s.execute(C, &json!({ "points": [[0, 0], [100, 0]], "anchors": "points" })).unwrap()); + let anchors: Vec = node(&s, id).path_data().unwrap().subpaths[0].anchors.iter().map(|a| a.p).collect(); + assert_eq!(anchors.len(), 4, "{anchors:?}"); + assert_eq!((anchors[0], anchors[2]), (Point::new(0.0, 0.0), Point::new(100.0, 0.0))); + let (count, undo) = (object_count(&s), undo_len(&s)); + for bad in [json!("corners"), json!(true), json!(4)] { + let e = s.execute(C, &json!({ "points": [[0, 0], [100, 0]], "anchors": bad })).unwrap_err().to_string(); + assert!(e.contains("`anchors` must be one of standard, points"), "{e}"); + } + assert_eq!((object_count(&s), undo_len(&s)), (count, undo)); +} + fn view() -> ViewInfo { ViewInfo { smart_guides: false, ..ViewInfo::default() } } diff --git a/crates/engine/src/tooling.rs b/crates/engine/src/tooling.rs index 8b8cf4628b..d17caea3dd 100644 --- a/crates/engine/src/tooling.rs +++ b/crates/engine/src/tooling.rs @@ -1369,6 +1369,9 @@ impl Session { } // Every value is checked before any is set, so an invalid one changes nothing. vectorcraft_tools::builder::check_builder_options(tool.unwrap_or(self.tool.id()), &values)?; + if tool.unwrap_or(self.tool.id()) == vectorcraft_tools::circle::ID { + vectorcraft_tools::circle::check_options(&values)?; + } if tool.unwrap_or(self.tool.id()) == vectorcraft_tools::cropimage::ID { use vectorcraft_tools::cropimage as crop; // The most the selected image can be cropped to, when one is selected. diff --git a/crates/geom/src/shapes.rs b/crates/geom/src/shapes.rs index 838015115b..d194fcac4e 100644 --- a/crates/geom/src/shapes.rs +++ b/crates/geom/src/shapes.rs @@ -367,6 +367,53 @@ pub fn circle_through_points(points: &[Point]) -> Option<(Point, f64)> { circle.filter(|(c, r)| c.is_finite() && r.is_finite() && *r > 0.0) } +/// The circle at `center` with `radius` as a closed path whose anchors are `points` (points on the +/// circle, as [`circle_through_points`] gives it) plus as many more as split each arc between two +/// of them into equal parts of at most a quarter turn. The path starts at the first point and runs +/// as [`ellipse`] does (left, top, right on the page); each curve's handles are 4/3·tan(θ/4) of +/// the radius along the tangents at its ends (θ, its turn). A point given twice is one anchor; +/// with no points it starts at the left, as [`ellipse`] does. +pub fn circle_with_anchors_at(center: Point, radius: f64, points: &[Point]) -> PathData { + let quarter = PI / 2.0; + let angle = |p: Point| (p.y - center.y).atan2(p.x - center.x); + let start = points.first().map_or(PI, |p| angle(*p)); + // (turn from the first point, the point itself). + let mut placed: Vec<(f64, Point)> = points.iter().map(|p| ((angle(*p) - start).rem_euclid(TAU), *p)).collect(); + placed.sort_by(|a, b| a.0.total_cmp(&b.0)); + placed.dedup_by(|a, b| a.1 == b.1); + if placed.is_empty() { + placed.push((0.0, Point::new(center.x - radius, center.y))); + } + let on_circle = |t: f64| Point::new(center.x + radius * (start + t).cos(), center.y + radius * (start + t).sin()); + // Every anchor: (turn, position), the given points where they are and the others on the circle. + let mut turns: Vec<(f64, Point)> = Vec::new(); + for (i, &(t, p)) in placed.iter().enumerate() { + turns.push((t, p)); + let next = placed.get(i + 1).map_or(TAU, |n| n.0); + let gap = next - t; + // At most 4 parts for the whole turn: a gap is never more than a full turn. + let parts = (gap / quarter - 1e-9).ceil().clamp(1.0, 4.0); + for k in 1..parts as u32 { + let tk = t + gap * f64::from(k) / parts; + turns.push((tk, on_circle(tk))); + } + } + let n = turns.len(); + let anchors = (0..n) + .filter_map(|i| { + let &(t, p) = turns.get(i)?; + let prev = if i == 0 { turns.last()?.0 - TAU } else { turns.get(i - 1)?.0 }; + let next = turns.get(i + 1).map_or(TAU, |n| n.0); + // The unit tangent along the run (y down: increasing angle). + let a = start + t; + let tangent = Vec2::new(-a.sin(), a.cos()); + let handle = |turn: f64| radius * 4.0 / 3.0 * (turn / 4.0).tan(); + Some(Anchor { p, h_in: p - tangent * handle(t - prev), h_out: p + tangent * handle(next - t), kind: AnchorKind::Smooth }) + }) + .collect(); + PathData::single(SubPath::new(anchors, true)) +} + /// Regular polygon with `sides` (≥ 3), first vertex straight up from the centre. pub fn polygon(center: Point, radius: f64, sides: u32, rotation_deg: f64) -> PathData { let n = sides.max(3); @@ -781,6 +828,39 @@ mod tests { } } + /// The anchors are the given points exactly, plus enough more that no curve turns more than a + /// quarter; every anchor and every curve's middle lies on the circle, and the path starts at + /// the first point. + #[test] + fn a_circle_with_its_anchors_at_given_points() { + use kurbo::ParamCurve; + let (a, b, c) = (Point::new(8.0, 0.0), Point::new(0.0, 6.0), Point::ORIGIN); + let center = Point::new(4.0, 3.0); + for (points, count) in [(&[a, b][..], 4), (&[a, b, c][..], 5), (&[b, a, c, b][..], 5), (&[][..], 4)] { + let path = circle_with_anchors_at(center, 5.0, points); + let sub = &path.subpaths[0]; + assert!(sub.closed, "{points:?}"); + assert_eq!(sub.anchors.len(), count, "{points:?}: {sub:?}"); + for p in points { + assert!(sub.anchors.iter().any(|q| q.p == *p), "{p:?} is an anchor: {sub:?}"); + } + if let Some(first) = points.first() { + assert_eq!(sub.anchors[0].p, *first); + } + for q in &sub.anchors { + assert!((q.p.distance(center) - 5.0).abs() < 1e-9, "{q:?}"); + } + for seg in path.to_bezpath().segments() { + let turn = { + let (p0, p1) = (seg.start() - center, seg.end() - center); + p0.cross(p1).atan2(p0.dot(p1)) + }; + assert!(turn > 0.0 && turn <= PI / 2.0 + 1e-9, "{turn} for {seg:?}"); + assert!((seg.eval(0.5).distance(center) - 5.0).abs() < 5.0 * 1e-3, "{seg:?}"); + } + } + } + /// Nearly on one line: a point 10⁻⁴ off a chord 2000 long still gives the circle (its sagitta /// formula `r = (h² + (L/2)²) / 2h`), and its center sits on the chord's perpendicular /// bisector; a point 10⁻¹² off it does not. diff --git a/crates/tools/src/circle.rs b/crates/tools/src/circle.rs index 76e5a2df36..e8d5a4f4e2 100644 --- a/crates/tools/src/circle.rs +++ b/crates/tools/src/circle.rs @@ -15,8 +15,17 @@ //! circle passes through the points (two are the same, three lie on one line) or the circle would //! reach past the canvas, the tool shows none and the release draws nothing; for three different //! points on one line, or a circle past the canvas, the pointer shows "Circle too large". +//! +//! The tool's options (Circle Tool Options, `tool.setOption`; kept with the preferences): +//! `center`, `radii` and `diameter` show or hide the center cross, the radius lines and the +//! diameter label; `color` is the color of the cross and the lines (one of [`COLORS`]); +//! `standardAnchors` off puts the circle's anchors at the points it was drawn through instead of +//! at 0°, 90°, 180° and 270° (`anchors: "points"`); `dragThird` off places the second point with +//! a click and draws the circle through three points with a third click, and a click on the second +//! point again (as a double-click there does) draws the circle on the two points. Every option is +//! on by default, and `color` is blue. -use serde_json::{Value, json}; +use serde_json::{Map, Value, json}; use vectorcraft_doc::MAX_COORD; use vectorcraft_geom::{Point, Rect, Vec2, shapes}; @@ -34,6 +43,71 @@ const REACH_PX: f64 = 3.0; /// The longest outline (screen points) the preview draws dashed, about 7,000 dashes. const DASHED_PX: f64 = 50_000.0; +/// The colors the center cross and the radius lines can be drawn in, by option value. Blue is the +/// feedback color the other drawing tools use. +pub const COLORS: &[(&str, [u8; 3])] = &[ + ("red", [0xe5, 0x2d, 0x27]), + ("blue", crate::draw2::FEEDBACK), + ("magenta", [0xd6, 0x2c, 0xd6]), + ("green", [0x1f, 0xb4, 0x4b]), + ("black", [0x00, 0x00, 0x00]), + ("gray", [0x80, 0x80, 0x80]), +]; + +/// The option keys that are true or false. +const SWITCHES: &[&str] = &["center", "radii", "diameter", "standardAnchors", "dragThird"]; + +/// The tool's options (see the module comment). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +struct Options { + center: bool, + radii: bool, + diameter: bool, + /// An entry of [`COLORS`]. + color: usize, + standard_anchors: bool, + drag_third: bool, +} + +impl Default for Options { + fn default() -> Self { + Options { center: true, radii: true, diameter: true, color: 1, standard_anchors: true, drag_third: true } + } +} + +impl Options { + fn switch(&mut self, key: &str) -> Option<&mut bool> { + Some(match key { + "center" => &mut self.center, + "radii" => &mut self.radii, + "diameter" => &mut self.diameter, + "standardAnchors" => &mut self.standard_anchors, + "dragThird" => &mut self.drag_third, + _ => return None, + }) + } +} + +/// Is every value in `values` one the tool takes? `tool.setOption` checks them all before setting +/// any; [`Tool::set_option`] skips a value it cannot read. +pub fn check_options(values: &Map) -> Result<(), String> { + for (key, v) in values { + if SWITCHES.contains(&key.as_str()) { + if !v.is_boolean() { + return Err(format!("`{key}` must be true or false")); + } + } else if key == "color" { + if !v.as_str().is_some_and(|s| COLORS.iter().any(|(name, _)| *name == s)) { + let names: Vec<&str> = COLORS.iter().map(|(name, _)| *name).collect(); + return Err(format!("`{key}` must be one of {}", names.join(", "))); + } + } else { + return Err(format!("unknown Circle tool option `{key}`")); + } + } + Ok(()) +} + /// The press in progress. #[derive(Clone, Copy, Debug, PartialEq)] enum Press { @@ -46,23 +120,36 @@ enum Press { /// places the third point and the circle passes through `snapped`. A press within /// [`REACH_PX`] of the first point, or one that snaps to it (`on_first`), is a press on it: let /// go there it places nothing, and dragged out it draws the circle on the diameter it drags out. + /// With `dragThird` off, a drag moves the second point and the release places it. Second { at: Point, snapped: Point, from: Point, on_first: bool, dragged: bool }, + /// With `dragThird` off, the press after the second point was placed, at `at` (snapped). Let go + /// on the second point (`on_second`), it draws the circle on the two points; let go on the + /// first point it places nothing; otherwise it draws the circle through the three points. + Third { at: Point, from: Point, on_first: bool, on_second: bool, dragged: bool }, } #[derive(Default)] pub struct CircleTool { snap: DrawSnap, + options: Options, /// The first point, placed by a click (or by the press of a drag in progress). first: Option, + /// With `dragThird` off, the second point, placed by a click where it is shown (snapped, with + /// Alt's rounding of the diameter when Alt was held), and where the click let go: a press near + /// either is a press on the second point, so the second click of a double-click finds it even + /// where Alt's rounding moved it away from the pointer. + second: Option<(Point, Point)>, press: Option, /// Where the pointer is, snapped: the point the next press or release places. pointer: Option, } -/// The command the tool runs for `points`. -fn command(points: &[Point]) -> (String, Value) { +/// The command the tool runs for `points`; with `standard_anchors` off, the circle's anchors are +/// at the points. +fn command(points: &[Point], standard_anchors: bool) -> (String, Value) { let pairs: Vec = points.iter().map(|p| json!([p.x, p.y])).collect(); - ("shape.circleThroughPoints".into(), json!({ "points": pairs })) + let params = if standard_anchors { json!({ "points": pairs }) } else { json!({ "points": pairs, "anchors": "points" }) }; + ("shape.circleThroughPoints".into(), params) } /// The circle through two points (the ends of a diameter) or three, as `shape.circleThroughPoints` @@ -91,35 +178,49 @@ fn too_large(points: &[Point]) -> bool { impl CircleTool { fn clear(&mut self) { self.first = None; + self.second = None; self.press = None; self.pointer = None; self.snap.clear(); } - /// How the second point keeps to the first: Shift's 45° steps and the construction guides. + /// How the second point keeps to the first: Shift's 45° steps and the construction guides. A + /// third point keeps to neither. fn leave(&self, cx: &ToolContext, mods: Mods) -> Option { - self.first.map(|a| Leave::segment(cx, a, mods.shift)) + self.first.filter(|_| self.second.is_none()).map(|a| Leave::segment(cx, a, mods.shift)) } /// The points the circle passes through as the tool shows it now. fn points(&self) -> Vec { let mut out: Vec = self.first.into_iter().collect(); + if let Some((b, _)) = self.second { + out.push(b); + out.extend(self.pointer); + return out; + } match self.press { Some(Press::First { .. }) | None => out.extend(self.pointer.filter(|_| self.first.is_some())), // A press on the first point adds no point: a drag from it drags out a diameter. Some(Press::Second { on_first: true, dragged, .. }) => out.extend(self.pointer.filter(|_| dragged)), Some(Press::Second { at, dragged: false, .. }) => out.push(at), + // With `dragThird` off, a drag moves the second point. + Some(Press::Second { at, .. }) if !self.options.drag_third => out.push(at), Some(Press::Second { snapped, dragged: true, .. }) => { out.push(snapped); out.extend(self.pointer); } + Some(Press::Third { .. }) => {} } out } /// The second point as the tool shows it: none for a press on the first point. fn second(&self) -> Option { + if let Some((b, _)) = self.second { + return Some(b); + } match self.press { + Some(Press::Second { on_first: false, at, .. }) if !self.options.drag_third => Some(at), Some(Press::Second { on_first: false, dragged: false, at, .. }) => Some(at), Some(Press::Second { on_first: false, dragged: true, snapped, .. }) => Some(snapped), _ => None, @@ -133,9 +234,25 @@ impl CircleTool { if circle_of(points).is_none() { return vec![]; } - let (c, v) = command(points); + let (c, v) = command(points, self.options.standard_anchors); vec![Action::Exec(c, v)] } + + /// With `dragThird` off, the release of a press after the second point was placed: on the + /// second point it draws the circle on the two points, on the first it places nothing, and + /// elsewhere it draws the circle through the three, or keeps the points where none passes + /// through them. + fn third_up(&mut self, at: Point, on_first: bool, on_second: bool, dragged: bool) -> Vec { + let (Some(a), Some((b, _))) = (self.first, self.second) else { return vec![] }; + if on_second && !dragged { + return self.draw(&[a, b]); + } + if (on_first && !dragged) || circle_of(&[a, b, at]).is_none() { + self.snap.clear(); + return vec![]; + } + self.draw(&[a, b, at]) + } } impl Tool for CircleTool { @@ -151,10 +268,20 @@ impl Tool for CircleTool { PointerKind::Move => { let leave = self.leave(cx, ev.mods); let p = self.snap.hover(cx, ev.pos, &[], leave.as_ref()); - self.pointer = Some(self.first.map_or(p, |a| round_diameter(cx, a, p, ev.mods))); + // Alt's rounding of the diameter is for the second point only. + let rounds = self.first.filter(|_| self.second.is_none()); + self.pointer = Some(rounds.map_or(p, |a| round_diameter(cx, a, p, ev.mods))); vec![] } PointerKind::Down => { + if let (Some(a), Some((b, clicked))) = (self.first, self.second) { + let at = self.snap.press(cx, ev.pos, &[], None); + let on = |q: Point| at == q || ev.pos.distance(q) <= cx.tol(REACH_PX); + let on_second = on(b) || ev.pos.distance(clicked) <= cx.tol(REACH_PX); + self.press = Some(Press::Third { at, from: ev.pos, on_first: on(a), on_second, dragged: false }); + self.pointer = Some(at); + return vec![]; + } match self.first { None => { let at = self.snap.press(cx, ev.pos, &[], None); @@ -174,7 +301,23 @@ impl Tool for CircleTool { vec![] } PointerKind::Drag => { + let drag_third = self.options.drag_third; + let first = self.first; match &mut self.press { + // With `dragThird` off, the second point follows the pointer as it does before + // the press. + Some(Press::Second { at, snapped, from, on_first: false, dragged }) if !drag_third => { + *dragged |= ev.pos.distance(*from) >= cx.tol(DRAG_PX); + let leave = first.map(|a| Leave::segment(cx, a, ev.mods.shift)); + *snapped = self.snap.drag(cx, ev.pos, leave.as_ref()); + *at = first.map_or(*snapped, |a| round_diameter(cx, a, *snapped, ev.mods)); + self.pointer = Some(*at); + } + Some(Press::Third { at, from, dragged, .. }) => { + *dragged |= ev.pos.distance(*from) >= cx.tol(DRAG_PX); + *at = self.snap.drag(cx, ev.pos, None); + self.pointer = Some(*at); + } Some(Press::First { at, from, dragged }) => { *dragged |= ev.pos.distance(*from) >= cx.tol(DRAG_PX); let leave = Leave::segment(cx, *at, ev.mods.shift); @@ -197,6 +340,16 @@ impl Tool for CircleTool { vec![] } PointerKind::Up => match (self.press.take(), self.first, self.pointer) { + (Some(Press::Third { at, on_first, on_second, dragged, .. }), ..) => self.third_up(at, on_first, on_second, dragged), + // With `dragThird` off, the release places the second point; let go on the first + // point, as a press there is, it places nothing. + (Some(Press::Second { at, snapped, on_first: false, .. }), Some(a), _) if !self.options.drag_third => { + if !(at == a || snapped == a || ev.pos.distance(a) <= cx.tol(REACH_PX)) { + self.second = Some((at, ev.pos)); + } + self.snap.clear(); + vec![] + } (Some(Press::First { at, dragged: true, .. }), _, Some(b)) if b.distance(at) >= cx.tol(DRAG_PX) => self.draw(&[at, b]), // A click places the first point; the guides of the press go. (Some(Press::First { .. }), ..) => { @@ -269,13 +422,19 @@ impl Tool for CircleTool { // than DASHED_PX on screen is drawn solid instead. let dashed = std::f64::consts::TAU * r <= cx.tol(DASHED_PX); o.push(Overlay::Path { path, color, width: 1.0, dashed }); - for p in &points { - o.push(Overlay::Line { a: c, b: *p, color, dashed: false }); + let opts = self.options; + let lines = COLORS.get(opts.color).map_or(color, |(_, rgb)| *rgb); + if opts.radii { + for p in &points { + o.push(Overlay::Line { a: c, b: *p, color: lines, dashed: false }); + } } - let arm = cx.tol(CROSS_PX); - o.push(Overlay::Line { a: c - Vec2::new(arm, 0.0), b: c + Vec2::new(arm, 0.0), color, dashed: false }); - o.push(Overlay::Line { a: c - Vec2::new(0.0, arm), b: c + Vec2::new(0.0, arm), color, dashed: false }); - if let Some(p) = self.pointer.filter(|_| cx.measurement_labels) { + if opts.center { + let arm = cx.tol(CROSS_PX); + o.push(Overlay::Line { a: c - Vec2::new(arm, 0.0), b: c + Vec2::new(arm, 0.0), color: lines, dashed: false }); + o.push(Overlay::Line { a: c - Vec2::new(0.0, arm), b: c + Vec2::new(0.0, arm), color: lines, dashed: false }); + } + if let Some(p) = self.pointer.filter(|_| cx.measurement_labels && opts.diameter) { o.push(Overlay::Measure { p: p + Vec2::new(cx.tol(12.0), cx.tol(12.0)), text: format!("D: {}", cx.len(2.0 * r)) }); } } else if let Some(p) = self.pointer.filter(|_| too_large(&points)) { @@ -290,6 +449,38 @@ impl Tool for CircleTool { fn cursor(&self, _cx: &ToolContext, _p: Point, _mods: Mods) -> Cursor { Cursor::Crosshair } + + fn options(&self) -> Value { + let o = self.options; + let color = COLORS.get(o.color).map_or("blue", |(name, _)| *name); + json!({ + "center": o.center, + "radii": o.radii, + "diameter": o.diameter, + "color": color, + "standardAnchors": o.standard_anchors, + "dragThird": o.drag_third, + }) + } + + /// Sets one option; a value the option does not take leaves it as it was. Switching + /// `dragThird` drops the points placed so far. + fn set_option(&mut self, key: &str, value: &Value) { + if key == "color" { + if let Some(i) = value.as_str().and_then(|s| COLORS.iter().position(|(name, _)| *name == s)) { + self.options.color = i; + } + return; + } + let Some(on) = value.as_bool() else { return }; + let was = self.options.drag_third; + if let Some(switch) = self.options.switch(key) { + *switch = on; + } + if self.options.drag_third != was { + self.clear(); + } + } } #[cfg(test)] diff --git a/crates/tools/src/circle/tests.rs b/crates/tools/src/circle/tests.rs index a6caafbc1d..6b83f73838 100644 --- a/crates/tools/src/circle/tests.rs +++ b/crates/tools/src/circle/tests.rs @@ -94,6 +94,181 @@ fn a_click_and_a_drag_draw_the_circle_through_three_points() { assert_eq!(t.pointer(&cx, &ev(PointerKind::Up, (300.0, 360.0), Mods::default())), circle(&[(300.0, 300.0), (380.0, 300.0), (300.0, 360.0)])); } +/// The lines the tool shows from the center `c`: (radius lines, arms of the center cross), each +/// with its color. +fn annotations(o: &[Overlay], c: Point) -> (Vec<[u8; 3]>, Vec<[u8; 3]>) { + let (mut radii, mut cross) = (vec![], vec![]); + for o in o { + if let Overlay::Line { a, b, color, .. } = o { + if *a == c { + radii.push(*color); + } else if a.midpoint(*b).distance(c) < 1e-9 { + cross.push(*color); + } + } + } + (radii, cross) +} + +/// `center`, `radii` and `diameter` show or hide the center cross, the radius lines and the +/// diameter label, each on its own, and `color` is the color of the cross and the lines; the +/// outline stays in the feedback color. Each option lasts in [`Tool::options`]. +#[test] +fn the_options_show_or_hide_the_center_radii_and_diameter_in_their_color() { + let (d, _) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) }; + let mut t = CircleTool::default(); + click(&mut t, &cx, (300.0, 300.0)); + t.pointer(&cx, &ev(PointerKind::Move, (380.0, 360.0), Mods::default())); + let c = Point::new(340.0, 330.0); + let blue = crate::draw2::FEEDBACK; + assert_eq!(annotations(&t.overlays(&cx), c), (vec![blue; 2], vec![blue; 2])); + let diameter = |t: &CircleTool| t.overlays(&cx).iter().any(|o| matches!(o, Overlay::Measure { .. })); + assert!(diameter(&t)); + t.set_option("center", &json!(false)); + assert_eq!(annotations(&t.overlays(&cx), c), (vec![blue; 2], vec![])); + t.set_option("radii", &json!(false)); + assert_eq!(annotations(&t.overlays(&cx), c), (vec![], vec![])); + assert!(diameter(&t)); + t.set_option("diameter", &json!(false)); + assert!(!diameter(&t)); + t.set_option("center", &json!(true)); + t.set_option("radii", &json!(true)); + t.set_option("color", &json!("red")); + let red = [0xe5, 0x2d, 0x27]; + let o = t.overlays(&cx); + assert_eq!(annotations(&o, c), (vec![red; 2], vec![red; 2])); + assert!(o.iter().any(|o| matches!(o, Overlay::Path { color, .. } if *color == blue)), "{o:?}"); + assert_eq!(t.options(), json!({"center": true, "radii": true, "diameter": false, "color": "red", "standardAnchors": true, "dragThird": true})); + // A value an option does not take leaves it as it was. + for (key, value) in [("color", json!("orange")), ("center", json!("no")), ("radii", json!(0))] { + t.set_option(key, &value); + } + assert_eq!(t.options()["color"], json!("red")); + assert_eq!((&t.options()["center"], &t.options()["radii"]), (&json!(true), &json!(true))); +} + +/// With `standardAnchors` off, the circle's anchors go at the points it was drawn through. +#[test] +fn anchors_at_the_points_asks_for_them() { + let (d, _) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) }; + let mut t = CircleTool::default(); + t.set_option("standardAnchors", &json!(false)); + let acts = drag(&mut t, &cx, (300.0, 300.0), &[(380.0, 360.0)], Mods::default()); + let points = json!([[300.0, 300.0], [380.0, 360.0]]); + assert_eq!(acts, vec![Action::Exec("shape.circleThroughPoints".into(), json!({"points": points, "anchors": "points"}))]); +} + +/// With `dragThird` off, a second click places the second point and a third click draws the circle +/// through the three; a click on the second point again (as a double-click there does) draws the +/// circle on the two; a second point let go on the first places nothing; a drag from the first +/// point still draws the circle on its diameter. +#[test] +fn with_third_point_by_dragging_off_three_clicks_draw_the_circle() { + let (d, _) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) }; + let mut t = CircleTool::default(); + t.set_option("dragThird", &json!(false)); + click(&mut t, &cx, (300.0, 300.0)); + assert_eq!(click(&mut t, &cx, (380.0, 300.0)), vec![]); + t.pointer(&cx, &ev(PointerKind::Move, (300.0, 360.0), Mods::default())); + let o = t.overlays(&cx); + assert!(near(preview(&o).expect("the circle through the three is shown"), Rect::new(290.0, 280.0, 390.0, 380.0)), "{o:?}"); + assert_eq!(o.iter().filter(|o| matches!(o, Overlay::Anchor { .. })).count(), 2, "{o:?}"); + // A click on the first point places nothing and keeps both points. + assert_eq!(click(&mut t, &cx, (300.0, 300.0)), vec![]); + assert!(t.busy()); + assert_eq!(click(&mut t, &cx, (300.0, 360.0)), circle(&[(300.0, 300.0), (380.0, 300.0), (300.0, 360.0)])); + assert!(!t.busy()); + // The events of a double-click on the second point: its first click places it, the second + // draws the circle on the two points, and the double-click event that follows adds nothing. + click(&mut t, &cx, (100.0, 100.0)); + assert_eq!(click(&mut t, &cx, (200.0, 100.0)), vec![]); + assert_eq!(click(&mut t, &cx, (200.0, 100.0)), circle(&[(100.0, 100.0), (200.0, 100.0)])); + assert_eq!(t.pointer(&cx, &ev(PointerKind::DoubleClick, (200.0, 100.0), Mods::default())), vec![]); + assert!(!t.busy()); + // A drag that moves the second point places it where it is let go. + click(&mut t, &cx, (100.0, 100.0)); + assert_eq!(drag(&mut t, &cx, (150.0, 100.0), &[(180.0, 100.0), (200.0, 100.0)], Mods::default()), vec![]); + assert_eq!(click(&mut t, &cx, (100.0, 200.0)), circle(&[(100.0, 100.0), (200.0, 100.0), (100.0, 200.0)])); + // Three points on one line keep the two placed: the next click elsewhere draws. + click(&mut t, &cx, (100.0, 100.0)); + click(&mut t, &cx, (200.0, 100.0)); + assert_eq!(click(&mut t, &cx, (300.0, 100.0)), vec![]); + assert_eq!(click(&mut t, &cx, (100.0, 200.0)), circle(&[(100.0, 100.0), (200.0, 100.0), (100.0, 200.0)])); + // A second press elsewhere, dragged back and let go on the first point, places nothing: the + // next click places the second point. + click(&mut t, &cx, (100.0, 100.0)); + assert_eq!(drag(&mut t, &cx, (200.0, 100.0), &[(150.0, 100.0), (100.0, 100.0)], Mods::default()), vec![]); + assert!(t.busy()); + assert_eq!(click(&mut t, &cx, (200.0, 100.0)), vec![]); + assert_eq!(click(&mut t, &cx, (100.0, 200.0)), circle(&[(100.0, 100.0), (200.0, 100.0), (100.0, 200.0)])); + // A drag from the first point. + assert_eq!(drag(&mut t, &cx, (300.0, 300.0), &[(380.0, 360.0)], Mods::default()), circle(&[(300.0, 300.0), (380.0, 360.0)])); + // Switching the option drops the points placed so far. + click(&mut t, &cx, (100.0, 100.0)); + t.set_option("dragThird", &json!(true)); + assert!(!t.busy()); +} + +/// With `dragThird` off, an Alt-click places the second point where Alt's rounding of the diameter +/// puts it (88 pt rounds to 90 pt at 100%), and the tool shows it there: the marker, the preview, +/// the circle on the two points and the circle through three all use it. +#[test] +fn an_alt_click_places_the_second_point_where_it_is_shown() { + let (d, _) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) }; + let alt = Mods { alt: true, ..Mods::default() }; + let mut t = CircleTool::default(); + t.set_option("dragThird", &json!(false)); + click(&mut t, &cx, (300.0, 300.0)); + t.pointer(&cx, &ev(PointerKind::Down, (388.0, 300.0), alt)); + t.pointer(&cx, &ev(PointerKind::Up, (388.0, 300.0), alt)); + t.pointer(&cx, &ev(PointerKind::Move, (300.0, 390.0), Mods::default())); + let o = t.overlays(&cx); + let second = Point::new(390.0, 300.0); + assert!(o.iter().any(|o| matches!(o, Overlay::Anchor { p, .. } if p.distance(second) < 1e-9)), "{o:?}"); + // (300, 300), (390, 300) and (300, 390): center (345, 345), radius 45·√2. + let r = 45.0 * 2f64.sqrt(); + assert!(near(preview(&o).unwrap(), Rect::new(345.0 - r, 345.0 - r, 345.0 + r, 345.0 + r)), "{o:?}"); + assert_eq!(click(&mut t, &cx, (300.0, 390.0)), circle(&[(300.0, 300.0), (390.0, 300.0), (300.0, 390.0)])); + click(&mut t, &cx, (300.0, 300.0)); + t.pointer(&cx, &ev(PointerKind::Down, (388.0, 300.0), alt)); + t.pointer(&cx, &ev(PointerKind::Up, (388.0, 300.0), alt)); + assert_eq!(click(&mut t, &cx, (390.0, 300.0)), circle(&[(300.0, 300.0), (390.0, 300.0)])); + // In inches the ticks are farther apart, and the rounding can move the point more than the + // 3 screen points a click reaches: the second click of a double-click, where the first let go, + // still draws the circle on the two points, at the rounded point. + let inches = ToolContext { unit: vectorcraft_doc::Unit::Inches, ..cx }; + let d = 94.4; + let rounded = vectorcraft_doc::Unit::Inches.snap_to_ruler_tick(d, 1.0); + assert!((rounded - d).abs() > 3.0, "{rounded}"); + click(&mut t, &inches, (300.0, 300.0)); + t.pointer(&inches, &ev(PointerKind::Down, (300.0 + d, 300.0), alt)); + t.pointer(&inches, &ev(PointerKind::Up, (300.0 + d, 300.0), alt)); + assert_eq!(click(&mut t, &inches, (300.0 + d, 300.0)), circle(&[(300.0, 300.0), (300.0 + rounded, 300.0)])); +} + +/// `tool.setOption`'s check takes the values the options take and nothing else. +#[test] +fn check_options_takes_only_the_values_the_options_take() { + let ok = json!({"center": false, "radii": true, "diameter": false, "color": "gray", "standardAnchors": false, "dragThird": false}); + assert_eq!(check_options(ok.as_object().unwrap()), Ok(())); + for (bad, error) in [ + (json!({"center": 1}), "`center` must be true or false"), + (json!({"dragThird": null}), "`dragThird` must be true or false"), + (json!({"color": "orange"}), "`color` must be one of red, blue, magenta, green, black, gray"), + (json!({"colour": "red"}), "unknown Circle tool option `colour`"), + ] { + assert_eq!(check_options(bad.as_object().unwrap()), Err(error.to_string()), "{bad}"); + } +} + /// Three points on one line show no circle, and the release draws nothing and starts afresh. A /// circle past the canvas is not shown either. #[test] diff --git a/crates/tools/src/settings.rs b/crates/tools/src/settings.rs index 97e980e3c0..a2b579706c 100644 --- a/crates/tools/src/settings.rs +++ b/crates/tools/src/settings.rs @@ -53,6 +53,8 @@ const ROWS: &[Row] = &[ (&["star"], None, &["points"]), // The Ellipse dialog's Anchors. (&["ellipse"], None, &["anchors"]), + // Circle Tool Options (`circle::CircleTool`). + (&[crate::circle::ID], None, &["center", "radii", "diameter", "color", "standardAnchors", "dragThird"]), (&["freeTransform"], None, &["constrain"]), // Shape Builder Tool Options (`builder::ShapeBuilderOptions`). ( diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 9e54eb12f6..843de6c68d 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -23,6 +23,7 @@ pub mod brush_replace_art; pub mod bullets_numbering; pub mod char_style_options; pub mod check_spelling; +pub mod circle_options; pub mod color_balance; pub mod color_guide_options; mod color_picker; @@ -449,6 +450,7 @@ registry! { FreehandOptions: [freehand::KIND] => freehand::SPEC, ShapeBuilderOptions: [shape_builder_options::KIND] => shape_builder_options::SPEC, ObjectsOnPathOptions: [objects_on_path_options::KIND] => objects_on_path_options::SPEC, + CircleOptions: [circle_options::KIND] => circle_options::SPEC, FlareOptions: [flare_options::KIND] => flare_options::SPEC, SymbolOptions: [symbol_options::KIND] => symbol_options::SPEC, DeleteSymbol: [symbol_delete::KIND] => symbol_delete::SPEC, diff --git a/crates/ui-egui/src/dialogs/circle_options.rs b/crates/ui-egui/src/dialogs/circle_options.rs new file mode 100644 index 0000000000..6a828a7e17 --- /dev/null +++ b/crates/ui-egui/src/dialogs/circle_options.rs @@ -0,0 +1,169 @@ +//! Circle Tool Options (double-click the Circle tool, or `tool.options`): Show Center, Show Radii +//! and Show Diameter switch the center cross, the radius lines and the diameter label the tool +//! shows while a circle is drawn; Color is the color of the cross and the lines; Anchors at +//! Standard Positions off puts the circle's anchors at the points it was drawn through; Third +//! Point by Dragging off places the second point with a click and the third with another. OK sets +//! them with `tool.setOption {tool: "circle", values}`; they last across tool switches and are +//! saved with the preferences. + +use serde_json::{Map, Value, json}; +use vectorcraft_tools::circle::{COLORS, ID as TOOL}; + +use super::{DialogSpec, run_and_close}; +use crate::state::Dialog; +use crate::{VectorcraftApp, widgets}; + +/// The dialog kind of Circle Tool Options. +pub const KIND: &str = "circleOptions"; + +pub(super) const SPEC: DialogSpec = DialogSpec { heading, body, confirm, min_width: 300.0, ..DialogSpec::FORM }; + +/// The options the dialog edits, in the order it shows its check boxes, with their labels. +const SWITCHES: [(&str, &str); 5] = [ + ("center", "Show Center"), + ("radii", "Show Radii"), + ("diameter", "Show Diameter"), + ("standardAnchors", "Anchors at Standard Positions"), + ("dragThird", "Third Point by Dragging"), +]; + +/// The labels of [`COLORS`], in its order. +const COLOR_LABELS: [&str; 6] = ["Red", "Blue", "Magenta", "Green", "Black", "Gray"]; + +/// Width of the label column. +const LABEL_W: f32 = 60.0; + +fn heading(_: &Dialog) -> String { + let label = vectorcraft_tools::tool_info(TOOL).map_or("", |t| t.label); + crate::i18n::fmt(tl!("{tool} Options"), &[("tool", tl!(label))]) +} + +/// Open the tool's options with their current values. +pub fn open(app: &mut VectorcraftApp) -> Value { + let o = app.session.tool_options_of(TOOL); + let keys = SWITCHES.iter().map(|(key, _)| *key).chain(["color"]); + let fields: Map = keys.filter_map(|key| Some((key.to_string(), o.get(key)?.clone()))).collect(); + app.ui.dialog = Some(Dialog { kind: KIND.into(), fields }); + json!({ "dialog": KIND }) +} + +fn check(ui: &mut egui::Ui, d: &mut Dialog, key: &str, label: &str) { + let on = d.bool(key); + if widgets::check(ui, tl!(label), on, true) { + d.fields.insert(key.into(), json!(!on)); + } +} + +fn body(_app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { + for (key, label) in &SWITCHES[..3] { + check(ui, d, key, label); + } + let color = d.str("color"); + let at = COLORS.iter().position(|(name, _)| *name == color).unwrap_or(1); + widgets::label_row(ui, tl!("Color:"), LABEL_W, |ui| { + let shown = COLOR_LABELS.get(at).copied().unwrap_or("Blue"); + if let Some((name, _)) = + widgets::dropdown_named(ui, "circle-options-color", Some(tl!("Color:")), shown, &COLOR_LABELS, 110.0).and_then(|i| COLORS.get(i)) + { + d.fields.insert("color".into(), json!(name)); + } + }); + ui.add_space(8.0); + for (key, label) in &SWITCHES[3..] { + check(ui, d, key, label); + } + false +} + +/// OK: set the tool's options. +fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { + let keys = SWITCHES.iter().map(|(key, _)| *key).chain(["color"]); + let values: Map = keys.filter_map(|key| Some((key.to_string(), d.fields.get(key)?.clone()))).collect(); + run_and_close(app, "tool.setOption", json!({ "tool": TOOL, "values": values })) +} + +#[cfg(test)] +mod tests { + use super::*; + use vectorcraft_engine::Session; + + fn app() -> VectorcraftApp { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 400})).unwrap(); + app + } + + /// The labels the open dialog paints. + fn painted(app: &mut VectorcraftApp) -> String { + crate::tests_labels::painted_text(app, |app, ui| super::super::show(app, ui.ctx())) + } + + /// Every label the dialog shows has a row for each of [`COLORS`]. + #[test] + fn every_color_has_a_label() { + assert_eq!(COLOR_LABELS.len(), COLORS.len()); + for (label, (name, _)) in COLOR_LABELS.iter().zip(COLORS) { + assert_eq!(label.to_lowercase(), *name); + } + } + + #[test] + fn double_clicking_the_tool_opens_its_options_and_ok_sets_them() { + let mut app = app(); + let o = app.session.tool_options_of(TOOL); + for key in ["center", "radii", "diameter", "standardAnchors", "dragThird"] { + assert_eq!(o[key], json!(true), "{key}"); + } + assert_eq!(o["color"], json!("blue")); + let r = app.run("tool.options", json!({"tool": TOOL})).unwrap(); + assert_eq!(r["dialog"], json!(KIND)); + let text = painted(&mut app); + for label in [ + "Circle Tool Options", + "Show Center", + "Show Radii", + "Show Diameter", + "Color:", + "Blue", + "Anchors at Standard Positions", + "Third Point by Dragging", + "OK", + "Cancel", + ] { + assert!(text.contains(label), "{label} in {text}"); + } + let d = app.ui.dialog.as_mut().unwrap(); + for key in ["radii", "standardAnchors", "dragThird"] { + assert!(d.bool(key), "{key}"); + d.fields.insert(key.into(), json!(false)); + } + d.fields.insert("color".into(), json!("magenta")); + super::super::confirm(&mut app).unwrap(); + assert!(app.ui.dialog.is_none()); + let o = app.session.tool_options_of(TOOL); + let got: Vec<&Value> = ["center", "radii", "diameter", "standardAnchors", "dragThird", "color"].iter().map(|k| &o[*k]).collect(); + assert_eq!(got, [&json!(true), &json!(false), &json!(true), &json!(false), &json!(false), &json!("magenta")]); + // They last while another tool is chosen, and the dialog opens on them again. + app.select_tool(TOOL); + app.select_tool("selection"); + app.run("tool.options", json!({"tool": TOOL})).unwrap(); + let d = app.ui.dialog.as_ref().unwrap(); + assert!(!d.bool("standardAnchors") && d.bool("center")); + assert_eq!(d.str("color"), "magenta"); + } + + /// `tool.setOption` takes only the values the options take, and an invalid one changes none. + #[test] + fn invalid_values_are_errors_and_change_nothing() { + let mut app = app(); + for (values, error) in [ + (json!({"center": false, "radii": "no"}), "`radii` must be true or false"), + (json!({"center": false, "color": "orange"}), "`color` must be one of red, blue, magenta, green, black, gray"), + (json!({"center": false, "size": 3}), "unknown Circle tool option `size`"), + ] { + let e = app.run("tool.setOption", json!({"tool": TOOL, "values": values})).unwrap_err(); + assert!(e.contains(error), "{e}"); + assert_eq!(app.session.tool_options_of(TOOL)["center"], json!(true)); + } + } +} diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index d347439b69..b5e75362ea 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -467,6 +467,10 @@ font-technology Variable Променливи Circle Кръг Circle Tool Инструмент Кръг Circle too large Кръгът е твърде голям + Show Radii Показване на радиуси + Show Diameter Показване на диаметър + Anchors at Standard Positions Опорни точки в стандартни позиции + Third Point by Dragging Трета точка чрез плъзгане Classic Defaults Класически по подразбиране Clean Up… Почистване… Clear Изчистване diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index 6fea288f77..da7713e4d4 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -4527,6 +4527,10 @@ font-technology Variable Varijabilni Circle Krug Circle Tool Alat za krug Circle too large Krug je prevelik + Show Radii Prikaži poluprečnike + Show Diameter Prikaži prečnik + Anchors at Standard Positions Sidrene tačke na standardnim položajima + Third Point by Dragging Treća tačka povlačenjem Clip to Art Isijeci prema crtežu Colorize Oboji Gamma Gama diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index e99406bffe..67de169b13 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -702,6 +702,10 @@ antiAlias Sharp Nítid Circle Cercle Circle Tool Eina de cercle Circle too large El cercle és massa gran + Show Radii Mostra els radis + Show Diameter Mostra el diàmetre + Anchors at Standard Positions Punts d’ancoratge en posicions estàndard + Third Point by Dragging Tercer punt arrossegant Circle (open) Cercle (obert) Classic Clàssic Classic Defaults Valors predeterminats clàssics diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index b217199fe0..89f568143c 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -4631,6 +4631,10 @@ font-technology Variable Variabilní Circle Kruh Circle Tool Nástroj Kruh Circle too large Kruh je příliš velký + Show Radii Zobrazit poloměry + Show Diameter Zobrazit průměr + Anchors at Standard Positions Kotevní body ve standardních polohách + Third Point by Dragging Třetí bod tažením Clip to Art Oříznout podle kresby Colorize Obarvit Gamma Gama diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index de726e7860..a83d6d6a5e 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -7030,6 +7030,10 @@ font-technology Variable Variable Circle Cirkel Circle Tool Cirkelværktøj Circle too large Cirklen er for stor + Show Radii Vis radier + Show Diameter Vis diameter + Anchors at Standard Positions Ankerpunkter i standardpositioner + Third Point by Dragging Tredje punkt ved træk Clip to Art Beskær til grafik Colorize Farvelæg Gamma Gamma diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index f85240675f..e9a9c1d875 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -458,6 +458,11 @@ font-technology Variable Variabel Circle Kreis Circle Tool Kreis-Werkzeug Circle too large Kreis zu groß + Show Radii Radien anzeigen + Show Diameter Durchmesser anzeigen + Anchors at Standard Positions Ankerpunkte an Standardpositionen + Third Point by Dragging Dritter Punkt durch Ziehen + Gray Grau Classic Defaults Klassische Standardwerte Clean Up… Aufräumen… Clear Löschen diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index a26550a5ac..86c6928b6a 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -451,6 +451,10 @@ font-technology Variable Μεταβλητές Circle Κύκλος Circle Tool Εργαλείο κύκλου Circle too large Ο κύκλος είναι πολύ μεγάλος + Show Radii Εμφάνιση ακτίνων + Show Diameter Εμφάνιση διαμέτρου + Anchors at Standard Positions Σημεία αγκύρωσης σε τυπικές θέσεις + Third Point by Dragging Τρίτο σημείο με σύρσιμο Classic Defaults Κλασικές προεπιλογές Clean Up… Εκκαθάριση… Clear Εκκαθάριση diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 74e4627a9c..394b8c4793 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -481,6 +481,10 @@ font-technology Variable Variables Circle Círculo Circle Tool Herramienta Círculo Circle too large Círculo demasiado grande + Show Radii Mostrar radios + Show Diameter Mostrar diámetro + Anchors at Standard Positions Puntos de ancla en posiciones estándar + Third Point by Dragging Tercer punto arrastrando Classic Defaults Valores predeterminados clásicos Clean Up… Limpiar… Clear Borrar diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 170db8da57..fa9c958eaa 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -4550,6 +4550,10 @@ font-technology Variable Muuttuvat Circle Ympyrä Circle Tool Ympyrätyökalu Circle too large Ympyrä on liian suuri + Show Radii Näytä säteet + Show Diameter Näytä halkaisija + Anchors at Standard Positions Ankkuripisteet vakiokohdissa + Third Point by Dragging Kolmas piste vetämällä Clip to Art Rajaa kuvitukseen Colorize Väritä Gamma Gamma diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 9ca4919a2e..22a5b6a1d7 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -482,6 +482,10 @@ font-technology Variable Variables Circle Cercle Circle Tool Outil Cercle Circle too large Cercle trop grand + Show Radii Afficher les rayons + Show Diameter Afficher le diamètre + Anchors at Standard Positions Points d’ancrage aux positions standard + Third Point by Dragging Troisième point par glissement Classic Defaults Valeurs par défaut classiques Clean Up… Nettoyer… Clear Effacer diff --git a/crates/ui-egui/src/i18n/gu.tsv b/crates/ui-egui/src/i18n/gu.tsv index 532fcb06cb..e1c3a43ab6 100644 --- a/crates/ui-egui/src/i18n/gu.tsv +++ b/crates/ui-egui/src/i18n/gu.tsv @@ -564,6 +564,11 @@ Circle વર્તુળ Circle Tool વર્તુળ ટૂલ Circle too large વર્તુળ ખૂબ મોટું છે + Show Radii ત્રિજ્યાઓ બતાવો + Show Diameter વ્યાસ બતાવો + Anchors at Standard Positions પ્રમાણભૂત સ્થાનો પર એન્કર બિંદુઓ + Third Point by Dragging ખેંચીને ત્રીજું બિંદુ + Gray રાખોડી Circle: વર્તુળ: Classic ક્લાસિક Clean Up સાફ કરો diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index 3bfe38fb3e..622cc7cc4f 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -822,6 +822,10 @@ antiAlias Sharp शार्प Circle वृत्त Circle Tool वृत्त टूल Circle too large वृत्त बहुत बड़ा है + Show Radii त्रिज्याएँ दिखाएँ + Show Diameter व्यास दिखाएँ + Anchors at Standard Positions मानक स्थानों पर एंकर पॉइंट्स + Third Point by Dragging खींचकर तीसरा बिंदु Circle (open) सर्किल (ओपन) Circle: वृत्त: Classic क्लासिक diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index cfc6c224a3..4bcdc856cd 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -643,6 +643,10 @@ font-technology Variable Változó Circle Kör Circle Tool Kör eszköz Circle too large A kör túl nagy + Show Radii Sugarak megjelenítése + Show Diameter Átmérő megjelenítése + Anchors at Standard Positions Horgonypontok szabványos helyeken + Third Point by Dragging Harmadik pont húzással Circle (open) Kör (nyitott) Classic Defaults Klasszikus alapértékek Clean Up… Tisztítás… diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 0526f18380..162d4c2158 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -4282,6 +4282,10 @@ font-technology Variable Variabel Circle Lingkaran Circle Tool Alat lingkaran Circle too large Lingkaran terlalu besar + Show Radii Tampilkan jari-jari + Show Diameter Tampilkan diameter + Anchors at Standard Positions Titik jangkar di posisi standar + Third Point by Dragging Titik ketiga dengan menyeret Clip to Art Pangkas ke karya seni Colorize Warnai Gamma Gamma diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 066a4ef6fd..2024a50923 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -483,6 +483,11 @@ font-technology Variable Variabili Circle Cerchio Circle Tool Strumento Cerchio Circle too large Cerchio troppo grande + Show Radii Mostra raggi + Show Diameter Mostra diametro + Anchors at Standard Positions Punti di ancoraggio in posizioni standard + Third Point by Dragging Terzo punto trascinando + Gray Grigio Classic Defaults Valori predefiniti classici Clean Up… Pulisci… Clear Cancella diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 597abda551..a574d4b49f 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -1299,6 +1299,11 @@ antiAlias Sharp シャープ Circle 円 Circle Tool 円ツール Circle too large 円が大きすぎます + Show Radii 半径を表示 + Show Diameter 直径を表示 + Anchors at Standard Positions アンカーポイントを標準位置に配置 + Third Point by Dragging 3 点目をドラッグで指定 + Gray グレー Clear All Tabs すべてのタブを消去 Above Text テキストの上 Position Panel Above Text テキストの上にパネルを配置 diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 0eb74ca1c0..88db3c988a 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -6348,6 +6348,10 @@ font-technology Variable ცვლადი Circle წრე Circle Tool წრის ხელსაწყო Circle too large წრე ზედმეტად დიდია + Show Radii რადიუსების ჩვენება + Show Diameter დიამეტრის ჩვენება + Anchors at Standard Positions საყრდენი წერტილები სტანდარტულ პოზიციებზე + Third Point by Dragging მესამე წერტილი გადათრევით Clip to Art ნახატზე მოჭრა Colorize გაფერადება Gamma გამა diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 83219f8de8..eb99376108 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -1289,6 +1289,11 @@ antiAlias Sharp 날카롭게 Circle 원 Circle Tool 점 기준 원 도구 Circle too large 원이 너무 큽니다 + Show Radii 반지름 표시 + Show Diameter 지름 표시 + Anchors at Standard Positions 표준 위치에 앵커 포인트 + Third Point by Dragging 드래그로 세 번째 점 지정 + Gray 회색 Clear All Tabs 모든 탭 지우기 Above Text 문자 위 Position Panel Above Text 패널을 문자 위에 배치 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index f40a61047c..feb3c77362 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -4904,6 +4904,10 @@ font-technology Variable Variabel Circle Cirkel Circle Tool Cirkelgereedschap Circle too large Cirkel te groot + Show Radii Stralen tonen + Show Diameter Diameter tonen + Anchors at Standard Positions Ankerpunten op standaardposities + Third Point by Dragging Derde punt door slepen Clip to Art Clippen op artwork Colorize Inkleuren Gamma Gamma diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 52e33d639a..a75736d725 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -4472,6 +4472,11 @@ font-technology Variable Zmienne Circle Okrąg Circle Tool Narzędzie Okrąg Circle too large Okrąg jest za duży + Show Radii Pokaż promienie + Show Diameter Pokaż średnicę + Anchors at Standard Positions Punkty kontrolne w standardowych położeniach + Third Point by Dragging Trzeci punkt przez przeciągnięcie + Gray Szary Clip to Art Przytnij do kompozycji Colorize Koloruj Gamma Gamma diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 5ae5b28f19..690ab56e7f 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -448,6 +448,10 @@ antiAlias Sharp Nítido Circle Círculo Circle Tool Ferramenta Círculo Circle too large Círculo grande demais + Show Radii Mostrar Raios + Show Diameter Mostrar Diâmetro + Anchors at Standard Positions Pontos de Ancoragem em Posições Padrão + Third Point by Dragging Terceiro Ponto Arrastando Clean Up… Limpar… Clear Limpar Clear All Tabs Limpar Todas as Paradas de Tabulação diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 3dc089a76d..7559717a49 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -479,6 +479,10 @@ font-technology Variable Вариативные Circle Круг Circle Tool Инструмент «Круг» Circle too large Круг слишком большой + Show Radii Показать радиусы + Show Diameter Показать диаметр + Anchors at Standard Positions Опорные точки в стандартных позициях + Third Point by Dragging Третья точка перетаскиванием Classic Defaults Классические значения по умолчанию Clean Up… Очистить… Clear Очистить diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 5e852da822..674f2c21e7 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -469,6 +469,10 @@ font-technology Variable Variabla Circle Cirkel Circle Tool Cirkelverktyg Circle too large Cirkeln är för stor + Show Radii Visa radier + Show Diameter Visa diameter + Anchors at Standard Positions Ankarpunkter på standardpositioner + Third Point by Dragging Tredje punkt genom att dra Classic Defaults Klassiska standardvärden Clean Up… Rensa upp… Clear Rensa diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index de1d7280f1..80ce287e83 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -463,6 +463,10 @@ font-technology Variable Değişken Circle daire Circle Tool Daire Aracı Circle too large Daire çok büyük + Show Radii Yarıçapları Göster + Show Diameter Çapı Göster + Anchors at Standard Positions Standart Konumlarda Bağlantı Noktaları + Third Point by Dragging Sürükleyerek Üçüncü Nokta Classic Defaults Klasik Varsayılanlar Clean Up… Temizleme… Clear Temizle diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index e82439dca3..e646a0f45c 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -477,6 +477,11 @@ font-technology Variable Варіативні Circle Коло Circle Tool Інструмент «Коло» Circle too large Коло завелике + Show Radii Показати радіуси + Show Diameter Показати діаметр + Anchors at Standard Positions Опорні точки в стандартних позиціях + Third Point by Dragging Третя точка перетягуванням + Gray Сірий Classic Defaults Класичні значення за промовчанням Clean Up… Очистити… Clear Очистити diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 0f088fec2b..9cc7f93932 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -559,6 +559,11 @@ font-technology Variable Biến thiên Circle Hình tròn Circle Tool Công cụ Hình tròn Circle too large Hình tròn quá lớn + Show Radii Hiện bán kính + Show Diameter Hiện đường kính + Anchors at Standard Positions Điểm neo ở vị trí chuẩn + Third Point by Dragging Điểm thứ ba bằng cách kéo + Gray Xám Classic Cổ điển Classic Defaults Mặc định cổ điển Clean Up… Dọn dẹp… diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index ed027b9f23..2ab7d69a78 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -430,6 +430,10 @@ antiAlias Sharp 锐利 Circle 圆形 Circle Tool 圆形工具 Circle too large 圆形过大 + Show Radii 显示半径 + Show Diameter 显示直径 + Anchors at Standard Positions 锚点位于标准位置 + Third Point by Dragging 拖动放置第三点 Classic Defaults 经典默认 Clean Up… 清理… Clear 清除 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index d5d613a7d8..b8c42e647f 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -445,6 +445,11 @@ font-technology Variable 可變 Circle 圓形 Circle Tool 圓形工具 Circle too large 圓形過大 + Show Radii 顯示半徑 + Show Diameter 顯示直徑 + Anchors at Standard Positions 錨點位於標準位置 + Third Point by Dragging 拖曳放置第三點 + Gray 灰 Classic Defaults 經典預設值 Clean Up… 清除… Clear 清除 diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index 677b804720..04be4bbc55 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -980,7 +980,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "tool.options", "Tool Options…", "", - "{tool: id} what double-clicking a tool button opens: hand → fits the artboard in the window (view.fitArtboard), zoom → 100% (view.actualSize), rotate|scale|reflect|shear → that Object › Transform dialog (dialog `rotate`, `scale`, `reflect` or `shear`; error `nothing selected` without a selection), selection|directSelection|groupSelection → the Move dialog (dialog `move`; the same error), gradient|magicWand → the Gradient or Magic Wand panel (window.panel), artboard → Artboard Options of the active artboard (dialog `artboardOptions`, fields index, name, x, y, width, height, showCenterMark, showCrossHairs; OK runs artboard.setProps, and with other artboards selected with the Artboard tool a new width or height goes to each of them too, in its `artboards` list, each resized about the reference point the form used for that size, or about its top-left corner when the size was set in the fields directly), flare → Flare Tool Options (dialog `flareOptions`, fields diameter and pathLength (pt), opacity, brightness, growth, fuzziness, longest, rayFuzziness, largest (%), rays, rings, direction (°), raysOn, ringsOn; OK runs tool.setOption {tool: \"flare\", values}: the next flare dragged out uses them, and a Flare click's dialog, which also has x, y and preview (on initially), previews one there and accepts it as one Undo step; Cancel rolls back the preview), lineSegment|arc|rectangularGrid|polarGrid → that tool's Tool Options, its click dialog without x and y (dialog kind = the tool id, `__toolOptions: true`; lineSegment: length (pt), angle (°), fillLine; arc: lengthX, lengthY (pt), reference (0–8), arcType: open|closed, baseAlong: x|y, slope (−100…100), fillArc; rectangularGrid: width, height (pt, the Default Size), reference (0–8), rows, columns, rowSkew, columnSkew (%), frame, fill; polarGrid: the same with concentric, radial, concentricSkew, radialSkew and compound for rows, columns, the skews and frame; OK runs tool.setOption {tool, values} and draws nothing: the next drag uses them (Fill Line, the arc's type, base, slope and fill, the grids' dividers, skews and switches) and a click's dialog opens at them), columnGraph|stackedColumnGraph|barGraph|stackedBarGraph|lineGraph|areaGraph|scatterGraph|pieGraph|radarGraph → Graph Type for the selected graph, or for the series picked in it with Group Selection (dialog `graphType`, fields the options graph.setType {} returns under their names, with legend, pieLegend, piePosition, pieSort, firstRowInFront, firstColumnInFront, filledLines and lineWidth held for every type; overrideValues and rightOverrideValues, Override Calculated Values of the left or only value axis and of the right one: while one is on OK sends axisMin, axisMax and ticks, or rightAxisMin, rightAxisMax and rightTicks, filled with the calculated values where the graph has none, and one turned off sends null, null and 0; __page: options|valueAxis|rightAxis|categoryAxis, the page shown, options when the type picked has no such page; OK runs graph.setType, and with nothing changed closes without a step of history; an overridden value axis whose maximum is not more than its minimum is an error and the dialog stays open; an error without a selected graph), typeOnPath|verticalTypeOnPath → Type on a Path Options for the selected type on a path (dialog `command` running type.pathOptions; error `nothing selected` without a selection, and the command's error when no type on a path is selected),symbolSprayer|symbolShifter|symbolScruncher|symbolSizer|symbolSpinner|symbolStainer|symbolScreener|symbolStyler → Symbolism Tools Options (dialog `symbolismOptions`, fields tool, diameter (pt), intensity and density (1–10), shared by the eight tools; OK runs tool.setOption {tool, values}), blend → Blend Options, perspectiveGrid → Perspective Grid Options, eyedropper → Eyedropper Options (dialog `eyedropperOptions`, fields sampleSize, pickUp, apply; OK runs eyedropper.setOptions), printTiling → resets the print tiling (print.tiling.set {reset: true}), warp|twirl|pucker|bloat|scallop|crystallize|wrinkle → that tool's Tool Options (dialog `liquifyOptions`, fields tool, width, height, angle, intensity %, usePressure, detail, simplify, simplifyOn, rate, complexity, horizontal %, vertical %, affectAnchors, affectIn, affectOut, showBrush; OK runs tool.setOption {tool, values}), pencil|paintbrush|smooth|blobBrush|eraser → that tool's Tool Options (dialog `freehandOptions`, fields tool and the options the tool keeps: fidelity (px for pencil, paintbrush and smooth, the same at any zoom; pt for blobBrush), fill, keepSelected (on for pencil and paintbrush, off for blobBrush), mergeOnlySelection (off), closeWithin and editWithin (px, 0 is off), livePreview (pencil, on: off draws a thin line while the stroke is drawn, and the path's fill and stroke on release), size (pt), angle (°, −180–180; 0) and roundness (%, 1–100; 100) of the eraser's tip; OK runs tool.setOption {tool, values}), livePaintSelection → Live Paint Selection Tool Options (dialog `livePaintSelectionOptions`, fields selectFills and selectStrokes (both on), color (the highlight color, #rrggbb or a layer color's name; #ff2a2a), width (the highlight's width, 1–20 px; 4); OK runs tool.setOption {tool: \"livePaintSelection\", values}; a color with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), livePaintBucket → Live Paint Bucket Options (dialog `livePaintBucketOptions`, fields paintFills (on) and paintStrokes (off), cursorSwatchPreview (on: the active fill or stroke shows above the pointer between the color swatches before and after it; Left and Right without modifiers step it through the color swatches whether it is on or off), highlight (on), color (the highlight color, #rrggbb or a layer color's name; #ff2a2a), width (the face highlight's width, 1–20 px; 4; an edge's highlight is half as wide); OK runs tool.setOption {tool: \"livePaintBucket\", values}; a color with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), shapeBuilder → Shape Builder Tool Options (dialog `shapeBuilderOptions`, fields gapDetection (off), gapLength (pt, 0–72; 3), openFilledAsClosed (on), clickStrokeSplitsPath (off), pickColorFrom: artwork|swatches (artwork), cursorSwatchPreview (off), selection: freeform|straightLine (freeform), highlightFill (on), highlightStroke (on), highlightColor (#rrggbb or a layer color's name; #ff4f4f); OK runs tool.setOption {tool: \"shapeBuilder\", values}; a highlightColor with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), objectsOnPath → Objects on Path Tool Options (dialog `objectsOnPathOptions`, fields pivot (0–8, row by row from the top left; 4, the center) and rotate (°, −360–360; 0); Reset puts 4 and 0 back; Save runs tool.setOption {tool: \"objectsOnPath\", values}: the objects attached next use them, groups attached before keep theirs)", + "{tool: id} what double-clicking a tool button opens: hand → fits the artboard in the window (view.fitArtboard), zoom → 100% (view.actualSize), rotate|scale|reflect|shear → that Object › Transform dialog (dialog `rotate`, `scale`, `reflect` or `shear`; error `nothing selected` without a selection), selection|directSelection|groupSelection → the Move dialog (dialog `move`; the same error), gradient|magicWand → the Gradient or Magic Wand panel (window.panel), artboard → Artboard Options of the active artboard (dialog `artboardOptions`, fields index, name, x, y, width, height, showCenterMark, showCrossHairs; OK runs artboard.setProps, and with other artboards selected with the Artboard tool a new width or height goes to each of them too, in its `artboards` list, each resized about the reference point the form used for that size, or about its top-left corner when the size was set in the fields directly), flare → Flare Tool Options (dialog `flareOptions`, fields diameter and pathLength (pt), opacity, brightness, growth, fuzziness, longest, rayFuzziness, largest (%), rays, rings, direction (°), raysOn, ringsOn; OK runs tool.setOption {tool: \"flare\", values}: the next flare dragged out uses them, and a Flare click's dialog, which also has x, y and preview (on initially), previews one there and accepts it as one Undo step; Cancel rolls back the preview), lineSegment|arc|rectangularGrid|polarGrid → that tool's Tool Options, its click dialog without x and y (dialog kind = the tool id, `__toolOptions: true`; lineSegment: length (pt), angle (°), fillLine; arc: lengthX, lengthY (pt), reference (0–8), arcType: open|closed, baseAlong: x|y, slope (−100…100), fillArc; rectangularGrid: width, height (pt, the Default Size), reference (0–8), rows, columns, rowSkew, columnSkew (%), frame, fill; polarGrid: the same with concentric, radial, concentricSkew, radialSkew and compound for rows, columns, the skews and frame; OK runs tool.setOption {tool, values} and draws nothing: the next drag uses them (Fill Line, the arc's type, base, slope and fill, the grids' dividers, skews and switches) and a click's dialog opens at them), circle → Circle Tool Options (dialog `circleOptions`, fields center, radii, diameter (all on), color (red|blue|magenta|green|black|gray; blue), standardAnchors (on) and dragThird (on); OK runs tool.setOption {tool: \"circle\", values}), columnGraph|stackedColumnGraph|barGraph|stackedBarGraph|lineGraph|areaGraph|scatterGraph|pieGraph|radarGraph → Graph Type for the selected graph, or for the series picked in it with Group Selection (dialog `graphType`, fields the options graph.setType {} returns under their names, with legend, pieLegend, piePosition, pieSort, firstRowInFront, firstColumnInFront, filledLines and lineWidth held for every type; overrideValues and rightOverrideValues, Override Calculated Values of the left or only value axis and of the right one: while one is on OK sends axisMin, axisMax and ticks, or rightAxisMin, rightAxisMax and rightTicks, filled with the calculated values where the graph has none, and one turned off sends null, null and 0; __page: options|valueAxis|rightAxis|categoryAxis, the page shown, options when the type picked has no such page; OK runs graph.setType, and with nothing changed closes without a step of history; an overridden value axis whose maximum is not more than its minimum is an error and the dialog stays open; an error without a selected graph), typeOnPath|verticalTypeOnPath → Type on a Path Options for the selected type on a path (dialog `command` running type.pathOptions; error `nothing selected` without a selection, and the command's error when no type on a path is selected),symbolSprayer|symbolShifter|symbolScruncher|symbolSizer|symbolSpinner|symbolStainer|symbolScreener|symbolStyler → Symbolism Tools Options (dialog `symbolismOptions`, fields tool, diameter (pt), intensity and density (1–10), shared by the eight tools; OK runs tool.setOption {tool, values}), blend → Blend Options, perspectiveGrid → Perspective Grid Options, eyedropper → Eyedropper Options (dialog `eyedropperOptions`, fields sampleSize, pickUp, apply; OK runs eyedropper.setOptions), printTiling → resets the print tiling (print.tiling.set {reset: true}), warp|twirl|pucker|bloat|scallop|crystallize|wrinkle → that tool's Tool Options (dialog `liquifyOptions`, fields tool, width, height, angle, intensity %, usePressure, detail, simplify, simplifyOn, rate, complexity, horizontal %, vertical %, affectAnchors, affectIn, affectOut, showBrush; OK runs tool.setOption {tool, values}), pencil|paintbrush|smooth|blobBrush|eraser → that tool's Tool Options (dialog `freehandOptions`, fields tool and the options the tool keeps: fidelity (px for pencil, paintbrush and smooth, the same at any zoom; pt for blobBrush), fill, keepSelected (on for pencil and paintbrush, off for blobBrush), mergeOnlySelection (off), closeWithin and editWithin (px, 0 is off), livePreview (pencil, on: off draws a thin line while the stroke is drawn, and the path's fill and stroke on release), size (pt), angle (°, −180–180; 0) and roundness (%, 1–100; 100) of the eraser's tip; OK runs tool.setOption {tool, values}), livePaintSelection → Live Paint Selection Tool Options (dialog `livePaintSelectionOptions`, fields selectFills and selectStrokes (both on), color (the highlight color, #rrggbb or a layer color's name; #ff2a2a), width (the highlight's width, 1–20 px; 4); OK runs tool.setOption {tool: \"livePaintSelection\", values}; a color with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), livePaintBucket → Live Paint Bucket Options (dialog `livePaintBucketOptions`, fields paintFills (on) and paintStrokes (off), cursorSwatchPreview (on: the active fill or stroke shows above the pointer between the color swatches before and after it; Left and Right without modifiers step it through the color swatches whether it is on or off), highlight (on), color (the highlight color, #rrggbb or a layer color's name; #ff2a2a), width (the face highlight's width, 1–20 px; 4; an edge's highlight is half as wide); OK runs tool.setOption {tool: \"livePaintBucket\", values}; a color with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), shapeBuilder → Shape Builder Tool Options (dialog `shapeBuilderOptions`, fields gapDetection (off), gapLength (pt, 0–72; 3), openFilledAsClosed (on), clickStrokeSplitsPath (off), pickColorFrom: artwork|swatches (artwork), cursorSwatchPreview (off), selection: freeform|straightLine (freeform), highlightFill (on), highlightStroke (on), highlightColor (#rrggbb or a layer color's name; #ff4f4f); OK runs tool.setOption {tool: \"shapeBuilder\", values}; a highlightColor with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), objectsOnPath → Objects on Path Tool Options (dialog `objectsOnPathOptions`, fields pivot (0–8, row by row from the top left; 4, the center) and rotate (°, −360–360; 0); Reset puts 4 and 0 back; Save runs tool.setOption {tool: \"objectsOnPath\", values}: the objects attached next use them, groups attached before keep theirs)", ), ( "ui.colorGuideOptions", diff --git a/crates/ui-egui/src/toolbar.rs b/crates/ui-egui/src/toolbar.rs index 3c78f12df0..da85c2fbc0 100644 --- a/crates/ui-egui/src/toolbar.rs +++ b/crates/ui-egui/src/toolbar.rs @@ -423,7 +423,7 @@ pub(crate) fn flyout_press(ui: &Ui, resp: &egui::Response, rect: egui::Rect) -> /// Reflect and Shear tools' are their Object › Transform dialogs, the selection tools' are the /// Move dialog, and the Pencil, Paintbrush, Smooth, Blob Brush, Eraser, Shape Builder and Objects /// on Path tools' are their Tool Options, as are the Line Segment, Arc, Rectangular Grid and Polar Grid tools' -/// ([`crate::dialogs::shapes::open_options`]). The Type on a Path and Vertical Type on a Path +/// ([`crate::dialogs::shapes::open_options`]) and the Circle tool's ([`crate::dialogs::circle_options::open`]). The Type on a Path and Vertical Type on a Path /// tools' are Type on a Path Options for the selected type on a path. pub fn open_options(app: &mut VectorcraftApp, tool: &str) -> Result { match tool { @@ -460,6 +460,9 @@ pub fn open_options(app: &mut VectorcraftApp, tool: &str) -> Result crate::dialogs::shapes::open_options(app, tool), + // The Circle tool: what it shows while a circle is drawn, where its anchors go and how + // the third point is placed. + vectorcraft_tools::circle::ID => Ok(crate::dialogs::circle_options::open(app)), // The Flare tool: its options, which draw the next flare (OK draws none). "flare" => Ok(crate::dialogs::flare_options::open(app, None)), // A double click on the Print Tiling tool puts the pages back where the placement puts them. diff --git a/docs/mcp.md b/docs/mcp.md index bdfa886286..e74ddf58e5 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -6189,6 +6189,12 @@ one line (twice the triangle's area at most 10⁻¹⁰ of its longest side squar canvas (4,000,000 pt from the origin), when `points` is not two or three pairs of numbers, and when `points` is left out and the selection does not hold two or three anchor points of paths. +`anchors` sets where the circle's anchors go. With `"standard"`, the default, the circle has four anchors at 0°, 90°, +180° and 270°. With `"points"`, the circle is a plain path with an anchor exactly at each point, and more anchors +between them, evenly spaced, so that no curve turns more than a quarter of the circle: two points give four anchors, +and three points give four to six. Any other `anchors` value is an error (`` `anchors` must be one of standard, points ``), and nothing +is drawn. + The Circle tool, after the Ellipse tool in its toolbar group, draws with this command. A drag from one point to another, or a click on each, draws the circle with the two points as the ends of a diameter. A click on a first point, then a press on a second point dragged to a third, draws the circle through the three. Shift keeps the second point at @@ -6203,6 +6209,28 @@ Escape, a dropped press, and an edit, Undo or Redo made outside the tool drop th screen points of the first point, or one that snaps to it, is a press on it: let go there (a double-click), it places no second point, and dragged out, it draws the circle on the diameter it drags out. +Circle Tool Options (`tool.options {tool: "circle"}`, or a double-click on the tool, dialog `circleOptions`) sets the +tool's options, which `tool.setOption {tool: "circle", values}` also sets and the preferences keep. All are on by +default, and `color` is `"blue"`: + +- `center`, `radii` and `diameter` (Show Center, Show Radii, Show Diameter) show or hide the cross at the center, the + lines from the center to the points and the diameter label. The diameter label also needs Measurement Labels on. +- `color` (Color) is the color of the cross and the lines: `"red"`, `"blue"`, `"magenta"`, `"green"`, `"black"` or + `"gray"`. The outline stays blue. +- `standardAnchors` (Anchors at Standard Positions) off draws the circle with `anchors: "points"`, so its anchors are + at the points it was drawn through. +- `dragThird` (Third Point by Dragging) off changes how the points are placed. A click on a second point places it, and + a click on a third point draws the circle through the three. A click on the second point again, as the second click + of a double-click there is, draws the circle on the two points. An Alt-click places the second point where Alt's + rounding of the diameter puts it, and both circles pass through it there. A click on the first point, or a second + point dragged back and let go on it, places nothing, and a click on the line through the first two points draws + nothing and keeps them. A drag from the first point still draws the circle on the diameter it drags out, and a drag + from a second point places it where it is let go. Switching `dragThird` drops the points placed so far. + +`tool.setOption` returns an error and changes none of the options when a value is not one the option takes +(`` `radii` must be true or false ``, `` `color` must be one of red, blue, magenta, green, black, gray ``) or the key is +not one of these (`` unknown Circle tool option `size` ``). + With the Ellipse tool, the first two Shift-clicks place points, and the third draws the circle through the three with this command. After two points the tool previews the circle through them and the pointer as a dashed outline. Once a point is placed, a Shift-click on the selection's handles, center point or shape widgets places a point too. Escape, a From 8af2a300e6d341226a7b85f1e14ea3e4b6cd76ed Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 17 Nov 2026 17:41:58 -0800 Subject: [PATCH 2/6] Shapes: a Circle tool drag of the second or third point ends where it is let go With Third Point by Dragging off, a release away from the last drag of the second or third point now places that point at the release position. --- crates/tools/src/circle/tests.rs | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/crates/tools/src/circle/tests.rs b/crates/tools/src/circle/tests.rs index afab9bb291..c0a82a51ef 100644 --- a/crates/tools/src/circle/tests.rs +++ b/crates/tools/src/circle/tests.rs @@ -215,6 +215,25 @@ fn with_third_point_by_dragging_off_three_clicks_draw_the_circle() { assert!(!t.busy()); } +/// With `dragThird` off, a drag of the second or third point ends where it is let go, also when the +/// release is away from the last drag. +#[test] +fn with_third_point_by_dragging_off_a_drag_ends_where_it_is_let_go() { + let (d, _) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) }; + let (down, drag, up) = (PointerKind::Down, PointerKind::Drag, PointerKind::Up); + let mut t = CircleTool::default(); + t.set_option("dragThird", &json!(false)); + click(&mut t, &cx, (300.0, 300.0)); + t.pointer(&cx, &ev(down, (350.0, 300.0), Mods::default())); + t.pointer(&cx, &ev(drag, (380.0, 300.0), Mods::default())); + assert_eq!(t.pointer(&cx, &ev(up, (400.0, 300.0), Mods::default())), vec![]); + t.pointer(&cx, &ev(down, (350.0, 350.0), Mods::default())); + t.pointer(&cx, &ev(drag, (320.0, 380.0), Mods::default())); + assert_eq!(t.pointer(&cx, &ev(up, (300.0, 400.0), Mods::default())), circle(&[(300.0, 300.0), (400.0, 300.0), (300.0, 400.0)])); +} + /// With `dragThird` off, an Alt-click places the second point where Alt's rounding of the diameter /// puts it (88 pt rounds to 90 pt at 100%), and the tool shows it there: the marker, the preview, /// the circle on the two points and the circle through three all use it. From e144392bec1f7db9f7ff221494a3c018602e7745 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 17 Nov 2026 18:09:52 -0800 Subject: [PATCH 3/6] Shapes: shape.circleThroughPoints refuses a null anchors --- crates/engine/src/cmd/create.rs | 2 +- crates/engine/src/tests/circle_through.rs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/cmd/create.rs b/crates/engine/src/cmd/create.rs index 61b22d12b9..dc28eef546 100644 --- a/crates/engine/src/cmd/create.rs +++ b/crates/engine/src/cmd/create.rs @@ -425,7 +425,7 @@ fn circle_through_points(s: &mut Session, p: &Value) -> Result { None => selected_anchor_points(s)?.ok_or_else(|| bad(C, "direct-select two or three anchor points, or give `points`"))?, }; let key = "anchors"; - let at_points = match p.get(key).filter(|v| !v.is_null()).map(Value::as_str) { + let at_points = match p.get(key).map(Value::as_str) { None | Some(Some("standard")) => false, Some(Some("points")) => true, Some(_) => return Err(bad(C, format!("`{key}` must be one of {}", "standard, points"))), diff --git a/crates/engine/src/tests/circle_through.rs b/crates/engine/src/tests/circle_through.rs index a6f69d1bea..c9b66f9f06 100644 --- a/crates/engine/src/tests/circle_through.rs +++ b/crates/engine/src/tests/circle_through.rs @@ -226,7 +226,7 @@ fn anchors_at_the_points_puts_an_anchor_at_each_point() { assert_eq!(anchors.len(), 4, "{anchors:?}"); assert_eq!((anchors[0], anchors[2]), (Point::new(0.0, 0.0), Point::new(100.0, 0.0))); let (count, undo) = (object_count(&s), undo_len(&s)); - for bad in [json!("corners"), json!(true), json!(4)] { + for bad in [json!("corners"), json!(true), json!(4), Value::Null] { let e = s.execute(C, &json!({ "points": [[0, 0], [100, 0]], "anchors": bad })).unwrap_err().to_string(); assert!(e.contains("`anchors` must be one of standard, points"), "{e}"); } From 22d799fd41a8e367b17c104e541dd60b11307278 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 17 Nov 2026 18:19:38 -0800 Subject: [PATCH 4/6] Shapes: the Circle tool shows no circle its anchored path cannot draw With Standard Anchors off, a circle near the canvas edge whose path with anchors at the points curves past the edge is no longer previewed or drawn, as shape.circleThroughPoints refuses it. --- crates/tools/src/circle.rs | 23 +++++++++++++++++------ crates/tools/src/circle/tests.rs | 26 ++++++++++++++++++++++++-- 2 files changed, 41 insertions(+), 8 deletions(-) diff --git a/crates/tools/src/circle.rs b/crates/tools/src/circle.rs index f2686cd5a4..fb19af46e0 100644 --- a/crates/tools/src/circle.rs +++ b/crates/tools/src/circle.rs @@ -159,6 +159,17 @@ pub fn circle_of(points: &[Point]) -> Option<(Point, f64)> { shapes::circle_through_points(points).filter(on_canvas) } +/// [`circle_of`], as the tool draws it: with `standard_anchors` off, also none where the path with +/// an anchor at each point ([`shapes::circle_with_anchors_at`]) reaches past the canvas, since its +/// curves can reach slightly outside the circle. +fn drawn_circle(points: &[Point], standard_anchors: bool) -> Option<(Point, f64)> { + let fits = |(c, r): &(Point, f64)| { + let b = vectorcraft_geom::Shape::bounding_box(&shapes::circle_with_anchors_at(*c, *r, points).to_bezpath()); + [b.x0, b.y0, b.x1, b.y1].iter().all(|v| v.is_finite() && v.abs() <= MAX_COORD) + }; + circle_of(points).filter(|c| standard_anchors || fits(c)) +} + /// With Alt, `p` moved along the line from `first` so that their distance (the diameter) is on /// the nearest ruler tick at the current zoom, in the General unit; `p` itself without Alt, and /// when that rounding leaves no distance. @@ -170,9 +181,9 @@ fn round_diameter(cx: &ToolContext, first: Point, p: Point, mods: Mods) -> Point /// Are the points two or more different points through which no circle is drawn: three on one /// line, or a circle that would reach past the canvas? -fn too_large(points: &[Point]) -> bool { +fn too_large(points: &[Point], standard_anchors: bool) -> bool { let distinct = points.iter().enumerate().all(|(i, p)| !points.iter().take(i).any(|q| q == p)); - points.len() >= 2 && distinct && circle_of(points).is_none() + points.len() >= 2 && distinct && drawn_circle(points, standard_anchors).is_none() } impl CircleTool { @@ -231,7 +242,7 @@ impl CircleTool { /// (the tool showed none), it only starts afresh. fn draw(&mut self, points: &[Point]) -> Vec { self.clear(); - if circle_of(points).is_none() { + if drawn_circle(points, self.options.standard_anchors).is_none() { return vec![]; } let (c, v) = command(points, self.options.standard_anchors); @@ -247,7 +258,7 @@ impl CircleTool { if on_second && !dragged { return self.draw(&[a, b]); } - if (on_first && !dragged) || circle_of(&[a, b, at]).is_none() { + if (on_first && !dragged) || drawn_circle(&[a, b, at], self.options.standard_anchors).is_none() { self.snap.clear(); return vec![]; } @@ -431,7 +442,7 @@ impl Tool for CircleTool { let mut o = self.snap.guides().to_vec(); let points = self.points(); let color = crate::draw2::FEEDBACK; - if let Some((c, r)) = circle_of(&points) { + if let Some((c, r)) = drawn_circle(&points, self.options.standard_anchors) { let path = shapes::ellipse(Rect::new(c.x - r, c.y - r, c.x + r, c.y + r)).to_bezpath(); // The canvas draws a dashed outline dash by dash along its whole length: a circle longer // than DASHED_PX on screen is drawn solid instead. @@ -452,7 +463,7 @@ impl Tool for CircleTool { if let Some(p) = self.pointer.filter(|_| cx.measurement_labels && opts.diameter) { o.push(Overlay::Measure { p: p + Vec2::new(cx.tol(12.0), cx.tol(12.0)), text: format!("D: {}", cx.len(2.0 * r)) }); } - } else if let Some(p) = self.pointer.filter(|_| too_large(&points)) { + } else if let Some(p) = self.pointer.filter(|_| too_large(&points, self.options.standard_anchors)) { o.push(Overlay::Label { p, text: "Circle too large".into(), color }); } for p in self.first.into_iter().chain(self.second()) { diff --git a/crates/tools/src/circle/tests.rs b/crates/tools/src/circle/tests.rs index c0a82a51ef..40be85c4e7 100644 --- a/crates/tools/src/circle/tests.rs +++ b/crates/tools/src/circle/tests.rs @@ -162,6 +162,28 @@ fn anchors_at_the_points_asks_for_them() { assert_eq!(acts, vec![Action::Exec("shape.circleThroughPoints".into(), json!({"points": points, "anchors": "points"}))]); } +/// With `standardAnchors` off, a circle within 1 pt of the canvas edge whose path with anchors at +/// the points curves past that edge is not shown and not drawn; with standard anchors it is. +#[test] +fn anchors_at_the_points_keep_the_path_on_the_canvas() { + let (d, _) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) }; + let r = MAX_COORD - 1.0; + let at = |deg: f64| (r * deg.to_radians().cos(), r * deg.to_radians().sin()); + let points = [at(0.0), at(70.0), at(180.0)]; + let geom: Vec = points.iter().map(|(x, y)| Point::new(*x, *y)).collect(); + assert!(drawn_circle(&geom, true).is_some()); + assert_eq!(drawn_circle(&geom, false), None); + let mut t = CircleTool::default(); + t.set_option("standardAnchors", &json!(false)); + click(&mut t, &cx, points[0]); + t.pointer(&cx, &ev(PointerKind::Down, points[1], Mods::default())); + t.pointer(&cx, &ev(PointerKind::Drag, points[2], Mods::default())); + assert_eq!(preview(&t.overlays(&cx)), None); + assert_eq!(t.pointer(&cx, &ev(PointerKind::Up, points[2], Mods::default())), vec![]); +} + /// With `dragThird` off, a second click places the second point and a third click draws the circle /// through the three; a click on the second point again (as a double-click there does) draws the /// circle on the two; a second point let go on the first places nothing; a drag from the first @@ -419,8 +441,8 @@ fn points_on_one_line_say_the_circle_is_too_large() { assert_eq!(label(&t), None, "a circle is shown"); t.pointer(&cx, &ev(PointerKind::Drag, (200.0, 200.0), Mods::default())); assert_eq!(label(&t), None, "the third point is on the second"); - assert!(too_large(&[Point::new(0.0, 0.0), Point::new(4.1e6, 0.0)])); - assert!(!too_large(&[Point::new(0.0, 0.0)]) && !too_large(&[Point::new(1.0, 0.0), Point::new(1.0, 0.0)])); + assert!(too_large(&[Point::new(0.0, 0.0), Point::new(4.1e6, 0.0)], true)); + assert!(!too_large(&[Point::new(0.0, 0.0)], true) && !too_large(&[Point::new(1.0, 0.0), Point::new(1.0, 0.0)], true)); } /// Escape drops the first point; so do a dropped press and an edit made outside the tool. A From b66e43f0486a7f12ff8fc3fccf249b2d6b38704d Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 18 Nov 2026 16:06:24 -0800 Subject: [PATCH 5/6] Shapes: Circle tool options pass the tool's own option check The Circle tool now answers Tool::check_option with the values check_options takes, so tool.setOption and the option check that runs on every tool accept the options the tool reports. - With Third Point by Dragging off, a click in reach of both placed points is on the nearer one (or the one it snapped to). - A press on the second point previews the circle on the two points that its release draws, and a press on the first point previews none. - With Anchors at Standard Positions off, the preview is the path with an anchor at each point, which the release draws. - A move of less than 2 screen points keeps the second or third point where it was pressed. - circle_with_anchors_at gives the two ends of a diameter four anchors also where rounding of the midpoint puts the second point more than half a turn from the first. - The canvas-edge test checks for an outline whether dashed or solid. - docs/mcp.md says that only anchors: "standard" draws a live ellipse. --- crates/geom/src/shapes.rs | 26 +++++++++- crates/tools/src/circle.rs | 54 ++++++++++++++++----- crates/tools/src/circle/tests.rs | 82 +++++++++++++++++++++++++++++++- docs/mcp.md | 5 +- 4 files changed, 150 insertions(+), 17 deletions(-) diff --git a/crates/geom/src/shapes.rs b/crates/geom/src/shapes.rs index d194fcac4e..419c2b8ddf 100644 --- a/crates/geom/src/shapes.rs +++ b/crates/geom/src/shapes.rs @@ -371,8 +371,9 @@ pub fn circle_through_points(points: &[Point]) -> Option<(Point, f64)> { /// circle, as [`circle_through_points`] gives it) plus as many more as split each arc between two /// of them into equal parts of at most a quarter turn. The path starts at the first point and runs /// as [`ellipse`] does (left, top, right on the page); each curve's handles are 4/3·tan(θ/4) of -/// the radius along the tangents at its ends (θ, its turn). A point given twice is one anchor; -/// with no points it starts at the left, as [`ellipse`] does. +/// the radius along the tangents at its ends (θ, its turn). Two points with `center` at their +/// midpoint give four anchors. A point given twice is one anchor; with no points it starts at the +/// left, as [`ellipse`] does. pub fn circle_with_anchors_at(center: Point, radius: f64, points: &[Point]) -> PathData { let quarter = PI / 2.0; let angle = |p: Point| (p.y - center.y).atan2(p.x - center.x); @@ -381,6 +382,13 @@ pub fn circle_with_anchors_at(center: Point, radius: f64, points: &[Point]) -> P let mut placed: Vec<(f64, Point)> = points.iter().map(|p| ((angle(*p) - start).rem_euclid(TAU), *p)).collect(); placed.sort_by(|a, b| a.0.total_cmp(&b.0)); placed.dedup_by(|a, b| a.1 == b.1); + // Two points with the center at their midpoint are the ends of a diameter: the second is half a + // turn from the first, also where rounding moves the angle from the center off it. + if let [(_, a), (turn, b)] = placed.as_mut_slice() + && a.midpoint(*b) == center + { + *turn = PI; + } if placed.is_empty() { placed.push((0.0, Point::new(center.x - radius, center.y))); } @@ -861,6 +869,20 @@ mod tests { } } + /// The two ends of a diameter give four anchors, also where the midpoint rounds off it: at + /// x = 10⁶, steps of 2⁻³³ put the second point more than half a turn from the first, seen from + /// the rounded center. + #[test] + fn a_diameter_gives_four_anchors_where_its_midpoint_rounds() { + let u = 2f64.powi(-33); + let (a, b) = (Point::new(1_000_000.0, 0.0), Point::new(1_000_000.0 + 9.0 * u, 8.0 * u)); + let (center, radius) = circle_through_points(&[a, b]).expect("a circle"); + let path = circle_with_anchors_at(center, radius, &[a, b]); + let sub = &path.subpaths[0]; + assert_eq!(sub.anchors.len(), 4, "{sub:?}"); + assert_eq!((sub.anchors[0].p, sub.anchors[2].p), (a, b)); + } + /// Nearly on one line: a point 10⁻⁴ off a chord 2000 long still gives the circle (its sagitta /// formula `r = (h² + (L/2)²) / 2h`), and its center sits on the chord's perpendicular /// bisector; a point 10⁻¹² off it does not. diff --git a/crates/tools/src/circle.rs b/crates/tools/src/circle.rs index fb19af46e0..9e08f79d49 100644 --- a/crates/tools/src/circle.rs +++ b/crates/tools/src/circle.rs @@ -205,8 +205,16 @@ impl CircleTool { fn points(&self) -> Vec { let mut out: Vec = self.first.into_iter().collect(); if let Some((b, _)) = self.second { - out.push(b); - out.extend(self.pointer); + match self.press { + // Let go where it was pressed, a press on the first point draws nothing and one on + // the second point draws the circle on the two. + Some(Press::Third { on_first: true, dragged: false, .. }) => {} + Some(Press::Third { on_second: true, dragged: false, .. }) => out.push(b), + _ => { + out.push(b); + out.extend(self.pointer); + } + } return out; } match self.press { @@ -302,9 +310,16 @@ impl Tool for CircleTool { PointerKind::Down => { if let (Some(a), Some((b, clicked))) = (self.first, self.second) { let at = self.snap.press(cx, ev.pos, &[], None); - let on = |q: Point| at == q || ev.pos.distance(q) <= cx.tol(REACH_PX); - let on_second = on(b) || ev.pos.distance(clicked) <= cx.tol(REACH_PX); - self.press = Some(Press::Third { at, from: ev.pos, on_first: on(a), on_second, dragged: false }); + let reach = cx.tol(REACH_PX); + let to_second = ev.pos.distance(b).min(ev.pos.distance(clicked)); + let (mut on_first, mut on_second) = (at == a || ev.pos.distance(a) <= reach, at == b || to_second <= reach); + // A press in reach of both points is on the one it snapped to, otherwise on the + // nearer one. + if on_first && on_second { + let first = if (at == a) != (at == b) { at == a } else { ev.pos.distance(a) < to_second }; + (on_first, on_second) = (first, !first); + } + self.press = Some(Press::Third { at, from: ev.pos, on_first, on_second, dragged: false }); self.pointer = Some(at); return vec![]; } @@ -332,17 +347,22 @@ impl Tool for CircleTool { match &mut self.press { // With `dragThird` off, the second point follows the pointer as it does before // the press. + // The point stays where it was pressed until the press is a drag. Some(Press::Second { at, snapped, from, on_first: false, dragged }) if !drag_third => { *dragged |= ev.pos.distance(*from) >= cx.tol(DRAG_PX); - let leave = first.map(|a| Leave::segment(cx, a, ev.mods.shift)); - *snapped = self.snap.drag(cx, ev.pos, leave.as_ref()); - *at = first.map_or(*snapped, |a| round_diameter(cx, a, *snapped, ev.mods)); - self.pointer = Some(*at); + if *dragged { + let leave = first.map(|a| Leave::segment(cx, a, ev.mods.shift)); + *snapped = self.snap.drag(cx, ev.pos, leave.as_ref()); + *at = first.map_or(*snapped, |a| round_diameter(cx, a, *snapped, ev.mods)); + self.pointer = Some(*at); + } } Some(Press::Third { at, from, dragged, .. }) => { *dragged |= ev.pos.distance(*from) >= cx.tol(DRAG_PX); - *at = self.snap.drag(cx, ev.pos, None); - self.pointer = Some(*at); + if *dragged { + *at = self.snap.drag(cx, ev.pos, None); + self.pointer = Some(*at); + } } Some(Press::First { at, from, dragged }) => { *dragged |= ev.pos.distance(*from) >= cx.tol(DRAG_PX); @@ -443,7 +463,12 @@ impl Tool for CircleTool { let points = self.points(); let color = crate::draw2::FEEDBACK; if let Some((c, r)) = drawn_circle(&points, self.options.standard_anchors) { - let path = shapes::ellipse(Rect::new(c.x - r, c.y - r, c.x + r, c.y + r)).to_bezpath(); + // The path the release draws: with `standardAnchors` off, the one with an anchor at each point. + let path = if self.options.standard_anchors { + shapes::ellipse(Rect::new(c.x - r, c.y - r, c.x + r, c.y + r)).to_bezpath() + } else { + shapes::circle_with_anchors_at(c, r, &points).to_bezpath() + }; // The canvas draws a dashed outline dash by dash along its whole length: a circle longer // than DASHED_PX on screen is drawn solid instead. let dashed = std::f64::consts::TAU * r <= cx.tol(DASHED_PX); @@ -489,6 +514,11 @@ impl Tool for CircleTool { }) } + /// Takes the values [`check_options`] takes. + fn check_option(&self, key: &str, value: &Value) -> Result<(), String> { + check_options(&Map::from_iter([(key.to_string(), value.clone())])) + } + /// Sets one option; a value the option does not take leaves it as it was. Switching /// `dragThird` drops the points placed so far. fn set_option(&mut self, key: &str, value: &Value) { diff --git a/crates/tools/src/circle/tests.rs b/crates/tools/src/circle/tests.rs index 40be85c4e7..e526f044a5 100644 --- a/crates/tools/src/circle/tests.rs +++ b/crates/tools/src/circle/tests.rs @@ -162,6 +162,25 @@ fn anchors_at_the_points_asks_for_them() { assert_eq!(acts, vec![Action::Exec("shape.circleThroughPoints".into(), json!({"points": points, "anchors": "points"}))]); } +/// With `standardAnchors` off, the tool shows the path with an anchor at each point, the one its +/// release draws. +#[test] +fn anchors_at_the_points_show_the_path_they_draw() { + let (d, _) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) }; + let mut t = CircleTool::default(); + t.set_option("standardAnchors", &json!(false)); + click(&mut t, &cx, (300.0, 300.0)); + t.pointer(&cx, &ev(PointerKind::Down, (380.0, 300.0), Mods::default())); + t.pointer(&cx, &ev(PointerKind::Drag, (310.0, 340.0), Mods::default())); + let points = [Point::new(300.0, 300.0), Point::new(380.0, 300.0), Point::new(310.0, 340.0)]; + let (c, r) = circle_of(&points).expect("a circle"); + let want = shapes::circle_with_anchors_at(c, r, &points).to_bezpath(); + let o = t.overlays(&cx); + assert!(o.iter().any(|o| matches!(o, Overlay::Path { path, .. } if *path == want)), "{o:?}"); +} + /// With `standardAnchors` off, a circle within 1 pt of the canvas edge whose path with anchors at /// the points curves past that edge is not shown and not drawn; with standard anchors it is. #[test] @@ -180,10 +199,67 @@ fn anchors_at_the_points_keep_the_path_on_the_canvas() { click(&mut t, &cx, points[0]); t.pointer(&cx, &ev(PointerKind::Down, points[1], Mods::default())); t.pointer(&cx, &ev(PointerKind::Drag, points[2], Mods::default())); - assert_eq!(preview(&t.overlays(&cx)), None); + // No outline at all: at this size the tool would draw it solid, not dashed. + let o = t.overlays(&cx); + assert!(!o.iter().any(|o| matches!(o, Overlay::Path { .. })), "{o:?}"); assert_eq!(t.pointer(&cx, &ev(PointerKind::Up, points[2], Mods::default())), vec![]); } +/// With `dragThird` off, a click in reach of both placed points is on the nearer one: nearer the +/// first point it places nothing, nearer the second it draws the circle on the two. +#[test] +fn with_third_point_by_dragging_off_a_click_near_both_points_takes_the_nearer() { + let (d, _) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) }; + let mut t = CircleTool::default(); + t.set_option("dragThird", &json!(false)); + click(&mut t, &cx, (100.0, 100.0)); + assert_eq!(click(&mut t, &cx, (104.0, 100.0)), vec![]); + assert_eq!(click(&mut t, &cx, (101.0, 100.0)), vec![]); + assert_eq!(click(&mut t, &cx, (103.0, 100.0)), circle(&[(100.0, 100.0), (104.0, 100.0)])); +} + +/// With `dragThird` off, a press on the second point shows the circle on the two points, which its +/// release draws, and a press on the first point shows none. +#[test] +fn with_third_point_by_dragging_off_a_press_shows_the_circle_its_release_draws() { + let (d, _) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) }; + let mut t = CircleTool::default(); + t.set_option("dragThird", &json!(false)); + click(&mut t, &cx, (100.0, 100.0)); + click(&mut t, &cx, (200.0, 100.0)); + t.pointer(&cx, &ev(PointerKind::Down, (101.0, 101.0), Mods::default())); + assert_eq!(preview(&t.overlays(&cx)), None); + assert_eq!(t.pointer(&cx, &ev(PointerKind::Up, (101.0, 101.0), Mods::default())), vec![]); + t.pointer(&cx, &ev(PointerKind::Down, (202.0, 101.0), Mods::default())); + let o = t.overlays(&cx); + assert!(near(preview(&o).expect("the circle is shown"), Rect::new(100.0, 50.0, 200.0, 150.0)), "{o:?}"); + assert_eq!(t.pointer(&cx, &ev(PointerKind::Up, (202.0, 101.0), Mods::default())), circle(&[(100.0, 100.0), (200.0, 100.0)])); +} + +/// With `dragThird` off, a press that moves less than 2 screen points keeps the point where it was +/// pressed, for the second point and for the third. +#[test] +fn with_third_point_by_dragging_off_a_short_move_keeps_the_pressed_point() { + let (d, _) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) }; + let (down, drag, up) = (PointerKind::Down, PointerKind::Drag, PointerKind::Up); + let mut t = CircleTool::default(); + t.set_option("dragThird", &json!(false)); + click(&mut t, &cx, (100.0, 100.0)); + t.pointer(&cx, &ev(down, (200.0, 100.0), Mods::default())); + t.pointer(&cx, &ev(drag, (201.0, 100.0), Mods::default())); + assert_eq!(t.pointer(&cx, &ev(up, (200.0, 100.0), Mods::default())), vec![]); + t.pointer(&cx, &ev(down, (150.0, 200.0), Mods::default())); + t.pointer(&cx, &ev(drag, (151.0, 200.0), Mods::default())); + let three = circle(&[(100.0, 100.0), (200.0, 100.0), (150.0, 200.0)]); + assert_eq!(t.pointer(&cx, &ev(up, (150.0, 200.0), Mods::default())), three); +} + /// With `dragThird` off, a second click places the second point and a third click draws the circle /// through the three; a click on the second point again (as a double-click there does) draws the /// circle on the two; a second point let go on the first places nothing; a drag from the first @@ -300,6 +376,9 @@ fn an_alt_click_places_the_second_point_where_it_is_shown() { fn check_options_takes_only_the_values_the_options_take() { let ok = json!({"center": false, "radii": true, "diameter": false, "color": "gray", "standardAnchors": false, "dragThird": false}); assert_eq!(check_options(ok.as_object().unwrap()), Ok(())); + // The tool's own check, which `tool.setOption` also runs, takes the same values. + let tool = CircleTool::default(); + assert_eq!(tool.check_options(ok.as_object().unwrap()), Ok(())); for (bad, error) in [ (json!({"center": 1}), "`center` must be true or false"), (json!({"dragThird": null}), "`dragThird` must be true or false"), @@ -307,6 +386,7 @@ fn check_options_takes_only_the_values_the_options_take() { (json!({"colour": "red"}), "unknown Circle tool option `colour`"), ] { assert_eq!(check_options(bad.as_object().unwrap()), Err(error.to_string()), "{bad}"); + assert_eq!(tool.check_options(bad.as_object().unwrap()), Err(error.to_string()), "{bad}"); } } diff --git a/docs/mcp.md b/docs/mcp.md index 63a0215986..445c52ec3d 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -6582,8 +6582,9 @@ slider back to the Auto-Smooth level. ## Circle through two or three points -`shape.circleThroughPoints {points?: [[x, y], [x, y]] or [[x, y], [x, y], [x, y]]}` draws the circle whose edge passes -through the points, as a live ellipse with the current paint, and selects it. Two points are the ends of a diameter. +`shape.circleThroughPoints {points?: [[x, y], [x, y]] or [[x, y], [x, y], [x, y]], anchors?}` draws the circle whose +edge passes through the points, with the current paint, and selects it: a live ellipse with the default +`anchors: "standard"`, and a plain path with `anchors: "points"`. Two points are the ends of a diameter. Without `points`, it uses the two or three selected anchor points, from one path or several: anchor points selected with Direct Selection, or all the anchor points of a path selected whole, such as a triangle. The ends of selected segments do not count. The result is `{id, cx, cy, radius}`, and one undo removes the circle. The circle is not pixel-aligned, From 1bb3becb2733e6f5162895857b5b316e0977fd87 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 18 Nov 2026 19:00:16 -0800 Subject: [PATCH 6/6] MCP: the UI command catalog lists Circle Tool Options crates/mcp/src/ui_catalog.rs is regenerated from ui_commands.rs, so the tool.options entry describes the circleOptions dialog as the desktop table does. --- crates/mcp/src/ui_catalog.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/mcp/src/ui_catalog.rs b/crates/mcp/src/ui_catalog.rs index 88f60fd6c8..3d85a7f3b1 100644 --- a/crates/mcp/src/ui_catalog.rs +++ b/crates/mcp/src/ui_catalog.rs @@ -1078,7 +1078,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "tool.options", "Tool Options…", "", - "{tool: id} what double-clicking a tool button opens: hand → fits the artboard in the window (view.fitArtboard), zoom → 100% (view.actualSize), rotate|scale|reflect|shear → that Object › Transform dialog (dialog `rotate`, `scale`, `reflect` or `shear`; error `nothing selected` without a selection), selection|directSelection|groupSelection → the Move dialog (dialog `move`; the same error), gradient|magicWand → the Gradient or Magic Wand panel (window.panel), artboard → Artboard Options of the active artboard (dialog `artboardOptions`, fields index, name, x, y, width, height, showCenterMark, showCrossHairs; OK runs artboard.setProps, and with other artboards selected with the Artboard tool a new width or height goes to each of them too, in its `artboards` list, each resized about the reference point the form used for that size, or about its top-left corner when the size was set in the fields directly), flare → Flare Tool Options (dialog `flareOptions`, fields diameter and pathLength (pt), opacity, brightness, growth, fuzziness, longest, rayFuzziness, largest (%), rays, rings, direction (°), raysOn, ringsOn; OK runs tool.setOption {tool: \"flare\", values}: the next flare dragged out uses them, and a Flare click's dialog, which also has x, y and preview (on initially), previews one there and accepts it as one Undo step; Cancel rolls back the preview; with flares selected, the fields show the first one's settings, `flares` lists them and OK runs shape.editFlare with the settings changed instead, leaving the tool's options), lineSegment|arc|rectangularGrid|polarGrid → that tool's Tool Options, its click dialog without x and y (dialog kind = the tool id, `__toolOptions: true`; lineSegment: length (pt), angle (°), fillLine; arc: lengthX, lengthY (pt), reference (0–8), arcType: open|closed, baseAlong: x|y, slope (−100…100), fillArc; rectangularGrid: width, height (pt, the Default Size), reference (0–8), rows, columns, rowSkew, columnSkew (%), frame, fill; polarGrid: the same with concentric, radial, concentricSkew, radialSkew and compound for rows, columns, the skews and frame; OK runs tool.setOption {tool, values} and draws nothing: the next drag uses them (Fill Line, the arc's type, base, slope and fill, the grids' dividers, skews and switches) and a click's dialog opens at them), columnGraph|stackedColumnGraph|barGraph|stackedBarGraph|lineGraph|areaGraph|scatterGraph|pieGraph|radarGraph → Graph Type for the selected graph, or for the series picked in it with Group Selection (dialog `graphType`, fields the options graph.setType {} returns under their names, with legend, pieLegend, piePosition, pieSort, firstRowInFront, firstColumnInFront, filledLines and lineWidth held for every type; overrideValues and rightOverrideValues, Override Calculated Values of the left or only value axis and of the right one: while one is on OK sends axisMin, axisMax and ticks, or rightAxisMin, rightAxisMax and rightTicks, filled with the calculated values where the graph has none, and one turned off sends null, null and 0; __page: options|valueAxis|rightAxis|categoryAxis, the page shown, options when the type picked has no such page; OK runs graph.setType, and with nothing changed closes without a step of history; an overridden value axis whose maximum is not more than its minimum is an error and the dialog stays open; an error without a selected graph), typeOnPath|verticalTypeOnPath → Type on a Path Options for the selected type on a path (dialog `command` running type.pathOptions; error `nothing selected` without a selection, and the command's error when no type on a path is selected),symbolSprayer|symbolShifter|symbolScruncher|symbolSizer|symbolSpinner|symbolStainer|symbolScreener|symbolStyler → Symbolism Tools Options (dialog `symbolismOptions`, fields tool, diameter (pt), intensity and density (1–10), shared by the eight tools; OK runs tool.setOption {tool, values}), blend → Blend Options, perspectiveGrid → Perspective Grid Options, eyedropper → Eyedropper Options (dialog `eyedropperOptions`, fields sampleSize, pickUp, apply; OK runs eyedropper.setOptions), printTiling → resets the print tiling (print.tiling.set {reset: true}), warp|twirl|pucker|bloat|scallop|crystallize|wrinkle → that tool's Tool Options (dialog `liquifyOptions`, fields tool, width, height, angle, intensity %, usePressure, detail, simplify, simplifyOn, rate, complexity, horizontal %, vertical %, affectAnchors, affectIn, affectOut, showBrush; OK runs tool.setOption {tool, values}), pencil|paintbrush|smooth|blobBrush|eraser → that tool's Tool Options (dialog `freehandOptions`, fields tool and the options the tool keeps: fidelity (px for pencil, paintbrush and smooth, the same at any zoom; pt for blobBrush), fill, keepSelected (on for pencil and paintbrush, off for blobBrush), mergeOnlySelection (off), closeWithin and editWithin (px, 0 is off), livePreview (pencil, on: off draws a thin line while the stroke is drawn, and the path's fill and stroke on release), size (pt), angle (°, −180–180; 0) and roundness (%, 1–100; 100) of the eraser's tip; OK runs tool.setOption {tool, values}), livePaintSelection → Live Paint Selection Tool Options (dialog `livePaintSelectionOptions`, fields selectFills and selectStrokes (both on), color (the highlight color, #rrggbb or a layer color's name; #ff2a2a), width (the highlight's width, 1–20 px; 4); OK runs tool.setOption {tool: \"livePaintSelection\", values}; a color with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), livePaintBucket → Live Paint Bucket Options (dialog `livePaintBucketOptions`, fields paintFills (on) and paintStrokes (off), cursorSwatchPreview (on: the active fill or stroke shows above the pointer between the color swatches before and after it; Left and Right without modifiers step it through the color swatches whether it is on or off), highlight (on), color (the highlight color, #rrggbb or a layer color's name; #ff2a2a), width (the face highlight's width, 1–20 px; 4; an edge's highlight is half as wide); OK runs tool.setOption {tool: \"livePaintBucket\", values}; a color with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), shapeBuilder → Shape Builder Tool Options (dialog `shapeBuilderOptions`, fields gapDetection (off), gapLength (pt, 0–72; 3), openFilledAsClosed (on), clickStrokeSplitsPath (off), pickColorFrom: artwork|swatches (artwork), cursorSwatchPreview (off), selection: freeform|straightLine (freeform), highlightFill (on), highlightStroke (on), highlightColor (#rrggbb or a layer color's name; #ff4f4f); OK runs tool.setOption {tool: \"shapeBuilder\", values}; a highlightColor with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), objectsOnPath → Objects on Path Tool Options (dialog `objectsOnPathOptions`, fields pivot (0–8, row by row from the top left; 4, the center) and rotate (°, −360–360; 0); Reset puts 4 and 0 back; Save runs tool.setOption {tool: \"objectsOnPath\", values}: the objects attached next use them, groups attached before keep theirs)", + "{tool: id} what double-clicking a tool button opens: hand → fits the artboard in the window (view.fitArtboard), zoom → 100% (view.actualSize), rotate|scale|reflect|shear → that Object › Transform dialog (dialog `rotate`, `scale`, `reflect` or `shear`; error `nothing selected` without a selection), selection|directSelection|groupSelection → the Move dialog (dialog `move`; the same error), gradient|magicWand → the Gradient or Magic Wand panel (window.panel), artboard → Artboard Options of the active artboard (dialog `artboardOptions`, fields index, name, x, y, width, height, showCenterMark, showCrossHairs; OK runs artboard.setProps, and with other artboards selected with the Artboard tool a new width or height goes to each of them too, in its `artboards` list, each resized about the reference point the form used for that size, or about its top-left corner when the size was set in the fields directly), flare → Flare Tool Options (dialog `flareOptions`, fields diameter and pathLength (pt), opacity, brightness, growth, fuzziness, longest, rayFuzziness, largest (%), rays, rings, direction (°), raysOn, ringsOn; OK runs tool.setOption {tool: \"flare\", values}: the next flare dragged out uses them, and a Flare click's dialog, which also has x, y and preview (on initially), previews one there and accepts it as one Undo step; Cancel rolls back the preview; with flares selected, the fields show the first one's settings, `flares` lists them and OK runs shape.editFlare with the settings changed instead, leaving the tool's options), lineSegment|arc|rectangularGrid|polarGrid → that tool's Tool Options, its click dialog without x and y (dialog kind = the tool id, `__toolOptions: true`; lineSegment: length (pt), angle (°), fillLine; arc: lengthX, lengthY (pt), reference (0–8), arcType: open|closed, baseAlong: x|y, slope (−100…100), fillArc; rectangularGrid: width, height (pt, the Default Size), reference (0–8), rows, columns, rowSkew, columnSkew (%), frame, fill; polarGrid: the same with concentric, radial, concentricSkew, radialSkew and compound for rows, columns, the skews and frame; OK runs tool.setOption {tool, values} and draws nothing: the next drag uses them (Fill Line, the arc's type, base, slope and fill, the grids' dividers, skews and switches) and a click's dialog opens at them), circle → Circle Tool Options (dialog `circleOptions`, fields center, radii, diameter (all on), color (red|blue|magenta|green|black|gray; blue), standardAnchors (on) and dragThird (on); OK runs tool.setOption {tool: \"circle\", values}), columnGraph|stackedColumnGraph|barGraph|stackedBarGraph|lineGraph|areaGraph|scatterGraph|pieGraph|radarGraph → Graph Type for the selected graph, or for the series picked in it with Group Selection (dialog `graphType`, fields the options graph.setType {} returns under their names, with legend, pieLegend, piePosition, pieSort, firstRowInFront, firstColumnInFront, filledLines and lineWidth held for every type; overrideValues and rightOverrideValues, Override Calculated Values of the left or only value axis and of the right one: while one is on OK sends axisMin, axisMax and ticks, or rightAxisMin, rightAxisMax and rightTicks, filled with the calculated values where the graph has none, and one turned off sends null, null and 0; __page: options|valueAxis|rightAxis|categoryAxis, the page shown, options when the type picked has no such page; OK runs graph.setType, and with nothing changed closes without a step of history; an overridden value axis whose maximum is not more than its minimum is an error and the dialog stays open; an error without a selected graph), typeOnPath|verticalTypeOnPath → Type on a Path Options for the selected type on a path (dialog `command` running type.pathOptions; error `nothing selected` without a selection, and the command's error when no type on a path is selected),symbolSprayer|symbolShifter|symbolScruncher|symbolSizer|symbolSpinner|symbolStainer|symbolScreener|symbolStyler → Symbolism Tools Options (dialog `symbolismOptions`, fields tool, diameter (pt), intensity and density (1–10), shared by the eight tools; OK runs tool.setOption {tool, values}), blend → Blend Options, perspectiveGrid → Perspective Grid Options, eyedropper → Eyedropper Options (dialog `eyedropperOptions`, fields sampleSize, pickUp, apply; OK runs eyedropper.setOptions), printTiling → resets the print tiling (print.tiling.set {reset: true}), warp|twirl|pucker|bloat|scallop|crystallize|wrinkle → that tool's Tool Options (dialog `liquifyOptions`, fields tool, width, height, angle, intensity %, usePressure, detail, simplify, simplifyOn, rate, complexity, horizontal %, vertical %, affectAnchors, affectIn, affectOut, showBrush; OK runs tool.setOption {tool, values}), pencil|paintbrush|smooth|blobBrush|eraser → that tool's Tool Options (dialog `freehandOptions`, fields tool and the options the tool keeps: fidelity (px for pencil, paintbrush and smooth, the same at any zoom; pt for blobBrush), fill, keepSelected (on for pencil and paintbrush, off for blobBrush), mergeOnlySelection (off), closeWithin and editWithin (px, 0 is off), livePreview (pencil, on: off draws a thin line while the stroke is drawn, and the path's fill and stroke on release), size (pt), angle (°, −180–180; 0) and roundness (%, 1–100; 100) of the eraser's tip; OK runs tool.setOption {tool, values}), livePaintSelection → Live Paint Selection Tool Options (dialog `livePaintSelectionOptions`, fields selectFills and selectStrokes (both on), color (the highlight color, #rrggbb or a layer color's name; #ff2a2a), width (the highlight's width, 1–20 px; 4); OK runs tool.setOption {tool: \"livePaintSelection\", values}; a color with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), livePaintBucket → Live Paint Bucket Options (dialog `livePaintBucketOptions`, fields paintFills (on) and paintStrokes (off), cursorSwatchPreview (on: the active fill or stroke shows above the pointer between the color swatches before and after it; Left and Right without modifiers step it through the color swatches whether it is on or off), highlight (on), color (the highlight color, #rrggbb or a layer color's name; #ff2a2a), width (the face highlight's width, 1–20 px; 4; an edge's highlight is half as wide); OK runs tool.setOption {tool: \"livePaintBucket\", values}; a color with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), shapeBuilder → Shape Builder Tool Options (dialog `shapeBuilderOptions`, fields gapDetection (off), gapLength (pt, 0–72; 3), openFilledAsClosed (on), clickStrokeSplitsPath (off), pickColorFrom: artwork|swatches (artwork), cursorSwatchPreview (off), selection: freeform|straightLine (freeform), highlightFill (on), highlightStroke (on), highlightColor (#rrggbb or a layer color's name; #ff4f4f); OK runs tool.setOption {tool: \"shapeBuilder\", values}; a highlightColor with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), objectsOnPath → Objects on Path Tool Options (dialog `objectsOnPathOptions`, fields pivot (0–8, row by row from the top left; 4, the center) and rotate (°, −360–360; 0); Reset puts 4 and 0 back; Save runs tool.setOption {tool: \"objectsOnPath\", values}: the objects attached next use them, groups attached before keep theirs)", ), ( "ui.colorGuideOptions",