From 78b1c6bf091c359724501071beae623f681e1247 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 10:19:38 -0800 Subject: [PATCH 01/78] Shapes: draw the circle through three points shape.circleThroughPoints draws the circle whose edge passes through three points, as a live ellipse with the current paint, in one undo step. The points come from `points` or, when it is left out, from the three selected anchor points: anchor points selected with Direct Selection, or all the anchor points of a path selected whole. The ends of selected segments do not count. The result gives the circle's center and radius. The circle is not pixel-aligned, even while Align New Objects to Pixel Grid is on, so it stays through the points. Two points that are the same, or three on one line (twice the triangle's area at most 1e-10 of its longest side squared), are refused with a message and nothing is drawn. The center is computed from the corner opposite the longest side, so nearly collinear points and points far from the origin keep their precision. With the Ellipse tool, the first two Shift-clicks place points and the third draws the circle through the three. After two points the tool previews the circle through the snapped pointer as a dashed outline; the preview goes when the pointer leaves the canvas. Once a point is placed, a Shift-click on the selection's handles or shape widgets places a point too. Escape, a click without Shift, a drag, a press without Shift on the selection or a shape widget, and an edit, Undo or Redo made outside the tool remove the points placed so far. A Shift-click without a drag used to open the size dialog, as a plain click does; a plain click still opens it, and so does a Shift-click while the perspective grid shows with an active plane, so that shape still goes on the plane. Docs: docs/mcp.md, ROADMAP. Messages translated in the 24 catalogs with complete messages. --- ROADMAP.md | 1 + crates/engine/src/cmd/create.rs | 99 ++++++++- crates/engine/src/cmd/plugin_call/reviewed.rs | 1 + crates/engine/src/tests.rs | 1 + crates/engine/src/tests/circle_through.rs | 209 ++++++++++++++++++ crates/geom/src/shapes.rs | 68 ++++++ crates/tools/src/shape.rs | 120 ++++++++-- crates/tools/src/shape/tests.rs | 184 +++++++++++++++ crates/ui-egui/src/i18n/ca.tsv | 3 + crates/ui-egui/src/i18n/cs.tsv | 3 + crates/ui-egui/src/i18n/da.tsv | 3 + crates/ui-egui/src/i18n/de.tsv | 3 + crates/ui-egui/src/i18n/el.tsv | 3 + crates/ui-egui/src/i18n/es.tsv | 3 + crates/ui-egui/src/i18n/fi.tsv | 3 + crates/ui-egui/src/i18n/fr.tsv | 3 + crates/ui-egui/src/i18n/hi.tsv | 3 + crates/ui-egui/src/i18n/hu.tsv | 3 + crates/ui-egui/src/i18n/it.tsv | 3 + crates/ui-egui/src/i18n/ja.tsv | 3 + crates/ui-egui/src/i18n/ka.tsv | 3 + crates/ui-egui/src/i18n/ko.tsv | 3 + crates/ui-egui/src/i18n/nl.tsv | 3 + crates/ui-egui/src/i18n/pl.tsv | 3 + crates/ui-egui/src/i18n/pt-br.tsv | 3 + crates/ui-egui/src/i18n/ru.tsv | 3 + crates/ui-egui/src/i18n/sv.tsv | 3 + crates/ui-egui/src/i18n/tr.tsv | 3 + crates/ui-egui/src/i18n/uk.tsv | 3 + crates/ui-egui/src/i18n/vi.tsv | 3 + crates/ui-egui/src/i18n/zh-hans.tsv | 3 + crates/ui-egui/src/i18n/zh-hant.tsv | 3 + docs/mcp.md | 23 ++ 33 files changed, 758 insertions(+), 20 deletions(-) create mode 100644 crates/engine/src/tests/circle_through.rs diff --git a/ROADMAP.md b/ROADMAP.md index ec3f6e9c76..253c7ef45f 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -134,6 +134,7 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap - 2026-11-05: Release Type on a Path joins the Type Tools add-on (Object › Plug-ins › Type Tools): each selected type on a path splits into point type with the same text and attributes, on one straight line starting where its first character sat, and the plain path it was set on, with its exact shape and place in the stacking order and no paint; or keeps only the path or only the text, optionally leaving the original. A dialog with Preview, one undo step (`addon.type.releasePath`, #5532). A VectorCraft addition: headline numbers unchanged. - 2026-11-04: New Document: the units chosen in Preset Details now belong to the chosen document, as the pane's options are listed for the selected preset; the chosen card shows them, every other Recent and Saved card keeps the units its document or preset was made in, and the built-in tabs still follow the chosen units, so switching between inches and millimetres no longer restyles every recent template. Scores and estimates unchanged. - 2026-11-02: Mouse wheel over a closed font-family field in Character, Properties or Control changes selected text through the family list using saved font filters (excluding search text), one undo step per notch, stopping at the ends (#5253). Scores and estimates unchanged. +- 2026-11-15: Circle through three points: three Shift-clicks with the Ellipse tool, or `shape.circleThroughPoints` with three points or three selected anchor points, draw the circle whose edge passes through them, with the current paint, in one undo step; after two points the tool previews the circle through the pointer, and two points that are the same or three on one line are refused with a message. Scores and estimates unchanged. - 2026-10-31: Pattern libraries: Window › Swatch Libraries › Patterns and the Swatches panel's library menu open Geometric Patterns, a built-in library of eleven pattern swatches (dots, stripes, checks, a grid and shapes); clicking one adds its pattern and swatch to the document, once, and applies it to the active fill or stroke (`swatch.library.add`). - 2026-11-11: Pattern libraries: Patterns › Grit Textures, a second built-in pattern library, holds eight seamless black textures (Fine Grain, Coarse Grit, Sand, Speckle, Stipple, Scratches, Sparse Flecks and Dense Flecks) on tiles of 18 to 36 pt, each drawn the same way every time; marks that reach past a tile edge continue on the next tile, so the tiles join without a seam (`swatch.library.add`). Scores and estimates unchanged. - 2026-11-11: Pattern libraries: Patterns › Optical Effects, a third built-in pattern library, of VectorCraft's own designs, holds eight black wave, moiré and op-art tiles (Sine Bands, Ripple Lines, Interference Rings, Offset Rings, Warped Checks, Pinched Stripes, Chevron Pulse and Radiating Lenses) of 32 to 48 pt, each drawn the same way every time; each tile is one period of its design, and art that reaches past a tile edge continues on the next tile, so the tiles join without a seam (`swatch.library.add`). Scores and estimates unchanged. diff --git a/crates/engine/src/cmd/create.rs b/crates/engine/src/cmd/create.rs index 08944940a2..9c6e042e9e 100644 --- a/crates/engine/src/cmd/create.rs +++ b/crates/engine/src/cmd/create.rs @@ -57,6 +57,15 @@ pub fn specs() -> Vec { has_doc, flare ), + cmd!( + "shape.circleThroughPoints", + "Circle Through Points", + [], + None, + "{points?: [[x, y], [x, y], [x, y]] (left out: the 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 three points, not pixel-aligned even while Align New Objects to Pixel Grid is on; two points that are the same or three on one line are an error, and nothing is drawn", + has_doc, + circle_through_points + ), cmd!("shape.line", "Line Segment", [], None, "{x1, y1, x2, y2, fill?: bool (Fill Line: the current fill, else none)} → {id}", has_doc, line), cmd!("shape.spiral", "Spiral", [], None, "{cx, cy, radius, decay=80 (%), segments=10, clockwise?} → {id}", has_doc, spiral), cmd!( @@ -131,14 +140,21 @@ pub(crate) fn add_look(s: &mut Session, label: &str, kind: NodeKind, look: NewAr /// [`add_look`] that selects the new object only when `select` is set; otherwise the selection /// stays as it was. pub(crate) fn insert_look(s: &mut Session, label: &str, kind: NodeKind, look: NewArt, name: Option, select: bool) -> Result { - insert_look_turned(s, label, kind, look, name, select, 0.0) + insert_look_turned(s, label, kind, look, name, select, 0.0, true) } /// [`add_art`] for an object made turned by a `rotation` param (degrees, clockwise on the page): /// its bounding box turns with it, as after the Rotate tool. fn add_art_turned(s: &mut Session, label: &str, kind: NodeKind, rotation: f64) -> Result { let look = s.new_art_look(s.paint.fill.clone(), s.paint.stroke.clone(), s.paint.stroke_width); - insert_look_turned(s, label, kind, look, None, true, bbox_turn(rotation)) + insert_look_turned(s, label, kind, look, None, true, bbox_turn(rotation), true) +} + +/// [`add_art`] for an object whose geometry must stay where it was computed: it is not +/// pixel-aligned, even while the document's Align New Objects to Pixel Grid is on. +fn add_art_unaligned(s: &mut Session, label: &str, kind: NodeKind) -> Result { + let look = s.new_art_look(s.paint.fill.clone(), s.paint.stroke.clone(), s.paint.stroke_width); + insert_look_turned(s, label, kind, look, None, true, 0.0, false) } /// The bounding-box angle (counter-clockwise, as `Node::bbox_angle` and the Rotate tool keep it) @@ -162,8 +178,10 @@ fn constrained_turn(s: &Session, rotation: f64) -> f64 { } } -/// [`insert_look`] with the new object's bounding box turned to `bbox_angle`. A new path or -/// compound path is pixel-aligned while the document's Align New Objects to Pixel Grid is on. +/// [`insert_look`] with the new object's bounding box turned to `bbox_angle`. With `align`, a new +/// path or compound path is pixel-aligned while the document's Align New Objects to Pixel Grid is +/// on. +#[allow(clippy::too_many_arguments)] fn insert_look_turned( s: &mut Session, label: &str, @@ -172,6 +190,7 @@ fn insert_look_turned( name: Option, select: bool, bbox_angle: f64, + align: bool, ) -> Result { let parent = s.doc()?.target_parent()?; let mode = s.draw_mode; @@ -181,7 +200,9 @@ fn insert_look_turned( let id = d.alloc_id(); let mut n = Node::new(id, kind); look.apply(d, &mut n); - super::object::align_new_object(d, &mut n); + if align { + super::object::align_new_object(d, &mut n); + } n.name = name; n.bbox_angle = bbox_angle; let mut into = None; @@ -368,6 +389,71 @@ fn ellipse(s: &mut Session, p: &Value) -> Result { add_art_turned(s, "Ellipse", path_kind(live.to_path(), Some(live)), f64_or(p, "rotation", 0.0)) } +/// A live ellipse whose edge passes through three points: `points`, or the three selected anchor +/// points ([`selected_anchor_points`]). 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) => three_points(v).ok_or_else(|| bad(C, "`points` must be three [x, y] pairs of numbers"))?, + None => selected_anchor_points(s)?.ok_or_else(|| bad(C, "direct-select three anchor points, or give `points`"))?, + }; + let [a, b, c] = points; + let (center, radius) = shapes::circle_through(a, b, c) + .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)))?; + out["cx"] = json!(center.x); + out["cy"] = json!(center.y); + out["radius"] = json!(radius); + Ok(out) +} + +/// The three points `[[x, y], [x, y], [x, y]]` holds, each pair two finite numbers. +fn three_points(v: &Value) -> Option<[Point; 3]> { + let pair = |v: &Value| match v.as_array().map(Vec::as_slice) { + Some([x, y]) => x.as_f64().zip(y.as_f64()).filter(|(x, y)| x.is_finite() && y.is_finite()).map(|(x, y)| Point::new(x, y)), + _ => None, + }; + match v.as_array().map(Vec::as_slice) { + Some([a, b, c]) => Some([pair(a)?, pair(b)?, pair(c)?]), + _ => None, + } +} + +/// The positions of the selected anchor points, when there are exactly three. They are counted as +/// the other anchor commands count them ([`super::path::anchor_targets`]): a selected path with +/// anchors picked by Direct Selection gives those, and a path selected whole gives all of its own. +/// A selected segment's ends are not selected anchor points, so a selection with segments gives +/// none; so does a selection holding an object that is not a path, or an anchor that is gone. +fn selected_anchor_points(s: &Session) -> Result> { + let st = s.doc()?; + if st.selection.segments.values().any(|set| !set.is_empty()) { + return Ok(None); + } + let mut points = Vec::with_capacity(4); + for id in &st.selection.objects { + let Some(pd) = st.doc.node(*id).and_then(|n| n.path_data()) else { return Ok(None) }; + match st.selection.anchors.get(id) { + Some(set) => { + for &(si, ai) in set.iter().take(4) { + let Some(a) = pd.subpaths.get(si).and_then(|sp| sp.anchors.get(ai)) else { return Ok(None) }; + points.push(a.p); + } + } + None => points.extend(pd.anchors().take(4).map(|(_, _, a)| a.p)), + } + if points.len() > 3 { + return Ok(None); + } + } + Ok(match points.as_slice() { + &[a, b, c] => Some([a, b, c]), + _ => None, + }) +} + /// The whole-number count `p` gives for `key` (`5` or `5.0`), or `default` when it is left out or /// null. A fraction, a negative, a non-finite or a non-number is an error rather than the default. fn count_or(p: &Value, key: &str, default: u64, cmd: &str) -> Result { @@ -781,7 +867,8 @@ fn text_create(s: &mut Session, p: &Value) -> Result { // Lays the text out (and sizes an Auto Size frame). super::typecmd::refresh_bounds(&mut t); } - let made = insert_look_turned(s, "Type", NodeKind::Text(Box::new(t)), NewArt::plain(Appearance::default()), None, true, bbox_turn(rotation))?; + let made = + insert_look_turned(s, "Type", NodeKind::Text(Box::new(t)), NewArt::plain(Appearance::default()), None, true, bbox_turn(rotation), true)?; let id = made.get("id").and_then(Value::as_u64).map(NodeId); let made = super::typecmd::with_bounds(s, id, made); let mut made = super::typecmd::with_overflow(s, id.as_slice(), made); diff --git a/crates/engine/src/cmd/plugin_call/reviewed.rs b/crates/engine/src/cmd/plugin_call/reviewed.rs index 67d0fec2a3..a269ace561 100644 --- a/crates/engine/src/cmd/plugin_call/reviewed.rs +++ b/crates/engine/src/cmd/plugin_call/reviewed.rs @@ -542,6 +542,7 @@ pub(super) const ALLOWED: &[&str] = &[ "select.toggle", "select.update", "shape.arc", + "shape.circleThroughPoints", "shape.ellipse", "shape.flare", "shape.line", diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 1b420d7805..2c475c87d4 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -24,6 +24,7 @@ mod build; mod cancel; mod caret_kerning; mod charstroke; +mod circle_through; pub(super) mod clip; mod clipboard; mod clipflavours; diff --git a/crates/engine/src/tests/circle_through.rs b/crates/engine/src/tests/circle_through.rs new file mode 100644 index 0000000000..25fcc04beb --- /dev/null +++ b/crates/engine/src/tests/circle_through.rs @@ -0,0 +1,209 @@ +//! `shape.circleThroughPoints`: a circle through three given points, or through the three anchor +//! points selected with Direct Selection, and the Ellipse tool's three Shift-clicks that run it. + +use serde_json::{Value, json}; +use vectorcraft_doc::{LiveShape, Node, NodeKind}; +use vectorcraft_geom::Point; +use vectorcraft_tools::{Mods, PointerEvent, PointerKind, ToolKey}; + +use crate::*; + +const C: &str = "shape.circleThroughPoints"; + +fn session() -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap(); + s +} + +fn node(s: &Session, id: NodeId) -> Node { + s.doc().unwrap().doc.node(id).unwrap().clone() +} + +fn undo_len(s: &Session) -> usize { + s.doc().unwrap().history.undo.len() +} + +fn object_count(s: &Session) -> usize { + let mut n = 0; + s.doc().unwrap().doc.walk(|_| n += 1); + n +} + +fn id_of(v: &Value) -> NodeId { + NodeId(v["id"].as_u64().unwrap()) +} + +/// Whether the geometric bounds of `id` are `want` to within 10⁻⁹ pt. +fn bounds_are(s: &Session, id: NodeId, want: vectorcraft_geom::Rect) -> bool { + let b = s.doc().unwrap().doc.bounds_of(&[id], false).unwrap(); + [(b.x0, want.x0), (b.y0, want.y0), (b.x1, want.x1), (b.y1, want.y1)].iter().all(|(a, w)| (a - w).abs() < 1e-9) +} + +/// The largest distance of `points` from the path of `id`. +fn farthest_from_path(s: &Session, id: NodeId, points: &[Point]) -> f64 { + let n = node(s, id); + let path = n.path_data().unwrap(); + points.iter().map(|p| path.nearest(*p).unwrap().4).fold(0.0, f64::max) +} + +/// (0, 0), (80, 0) and (0, 60) lie on the circle centered at (40, 30) with radius 50 (their +/// right angle stands on the diameter). The circle is a live ellipse with the current paint, is +/// selected, passes through the points to within the four-curve circle's error (about 0.03% of the +/// radius), and one undo removes it. +#[test] +fn the_circle_through_three_given_points_is_exact_and_one_undo_step() { + let mut s = session(); + let reference = id_of(&s.execute("shape.ellipse", &json!({"x": 200, "y": 200, "width": 10, "height": 10})).unwrap()); + let undo = undo_len(&s); + let points = [Point::new(0.0, 0.0), Point::new(80.0, 0.0), Point::new(0.0, 60.0)]; + let out = s.execute(C, &json!({"points": [[0, 0], [80, 0], [0, 60]]})).unwrap(); + assert_eq!((out["cx"].as_f64(), out["cy"].as_f64(), out["radius"].as_f64()), (Some(40.0), Some(30.0), Some(50.0)), "{out}"); + let id = id_of(&out); + let n = node(&s, id); + match &n.kind { + NodeKind::Path { live: Some(live), .. } => match live.as_ref() { + LiveShape::Ellipse { w, h, pie, .. } => assert_eq!((*w, *h, *pie), (100.0, 100.0, (0.0, 360.0))), + other => panic!("not a live ellipse: {other:?}"), + }, + other => panic!("not a live shape: {other:?}"), + } + assert!(bounds_are(&s, id, vectorcraft_geom::Rect::new(-10.0, -20.0, 90.0, 80.0))); + assert!(farthest_from_path(&s, id, &points) < 50.0 * 3e-4, "{}", farthest_from_path(&s, id, &points)); + assert_eq!(n.appearance, node(&s, reference).appearance, "the current paint, as the Ellipse tool draws"); + assert_eq!(s.doc().unwrap().selection.objects, [id]); + assert_eq!(undo_len(&s), undo + 1); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(s.doc().unwrap().doc.node(id).is_none()); +} + +/// Two points that are the same, or three on one line, are refused with a message; nothing is +/// drawn and no undo step is recorded. Points nearly on one line still give their circle. +#[test] +fn coincident_or_collinear_points_are_refused() { + let mut s = session(); + let (undo, count) = (undo_len(&s), object_count(&s)); + for points in [json!([[10, 10], [10, 10], [50, 80]]), json!([[0, 0], [50, 50], [100, 100]]), json!([[5, 5], [5, 5], [5, 5]])] { + let e = s.execute(C, &json!({ "points": points })).unwrap_err().to_string(); + assert!(e.contains("no circle passes through these points"), "{points}: {e}"); + assert_eq!((undo_len(&s), object_count(&s)), (undo, count), "{points}"); + } + // 0.01 pt off a chord 200 pt long: the sagitta formula r = (h² + (L/2)²) / 2h. + let out = s.execute(C, &json!({"points": [[100, 200], [300, 200], [200, 199.99]]})).unwrap(); + let want = (0.01f64 * 0.01 + 100.0 * 100.0) / 0.02; + let (cx, cy, r) = (out["cx"].as_f64().unwrap(), out["cy"].as_f64().unwrap(), out["radius"].as_f64().unwrap()); + assert!((r - want).abs() / want < 1e-9 && (cx - 200.0).abs() < 1e-6 && (cy - (199.99 + want)).abs() / want < 1e-9, "{out}"); +} + +/// Points that are not three pairs of finite numbers are an error, not a fallback. +#[test] +fn malformed_points_are_refused() { + let mut s = session(); + let undo = undo_len(&s); + for points in [ + json!([[0, 0], [10, 0]]), + json!([[0, 0], [10, 0], [0, 10], [5, 5]]), + json!([[0, 0], [10, 0], [0]]), + json!([[0, 0], [10, 0], ["0", 10]]), + json!("0,0 10,0 0,10"), + json!([[0, 0], [10, 0], [0, 10, 3]]), + ] { + let e = s.execute(C, &json!({ "points": points })).unwrap_err().to_string(); + assert!(e.contains("`points` must be three [x, y] pairs of numbers"), "{points}: {e}"); + } + assert_eq!(undo_len(&s), undo); +} + +/// With `points` left out, the three anchor points selected with Direct Selection give the +/// circle, from one path or several; any other number of them is an error. +#[test] +fn three_direct_selected_anchor_points_give_the_circle() { + let mut s = session(); + let anchors: Vec = [(0, 0), (80, 0), (0, 60), (50, 120)].iter().map(|(x, y)| json!({"x": x, "y": y})).collect(); + let path = id_of(&s.execute("path.create", &json!({ "anchors": anchors })).unwrap()); + s.execute("select.anchors", &json!({"id": path.0, "anchors": [[0, 0], [0, 1], [0, 2]], "mode": "set"})).unwrap(); + let out = s.execute(C, &json!({})).unwrap(); + assert_eq!((out["cx"].as_f64(), out["cy"].as_f64(), out["radius"].as_f64()), (Some(40.0), Some(30.0), Some(50.0)), "{out}"); + // Anchors of two paths. + let other = id_of(&s.execute("path.create", &json!({"anchors": [{"x": 0, "y": 60}, {"x": 0, "y": 200}]})).unwrap()); + s.execute("select.anchors", &json!({"id": path.0, "anchors": [[0, 0], [0, 1]], "mode": "set"})).unwrap(); + s.execute("select.anchors", &json!({"id": other.0, "anchors": [[0, 0]], "mode": "add"})).unwrap(); + let out = s.execute(C, &json!({"points": null})).unwrap(); + assert_eq!((out["cx"].as_f64(), out["cy"].as_f64()), (Some(40.0), Some(30.0)), "{out}"); + // Two or four anchors, or a path of four anchors selected whole. + for picked in [json!([[0, 0], [0, 1]]), json!([[0, 0], [0, 1], [0, 2], [0, 3]])] { + s.execute("select.anchors", &json!({"id": path.0, "anchors": picked, "mode": "set"})).unwrap(); + let e = s.execute(C, &json!({})).unwrap_err().to_string(); + assert!(e.contains("direct-select three anchor points, or give `points`"), "{picked}: {e}"); + } + s.execute("select.set", &json!({"ids": [path.0]})).unwrap(); + assert!(s.execute(C, &json!({})).is_err()); + // A path of three anchors selected whole counts all three, as the other anchor commands count + // them; with an object that is not a path also selected, there is no circle. + let triangle = id_of(&s.execute("path.create", &json!({"anchors": [{"x": 0, "y": 0}, {"x": 80, "y": 0}, {"x": 0, "y": 60}]})).unwrap()); + s.execute("select.set", &json!({"ids": [triangle.0]})).unwrap(); + let out = s.execute(C, &json!({})).unwrap(); + assert_eq!((out["cx"].as_f64(), out["cy"].as_f64(), out["radius"].as_f64()), (Some(40.0), Some(30.0), Some(50.0)), "{out}"); + s.execute("edit.undo", &json!({})).unwrap(); + let text = id_of(&s.execute("text.create", &json!({"x": 300, "y": 300, "text": "A"})).unwrap()); + s.execute("select.set", &json!({"ids": [triangle.0, text.0]})).unwrap(); + assert!(s.execute(C, &json!({})).is_err()); + let undo = undo_len(&s); + // Two selected segments hold three ends, which are not selected anchor points. + s.execute("select.segments", &json!({"id": path.0, "segments": [[0, 0], [0, 1]], "mode": "set"})).unwrap(); + assert_eq!(s.doc().unwrap().selection.anchors.get(&path).map(|a| a.len()), Some(3)); + let e = s.execute(C, &json!({})).unwrap_err().to_string(); + assert!(e.contains("direct-select three anchor points, or give `points`"), "{e}"); + assert_eq!(undo_len(&s), undo); +} + +/// With Align New Objects to Pixel Grid on, the circle is still drawn through the points: it is +/// not pixel-aligned, so the grid does not move it. +#[test] +fn the_circle_is_not_moved_onto_the_pixel_grid() { + let mut s = session(); + s.execute("document.setup", &json!({"alignNewObjectsToPixelGrid": true})).unwrap(); + 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 })).unwrap()); + assert!(farthest_from_path(&s, id, &points) < 51.0 * 3e-4, "{}", farthest_from_path(&s, id, &points)); + assert!(!node(&s, id).extras().pixel_aligned); +} + +fn view() -> ViewInfo { + ViewInfo { smart_guides: false, ..ViewInfo::default() } +} + +fn click(s: &mut Session, mods: Mods, x: f64, y: f64) { + for k in [PointerKind::Down, PointerKind::Up] { + s.pointer(&PointerEvent::new(k, x, y).with_mods(mods), view()).unwrap(); + } +} + +/// With the Ellipse tool, three Shift-clicks draw the circle through the three points, in one +/// undo step; Escape drops the points placed so far. +#[test] +fn three_shift_clicks_with_the_ellipse_tool_draw_the_circle_through_them() { + let mut s = session(); + s.select_tool("ellipse", view()).unwrap(); + let shift = Mods { shift: true, ..Mods::default() }; + let (undo, count) = (undo_len(&s), object_count(&s)); + click(&mut s, shift, 100.0, 100.0); + click(&mut s, shift, 180.0, 100.0); + assert_eq!((undo_len(&s), object_count(&s)), (undo, count), "two points draw nothing yet"); + click(&mut s, shift, 100.0, 160.0); + assert_eq!(undo_len(&s), undo + 1); + let id = *s.doc().unwrap().selection.objects.first().unwrap(); + assert!(bounds_are(&s, id, vectorcraft_geom::Rect::new(90.0, 80.0, 190.0, 180.0))); + // Escape after two points: the next three clicks start afresh. + click(&mut s, shift, 0.0, 0.0); + click(&mut s, shift, 10.0, 300.0); + s.tool_key(ToolKey::Escape, Mods::default(), view()).unwrap(); + click(&mut s, shift, 200.0, 200.0); + click(&mut s, shift, 280.0, 200.0); + let undo = undo_len(&s); + click(&mut s, shift, 200.0, 260.0); + assert_eq!(undo_len(&s), undo + 1); + let id = *s.doc().unwrap().selection.objects.first().unwrap(); + assert!(bounds_are(&s, id, vectorcraft_geom::Rect::new(190.0, 180.0, 290.0, 280.0))); +} diff --git a/crates/geom/src/shapes.rs b/crates/geom/src/shapes.rs index 0ae8a75190..8eb1a69e9c 100644 --- a/crates/geom/src/shapes.rs +++ b/crates/geom/src/shapes.rs @@ -296,6 +296,33 @@ fn contour_with_rounding(pts: &[Point], rounded: f64) -> PathData { PathData::single(SubPath::new(anchors, true)) } +/// The circle through the points `a`, `b` and `c`: its center and radius. `None` when two of the +/// points are the same or the three lie on one line, which this takes to be when twice the +/// triangle's area is at most 10⁻¹⁰ of its longest side squared. +pub fn circle_through(a: Point, b: Point, c: Point) -> Option<(Point, f64)> { + // The corner opposite the longest side is the origin, so the two shorter sides are used. + let (ab, bc, ca) = ((b - a).hypot2(), (c - b).hypot2(), (a - c).hypot2()); + let (o, p, q, longest) = if bc >= ab && bc >= ca { + (a, b, c, bc) + } else if ca >= ab { + (b, c, a, ca) + } else { + (c, a, b, ab) + }; + let (u, v) = (p - o, q - o); + let cross = u.cross(v); + // Not a number, or nearly zero: no circle (a not-a-number side fails the finite check below). + if cross.is_nan() || cross.abs() <= 1e-10 * longest { + return None; + } + let (uu, vv) = (u.hypot2(), v.hypot2()); + let d = 2.0 * cross; + let offset = Vec2::new((v.y * uu - u.y * vv) / d, (u.x * vv - v.x * uu) / d); + let center = o + offset; + let radius = offset.hypot(); + (center.is_finite() && radius.is_finite()).then_some((center, radius)) +} + /// 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); @@ -670,6 +697,47 @@ mod tests { assert!(ellipse_pie(r, f64::NAN, 10.0).anchor_count() == 4, "not a number: the whole ellipse"); } + /// The circle through three points against the closed form: (0, 0), (8, 0) and (0, 6) lie on + /// the circle with the hypotenuse (8, 0)–(0, 6) as its diameter, center (4, 3) and radius 5. + #[test] + fn the_circle_through_three_points_has_the_closed_form_center_and_radius() { + let (o, a, b) = (Point::ORIGIN, Point::new(8.0, 0.0), Point::new(0.0, 6.0)); + for (p, q, r) in [(o, a, b), (a, b, o), (b, o, a), (b, a, o)] { + let (c, radius) = circle_through(p, q, r).unwrap(); + assert!(c.distance(Point::new(4.0, 3.0)) < 1e-12 && (radius - 5.0).abs() < 1e-12, "{c:?} {radius}"); + } + // Moved far from the origin, the answer moves with the points. + let far = Vec2::new(3.0e6, -2.0e6); + let (c, radius) = circle_through(o + far, a + far, b + far).unwrap(); + assert!(c.distance(Point::new(4.0, 3.0) + far) < 1e-6 && (radius - 5.0).abs() < 1e-6, "{c:?} {radius}"); + } + + /// Two points that are the same, or three on one line, give no circle. + #[test] + fn coincident_or_collinear_points_give_no_circle() { + let (a, b) = (Point::new(1.0, 2.0), Point::new(5.0, 7.0)); + assert_eq!(circle_through(a, a, b), None); + assert_eq!(circle_through(a, b, b), None); + assert_eq!(circle_through(a, a, a), None); + assert_eq!(circle_through(a, b, a.midpoint(b)), None); + assert_eq!(circle_through(a, b, a + (b - a) * 3.0), None); + assert_eq!(circle_through(a, b, Point::new(f64::NAN, 0.0)), None); + } + + /// 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. + #[test] + fn nearly_collinear_points_give_a_stable_circle() { + let (a, b) = (Point::new(-1000.0, 0.0), Point::new(1000.0, 0.0)); + let h = 1e-4; + let (c, radius) = circle_through(a, b, Point::new(0.0, h)).unwrap(); + let want = (h * h + 1000.0 * 1000.0) / (2.0 * h); + assert!((radius - want).abs() / want < 1e-9, "{radius} vs {want}"); + assert!(c.x.abs() < 1e-6 && (c.y - (h - want)).abs() / want < 1e-9, "{c:?}"); + assert_eq!(circle_through(a, b, Point::new(0.0, 1e-12)), None); + } + #[test] fn rect_is_4_corners_clockwise() { let p = rectangle(Rect::new(0.0, 0.0, 100.0, 50.0)); diff --git a/crates/tools/src/shape.rs b/crates/tools/src/shape.rs index 66728b4826..e124139b54 100644 --- a/crates/tools/src/shape.rs +++ b/crates/tools/src/shape.rs @@ -8,6 +8,14 @@ //! the dragged corner snap to Smart Guides ([`DrawSnap`]), hovering before the press too. //! Escape cancels the drag and puts back the options its keys and Ctrl/Cmd changed. //! +//! With the Ellipse tool, three Shift-clicks draw the circle through the three points clicked +//! (`shape.circleThroughPoints`). Once a point is placed, a Shift-click on the selection's handles +//! or widgets places a point too. Escape, a click without Shift, a drag, a press without Shift on the +//! selection or a shape widget, and an edit, Undo or Redo made outside the tool drop the points +//! placed so far. +//! While the perspective grid shows with an active plane, a Shift-click opens the size dialog, as a +//! click does, and the shape goes on the plane. +//! //! The selection keeps its bounding box and its Live Shape widgets on show with the Rectangle, //! Rounded Rectangle, Ellipse, Polygon and Star tools, so a shape just drawn can be adjusted at //! once: a drag on a live rectangle's or polygon's corner widget rounds its corners and a drag on @@ -109,6 +117,26 @@ pub struct ShapeTool { /// The move of the selection snapped to a point, a guide or the grid at its last step: the /// arrow turns hollow, as the Selection tool's does. snapped: bool, + /// Ellipse tool: the points placed by Shift-clicks so far (fewer than three); the third + /// Shift-click draws the circle through them ([`circle_through_points`]). + through: Vec, + /// Where the pointer was last seen while `through` holds points, for the circle's preview. + hover: Option, + /// The press in progress came with Shift held, with the Ellipse tool and no active perspective + /// plane: a click places a point. + places_point: bool, +} + +/// Whether the perspective grid shows with an active plane: shapes then go on the plane. +fn perspective_plane_shown(cx: &ToolContext) -> bool { + let g = crate::distort::perspective::PerspectiveGrid::current(cx.doc); + g.visible && g.plane != crate::distort::perspective::Plane::None +} + +/// The command three Shift-clicks with the Ellipse tool run: the circle through their points. +fn circle_through_points(points: &[Point]) -> (String, Value) { + let pairs: Vec = points.iter().map(|p| json!([p.x, p.y])).collect(); + ("shape.circleThroughPoints".into(), json!({ "points": pairs })) } /// The options that keys and Ctrl/Cmd change while a shape is dragged out. @@ -159,9 +187,18 @@ impl ShapeTool { guides: vec![], measure: None, snapped: false, + through: vec![], + hover: None, + places_point: false, } } + /// Whether a press with `m` places another point for a circle: Shift with the Ellipse tool once + /// a point is placed. Such a press skips the selection's handles and widgets. + fn placing_point(&self, m: Mods) -> bool { + self.id == "ellipse" && m.shift && !self.through.is_empty() + } + fn drag_options(&self) -> DragOptions { DragOptions { sides: self.sides, points: self.points, corner_radius: self.corner_radius, star_ratio: self.star_ratio } } @@ -527,29 +564,39 @@ impl Tool for ShapeTool { match ev.kind { PointerKind::Move => { // Over a widget a press would drag, no Smart Guide for a new shape's start. - if self.over_widget(cx, ev.pos) - || self.over_handle(cx, ev.pos).is_some() - || self.over_center(cx, ev.pos) - || self.over_rotate(cx, ev.pos).is_some() + if !self.placing_point(ev.mods) + && (self.over_widget(cx, ev.pos) + || self.over_handle(cx, ev.pos).is_some() + || self.over_center(cx, ev.pos) + || self.over_rotate(cx, ev.pos).is_some()) { self.snap.clear(); + // A press there drags the widget or the selection, which drops the points. + self.hover = None; } else { - self.snap.hover(cx, ev.pos, &[], None); + // The snapped point: the third Shift-click lands where the press snaps. + let p = self.snap.hover(cx, ev.pos, &[], None); + self.hover = (!self.through.is_empty()).then_some(p); } vec![] } PointerKind::Down => { - if self.press_widget(cx, ev) { - self.snap.clear(); - return vec![]; - } - if let Some(out) = self.press_selection(cx, ev) { - return out; + if !self.placing_point(ev.mods) { + if self.press_widget(cx, ev) { + self.snap.clear(); + self.through.clear(); + return vec![]; + } + if let Some(out) = self.press_selection(cx, ev) { + self.through.clear(); + return out; + } } let p = self.snap.press(cx, ev.pos, &[], None); self.start = Some(p); self.last = ev.pos; self.began = false; + self.places_point = self.id == "ellipse" && ev.mods.shift && !perspective_plane_shown(cx); self.inner = None; self.before_drag = None; vec![] @@ -589,8 +636,20 @@ impl Tool for ShapeTool { self.before_drag = None; if self.began { self.began = false; + self.through.clear(); vec![Action::Commit] + } else if self.places_point { + // A Shift-click places a point; the third draws the circle through the three. + self.through.push(s); + self.hover = None; + if self.through.len() < 3 { + return vec![]; + } + let (c, v) = circle_through_points(&self.through); + self.through.clear(); + vec![Action::Exec(c, v)] } else { + self.through.clear(); // Alt (draw from centre) is passed on, so the size dialog can centre the shape on the click. let args = if ev.mods.alt { json!({ "x": s.x, "y": s.y, "alt": true }) } else { json!({ "x": s.x, "y": s.y }) }; vec![Action::Dialog(self.id.into(), args)] @@ -619,6 +678,12 @@ impl Tool for ShapeTool { _ => vec![], }; } + // Escape drops the points Shift-clicks placed for a circle; the document stays as it is. + if key == ToolKey::Escape && self.start.is_none() && !self.through.is_empty() { + self.through.clear(); + self.hover = None; + return vec![]; + } let Some(s) = self.start.filter(|_| self.began) else { return vec![] }; let changed = match (self.id, key) { ("polygon", ToolKey::Up) => { @@ -653,6 +718,7 @@ impl Tool for ShapeTool { } else if key == ToolKey::Escape { self.start = None; self.began = false; + self.through.clear(); self.inner = None; if let Some(o) = self.before_drag.take() { self.restore_drag_options(o); @@ -695,9 +761,23 @@ impl Tool for ShapeTool { match (&self.widget, &self.selection) { (Some(WidgetDrag::Corner(_)), _) => matches!(key, ToolKey::Up | ToolKey::Down), (_, Some(_)) => key == ToolKey::Escape, - _ => false, + _ => key == ToolKey::Escape && !self.through.is_empty(), } } + /// Points placed by Shift-clicks for a circle: Escape drops them. + fn ends_on_escape(&self, _cx: &ToolContext) -> bool { + !self.through.is_empty() + } + /// The pointer left the canvas: the circle's preview through it goes. + fn hover_ended(&mut self, _cx: &ToolContext) { + self.hover = None; + } + /// An edit, Undo or Redo made outside the tool, or another document, drops the points placed + /// for a circle. + fn history_moved(&mut self) { + self.through.clear(); + self.hover = None; + } /// The widget being dragged, the Smart Guides of the shape being drawn or the selection being /// moved, and its size, angle or offset label. fn overlays(&self, cx: &ToolContext) -> Vec { @@ -708,6 +788,17 @@ impl Tool for ShapeTool { } let mut o = self.snap.guides().to_vec(); o.extend(self.guides.iter().cloned()); + // The points Shift-clicks placed, and after two of them the circle through them and the + // pointer, dashed. + for p in &self.through { + o.push(Overlay::Anchor { p: *p, color: crate::draw2::FEEDBACK, filled: true, size: 6.0 }); + } + if let ([a, b], Some(h)) = (self.through.as_slice(), self.hover) + && let Some((c, r)) = vectorcraft_geom::shapes::circle_through(*a, *b, h) + { + let path = vectorcraft_geom::shapes::ellipse(Rect::new(c.x - r, c.y - r, c.x + r, c.y + r)).to_bezpath(); + o.push(Overlay::Path { path, color: crate::draw2::FEEDBACK, width: 1.0, dashed: true }); + } if let Some((p, text)) = &self.measure { o.push(Overlay::Measure { p: *p, text: text.clone() }); } @@ -763,8 +854,9 @@ impl Tool for ShapeTool { None => {} } // A press takes the corner and pie widgets first, then the box's handles, then the centre - // point, then the zone just outside a corner; everywhere else it draws a new shape. - if idle { + // point, then the zone just outside a corner; everywhere else it draws a new shape. A + // Shift-press that places another point for a circle skips them all. + if idle && !self.placing_point(m) { if shows_shape_widgets(self.id) && corners::over_widget(cx, p, false) { return Cursor::CornerRadius; } diff --git a/crates/tools/src/shape/tests.rs b/crates/tools/src/shape/tests.rs index c76eef404e..fe7eaa7ca5 100644 --- a/crates/tools/src/shape/tests.rs +++ b/crates/tools/src/shape/tests.rs @@ -251,6 +251,190 @@ fn click_opens_dialog() { assert_eq!(t.pointer(&cx, &PointerEvent::new(PointerKind::Up, 10.0, 10.0)), vec![Action::Dialog("star".into(), json!({"x": 10.0, "y": 10.0}))]); } +/// With the Ellipse tool, the first two Shift-clicks place points (shown as marks, and with two +/// placed, the circle through them and the pointer is previewed); the third runs the circle +/// command through the three. A Shift-click with another shape tool still opens its dialog. +#[test] +fn three_shift_clicks_with_the_ellipse_tool_run_the_circle_through_them() { + let (d, _) = doc_with_rect(); + let s = Selection::default(); + let p = paint(); + let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) }; + let shift = Mods { shift: true, ..Default::default() }; + let mut t = ShapeTool::new("ellipse"); + let click = |t: &mut ShapeTool, x: f64, y: f64| { + t.pointer(&cx, &PointerEvent::new(PointerKind::Down, x, y).with_mods(shift)); + t.pointer(&cx, &PointerEvent::new(PointerKind::Up, x, y).with_mods(shift)) + }; + assert_eq!(click(&mut t, 10.0, 10.0), vec![]); + assert_eq!(click(&mut t, 90.0, 10.0), vec![]); + assert!(t.ends_on_escape(&cx) && t.claims_key(&cx, ToolKey::Escape)); + t.pointer(&cx, &PointerEvent::new(PointerKind::Move, 10.0, 70.0)); + let o = t.overlays(&cx); + assert_eq!(o.iter().filter(|o| matches!(o, Overlay::Anchor { .. })).count(), 2, "{o:?}"); + let preview = o.iter().find_map(|o| match o { + Overlay::Path { path, dashed: true, .. } => Some(path.clone()), + _ => None, + }); + let b = vectorcraft_geom::Shape::bounding_box(&preview.expect("the circle is previewed")); + assert!(b.x0.abs() < 1e-9 && (b.y0 + 10.0).abs() < 1e-9 && (b.x1 - 100.0).abs() < 1e-9 && (b.y1 - 90.0).abs() < 1e-9, "{b:?}"); + assert_eq!( + click(&mut t, 10.0, 70.0), + vec![Action::Exec("shape.circleThroughPoints".into(), json!({"points": [[10.0, 10.0], [90.0, 10.0], [10.0, 70.0]]}))] + ); + assert!(!t.ends_on_escape(&cx) && t.overlays(&cx).is_empty()); + // Another shape tool keeps its dialog on a Shift-click. + let mut r = ShapeTool::new("rectangle"); + assert_eq!(click(&mut r, 10.0, 10.0), vec![Action::Dialog("rectangle".into(), json!({"x": 10.0, "y": 10.0}))]); +} + +/// With Smart Guides on, the preview passes through the point the pointer snaps to, which is where +/// the third Shift-click lands. +#[test] +fn the_circle_preview_passes_through_the_snapped_pointer() { + let (d, _) = doc_with_rect(); + let s = Selection::default(); + let p = paint(); + let cx = cx(&d, &s, &p); + let shift = Mods { shift: true, ..Default::default() }; + let mut t = ShapeTool::new("ellipse"); + for (x, y) in [(300.0, 0.0), (300.0, 200.0)] { + t.pointer(&cx, &PointerEvent::new(PointerKind::Down, x, y).with_mods(shift)); + t.pointer(&cx, &PointerEvent::new(PointerKind::Up, x, y).with_mods(shift)); + } + // Near the rectangle's corner anchor at (100, 100): the circle through (300, 0), (300, 200) + // and (100, 100) has its center at (225, 100) and radius 125. + t.pointer(&cx, &PointerEvent::new(PointerKind::Move, 98.0, 102.0)); + let preview = t.overlays(&cx).into_iter().find_map(|o| match o { + Overlay::Path { path, dashed: true, .. } => Some(path), + _ => None, + }); + let b = vectorcraft_geom::Shape::bounding_box(&preview.expect("the circle is previewed")); + let want = [100.0, -25.0, 350.0, 225.0]; + assert!([b.x0, b.y0, b.x1, b.y1].iter().zip(want).all(|(a, w)| (a - w).abs() < 1e-9), "{b:?}"); + t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 98.0, 102.0).with_mods(shift)); + let a = t.pointer(&cx, &PointerEvent::new(PointerKind::Up, 98.0, 102.0).with_mods(shift)); + assert!(matches!(&a[..], [Action::Exec(_, v)] if v["points"][2] == json!([100.0, 100.0])), "{a:?}"); +} + +/// Escape, a plain click and a drag drop the points Shift-clicks placed, so the next Shift-click +/// starts a new circle. +#[test] +fn escape_a_click_or_a_drag_drops_the_shift_clicked_points() { + let (d, _) = doc_with_rect(); + let s = Selection::default(); + let p = paint(); + let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) }; + let shift = Mods { shift: true, ..Default::default() }; + let mut t = ShapeTool::new("ellipse"); + let shift_click = |t: &mut ShapeTool, x: f64, y: f64| { + t.pointer(&cx, &PointerEvent::new(PointerKind::Down, x, y).with_mods(shift)); + t.pointer(&cx, &PointerEvent::new(PointerKind::Up, x, y).with_mods(shift)) + }; + shift_click(&mut t, 10.0, 10.0); + shift_click(&mut t, 90.0, 10.0); + assert_eq!(t.key(&cx, ToolKey::Escape, Mods::default()), vec![]); + assert!(!t.ends_on_escape(&cx)); + shift_click(&mut t, 10.0, 10.0); + shift_click(&mut t, 90.0, 10.0); + t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 50.0, 50.0)); + assert_eq!( + t.pointer(&cx, &PointerEvent::new(PointerKind::Up, 50.0, 50.0)), + vec![Action::Dialog("ellipse".into(), json!({"x": 50.0, "y": 50.0}))] + ); + assert!(!t.ends_on_escape(&cx), "a plain click drops them"); + shift_click(&mut t, 10.0, 10.0); + t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 50.0, 50.0).with_mods(shift)); + t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 90.0, 90.0).with_mods(shift)); + assert_eq!(t.pointer(&cx, &PointerEvent::new(PointerKind::Up, 90.0, 90.0).with_mods(shift)), vec![Action::Commit]); + assert!(!t.ends_on_escape(&cx), "a Shift-drag draws a circle and drops them"); + // A move of the selection by its centre point drops them too. + let (d, s) = unfilled_live_rect(); + let c = ToolContext { smart_guides: false, ..crate::testutil::cx(&d, &s, &p) }; + let mut t = ShapeTool::new("ellipse"); + for (x, y) in [(10.0, 10.0), (90.0, 10.0)] { + t.pointer(&c, &PointerEvent::new(PointerKind::Down, x, y).with_mods(shift)); + t.pointer(&c, &PointerEvent::new(PointerKind::Up, x, y).with_mods(shift)); + } + assert!(t.ends_on_escape(&c)); + t.pointer(&c, &PointerEvent::new(PointerKind::Down, 150.0, 150.0)); + t.pointer(&c, &PointerEvent::new(PointerKind::Drag, 170.0, 160.0)); + assert_eq!(t.pointer(&c, &PointerEvent::new(PointerKind::Up, 170.0, 160.0)), vec![Action::Commit]); + assert!(!t.ends_on_escape(&c), "a move of the selection drops them"); +} + +/// Once a point is placed, a Shift-click on the selection's side handle or centre point places a +/// point instead of scaling or moving the selection, and the cursor over them is the crosshair. +#[test] +fn shift_clicks_on_the_selection_place_points_once_one_is_placed() { + let (d, s) = unfilled_live_rect(); + let p = paint(); + let c = ToolContext { smart_guides: false, ..cx(&d, &s, &p) }; + let shift = Mods { shift: true, ..Default::default() }; + let mut t = ShapeTool::new("ellipse"); + let centre = Point::new(150.0, 150.0); + assert_eq!(t.cursor(&c, centre, shift), Cursor::Move, "no point placed yet: the centre point moves"); + let click = |t: &mut ShapeTool, x: f64, y: f64| { + t.pointer(&c, &PointerEvent::new(PointerKind::Down, x, y).with_mods(shift)); + t.pointer(&c, &PointerEvent::new(PointerKind::Up, x, y).with_mods(shift)) + }; + assert_eq!(click(&mut t, 10.0, 10.0), vec![]); + assert_eq!(t.cursor(&c, centre, shift), Cursor::Crosshair); + assert_eq!(t.cursor(&c, centre, Mods::default()), Cursor::Move, "without Shift a press still moves the selection"); + assert_eq!(click(&mut t, 100.0, 150.0), vec![], "the left side handle"); + assert!(!t.busy()); + assert_eq!( + click(&mut t, centre.x, centre.y), + vec![Action::Exec("shape.circleThroughPoints".into(), json!({"points": [[10.0, 10.0], [100.0, 150.0], [150.0, 150.0]]}))] + ); +} + +/// The pointer leaving the canvas removes the circle's preview, and an edit, Undo or Redo made +/// outside the tool drops the points placed so far. +#[test] +fn leaving_the_canvas_or_an_outside_edit_clears_the_circle_in_progress() { + let (d, _) = doc_with_rect(); + let s = Selection::default(); + let p = paint(); + let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) }; + let shift = Mods { shift: true, ..Default::default() }; + let mut t = ShapeTool::new("ellipse"); + let click = |t: &mut ShapeTool, x: f64, y: f64| { + t.pointer(&cx, &PointerEvent::new(PointerKind::Down, x, y).with_mods(shift)); + t.pointer(&cx, &PointerEvent::new(PointerKind::Up, x, y).with_mods(shift)) + }; + let dashed = |t: &ShapeTool| t.overlays(&cx).iter().any(|o| matches!(o, Overlay::Path { dashed: true, .. })); + click(&mut t, 10.0, 10.0); + click(&mut t, 90.0, 10.0); + t.pointer(&cx, &PointerEvent::new(PointerKind::Move, 10.0, 70.0)); + assert!(dashed(&t)); + t.hover_ended(&cx); + assert!(!dashed(&t), "no preview through a pointer off the canvas"); + assert!(t.ends_on_escape(&cx), "the points stay"); + t.history_moved(); + assert!(!t.ends_on_escape(&cx) && t.overlays(&cx).is_empty()); + assert_eq!(click(&mut t, 10.0, 70.0), vec![], "the next Shift-click starts a new circle"); +} + +/// While the perspective grid shows with an active plane, a Shift-click with the Ellipse tool opens +/// the size dialog, whose shape goes on the plane, as before. +#[test] +fn a_shift_click_on_an_active_perspective_plane_opens_the_dialog() { + let (mut d, _) = doc_with_rect(); + crate::distort::perspective::PerspectiveGrid::preset(2, Rect::new(0.0, 0.0, 612.0, 792.0)).store(&mut d); + let s = Selection::default(); + let p = paint(); + let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) }; + let shift = Mods { shift: true, ..Default::default() }; + let mut t = ShapeTool::new("ellipse"); + t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 10.0, 10.0).with_mods(shift)); + assert_eq!( + t.pointer(&cx, &PointerEvent::new(PointerKind::Up, 10.0, 10.0).with_mods(shift)), + vec![Action::Dialog("ellipse".into(), json!({"x": 10.0, "y": 10.0}))] + ); + assert!(!t.ends_on_escape(&cx)); +} + #[test] fn alt_click_passes_draw_from_centre_to_the_dialog() { let (d, _) = doc_with_rect(); diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index 87ce2c3730..011a71e890 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -5940,6 +5940,9 @@ digits Malayalam Malaiàlam @msg no active document no hi ha cap document actiu @msg no active perspective plane no hi ha cap pla de perspectiva actiu @msg no anchor points selected no hi ha cap punt d’ancoratge seleccionat +@msg `points` must be three [x, y] pairs of numbers `points` han de ser tres parells de nombres [x, y] +@msg direct-select three anchor points, or give `points` seleccioneu directament tres punts d’ancoratge o indiqueu `points` +@msg no circle passes through these points: two are the same or all three lie on one line cap cercle no passa per aquests punts: dos són iguals o tots tres són en una mateixa recta @msg no app to open files here aquí no hi ha cap aplicació per obrir fitxers @msg no artboard no hi ha tauler @msg no artboard {i} (0-based; the document has {_1}) no hi ha el tauler {i} (basat en 0; el document en té {_1}) diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index ffc55aad5a..184b3ddb18 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -5111,6 +5111,9 @@ imageTrace Outline Obrys @msg no active document žádný aktivní dokument @msg no active perspective plane žádná aktivní perspektivní rovina @msg no anchor points selected nejsou vybrány žádné kotevní body +@msg `points` must be three [x, y] pairs of numbers `points` musí být tři dvojice čísel [x, y] +@msg direct-select three anchor points, or give `points` vyberte přímým výběrem tři kotevní body, nebo zadejte `points` +@msg no circle passes through these points: two are the same or all three lie on one line těmito body neprochází žádná kružnice: dva jsou stejné nebo všechny tři leží na jedné přímce @msg no app to open files here zde chybí aplikace pro otevírání souborů @msg no artboard žádná pracovní plocha @msg no artboard {i} (0-based; the document has {_1}) pracovní plocha {i} neexistuje (číslováno od 0; dokument jich má {_1}) diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index edce184e8e..21df082dac 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -5271,6 +5271,9 @@ imageTrace Outline Kontur @msg no active document intet aktivt dokument @msg no active perspective plane intet aktivt perspektivplan @msg no anchor points selected ingen ankerpunkter er markeret +@msg `points` must be three [x, y] pairs of numbers `points` skal være tre talpar [x, y] +@msg direct-select three anchor points, or give `points` direkte markér tre ankerpunkter, eller angiv `points` +@msg no circle passes through these points: two are the same or all three lie on one line ingen cirkel går gennem disse punkter: to er ens, eller alle tre ligger på én linje @msg no app to open files here ingen app til at åbne filer her @msg no artboard ingen tegneflade @msg no artboard {i} (0-based; the document has {_1}) ingen tegneflade {i} (0-baseret; dokumentet har {_1}) diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index c456cd5bc1..2664445fd0 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -4715,6 +4715,9 @@ theme Appearance Erscheinungsbild @msg no active document kein aktives Dokument @msg no active perspective plane keine aktive Perspektivebene @msg no anchor points selected keine Ankerpunkte ausgewählt +@msg `points` must be three [x, y] pairs of numbers `points` muss aus drei Zahlenpaaren [x, y] bestehen +@msg direct-select three anchor points, or give `points` wählen Sie drei Ankerpunkte direkt aus oder geben Sie `points` an +@msg no circle passes through these points: two are the same or all three lie on one line durch diese Punkte verläuft kein Kreis: zwei sind gleich oder alle drei liegen auf einer Linie @msg no app to open files here hier gibt es keine App zum Öffnen von Dateien @msg no artboard keine Zeichenfläche @msg no artboard {i} (0-based; the document has {_1}) keine Zeichenfläche {i} (Zählung ab 0; das Dokument hat {_1}) diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 4e30f47e3f..5844d70f89 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -4761,6 +4761,9 @@ digits Malayalam Μαλαγιάλαμ @msg no active document δεν υπάρχει ενεργό έγγραφο @msg no active perspective plane δεν υπάρχει ενεργό επίπεδο προοπτικής @msg no anchor points selected δεν έχουν επιλεγεί σημεία αγκύρωσης +@msg `points` must be three [x, y] pairs of numbers το `points` πρέπει να είναι τρία ζεύγη αριθμών [x, y] +@msg direct-select three anchor points, or give `points` επιλέξτε άμεσα τρία σημεία αγκύρωσης ή δώστε `points` +@msg no circle passes through these points: two are the same or all three lie on one line κανένας κύκλος δεν περνά από αυτά τα σημεία: δύο είναι ίδια ή και τα τρία βρίσκονται σε μία ευθεία @msg no app to open files here δεν υπάρχει εφαρμογή για άνοιγμα αρχείων εδώ @msg no artboard δεν υπάρχει πίνακας σχεδίασης @msg no artboard {i} (0-based; the document has {_1}) δεν υπάρχει πίνακας σχεδίασης {i} (αρίθμηση από 0· το έγγραφο περιέχει {_1}) diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 6719052a94..17a5bdae51 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -4804,6 +4804,9 @@ axis Both Ambos @msg no active document no hay ningún documento activo @msg no active perspective plane no hay ningún plano de perspectiva activo @msg no anchor points selected no hay puntos de ancla seleccionados +@msg `points` must be three [x, y] pairs of numbers `points` debe ser tres pares de números [x, y] +@msg direct-select three anchor points, or give `points` seleccione directamente tres puntos de ancla o indique `points` +@msg no circle passes through these points: two are the same or all three lie on one line ningún círculo pasa por estos puntos: dos son iguales o los tres están en una misma línea @msg no app to open files here aquí no hay ninguna aplicación para abrir archivos @msg no artboard no hay mesa de trabajo @msg no artboard {i} (0-based; the document has {_1}) no existe la mesa de trabajo {i} (contando desde 0; el documento tiene {_1}) diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 2ed3c5e427..5c4b3aaa81 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -5027,6 +5027,9 @@ imageTrace Outline Ääriviiva @msg no active document ei aktiivista asiakirjaa @msg no active perspective plane ei aktiivista perspektiivitasoa @msg no anchor points selected ankkuripisteitä ei ole valittu +@msg `points` must be three [x, y] pairs of numbers `points` on annettava kolmena lukuparina [x, y] +@msg direct-select three anchor points, or give `points` valitse suoraan kolme ankkuripistettä tai anna `points` +@msg no circle passes through these points: two are the same or all three lie on one line näiden pisteiden kautta ei kulje ympyrää: kaksi pisteistä on samoja tai kaikki kolme ovat samalla suoralla @msg no app to open files here täällä ei ole sovellusta tiedostojen avaamiseen @msg no artboard ei piirtoalustaa @msg no artboard {i} (0-based; the document has {_1}) ei piirtoalustaa {i} (0-pohjainen; asiakirjassa on {_1}) diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 6a735eb1eb..4bc1541415 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -4783,6 +4783,9 @@ axis Both Les deux @msg no active document aucun document actif @msg no active perspective plane aucun plan de perspective actif @msg no anchor points selected aucun point d’ancrage sélectionné +@msg `points` must be three [x, y] pairs of numbers `points` doit contenir trois paires de nombres [x, y] +@msg direct-select three anchor points, or give `points` sélectionnez trois points d’ancrage avec l’outil Sélection directe, ou indiquez `points` +@msg no circle passes through these points: two are the same or all three lie on one line aucun cercle ne passe par ces points : deux sont identiques ou les trois sont alignés @msg no app to open files here aucune application pour ouvrir des fichiers ici @msg no artboard aucun plan de travail @msg no artboard {i} (0-based; the document has {_1}) aucun plan de travail {i} (numérotation à partir de 0 ; le document en a {_1}) diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index aedec9da73..c3c114bd93 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -7411,6 +7411,9 @@ antiAlias Sharp शार्प @msg no active document कोई सक्रिय डॉक्यूमेंट @msg no active perspective plane कोई सक्रिय पर्सपेक्टिव विमान नहीं @msg no anchor points selected कोई एंकर पॉइंट सिलेक्ट नहीं है +@msg `points` must be three [x, y] pairs of numbers `points` में संख्याओं के तीन [x, y] जोड़े होने चाहिए +@msg direct-select three anchor points, or give `points` तीन एंकर पॉइंट्स डायरेक्ट-सिलेक्ट करें, या `points` दें +@msg no circle passes through these points: two are the same or all three lie on one line इन पॉइंट्स से होकर कोई वृत्त नहीं गुज़रता: दो एक जैसे हैं या तीनों एक ही रेखा पर हैं @msg no app to open files here यहां फ़ाइलों को ओपन करने के लिए कोई ऐप नहीं है @msg no appearance item {index} कोई उपस्थिति आइटम {index} @msg no artboard कोई आर्टबोर्ड नहीं diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 80a39e7c70..ff6b1620ee 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -5484,6 +5484,9 @@ imageTrace Outline Körvonal @msg no active document nincs aktív dokumentum @msg no active perspective plane nincs aktív perspektivikus sík @msg no anchor points selected nincs kijelölt horgonypont +@msg `points` must be three [x, y] pairs of numbers a `points` három [x, y] számpár legyen +@msg direct-select three anchor points, or give `points` jelölj ki közvetlen kijelöléssel három horgonypontot, vagy add meg a `points` értéket +@msg no circle passes through these points: two are the same or all three lie on one line ezeken a pontokon nem halad át kör: kettő egybeesik, vagy mindhárom egy egyenesen van @msg no app to open files here itt nincs fájlmegnyitó alkalmazás @msg no artboard nincs rajztábla @msg no artboard {i} (0-based; the document has {_1}) nincs ilyen sorszámú rajztábla: {i} (0-tól számozva; a dokumentumban ennyi van: {_1}) diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 66d162f02c..c65defea0f 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -4845,6 +4845,9 @@ axis Both Entrambi @msg no active document nessun documento attivo @msg no active perspective plane nessun piano prospettico attivo @msg no anchor points selected nessun punto di ancoraggio selezionato +@msg `points` must be three [x, y] pairs of numbers `points` deve essere composto da tre coppie di numeri [x, y] +@msg direct-select three anchor points, or give `points` seleziona con Selezione diretta tre punti di ancoraggio oppure indica `points` +@msg no circle passes through these points: two are the same or all three lie on one line nessun cerchio passa per questi punti: due coincidono oppure tutti e tre sono allineati @msg no app to open files here nessuna app per aprire file qui @msg no artboard nessuna tavola da disegno @msg no artboard {i} (0-based; the document has {_1}) nessuna tavola da disegno {i} (a partire da 0; il documento ne ha {_1}) diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index e6fcd47ccc..7594c1fd57 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -4690,6 +4690,9 @@ swatch Bright Violet ビビッドバイオレット @msg image would be too large; lower the resolution 画像が大きくなりすぎるため、解像度を下げてください @msg clipboard is empty クリップボードが空です @msg no anchor points selected アンカーポイントが選択されていません +@msg `points` must be three [x, y] pairs of numbers `points` は 3 組の数値 [x, y] にしてください +@msg direct-select three anchor points, or give `points` アンカーポイントを 3 つダイレクト選択するか、`points` を指定してください +@msg no circle passes through these points: two are the same or all three lie on one line これらの点を通る円はありません: 2 つの点が同じか、3 点すべてが一直線上にあります @msg select at least two objects オブジェクトを 2 つ以上選択してください @msg exit isolation mode first 先に分離モードを終了してください @msg no saved presets 保存したプリセットはありません diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 9475bb917c..2b3a57ca74 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -6557,6 +6557,9 @@ font-technology Variable ცვლადი @msg no active document აქტიური დოკუმენტი არ არის @msg no active perspective plane აქტიური პერსპექტივის სიბრტყე არ არის @msg no anchor points selected საყრდენი წერტილები მონიშნული არ არის +@msg `points` must be three [x, y] pairs of numbers `points` უნდა იყოს რიცხვების სამი [x, y] წყვილი +@msg direct-select three anchor points, or give `points` პირდაპირი მონიშვნით მონიშნეთ სამი საყრდენი წერტილი ან მიუთითეთ `points` +@msg no circle passes through these points: two are the same or all three lie on one line ამ წერტილებზე წრეწირი არ გადის: ორი ერთნაირია ან სამივე ერთ წრფეზე მდებარეობს @msg no app to open files here აქ ფაილების გასახსნელი აპი არ არის @msg no artboard სამუშაო დაფა არ არის @msg no artboard {i} (0-based; the document has {_1}) სამუშაო დაფა {i} არ არსებობს (0-დან ითვლება; დოკუმენტს აქვს {_1}) diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index ea9a413f88..c4cee8e14c 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -4617,6 +4617,9 @@ theme Appearance 외관 @msg image would be too large; lower the resolution 이미지가 너무 커집니다. 해상도를 낮추세요 @msg clipboard is empty 클립보드가 비어 있습니다 @msg no anchor points selected 선택한 앵커 포인트가 없습니다 +@msg `points` must be three [x, y] pairs of numbers `points`는 숫자 쌍 [x, y] 세 개여야 합니다 +@msg direct-select three anchor points, or give `points` 앵커 포인트 세 개를 직접 선택하거나 `points`를 지정하세요 +@msg no circle passes through these points: two are the same or all three lie on one line 이 점들을 지나는 원이 없습니다: 두 점이 같거나 세 점이 모두 한 직선 위에 있습니다 @msg select at least two objects 개체를 두 개 이상 선택하세요 @msg exit isolation mode first 먼저 격리 모드를 종료하세요 @msg no saved presets 저장된 프리셋이 없습니다 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index bf8fd86aa3..6a04803c76 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -5166,6 +5166,9 @@ imageTrace Outline Contour @msg no active document geen actief document @msg no active perspective plane geen actief perspectiefvlak @msg no anchor points selected geen ankerpunten geselecteerd +@msg `points` must be three [x, y] pairs of numbers `points` moet uit drie getallenparen [x, y] bestaan +@msg direct-select three anchor points, or give `points` selecteer met directe selectie drie ankerpunten of geef `points` op +@msg no circle passes through these points: two are the same or all three lie on one line er gaat geen cirkel door deze punten: twee zijn gelijk of alle drie liggen op één lijn @msg no app to open files here hier is geen app om bestanden mee te openen @msg no artboard geen tekengebied @msg no artboard {i} (0-based; the document has {_1}) geen tekengebied {i} (vanaf 0; het document heeft er {_1}) diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index da2304edad..4eca975dfd 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -4934,6 +4934,9 @@ imageTrace Outline Kontur @msg no active document brak aktywnego dokumentu @msg no active perspective plane brak aktywnej płaszczyzny perspektywy @msg no anchor points selected nie zaznaczono punktów kontrolnych +@msg `points` must be three [x, y] pairs of numbers `points` musi zawierać trzy pary liczb [x, y] +@msg direct-select three anchor points, or give `points` zaznacz bezpośrednio trzy punkty kontrolne lub podaj `points` +@msg no circle passes through these points: two are the same or all three lie on one line przez te punkty nie przechodzi żaden okrąg: dwa są takie same albo wszystkie trzy leżą na jednej prostej @msg no app to open files here brak aplikacji do otwierania plików @msg no artboard brak obszaru kompozycji @msg no artboard {i} (0-based; the document has {_1}) brak obszaru kompozycji {i} (numeracja od 0; dokument ma {_1}) diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 772a72544a..972af0b236 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -4168,6 +4168,9 @@ axis Both Ambos @msg no active document nenhum documento ativo @msg no active perspective plane nenhum plano de perspectiva ativo @msg no anchor points selected nenhum ponto de ancoragem selecionado +@msg `points` must be three [x, y] pairs of numbers `points` deve ter três pares de números [x, y] +@msg direct-select three anchor points, or give `points` selecione diretamente três pontos de ancoragem ou informe `points` +@msg no circle passes through these points: two are the same or all three lie on one line nenhum círculo passa por esses pontos: dois são iguais ou os três estão na mesma reta @msg no app to open files here nenhum aplicativo para abrir arquivos aqui @msg no artboard nenhuma prancheta @msg no artboard {i} (0-based; the document has {_1}) nenhuma prancheta {i} (base 0; o documento tem {_1}) diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 02cdb08e31..4ecf3e2988 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -4841,6 +4841,9 @@ axis Both Оба @msg no active document нет активного документа @msg no active perspective plane нет активной плоскости перспективы @msg no anchor points selected опорные точки не выделены +@msg `points` must be three [x, y] pairs of numbers `points` должен содержать три пары чисел [x, y] +@msg direct-select three anchor points, or give `points` выделите прямым выделением три опорные точки или задайте `points` +@msg no circle passes through these points: two are the same or all three lie on one line через эти точки не проходит ни одна окружность: две точки совпадают или все три лежат на одной прямой @msg no app to open files here здесь нет приложения для открытия файлов @msg no artboard нет монтажной области @msg no artboard {i} (0-based; the document has {_1}) нет монтажной области {i} (счёт с 0; в документе {_1}) diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index d4d0d0a4b5..38723ad2b6 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -4705,6 +4705,9 @@ axis Both Båda @msg no active document inget aktivt dokument @msg no active perspective plane inget aktivt perspektivplan @msg no anchor points selected inga ankarpunkter är markerade +@msg `points` must be three [x, y] pairs of numbers `points` måste vara tre talpar [x, y] +@msg direct-select three anchor points, or give `points` direktmarkera tre ankarpunkter eller ange `points` +@msg no circle passes through these points: two are the same or all three lie on one line ingen cirkel går genom de här punkterna: två är samma punkt eller så ligger alla tre på en linje @msg no app to open files here det finns ingen app för att öppna filer här @msg no artboard ingen rityta @msg no artboard {i} (0-based; the document has {_1}) ingen rityta {i} (räknat från 0; dokumentet har {_1}) diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index cd471d910c..a3e61585b8 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -4537,6 +4537,9 @@ axis Both Her İkisi @msg no active document etkin belge yok @msg no active perspective plane aktif perspektif düzlemi yok @msg no anchor points selected bağlantı noktası seçilmedi +@msg `points` must be three [x, y] pairs of numbers `points` üç [x, y] sayı çifti olmalıdır +@msg direct-select three anchor points, or give `points` üç bağlantı noktasını doğrudan seçin veya `points` verin +@msg no circle passes through these points: two are the same or all three lie on one line bu noktalardan geçen bir çember yok: ikisi aynı ya da üçü de aynı doğru üzerinde @msg no app to open files here burada dosyaları açacak uygulama yok @msg no artboard çalışma yüzeyi yok @msg no artboard {i} (0-based; the document has {_1}) çalışma yüzeyi yok {i} (0 tabanlı; belgede {_1} var) diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index bc0ffe5928..0a05b5e6b2 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -4829,6 +4829,9 @@ axis Both Обидві @msg no active document немає активного документа @msg no active perspective plane немає активної площини перспективи @msg no anchor points selected опорні точки не виділені +@msg `points` must be three [x, y] pairs of numbers `points` має містити три пари чисел [x, y] +@msg direct-select three anchor points, or give `points` виділіть три опорні точки прямим виділенням або задайте `points` +@msg no circle passes through these points: two are the same or all three lie on one line через ці точки не проходить жодне коло: дві точки збігаються або всі три лежать на одній прямій @msg no app to open files here тут немає програми для відкриття файлів @msg no artboard немає монтажної області @msg no artboard {i} (0-based; the document has {_1}) немає монтажної області {i} (рахунок з 0; у документі {_1}) diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index a8543b90ae..c4c1369586 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -5152,6 +5152,9 @@ theme Appearance Giao diện @msg no active document không có tài liệu đang hoạt động @msg no active perspective plane không có mặt phẳng phối cảnh đang hoạt động @msg no anchor points selected chưa chọn điểm neo +@msg `points` must be three [x, y] pairs of numbers `points` phải là ba cặp số [x, y] +@msg direct-select three anchor points, or give `points` hãy chọn trực tiếp ba điểm neo hoặc cung cấp `points` +@msg no circle passes through these points: two are the same or all three lie on one line không có đường tròn nào đi qua các điểm này: hai điểm trùng nhau hoặc cả ba điểm thẳng hàng @msg no app to open files here không có ứng dụng để mở tệp ở đây @msg no artboard không có bảng vẽ @msg no artboard {i} (0-based; the document has {_1}) không có bảng vẽ {i} (bắt đầu từ 0; tài liệu có {_1}) diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 04dedf4229..05889711cc 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -4388,6 +4388,9 @@ imageTrace Outline 轮廓 @msg image would be too large; lower the resolution 图像将过大;请降低分辨率 @msg clipboard is empty 剪贴板为空 @msg no anchor points selected 未选择锚点 +@msg `points` must be three [x, y] pairs of numbers `points` 必须是三对数字 [x, y] +@msg direct-select three anchor points, or give `points` 请直接选择三个锚点,或提供 `points` +@msg no circle passes through these points: two are the same or all three lie on one line 没有圆经过这些点:有两点相同,或三点共线 @msg select at least two objects 请至少选择两个对象 @msg exit isolation mode first 请先退出隔离模式 @msg no saved presets 没有已保存的预设 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 7e3cb24439..991791187f 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -2033,6 +2033,9 @@ file-filter Templates 範本 @msg image would be too large; lower the resolution 影像會過大;請降低解析度 @msg clipboard is empty 剪貼簿是空的 @msg no anchor points selected 未選取錨點 +@msg `points` must be three [x, y] pairs of numbers `points` 必須是三組數字 [x, y] +@msg direct-select three anchor points, or give `points` 請以直接選取方式選取三個錨點,或提供 `points` +@msg no circle passes through these points: two are the same or all three lie on one line 沒有圓通過這些點:有兩點相同,或三點共線 @msg select at least two objects 請選取至少兩個物件 @msg exit isolation mode first 請先結束隔離模式 @msg no saved presets 沒有已儲存的預設集 diff --git a/docs/mcp.md b/docs/mcp.md index b7b4905ef4..2a602f4d80 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -5851,6 +5851,29 @@ slider (`ui.menuDialog {command: "object.path.smooth"}`, dialog `smoothSlider` w Auto-Smooth level, and the slider previews the result until `ui.dialog.confirm`; `ui.smoothAuto` moves the open slider back to the Auto-Smooth level. +## Circle through three points + +`shape.circleThroughPoints {points?: [[x, y], [x, y], [x, y]]}` draws the circle whose edge passes through three +points, as a live ellipse with the current paint, and selects it. Without `points`, it uses the 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, even while the document's +[Align New Objects to Pixel Grid](#align-new-objects-to-pixel-grid) is on, so it stays through the points. The command +returns an error and draws nothing when two points are the same or the three lie on one line (twice the triangle's area +at most 10⁻¹⁰ of its longest side squared), when `points` is not three pairs of numbers, and when `points` is left out +and the selection does not hold exactly three anchor points of paths. + +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 +click without Shift, a drag, a press without Shift on the selection or a shape widget, and an edit, Undo or Redo made +outside the tool remove the points placed so far. A Shift-drag still draws a circle from corner to corner. While the +perspective grid shows with an active plane, a Shift-click opens the size dialog, as a click does. + +```json +{"name":"run_command","arguments":{"command":"shape.circleThroughPoints","params":{"points":[[0,0],[80,0],[0,60]]}}} +``` + ## Editing a path with the Curvature tool The Curvature tool edits any selected path, whatever drew it, keeping its shape except where edited (#798). Each edit From 5f33c7d7f346a763b2e446139c20b6f2a15b5ba6 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 12:13:53 -0800 Subject: [PATCH 02/78] Shapes: Escape during the third Shift-click drops the press With two points placed, Escape pressed while the third Shift-click is held now drops the points and the press, so the release draws no circle. --- crates/tools/src/shape.rs | 9 +++++++-- crates/tools/src/shape/tests.rs | 22 ++++++++++++++++++++++ 2 files changed, 29 insertions(+), 2 deletions(-) diff --git a/crates/tools/src/shape.rs b/crates/tools/src/shape.rs index e124139b54..8a1c4a1249 100644 --- a/crates/tools/src/shape.rs +++ b/crates/tools/src/shape.rs @@ -678,10 +678,15 @@ impl Tool for ShapeTool { _ => vec![], }; } - // Escape drops the points Shift-clicks placed for a circle; the document stays as it is. - if key == ToolKey::Escape && self.start.is_none() && !self.through.is_empty() { + // Escape drops the points Shift-clicks placed for a circle; the document stays as it is. A + // press that has not begun a drag is dropped too, so its release places no point. + if key == ToolKey::Escape && !self.began && !self.through.is_empty() { self.through.clear(); self.hover = None; + if self.start.take().is_some() { + self.places_point = false; + self.snap.clear(); + } return vec![]; } let Some(s) = self.start.filter(|_| self.began) else { return vec![] }; diff --git a/crates/tools/src/shape/tests.rs b/crates/tools/src/shape/tests.rs index fe7eaa7ca5..3968615715 100644 --- a/crates/tools/src/shape/tests.rs +++ b/crates/tools/src/shape/tests.rs @@ -363,6 +363,28 @@ fn escape_a_click_or_a_drag_drops_the_shift_clicked_points() { assert!(!t.ends_on_escape(&c), "a move of the selection drops them"); } +/// Escape pressed while the third Shift-click is held drops the points and the press, so the +/// release draws no circle. +#[test] +fn escape_during_the_third_shift_click_drops_the_points_and_the_press() { + let (d, _) = doc_with_rect(); + let s = Selection::default(); + let p = paint(); + let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) }; + let shift = Mods { shift: true, ..Default::default() }; + let mut t = ShapeTool::new("ellipse"); + for (x, y) in [(10.0, 10.0), (90.0, 10.0)] { + t.pointer(&cx, &PointerEvent::new(PointerKind::Down, x, y).with_mods(shift)); + t.pointer(&cx, &PointerEvent::new(PointerKind::Up, x, y).with_mods(shift)); + } + t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 10.0, 70.0).with_mods(shift)); + assert!(t.claims_key(&cx, ToolKey::Escape)); + assert_eq!(t.key(&cx, ToolKey::Escape, shift), vec![]); + assert!(!t.ends_on_escape(&cx) && t.overlays(&cx).is_empty()); + assert_eq!(t.pointer(&cx, &PointerEvent::new(PointerKind::Up, 10.0, 70.0).with_mods(shift)), vec![]); + assert!(!t.ends_on_escape(&cx), "the release places no point"); +} + /// Once a point is placed, a Shift-click on the selection's side handle or centre point places a /// point instead of scaling or moving the selection, and the cursor over them is the crosshair. #[test] From b04780190396e8d35c0ffa4129401d4be94353f9 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 19:25:14 -0800 Subject: [PATCH 03/78] Command Palette: keys in one frame move the highlight in the order pressed Page Down, Up and the other keys that move the highlighted result now apply in the order they were pressed, so Page Down then Up in one frame lands one row above the page rather than on the last result. A scroll by any amount, not only steps over half a point, moves the highlight onto a row in view, so slow scrolling cannot carry the highlighted result out of sight while Enter still runs it. --- crates/ui-egui/src/palette.rs | 122 +++++++++++++++++++++++++--------- 1 file changed, 89 insertions(+), 33 deletions(-) diff --git a/crates/ui-egui/src/palette.rs b/crates/ui-egui/src/palette.rs index 9219328a1f..20186a555f 100644 --- a/crates/ui-egui/src/palette.rs +++ b/crates/ui-egui/src/palette.rs @@ -411,29 +411,30 @@ fn footer(listed: usize, total: usize) -> String { } } -/// How many times each key that moves the highlighted result was pressed this frame. +/// The keys that move the highlighted result, in the order they were pressed this frame. #[derive(Default)] -struct Moves { - down: usize, - up: usize, - page_down: usize, - page_up: usize, -} +struct Moves(Vec); impl Moves { + /// The keys that move the highlighted result. + const KEYS: [egui::Key; 4] = [egui::Key::ArrowDown, egui::Key::ArrowUp, egui::Key::PageDown, egui::Key::PageUp]; + fn any(&self) -> bool { - self.down + self.up + self.page_down + self.page_up > 0 + !self.0.is_empty() } - /// The highlighted result of `n` after these moves from `sel`, a page being `page` rows: Up and - /// Down wrap at the ends, Page Up and Page Down stop at them. + /// The highlighted result of `n` after these moves from `sel`, taken in the order they were + /// pressed, a page being `page` rows: Up and Down wrap at the ends, Page Up and Page Down stop + /// at them. fn apply(&self, sel: usize, n: usize, page: usize) -> usize { let Some(last) = n.checked_sub(1) else { return 0 }; - let sel = sel.min(last); - let sel = (sel + self.down % n) % n; - let sel = (sel + n - self.up % n) % n; - let sel = sel.saturating_add(page.saturating_mul(self.page_down)).min(last); - sel.saturating_sub(page.saturating_mul(self.page_up)) + self.0.iter().fold(sel.min(last), |sel, key| match key { + egui::Key::ArrowDown => (sel + 1) % n, + egui::Key::ArrowUp => (sel + last) % n, + egui::Key::PageDown => sel.saturating_add(page).min(last), + egui::Key::PageUp => sel.saturating_sub(page), + _ => sel, + }) } } @@ -569,13 +570,15 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { let mut moves = Moves::default(); if n > 0 && !list_open { ctx.input_mut(|i| { - let mut key = |k| i.count_and_consume_key(egui::Modifiers::NONE, k); - moves = Moves { - down: key(egui::Key::ArrowDown), - up: key(egui::Key::ArrowUp), - page_down: key(egui::Key::PageDown), - page_up: key(egui::Key::PageUp), - }; + i.events.retain(|e| match e { + egui::Event::Key { key, pressed: true, modifiers, .. } + if Moves::KEYS.contains(key) && modifiers.matches_logically(egui::Modifiers::NONE) => + { + moves.0.push(*key); + false + } + _ => true, + }); }); } let screen = ctx.content_rect(); @@ -683,9 +686,9 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { }); let before = offset; offset = out.state.clamped_offset().y; - // After a scroll with the wheel or the scroll bar, the highlight moves to the - // nearest row in view, so Enter runs a result that can be seen. - if !new_query && !moves.any() && (offset - before).abs() > 0.5 { + // After a scroll with the wheel or the scroll bar, by any amount, the highlight + // moves to the nearest row in view, so Enter runs a result that can be seen. + if !new_query && !moves.any() && (offset - before).abs() > 0.0 { sel = nearest_in_view(sel, offset, view, n); } }); @@ -1917,14 +1920,17 @@ mod tests { /// Down wrap. #[test] fn page_keys_move_by_a_page_without_wrapping() { - let moves = |down, up, page_down, page_up| Moves { down, up, page_down, page_up }; - assert_eq!(moves(0, 0, 1, 0).apply(0, 50, 12), 12); - assert_eq!(moves(0, 0, 1, 0).apply(45, 50, 12), 49); - assert_eq!(moves(0, 0, 0, 1).apply(5, 50, 12), 0); - assert_eq!(moves(1, 0, 0, 0).apply(49, 50, 12), 0); - assert_eq!(moves(0, 1, 0, 0).apply(0, 50, 12), 49); - assert_eq!(moves(3, 0, 0, 0).apply(48, 50, 12), 1); - assert_eq!(moves(1, 0, 0, 0).apply(0, 0, 12), 0); + use egui::Key::{ArrowDown, ArrowUp, PageDown, PageUp}; + let moves = |keys: &[egui::Key]| Moves(keys.to_vec()); + assert_eq!(moves(&[PageDown]).apply(0, 50, 12), 12); + assert_eq!(moves(&[PageDown]).apply(45, 50, 12), 49); + assert_eq!(moves(&[PageUp]).apply(5, 50, 12), 0); + assert_eq!(moves(&[ArrowDown]).apply(49, 50, 12), 0); + assert_eq!(moves(&[ArrowUp]).apply(0, 50, 12), 49); + assert_eq!(moves(&[ArrowDown; 3]).apply(48, 50, 12), 1); + assert_eq!(moves(&[ArrowDown]).apply(0, 0, 12), 0); + assert_eq!(moves(&[PageDown, ArrowUp]).apply(0, 50, 12), 11, "in the order pressed"); + assert_eq!(moves(&[ArrowUp, PageDown]).apply(0, 50, 12), 49, "in the order pressed"); let mut open = Open::new("select", WINDOW); open.press(egui::Key::PageDown, 1); assert_eq!(open.highlighted(), VISIBLE_ROWS); @@ -1976,6 +1982,56 @@ mod tests { assert_eq!(lit[0].0, row_label(entries(&open.ctx, Lang::EN).iter().find(|e| e.id == open.listed()[sel]).unwrap())); } + /// Page Down, Up and Enter pressed in one frame move the highlight in that order, and Enter + /// runs the result they moved it to. + #[test] + fn keys_in_one_frame_move_the_highlight_in_the_order_pressed() { + let mut open = Open::new("show panel", WINDOW); + let listed = open.listed(); + assert!(listed.len() > VISIBLE_ROWS, "{listed:?}"); + let panel = listed[VISIBLE_ROWS - 1].strip_prefix("panel:").expect("a panel's result").to_string(); + assert!(!crate::panel_docking::showing(&open.app.ui, &panel), "{panel}"); + let key = |k| egui::Event::Key { key: k, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE }; + open.frame(vec![key(egui::Key::PageDown), key(egui::Key::ArrowUp), key(egui::Key::Enter)]); + assert!(!open.app.ui.palette_open); + assert!(crate::panel_docking::showing(&open.app.ui, &panel), "{panel}: {}", open.app.ui.status); + } + + /// A scroll in steps of less than half a point a frame still moves the highlight onto a row in + /// view once the highlighted row leaves it. + #[test] + fn a_scroll_in_small_steps_keeps_the_highlight_in_view() { + let mut open = Open::new("select", WINDOW); + let nodes = open.frame(vec![]); + let first = rows(&nodes).into_iter().next().unwrap(); + let at = egui::pos2(open.popup().center().x, ((first.2 + first.3) / 2.0) as f32); + open.frame(vec![egui::Event::PointerMoved(at)]); + let wheel = egui::Event::MouseWheel { + unit: egui::MouseWheelUnit::Point, + delta: egui::vec2(0.0, -0.4), + phase: egui::TouchPhase::Move, + source: egui::MouseWheelSource::Unknown, + modifiers: egui::Modifiers::NONE, + }; + let mut nodes = Vec::new(); + for _ in 0..200 { + nodes = open.frame(vec![wheel.clone()]); + } + for _ in 0..120 { + if !open.repaint { + break; + } + nodes = open.frame(vec![]); + } + let offset = open.ctx.data(|d| d.get_temp::(egui::Id::unique("palette-selected"))).unwrap().2; + assert!(offset > ROW_HEIGHT, "the list scrolled past the first row: {offset}"); + assert!(open.highlighted() > 0, "the highlight left the row scrolled out of view"); + let popup = open.popup(); + let lit: Vec<_> = rows(&nodes).into_iter().filter(|r| r.1).collect(); + assert_eq!(lit.len(), 1, "{lit:?}"); + assert!(lit[0].2 >= f64::from(popup.top()) && lit[0].3 <= f64::from(popup.bottom()), "{lit:?} in {popup:?}"); + } + /// When the window shrinks so the list shows fewer rows, the list scrolls to keep the /// highlighted result in view, and Enter runs that result. #[test] From d998629b8dc5716b762746d4351b8c8328fe8500 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 21:49:59 -0800 Subject: [PATCH 04/78] Eyedropper: Escape ends a gradient stop's or Key Color's pick and returns to the previous tool Escape with a gradient stop's or Brush Options' Key Color eyedropper armed now ends the pick without sampling and switches back to the tool that armed it. The stop keeps its color. With Brush Options open, the first Escape ends only the pick and the dialog stays open with its Key Color; a new Escape cancels the dialog as before. The plain Eyedropper keeps its Escape behavior, and a dropped touch leaves an armed pick waiting for its click. Fixes #8024 --- crates/tools/src/xform/eyedropper.rs | 72 ++++++++++++++++++- .../src/dialogs/brush_options/tests.rs | 21 ++++++ crates/ui-egui/src/panels/gradient/tests.rs | 21 ++++++ crates/ui-egui/src/shortcuts.rs | 14 ++++ docs/target-app-parity.md | 1 + 5 files changed, 128 insertions(+), 1 deletion(-) diff --git a/crates/tools/src/xform/eyedropper.rs b/crates/tools/src/xform/eyedropper.rs index c5e05f004b..79c5116887 100644 --- a/crates/tools/src/xform/eyedropper.rs +++ b/crates/tools/src/xform/eyedropper.rs @@ -16,6 +16,9 @@ //! //! Brush Options' Key Color eyedropper sets `brushKeyColor` and `stop`: the next click samples into //! the open dialog (`brushKeyColor` UI request) and switches back. +//! +//! Escape ends either pick without sampling and switches back to that tool. With neither pick +//! armed, Escape is left to the application. use std::collections::HashSet; @@ -28,7 +31,7 @@ use vectorcraft_geom::{Affine, Point, Rect}; use super::paint_owner; use crate::params::color_json; -use crate::{Action, Cursor, Mods, Overlay, PointerEvent, PointerKind, Tool, ToolContext}; +use crate::{Action, Cursor, Mods, Overlay, PointerEvent, PointerKind, Tool, ToolContext, ToolKey}; #[derive(Default)] pub struct EyedropperTool { @@ -530,6 +533,38 @@ impl Tool for EyedropperTool { fn cursor(&self, _cx: &ToolContext, _p: Point, _m: Mods) -> Cursor { Cursor::Eyedropper } + + /// Escape ends a gradient stop's or Key Color's pick without sampling and switches back to the + /// tool that armed it. + fn key(&mut self, _cx: &ToolContext, key: ToolKey, _mods: Mods) -> Vec { + if key != ToolKey::Escape || !self.picking() { + return vec![]; + } + let back = self.stop.take().unwrap_or_else(|| "selection".to_string()); + self.brush_key_color = false; + vec![Action::SwitchTool(back)] + } + + /// A dropped press (a long or canceled touch) leaves an armed pick waiting for its click. + fn drop_press(&mut self, _cx: &ToolContext) -> Vec { + vec![] + } + + /// Escape is the tool's while a pick is armed, so it switches back and ends nothing else. + fn claims_key(&self, _cx: &ToolContext, key: ToolKey) -> bool { + key == ToolKey::Escape && self.picking() + } + + fn ends_on_escape(&self, _cx: &ToolContext) -> bool { + self.picking() + } +} + +impl EyedropperTool { + /// Is a one-shot pick armed (a gradient stop's or Brush Options' Key Color)? + fn picking(&self) -> bool { + self.stop.is_some() || self.brush_key_color + } } #[cfg(test)] @@ -619,6 +654,41 @@ mod tests { assert_eq!(t.options(), json!({"stop": null, "brushKeyColor": false}), "one sample only"); } + /// #8024: Escape ends a gradient stop's pick and a Key Color pick without sampling and + /// switches back; the plain Eyedropper leaves Escape alone. + #[test] + fn escape_ends_a_pick_and_switches_back() { + let (d, _) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let mut cx = cx(&d, &s, &p); + cx.gradient_stop = Some(1); + let none = Mods::default(); + let mut t = EyedropperTool::default(); + assert!(!t.claims_key(&cx, ToolKey::Escape) && !t.ends_on_escape(&cx), "nothing armed"); + assert!(t.key(&cx, ToolKey::Escape, none).is_empty()); + + t.set_option("stop", &json!("gradient")); + assert!(t.claims_key(&cx, ToolKey::Escape) && t.ends_on_escape(&cx)); + assert!(!t.claims_key(&cx, ToolKey::Enter)); + assert!(t.drop_press(&cx).is_empty(), "a dropped press leaves the pick armed"); + assert_eq!(t.key(&cx, ToolKey::Escape, none), vec![Action::SwitchTool("gradient".into())]); + assert_eq!(t.options(), json!({"stop": null, "brushKeyColor": false})); + assert!(!t.claims_key(&cx, ToolKey::Escape) && t.key(&cx, ToolKey::Escape, none).is_empty(), "one cancel only"); + let a = t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 100.0, 150.0)); + assert!(!a.iter().any(|a| matches!(a, Action::Exec(_, v) if v.get("stop").is_some())), "no stop sample after the cancel: {a:?}"); + + t.set_option("brushKeyColor", &json!(true)); + t.set_option("stop", &json!("paintbrush")); + assert!(t.claims_key(&cx, ToolKey::Escape)); + assert_eq!(t.key(&cx, ToolKey::Escape, none), vec![Action::SwitchTool("paintbrush".into())]); + assert_eq!(t.options(), json!({"stop": null, "brushKeyColor": false})); + + // A Key Color pick with no tool to return to goes back to the Selection tool. + t.set_option("brushKeyColor", &json!(true)); + assert_eq!(t.key(&cx, ToolKey::Escape, none), vec![Action::SwitchTool("selection".into())]); + assert_eq!(t.options(), json!({"stop": null, "brushKeyColor": false})); + } + #[test] fn brush_key_color_samples_into_the_dialog_then_switches_back() { let (d, _) = doc_with_rect(); diff --git a/crates/ui-egui/src/dialogs/brush_options/tests.rs b/crates/ui-egui/src/dialogs/brush_options/tests.rs index 9ff55da454..df45452a02 100644 --- a/crates/ui-egui/src/dialogs/brush_options/tests.rs +++ b/crates/ui-egui/src/dialogs/brush_options/tests.rs @@ -204,6 +204,27 @@ fn brush_key_color_eyedropper_updates_the_open_dialog() { assert_eq!(app.session.tool_id(), back); } +/// #8024: the first Escape ends the Key Color pick and returns to the tool that armed it, leaving +/// Brush Options open with its Key Color; a new press then cancels the dialog. +#[test] +fn escape_ends_the_key_color_pick_and_leaves_brush_options_open() { + let (mut app, ctx) = (app(), ctx()); + app.select_tool("paintbrush"); + app.run("ui.brushOptions", json!({"name": "Confetti"})).unwrap(); + set(&mut app, json!({"colorization": "hueShift"})); + let before = app.ui.dialog.as_ref().and_then(|d| d.fields.get("keyColor").cloned()); + app.select_tool("eyedropper"); + app.session.set_tool_option("brushKeyColor", &json!(true)); + app.session.set_tool_option("stop", &json!("paintbrush")); + frame(&ctx, &mut app, vec![], ""); + escape(&ctx, &mut app); + assert!(app.ui.dialog.is_some(), "Brush Options stays open"); + assert_eq!(app.ui.dialog.as_ref().and_then(|d| d.fields.get("keyColor").cloned()), before, "the Key Color stays"); + assert_eq!(app.session.tool_id(), "paintbrush"); + escape(&ctx, &mut app); + assert!(app.ui.dialog.is_none(), "a new press cancels Brush Options"); +} + #[test] fn art_options_set_width_scale_direction_flips_and_colorization() { let mut app = app(); diff --git a/crates/ui-egui/src/panels/gradient/tests.rs b/crates/ui-egui/src/panels/gradient/tests.rs index d5362b8bab..14a711bf57 100644 --- a/crates/ui-egui/src/panels/gradient/tests.rs +++ b/crates/ui-egui/src/panels/gradient/tests.rs @@ -711,6 +711,27 @@ fn the_stop_eyedropper_arms_the_eyedropper_for_the_stop() { assert_eq!((app.session.tool_id(), app.session.tool_options()), ("eyedropper", json!({"stop": "gradient", "brushKeyColor": false}))); } +/// #8024: Escape ends the stop eyedropper's pick and returns to the Gradient tool. The stop keeps +/// its color, the selection stays, and a held Escape's repeats end nothing else. +#[test] +fn escape_ends_the_stop_eyedropper_and_returns_to_the_gradient_tool() { + let mut app = app(json!({"gradient": {}})); + crate::shortcut_editor::sync(&app.ui); + app.select_tool("gradient"); + app.run("gradient.selectStop", json!({"index": 0})).unwrap(); + let (paint, selected) = (current(&app), app.session.active().unwrap().selection.objects.clone()); + stop_eyedropper(&mut app); + let key = |pressed, repeat| Event::Key { key: egui::Key::Escape, physical_key: None, pressed, repeat, modifiers: Modifiers::NONE }; + let ctx = egui::Context::default(); + for events in [vec![key(true, false)], vec![key(true, true)], vec![key(false, false)]] { + let mut out = ctx.run_ui(egui::RawInput { events, ..Default::default() }, |ui| crate::shortcuts::handle(&mut app, ui.ctx())); + out.textures_delta.clear(); + } + assert_eq!(app.session.tool_id(), "gradient"); + assert_eq!(current(&app), paint, "the stop keeps its color"); + assert_eq!(app.session.active().unwrap().selection.objects, selected, "the selection stays"); +} + /// The gradient panel names its Angle and Aspect Ratio inputs. #[test] fn angle_and_aspect_fields_are_named() { diff --git a/crates/ui-egui/src/shortcuts.rs b/crates/ui-egui/src/shortcuts.rs index 6329f489b1..781bec4e74 100644 --- a/crates/ui-egui/src/shortcuts.rs +++ b/crates/ui-egui/src/shortcuts.rs @@ -231,6 +231,14 @@ pub fn handle(app: &mut VectorcraftApp, ctx: &egui::Context) { || crate::dialogs::new_document_popup_open(d) || crate::dialogs::export_artboard_name_editing(app, d) }); + // Escape ends Brush Options' Key Color pick and leaves the dialog open: the Eyedropper + // switches back to the tool that armed it. + if !popup && pressed_anew(ctx, Key::Escape) && key_color_pick_armed(app) { + let view = app.view_info(); + let r = app.session.tool_key(ToolKey::Escape, Mods::default(), view); + crate::canvas::apply_requests(app, r); + return; + } // Escape in Preferences' search field with text clears the field first. if !popup && pressed_anew(ctx, Key::Escape) && !crate::prefs_dialog::clear_search_on_escape(app, ctx) { crate::dialogs::cancel(app); @@ -387,6 +395,12 @@ pub(crate) fn pressed_anew(ctx: &egui::Context, key: Key) -> bool { ctx.input(|i| i.events.iter().any(|e| matches!(e, egui::Event::Key { key: k, pressed: true, repeat: false, .. } if *k == key))) } +/// Is Brush Options open with its Key Color eyedropper armed, waiting for a click on the art? +fn key_color_pick_armed(app: &VectorcraftApp) -> bool { + let open = app.ui.dialog.as_ref().is_some_and(|d| d.kind == crate::dialogs::brush_options::KIND); + open && app.session.tool_id() == "eyedropper" && app.session.tool_options()["brushKeyColor"] == true +} + /// Takes this frame's repeats of `key` when the tool claims it: a press acts once, and they stay out /// of the shortcuts. A chord a command is bound to keeps its repeats. fn take_claimed_repeat(app: &mut VectorcraftApp, ctx: &egui::Context, key: Key, tool_key: ToolKey, view: ViewInfo) -> bool { diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index cc4082ad68..c1d8b60559 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1692,6 +1692,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Hue Clockwise and Hue Counterclockwise, VectorCraft's own gradient methods, in the Gradient panel's Method menu and on `paint.editGradient` and `paint.setFill` (`method`: `hue-clockwise`, `hue-counterclockwise`): a linear, radial, conic or diamond gradient's colors mix around the hue wheel, with hue, saturation and brightness each changing evenly from one stop to the next and the hue angle keeping one direction, as the fixed-direction rules of [CSS Color 4](https://www.w3.org/TR/css-color-4/#hue-interpolation) do: falling with Hue Clockwise (red, magenta, blue), which is clockwise on the color wheels, and rising with Hue Counterclockwise (red, yellow, green). Hues less than half a color level apart count as one hue, so a color and its tint do not turn the wheel. A gray stop takes the hue of the stop it mixes with, and black its saturation too. The canvas and raster exports draw it through stops on that curve, within half a color level; Reverse Gradient turns the method the other way with the stops, so the ramp keeps its colors. SVG and PDF write it as an RGB image, EPS as a shading in process colors, and a legacy `.ai` file and the `.ai` editing data with the colors between its stops as stops of their own, with a warning. - Gradient spread, VectorCraft's own setting: Pad, Repeat or Reflect, with a Repeats count of 1 to 100, in the Gradient panel and on `paint.editGradient` and `paint.setFill`; Repeat and Reflect run a linear, radial, conic or diamond gradient's stops that many times along the vector and on past its ends, the Gradient tool marks where the runs meet, and SVG writes and reads `spreadMethod`, CSS writes repeating gradients, PDF writes a conic's sweep shading over one run and the other kinds with their stops repeated across the shape, as EPS, legacy `.ai` and the `.ai` editing data do. - The stop popover a double-click on a stop opens (the Gradient tool's annotator or the Gradient panel) has an eyedropper beside its Color and Swatches tabs: it closes the popover and samples the next colour clicked on the art into the stop, as the Gradient panel's eyedropper does (#4681). + Escape ends that eyedropper's pick, and Brush Options' Key Color pick, without sampling and returns to the tool that started it; the stop keeps its color, and Brush Options stays open with its Key Color until a new Escape cancels it (#8024, [Modify gradients, archived user guide](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=264)). Cmd/Ctrl-click on the Gradient panel's Gradient Fill box or on the Tools panel's Gradient button resets the gradient of the active Fill or Stroke to the linear White, Black gradient, as one undo step ([Default keyboard shortcuts](https://web.archive.org/web/20260726060015/https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html)). With a gradient stop or a freeform gradient point selected, Alt-clicking a color swatch in the Swatches panel recolors it instead of the inactive Fill or Stroke. - **Freeform gradient colors in their own model:** Object ▸ Expand and Object ▸ Create Gradient Mesh (`object.mesh.create`) mix a freeform gradient's points in the color model they share: points of C50 M20 Y0 K10 give mesh points of C50 M20 Y0 K10, and RGB points keep their values in a working RGB space other than sRGB. The canvas, the gradient chips and the SVG, PDF, EPS and EMF writers mix the points in that model too. PDF and EPS write a gradient whose points are all CMYK, or all Gray in a CMYK file, as a CMYK image, which PDF's Output settings convert as they convert any CMYK image. Points in different models mix in display RGB (on the canvas in a CMYK document that shows transparency, as the inks of each point), and a CMYK document stores the result of Expand as CMYK through the color settings. Points colored along CMYK stops (`paint.editGradient {stops}`, or a CMYK gradient switched to freeform) are CMYK, and so are a point `paint.freeform.splitLine` adds between CMYK points and a point `paint.freeform.addPoint` adds without `color` to CMYK points. Public reference: [Gradients](https://web.archive.org/web/20250714042311/https://helpx.adobe.com/illustrator/using/gradients.html) and [Meshes](https://web.archive.org/web/20250812201019/https://helpx.adobe.com/illustrator/using/meshes.html), which do not state how colors in different models mix; the rule is VectorCraft's own. From 069f6963c6df1de9945d5eb933bef25c1e66cf15 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 22:18:48 -0800 Subject: [PATCH 05/78] SVG glyphs: a glyph from a shared SVG document reads only what it refers to A font's SVG table can keep many glyphs in one document. Each glyph's art was read by handing the importer the whole document, with every other glyph moved into defs. The importer now gets the glyph's element and only what it refers to: elements named by its effective link (plain href, else xlink:href) or by url(#id) in attributes, style attributes and sheets, what those refer to in turn, the start and end tags of the elements holding them, and every + + {other}"## + ), + // Clip paths, masks, filters, markers and patterns, a cycle, the glyph using itself, a + // non-ASCII id. + format!( + r##" + + + + + + + {other}"## + ), + // A rule on the glyph's own parent, which it leaves either way; a quoted, spaced URL to + // an id with punctuation in it. + format!( + r##" + + {other}"## + ), + // A pattern whose art takes its paint from the group holding it. + format!( + r##" + + {other}"## + ), + ]; + for doc in &docs { + let (reduced, whole) = (rewrite(doc, 1, true), rewrite(doc, 1, false)); + assert!(reduced.len() < whole.len() && !reduced.contains("#123456"), "reduced: {reduced}"); + assert_eq!(art(doc, 1, true), art(doc, 1, false), "{reduced}"); + } + } + + /// Whatever the reduction can't follow keeps the whole document in the `defs`. + #[test] + fn what_cant_be_followed_keeps_the_whole_document() { + let glyph = |defs: &str, art: &str| { + format!( + r##"{defs}{art}"## + ) + }; + let gradient = r##""##; + let path = |fill: &str| format!(r##""##); + let docs = [ + glyph("", &path("#000")), + glyph("", &path("#000")), + glyph("", &path("#000")), + glyph("", &path("#000")), + glyph(r"", &path("#000")), + glyph("", &path("#000")), + glyph(gradient, &path(r"url(#\67)")), + glyph(gradient, r#""#), + glyph(gradient, &path("url(#%67)")), + glyph(gradient, &path("url('#g)")), + glyph(gradient, &path("url(#g) url(#g x)")), + glyph(gradient, &path("url(#nothing)")), + glyph(gradient, &path("url(other.svg#g)")), + glyph(gradient, r##""##), + glyph(&format!("{gradient}{gradient}"), &path("url(#g)")), + glyph(&format!(r#"{gradient}"#), &path("url(#g)")), + glyph(&format!("{gradient}"), &path("url(#g)")), + r##""## + .to_string(), + r##"]>"## + .to_string(), + ]; + for doc in &docs { + assert_eq!(rewrite(doc, 1, true), rewrite(doc, 1, false), "{doc}"); + } + } + + #[test] + fn edits_apply_inside_the_range_asked_for() { + let edits = vec![(0..1, "A".to_string()), (2..2, "B".into()), (3..5, String::new()), (4..6, "C".into())]; + // An edit overlapping one already made is passed by; one not inside the range is not made. + assert_eq!(edited("0123456", 0..7, &edits).as_deref(), Some("A1B256")); + assert_eq!(edited("0123456", 2..5, &edits).as_deref(), Some("B2")); + assert_eq!(edited("0123456", 4..7, &edits).as_deref(), Some("C6")); + assert_eq!(edited("0123456", 1..2, &edits).as_deref(), Some("1B")); + } + + /// Of an element's `href` and `xlink:href`, only the plain one is followed, as the importer + /// follows it: the other's element stays out, and one that isn't there doesn't keep the whole + /// document. + #[test] + fn only_the_link_the_importer_follows_is_kept() { + let doc = |xlink: &str| { + format!( + r##" + "## + ) + }; + for xlink in ["#nothing", "other.svg#b"] { + let doc = doc(xlink); + let reduced = rewrite(&doc, 1, true); + assert!(reduced.len() < rewrite(&doc, 1, false).len() && !reduced.contains("#123456"), "{reduced}"); + assert_eq!(art(&doc, 1, true), art(&doc, 1, false)); + } + let doc = doc("#b").replace(r##""##, ""); + let reduced = rewrite(&doc, 1, true); + assert!(reduced.contains(r#"id="a""#) && !reduced.contains(r#"id="b""#), "{reduced}"); + assert_eq!(art(&doc, 1, true), art(&doc, 1, false)); + } + + /// A glyph inside an element that gives a prefix (or the default namespace) another namespace + /// than the root does keeps its own after it leaves that element. + #[test] + fn a_glyph_keeps_its_namespaces_when_the_root_gives_them_others() { + let flat = r##" + "##; + let nested = r##" + "##; + // The glyph declaring the prefix itself keeps it as it is. + let declared = r##" + "##; + for reduce in [true, false] { + assert_eq!(art(nested, 1, reduce), art(flat, 1, reduce), "{}", rewrite(nested, 1, reduce)); + assert_eq!(art(declared, 1, reduce), art(flat, 1, reduce), "{}", rewrite(declared, 1, reduce)); + } + assert_eq!(rewrite(declared, 1, true).matches("xmlns:v=").count(), 2); + // A path in another default namespace is no SVG path, out of that element too. + let other = r##" + "##; + let only = r##""##; + for reduce in [true, false] { + assert_eq!(art(other, 1, reduce), art(only, 1, reduce), "{}", rewrite(other, 1, reduce)); + } + } + + /// Many references to the same elements keep each of them once. + #[test] + fn repeated_references_keep_each_element_once() { + let uses: String = (0..2000).map(|i| format!(r##""##)).collect(); + let doc = format!( + r##" + + {uses}"## + ); + let reduced = rewrite(&doc, 1, true); + for id in ["g", "a", "b"] { + assert_eq!(reduced.matches(&format!(r#"id="{id}""#)).count(), 1, "{id}"); + } + assert!(!reduced.contains("#123456")); + } + + /// An empty document, or one without the glyph, has no art; one of exactly the cap reads, one a + /// byte larger doesn't. + #[test] + fn empty_and_capped_documents() { + assert!(glyph_art(b"", 1, 1000.0, Color::BLACK, None).is_none()); + assert!(glyph_art(br#""#, 1, 1000.0, Color::BLACK, None).is_none()); + let doc = shared(20); + let at = doc.len() - "".len(); + let padded = |len: u64| { + let pad = "x".repeat(len as usize - doc.len() - "".len()); + format!("{}{}", &doc[..at], &doc[at..]) + }; + let (full, over) = (padded(MAX_SVG_GLYPH_BYTES), padded(MAX_SVG_GLYPH_BYTES + 1)); + assert_eq!(full.len() as u64, MAX_SVG_GLYPH_BYTES); + assert_eq!(art(&full, 3, true), art(&doc, 3, true)); + assert!(glyph_art(over.as_bytes(), 3, 1000.0, Color::BLACK, None).is_none()); + } + + /// This thread's CPU time in seconds where the system reports it, else the time since a first + /// call. + fn cpu_seconds() -> f64 { + static START: std::sync::OnceLock = std::sync::OnceLock::new(); + let schedstat = std::fs::read_to_string("/proc/thread-self/schedstat").ok(); + match schedstat.as_deref().and_then(|s| s.split_whitespace().next()?.parse::().ok()) { + Some(ns) => ns / 1e9, + None => START.get_or_init(std::time::Instant::now).elapsed().as_secs_f64(), + } + } + + /// The importer's time for 50 distinct glyphs of shared documents, read whole and reduced, the + /// two alternating in one process: `cargo test -p vectorcraft-svg --lib glyph::tests::timing -- + /// --ignored --nocapture`. + #[test] + #[ignore = "timing, run by hand"] + fn timing() { + for n in [100, 500, 2000] { + let doc = shared(n); + let gids: Vec = (0..50).map(|i| (i * n / 50) as u32).collect(); + let run = |reduce: bool| { + let t = cpu_seconds(); + for g in &gids { + assert!(glyph_art_with(doc.as_bytes(), *g, 1000.0, Color::BLACK, None, reduce).is_some()); + } + cpu_seconds() - t + }; + run(false); + run(true); + let (mut whole, mut reduced) = (vec![], vec![]); + for round in 0..9 { + if round % 2 == 0 { + whole.push(run(false)); + reduced.push(run(true)); + } else { + reduced.push(run(true)); + whole.push(run(false)); + } + } + let median = |v: &mut Vec| { + v.sort_by(f64::total_cmp); + v[v.len() / 2] + }; + let ms = |v: &[f64]| v.iter().map(|s| format!("{:.1}", s * 1e3)).collect::>().join(" "); + println!("{n} glyphs, {} bytes: whole {} ms, reduced {} ms", doc.len(), ms(&whole), ms(&reduced)); + println!("{n} glyphs: median whole {:.1} ms, reduced {:.1} ms", median(&mut whole) * 1e3, median(&mut reduced) * 1e3); + } + } +} diff --git a/crates/svg/tests/it/svg_glyphs.rs b/crates/svg/tests/it/svg_glyphs.rs index 20e5342412..3e4ba8b697 100644 --- a/crates/svg/tests/it/svg_glyphs.rs +++ b/crates/svg/tests/it/svg_glyphs.rs @@ -241,13 +241,10 @@ fn an_images_plain_href_decides_whether_it_is_an_svg_image() { let svg = vectorcraft_svg::base64_encode( br##""##, ); - let image = |href: &str, xlink: &str| { - format!( - r##""##, - if href == "png" { &png } else { &svg }, - if xlink == "png" { &png } else { &svg } - ) - }; + let data = |kind: &str| format!("data:image/{kind};base64,{}", if kind == "png" { &png } else { &svg }); + let image = |href: &str, xlink: &str| format!(r##""##, data(href), data(xlink)); + // The same, `xlink:href` written first. + let xlink_first = |href: &str, xlink: &str| format!(r##""##, data(xlink), data(href)); let images = |inner: String| { let doc = format!( r##"{inner}"## @@ -258,6 +255,38 @@ fn an_images_plain_href_decides_whether_it_is_an_svg_image() { }; assert_eq!(images(image("png", "svg+xml")), 1, "the PNG stays"); assert_eq!(images(image("svg+xml", "png")), 0, "the document goes"); + assert_eq!(images(xlink_first("png", "svg+xml")), 1, "the PNG stays, its link written last"); + assert_eq!(images(xlink_first("svg+xml", "png")), 0, "the document goes, its link written last"); +} + +/// A glyph draws what it refers to wherever its document defines it: here a sheet's `url()` to a +/// gradient inside another glyph's element, which takes its stops from one in `defs`. The other +/// glyph's own art is not drawn. +#[test] +fn a_glyph_draws_what_it_refers_to_from_anywhere_in_its_document() { + let doc = r##" + + + + "##; + let fills = fills(&art(doc, 5).unwrap()); + let stops = fills.iter().find_map(|p| match p { + Paint::Gradient(g) => Some(g.gradient.stops.iter().map(|s| s.color).collect::>()), + _ => None, + }); + assert_eq!(stops, Some(vec![Color::rgb8(255, 0, 0), Color::rgb8(0, 0, 255)]), "{fills:?}"); + assert!(!fills.contains(&Paint::solid(Color::rgb8(0, 255, 0))), "not the other glyph's art: {fills:?}"); +} + +/// A glyph in colors of its own doesn't use the text's because another glyph of its document does. +#[test] +fn another_glyphs_current_color_does_not_color_a_glyph() { + let doc = r##" + + + "##; + assert!(!glyph_art(doc.as_bytes(), 1, 1000.0, BLUE, None).unwrap().1); + assert!(glyph_art(doc.as_bytes(), 2, 1000.0, BLUE, None).unwrap().1); } /// A glyph's `` draws its art but keeps no link: outlined text must not export a diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 0782bacab9..3f46017fe5 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -718,6 +718,7 @@ since 2026-10-01. - **Colour emoji with bitmap glyphs:** `sbix` (Apple Color Emoji) and `CBDT` (Noto Color Emoji) glyphs draw as their largest strike's PNG, placed with the type and unpainted by its fill; PDF writes them in Type 3 glyphs or as images, SVG as images with outlined text, EPS and legacy `.ai` as images, and Create Outlines makes embedded images. Synthetic test fonts in `crates/text/src/test_fonts.rs`; tests `crates/text/src/tests/bitmaps.rs`, `crates/render/src/tests/bitmapglyphs.rs`, `crates/svg/tests/it/colour_glyphs.rs`, `pdf::tests::colour_bitmap_glyphs_export_as_images`, the `eps` `colour_bitmap_glyphs_*` tests and `tests_pathops::create_outlines_turns_bitmap_glyphs_into_images`. COLR and OpenType SVG fonts remain. - **COLR colour fonts:** v0 and v1 glyphs draw as vector layers (solid colours, linear and radial gradients, including ones that repeat or reflect, clips, blend modes, the foreground colour from the run's fill) on the canvas, as paths in SVG, EPS, legacy `.ai` and PDF with outlined text, as Type 3 text in PDF, and as editable groups with Create Outlines; sweep gradients, Porter-Duff compositing and radial gradients that repeat or reflect and start at a circle draw the glyph as an image. Measured by `tests_colr`, `render::tests_colrglyphs`, `pdf::tests::colr_glyphs_export_as_vector_art`, `svg/tests/it/colour_glyphs.rs`, `eps` `colr_glyphs_*`, `tests_pathops::create_outlines_turns_colr_glyphs_into_layer_groups`. Scores unchanged (estimated). - **OpenType SVG colour fonts:** each glyph's SVG document is read by the SVG importer (registered by the engine) into vector art in the run's colours, then drawn, exported and outlined as COLR glyphs are; PDF real text writes them as text that draws nothing and draws their art where they sit. Measured by `tests_svg_glyphs`, `svg/tests/it/svg_glyphs.rs`, `tests_colourfonts::create_outlines_turns_svg_glyphs_into_groups`, `tests_colourfonts::pdf_real_text_draws_svg_glyphs_as_art_and_keeps_their_characters`. Scores unchanged (estimated). +- **OpenType SVG glyphs from a shared document:** when one SVG document holds many glyphs, the importer reads only the glyph's element and what it refers to (by `href` or `url(#id)`, through other elements, the elements holding them and every `