diff --git a/ROADMAP.md b/ROADMAP.md index ef05d5dc9a..79ec54818f 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -146,6 +146,7 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap - 2026-11-17: Curvature Circle tool (after the Circle tool in its group): a click on a path draws the circle that touches it there and bends as it bends, on the side it bends toward, or with Shift on the other side; a segment that is the usual cubic of a circular arc of 90° or less gives the arc's own radius, so a click on a circle draws that circle; the tool shows the circle, its center and its radius (with an asterisk for an arc's radius) until the click, or "Straight segment", "Cusp", "Corner" or "Circle too large" where it draws none (`shape.curvatureCircle`). One undo step per circle. A VectorCraft addition: headline numbers 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-11-19: Quick Pen tool, in the Pen tool's group (Alt+P, Option+P on macOS): clicks or drags add straight lines, continuous arcs or sharp-corner arcs; Alt tapped on its own switches the action, C flips the last arc, `[` and `]` size it, a click on the first point closes the path and a click on an open end continues it (`path.quickPen`, part of #2660). 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. diff --git a/crates/engine/src/cmd/create.rs b/crates/engine/src/cmd/create.rs index f012bcfc82..0ce38be40b 100644 --- a/crates/engine/src/cmd/create.rs +++ b/crates/engine/src/cmd/create.rs @@ -73,7 +73,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 ), @@ -443,20 +443,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).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..c9b66f9f06 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), 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}"); + } + 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 fe38a92a49..7341d455c4 100644 --- a/crates/engine/src/tooling.rs +++ b/crates/engine/src/tooling.rs @@ -1478,6 +1478,9 @@ impl Session { } // Every value is checked before any is set, so an invalid one changes nothing. vectorcraft_tools::builder::check_builder_options(id, &values)?; + if id == vectorcraft_tools::circle::ID { + vectorcraft_tools::circle::check_options(&values)?; + } vectorcraft_tools::symbolism::check_options(id, &values)?; if id == vectorcraft_tools::cropimage::ID { use vectorcraft_tools::cropimage as crop; diff --git a/crates/geom/src/shapes.rs b/crates/geom/src/shapes.rs index 1cb52b4559..f3ab848e81 100644 --- a/crates/geom/src/shapes.rs +++ b/crates/geom/src/shapes.rs @@ -367,6 +367,61 @@ 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). 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); + 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); + // 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))); + } + 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); @@ -1146,6 +1201,53 @@ 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:?}"); + } + } + } + + /// 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/mcp/src/ui_catalog.rs b/crates/mcp/src/ui_catalog.rs index 931512640a..e2bcf01159 100644 --- a/crates/mcp/src/ui_catalog.rs +++ b/crates/mcp/src/ui_catalog.rs @@ -1156,7 +1156,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 (the tool whose options show; the Tool row changes it), diameter (pt), intensity and density (1–10), usePressure, method: userDefined|average|random (not used by the Sprayer and the Shifter), showBrush, sprayScrunch, spraySize, spraySpin, sprayScreen, sprayStain and sprayStyle: average|userDefined (the Symbol Sprayer's), proportional and affectsDensity (the Symbol Sizer's), shared by the eight tools; OK runs tool.setOption {tool, values}, after symbol.setDensity from the density the dialog opened with to the new one when symbol sets are selected and it changed), 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 (the tool whose options show; the Tool row changes it), diameter (pt), intensity and density (1–10), usePressure, method: userDefined|average|random (not used by the Sprayer and the Shifter), showBrush, sprayScrunch, spraySize, spraySpin, sprayScreen, sprayStain and sprayStyle: average|userDefined (the Symbol Sprayer's), proportional and affectsDensity (the Symbol Sizer's), shared by the eight tools; OK runs tool.setOption {tool, values}, after symbol.setDensity from the density the dialog opened with to the new one when symbol sets are selected and it changed), 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/tools/src/circle.rs b/crates/tools/src/circle.rs index 40f52290f4..e50e595e26 100644 --- a/crates/tools/src/circle.rs +++ b/crates/tools/src/circle.rs @@ -16,8 +16,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}; @@ -35,6 +44,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 { @@ -47,23 +121,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` @@ -73,6 +160,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. @@ -84,43 +182,65 @@ 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 { 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 { + 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 { 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, @@ -131,18 +251,34 @@ 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); + 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) || drawn_circle(&[a, b, at], self.options.standard_anchors).is_none() { + self.snap.clear(); + return vec![]; + } + self.draw(&[a, b, at]) + } + /// Is the press let go at `ev` a drag: is `ev` [`DRAG_PX`] or more from the press? A release /// nearer the press is a click, also after a drag that came back to it. fn drags(&self, cx: &ToolContext, ev: &PointerEvent) -> bool { match self.press { - Some(Press::First { from, .. } | Press::Second { from, .. }) => ev.pos.distance(from) >= cx.tol(DRAG_PX), + Some(Press::First { from, .. } | Press::Second { from, .. } | Press::Third { from, .. }) => ev.pos.distance(from) >= cx.tol(DRAG_PX), None => false, } } @@ -173,6 +309,13 @@ impl Tool for CircleTool { *dragged = false; (*at, *on_first) } + // With `dragThird` off, a click on the third point's press: the point goes back + // to where it was pressed. + Press::Third { at, from, dragged, .. } => { + *dragged = false; + *at = self.snap.press(cx, *from, &[], None); + (*at, false) + } }; // A click on the first point places nothing: the pointer goes back to that point, so // the tool shows no circle. @@ -184,10 +327,27 @@ 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 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![]; + } match self.first { None => { let at = self.snap.press(cx, ev.pos, &[], None); @@ -207,7 +367,28 @@ 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. + // 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); + 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); + 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); let leave = Leave::segment(cx, *at, ev.mods.shift); @@ -230,6 +411,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 { .. }), ..) => { @@ -296,22 +487,33 @@ 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) { - let path = shapes::ellipse(Rect::new(c.x - r, c.y - r, c.x + r, c.y + r)).to_bezpath(); + if let Some((c, r)) = drawn_circle(&points, self.options.standard_anchors) { + // 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); 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)) { + } 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()) { @@ -323,6 +525,43 @@ 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, + }) + } + + /// 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) { + 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 9d68bdbe27..4e700b6c3b 100644 --- a/crates/tools/src/circle/tests.rs +++ b/crates/tools/src/circle/tests.rs @@ -94,6 +94,302 @@ 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 `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] +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())); + // 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 +/// 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, 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. +#[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(())); + // 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"), + (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}"); + assert_eq!(tool.check_options(bad.as_object().unwrap()), Err(error.to_string()), "{bad}"); + } +} + /// A drag ends where it is let go, also when the release is away from the last drag: from a first /// press, from a second press, and from a press on the first point. A release within 2 screen /// points of a second press is still a click and keeps the point of the press. @@ -288,8 +584,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 diff --git a/crates/tools/src/settings.rs b/crates/tools/src/settings.rs index 3d3f2a3873..e4b67e6a9f 100644 --- a/crates/tools/src/settings.rs +++ b/crates/tools/src/settings.rs @@ -78,6 +78,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 12e0001944..8088413aa6 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -25,6 +25,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_group_options; pub mod color_guide_options; @@ -472,6 +473,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, ThreePointArcOptions: [three_point_arc_options::KIND] => three_point_arc_options::SPEC, FlareOptions: [flare_options::KIND] => flare_options::SPEC, SymbolOptions: [symbol_options::KIND] => symbol_options::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 1f8936e58e..74994c3bff 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -489,6 +489,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 974634b503..ce8525f5ae 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -4860,6 +4860,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 fabf012149..ea9ec485c2 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -734,6 +734,10 @@ arrowhead Target Diana Cusp Punta Straight segment Segment recte 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 4978a4c2be..a5c97c3b03 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -4969,6 +4969,10 @@ font-technology Variable Variabilní Cusp Hrot Straight segment Přímý segment 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 fa53829311..a229de4928 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -7415,6 +7415,10 @@ font-technology Variable Variable Cusp Spids Straight segment Lige segment 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 3e756045e6..90c70f1ee3 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -484,6 +484,11 @@ font-technology Variable Variabel Cusp Spitze Straight segment Gerades Segment 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 4b7b7b8324..f601852045 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -477,6 +477,10 @@ font-technology Variable Μεταβλητές Cusp Ακίδα Straight segment Ευθύ τμήμα 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 90d9a15aef..3e0dadcb54 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -507,6 +507,10 @@ font-technology Variable Variables Cusp Cúspide Straight segment Segmento recto 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 f4b1ec8db1..5dcd46d094 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -4879,6 +4879,10 @@ font-technology Variable Muuttuvat Cusp Kärki Straight segment Suora segmentti 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 c03693c7f7..40efa3ef79 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -508,6 +508,10 @@ font-technology Variable Variables Cusp Point de rebroussement Straight segment Segment droit 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 c3fb620344..2e4bf62f47 100644 --- a/crates/ui-egui/src/i18n/gu.tsv +++ b/crates/ui-egui/src/i18n/gu.tsv @@ -606,6 +606,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 64a3d21ddc..466f8fdf0f 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -1108,6 +1108,10 @@ arrowhead Feather पंख Cusp नुकीला बिंदु Straight segment सीधा सेगमेंट 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 c028eeade9..c9e681dbf0 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -673,6 +673,10 @@ arrowhead Target Céltábla Cusp Csúcspont Straight segment Egyenes szakasz 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 84d283408d..4bea0e4413 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -5281,6 +5281,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 c43360435b..b33bcfeea8 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -509,6 +509,11 @@ font-technology Variable Variabili Cusp Cuspide Straight segment Segmento diritto 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 7d16db8581..3f5f335d6e 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -1415,6 +1415,11 @@ antiAlias Sharp シャープ Cusp 尖点 Straight segment 直線セグメント 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 e1eea3c5b7..38a56301a8 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -6671,6 +6671,10 @@ font-technology Variable ცვლადი Cusp წვეტი Straight segment სწორი სეგმენტი 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 ab4f55e562..cb4079e771 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -1405,6 +1405,11 @@ antiAlias Sharp 날카롭게 Cusp 뾰족점 Straight segment 직선 세그먼트 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 6b0380cfc6..a9915989b9 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -5283,6 +5283,10 @@ font-technology Variable Variabel Cusp Keerpunt Straight segment Recht segment 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 9caa46f46f..cbb2a3142e 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -4813,6 +4813,11 @@ font-technology Variable Zmienne Cusp Ostrze Straight segment Prosty segment 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 0db13e6f05..a45f12e4db 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -474,6 +474,10 @@ antiAlias Sharp Nítido Cusp Cúspide Straight segment Segmento reto 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 cc44602666..bd9ae4b521 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -505,6 +505,10 @@ font-technology Variable Вариативные Cusp Точка возврата Straight segment Прямой сегмент 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 0a64e62411..4c8ad7a4a8 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -496,6 +496,10 @@ font-technology Variable Variabla Cusp Spets Straight segment Rakt segment 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 4285ea4e63..f16f412d8c 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -489,6 +489,10 @@ font-technology Variable Değişken Cusp Sivri nokta Straight segment Düz segment 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 245c3aa686..7fae63b67e 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -503,6 +503,11 @@ font-technology Variable Варіативні Cusp Точка звороту Straight segment Прямий сегмент 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 7b20e4e0cc..c407a0ee6b 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -587,6 +587,11 @@ font-technology Variable Biến thiên Cusp Điểm lùi Straight segment Đoạn thẳng 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 67c8ac5d9d..a3598b5318 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -456,6 +456,10 @@ antiAlias Sharp 锐利 Cusp 尖点 Straight segment 直线段 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 87ccb8c676..eaad44fa35 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -471,6 +471,11 @@ font-technology Variable 可變 Cusp 尖點 Straight segment 直線段 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 d1db926bf9..24b43b4409 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -1157,7 +1157,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 (the tool whose options show; the Tool row changes it), diameter (pt), intensity and density (1–10), usePressure, method: userDefined|average|random (not used by the Sprayer and the Shifter), showBrush, sprayScrunch, spraySize, spraySpin, sprayScreen, sprayStain and sprayStyle: average|userDefined (the Symbol Sprayer's), proportional and affectsDensity (the Symbol Sizer's), shared by the eight tools; OK runs tool.setOption {tool, values}, after symbol.setDensity from the density the dialog opened with to the new one when symbol sets are selected and it changed), 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 (the tool whose options show; the Tool row changes it), diameter (pt), intensity and density (1–10), usePressure, method: userDefined|average|random (not used by the Sprayer and the Shifter), showBrush, sprayScrunch, spraySize, spraySpin, sprayScreen, sprayStain and sprayStyle: average|userDefined (the Symbol Sprayer's), proportional and affectsDensity (the Symbol Sizer's), shared by the eight tools; OK runs tool.setOption {tool, values}, after symbol.setDensity from the density the dialog opened with to the new one when symbol sets are selected and it changed), 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 f7935c2fd5..20aa11a7f0 100644 --- a/crates/ui-egui/src/toolbar.rs +++ b/crates/ui-egui/src/toolbar.rs @@ -438,7 +438,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 { @@ -475,6 +475,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 Three-Point Arc tool: whether the third point gives a direction. vectorcraft_tools::three_point_arc::ID => Ok(crate::dialogs::three_point_arc_options::open(app)), // The Flare tool: its options, which draw the next flare (OK draws none); with flares diff --git a/docs/mcp.md b/docs/mcp.md index c2a9b4c552..5c5753d894 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -7119,8 +7119,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, @@ -7130,6 +7131,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 @@ -7145,6 +7152,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