From 6f684e6da97ea173ff3612064ee81b3b37941ad0 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 1 Dec 2026 11:16:00 -0800 Subject: [PATCH 1/2] Path Precision Tools: Common Tangents and Smooth Bridge are one dialog MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Common Tangents… now also does what Smooth Bridge… did (#10465). - Connect tangents joins the two tangents of each kind into one closed shape, along the chords between where they touch each path (a point's two lines make a triangle). `connect` on `addon.pathtools.commonTangents`. - With External, the dialog shows Straight and Curved. Straight keeps the tangent lines; Curved joins the circles along concave arcs, as Smooth Bridge did, with Radius, Constant Gap, Reach and Keep Originals, which take input only with Curved. `curved`, `radius`, `gap`, `reach` and `keepOriginals` on the command; options of the other mode are an error. - The Smooth Bridge… menu item is gone. `addon.pathtools.bridge` still runs for scripts and actions, opens the merged dialog with External and Curved, and is left out of the command palette and Keyboard Shortcuts. A palette search for "metaball" or "smooth bridge" finds Common Tangents. Docs: docs/mcp.md, docs/ui-parity.md, ROADMAP. --- ROADMAP.md | 1 + crates/engine/src/cmd.rs | 3 +- .../engine/src/cmd/addons/pathtools/bridge.rs | 6 +- .../src/cmd/addons/pathtools/tangents.rs | 65 ++++- .../cmd/addons/pathtools/tangents/tests.rs | 107 ++++++++ crates/engine/src/cmd/params.rs | 1 + crates/mcp/src/ui_catalog.rs | 2 +- crates/ui-egui/src/addons/cutting/tests.rs | 33 --- crates/ui-egui/src/addons/dialogs.rs | 3 +- crates/ui-egui/src/addons/dialogs/tests.rs | 4 +- crates/ui-egui/src/addons/pathtools.rs | 9 +- crates/ui-egui/src/addons/pathtools/bridge.rs | 254 ------------------ .../ui-egui/src/addons/pathtools/tangents.rs | 150 +++++++++++ .../src/addons/pathtools/tangents/tests.rs | 244 +++++++++++++++++ crates/ui-egui/src/dialogs/command.rs | 6 +- crates/ui-egui/src/menus/ui_commands.rs | 2 +- crates/ui-egui/src/palette.rs | 13 + docs/mcp.md | 29 +- docs/ui-parity.md | 2 +- 19 files changed, 613 insertions(+), 321 deletions(-) delete mode 100644 crates/ui-egui/src/addons/pathtools/bridge.rs create mode 100644 crates/ui-egui/src/addons/pathtools/tangents.rs create mode 100644 crates/ui-egui/src/addons/pathtools/tangents/tests.rs diff --git a/ROADMAP.md b/ROADMAP.md index 894065391d..b04a110d6c 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -182,6 +182,7 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap - 2026-11-28: The Three-Point Arc tool joins an arc to the open paths whose ends its ends are placed on, with Join to Open Path Ends (Tool Options, or J while drawing; `shape.threePointArc` `join`), and in direction mode snaps the third point to where the arc carries an open path on, the same way or turned back (Snap Where the Arc Continues a Path, on by default). Headline numbers unchanged. - 2026-11-15: Smooth Bridge joins the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): two selected circles become one closed outline joined by two concave arcs that touch both circles, so every anchor is smooth; the arcs' radius is a percentage of the smaller circle's radius (1 to 1000%, 100% by default), and Keep Originals adds the outline above the circles instead of replacing them. A dialog with Preview, one undo step (`addon.pathtools.bridge`). A VectorCraft addition: headline numbers unchanged. - 2026-11-18: Smooth Bridge also joins three or more circles: every two whose outlines are within Reach (10 pt by default) are joined, the bridges that connect become one shape each, and a circle bridged to no other stays as it is (at most 2000 circles); with Constant Gap the arcs' radius is the smaller circle's radius plus a gap (#8030). A VectorCraft addition: headline numbers unchanged. +- 2026-12-01: Common Tangents and Smooth Bridge are one dialog, Common Tangents… (#10465): Connect tangents joins the two tangents of each kind into one closed shape, and with External, Straight or Curved picks between the tangent lines and Smooth Bridge's curved outline, with Radius, Constant Gap, Reach and Keep Originals; the Smooth Bridge… menu item is gone, and `addon.pathtools.bridge` still runs and opens the dialog with External and Curved (`connect` and `curved` on `addon.pathtools.commonTangents`). A VectorCraft addition: headline numbers unchanged. - 2026-11-03: Text Tweaker, the first tool of the Type Tools add-on (Object › Plug-ins › Type Tools): one character attribute (size, baseline shift, rotation, horizontal or vertical scale, tracking, leading or stroke weight) goes letter by letter from a start value to an end value along a straight ramp, an ease, a bow, a spike or at random with a seed, set as the Character panel sets it, while the text stays live; a dialog with Preview, one undo step (`addon.type.textTweaker`, #4924). A VectorCraft addition: headline numbers unchanged. - 2026-11-01: Group Overlapping Objects joins the Arrange Tools add-on (Object › Plug-ins › Arrange Tools): the selected objects whose visual bounds overlap or touch, chains included, go into one group each, within their own layer or group, at the stacking place of their frontmost member; objects that overlap nothing stay as they are. One undo step, a sweep along x so thousands of loose pieces group quickly (at most 20000 objects). A VectorCraft addition: headline numbers unchanged. - 2026-10-31: Export for Screens works as the reference app's dialog: Artboards and Assets tabs with a grid or list of thumbnails, Clear Selection and Prefix, Create Sub-folders by Scale or Format (on by default), Export PDFs As Single File (the chosen artboards as one PDF's pages, `pdfs: "single"`) or Multiple Files, iOS and Android rows, format presets in a ☰ menu, and a count of the files the export writes (#4895). About 55 community PRs and fixes landed the same day: Find Font, Replace Font, Outline Stroke and Expand leave hidden and locked art alone (with a warning); DXF export writes LINE and ELLIPSE entities and outlines only the strokes a CAD line can't draw; Blob Brush Angle and Roundness; Shift-constrained Perspective Selection; Grid Repeat Options Preview; a gradient mesh from a file budgeted at about a million quads; width-profile strokes keep their shape zoomed out; `.ai`/EPS import fidelity (area type, envelopes, transparency in dictionaries, character styles); PDF import finds hyphenated and CMap-suffixed font names; Windows renders follow the process's core affinity; Enter or Escape in a floating panel's field no longer reaches the canvas (#4803); Properties shows Blend Options for any selected blend (#4817); Artwork Cleanup finds doubled type (#4835) and joins stacked lines into one object (Join Point Text, #4826). Headline numbers unchanged. diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index 8e8d96ea66..d2dc185222 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -1002,7 +1002,8 @@ pub use variablecmds::{VariableSort, VariableSortKey, variable_order}; /// Command ids kept only so older scripts keep working: `(alias, the command it duplicates)`. /// They run as before but the command palette leaves them out (it lists the command once). -pub const ALIASES: &[(&str, &str)] = &[("object.convertDocumentColorMode", "file.documentColorMode")]; +pub const ALIASES: &[(&str, &str)] = + &[("object.convertDocumentColorMode", "file.documentColorMode"), ("addon.pathtools.bridge", "addon.pathtools.commonTangents")]; /// Is `id` an [`ALIASES`] entry? pub fn is_alias(id: &str) -> bool { diff --git a/crates/engine/src/cmd/addons/pathtools/bridge.rs b/crates/engine/src/cmd/addons/pathtools/bridge.rs index 2f56079b18..6e02292917 100644 --- a/crates/engine/src/cmd/addons/pathtools/bridge.rs +++ b/crates/engine/src/cmd/addons/pathtools/bridge.rs @@ -32,15 +32,15 @@ pub(super) fn specs() -> Vec { vec![cmd!( "addon.pathtools.bridge", "Smooth Bridge", - ["Object", "Plug-ins", "Path Precision Tools"], + [], None, - "{radius?: % 1..1000 (100; the radius of each bridge's two arcs as a percentage of the smaller circle's radius: larger makes a wider, gentler bridge), gap?: pt 0..1000 (instead of radius: the arcs' radius is the smaller circle's radius plus this gap, so each arc stays this gap away from a circle of the smaller circle's size about the arc's center; for equal circles this gap apart that is where a third circle this gap from both sits, as in a triangular grid, so the channels around an empty place in such a grid are one width; giving both is an error), reach?: pt 0..10000 (10; with three or more circles: how far apart two circles' outlines may be for a bridge between them, overlapping ones included; two circles are bridged at any distance), keepOriginals?: bool (false: each outline replaces its circles, painted as the topmost of them, and a group or compound path the other circles leave empty goes; true: it goes directly above that circle and the circles stay), ids?: [id] (default: the selection; a group, other than a clipping group, gives the objects inside it)} join circles (paths whose outline is a circle, not hidden or locked) into metaball (aka meatball) shapes. Two circles become one closed outline: around each circle on its side away from the other, and along two concave arcs, one on each side, that touch both circles so the outline runs on smoothly into them. With three or more, every two circles within reach are bridged the same way, and the bridges that connect are united into one shape each (holes smaller than 1% of the smallest circle's area are filled); a pair within reach but too far apart for the radius gets no bridge, and so does one whose neck would be thinner than the precision its shape is united at, and a circle bridged to no other is left as it is. Overlapping and touching circles are joined too. An object that is not a circle is an error that says why (an ellipse whose width and height differ, a compound path, a hidden or locked object, or another object). One circle inside another (among three or more, any such pair within reach) is an error; so are two circles too far apart for the radius (the arcs would not reach both, or would cross), or three or more with no pair the arcs can join, which suggests a larger radius or gap when the largest one would bridge them; so are no two circles within reach, more than 2000 circles and more than 8000 bridges. One undo step; the outlines (and the circles left as they are) are selected → {ids, alone}, with {id} too for two circles", + "{radius?: % 1..1000 (100; the radius of each bridge's two arcs as a percentage of the smaller circle's radius: larger makes a wider, gentler bridge), gap?: pt 0..1000 (instead of radius: the arcs' radius is the smaller circle's radius plus this gap, so each arc stays this gap away from a circle of the smaller circle's size about the arc's center; for equal circles this gap apart that is where a third circle this gap from both sits, as in a triangular grid, so the channels around an empty place in such a grid are one width; giving both is an error), reach?: pt 0..10000 (10; with three or more circles: how far apart two circles' outlines may be for a bridge between them, overlapping ones included; two circles are bridged at any distance), keepOriginals?: bool (false: each outline replaces its circles, painted as the topmost of them, and a group or compound path the other circles leave empty goes; true: it goes directly above that circle and the circles stay), ids?: [id] (default: the selection; a group, other than a clipping group, gives the objects inside it)} join circles (paths whose outline is a circle, not hidden or locked) into metaball (aka meatball) shapes. Two circles become one closed outline: around each circle on its side away from the other, and along two concave arcs, one on each side, that touch both circles so the outline runs on smoothly into them. With three or more, every two circles within reach are bridged the same way, and the bridges that connect are united into one shape each (holes smaller than 1% of the smallest circle's area are filled); a pair within reach but too far apart for the radius gets no bridge, and so does one whose neck would be thinner than the precision its shape is united at, and a circle bridged to no other is left as it is. Overlapping and touching circles are joined too. An object that is not a circle is an error that says why (an ellipse whose width and height differ, a compound path, a hidden or locked object, or another object). One circle inside another (among three or more, any such pair within reach) is an error; so are two circles too far apart for the radius (the arcs would not reach both, or would cross), or three or more with no pair the arcs can join, which suggests a larger radius or gap when the largest one would bridge them; so are no two circles within reach, more than 2000 circles and more than 8000 bridges. One undo step; the outlines (and the circles left as they are) are selected → {ids, alone}, with {id} too for two circles (kept for older scripts: Common Tangents makes the same outline with `curved`, and the command palette leaves this command out)", has_selection, bridge )] } -fn bridge(s: &mut Session, p: &Value) -> Result { +pub(super) fn bridge(s: &mut Session, p: &Value) -> Result { let percent = given(p, "radius", Some(RADII), C)?; let gap = given(p, "gap", Some(GAPS), C)?; let reach = given(p, "reach", Some(REACHES), C)?.unwrap_or(REACH); diff --git a/crates/engine/src/cmd/addons/pathtools/tangents.rs b/crates/engine/src/cmd/addons/pathtools/tangents.rs index e47c009062..372ceb6e12 100644 --- a/crates/engine/src/cmd/addons/pathtools/tangents.rs +++ b/crates/engine/src/cmd/addons/pathtools/tangents.rs @@ -31,7 +31,7 @@ pub(super) fn specs() -> Vec { "Common Tangents", ["Object", "Plug-ins", "Path Precision Tools"], None, - "{tangents?: \"external\" (both paths on the same side of each line) | \"internal\" (the lines that run between them) | \"all\" (\"all\"), centerline?: bool (false: true also adds the line joining the two centers, an ellipse's center or a path's center of area), ids?: [id, id] (default: the selection)} add the common tangent lines of two convex closed paths as separate open paths, each from where it touches the first path to where it touches the second (the whole stretch where a straight side lies along it), stroked with the current stroke color and weight (black when the stroke is None) and unfilled, directly above the upper of the two, as one undo step; the new lines are selected. An ellipse drawn with the Ellipse tool, turned or scaled, is measured as an exact ellipse; any other path must be closed, have one outline, bend the same way all around and have at most 10000 segments. Separate paths have two external and two internal tangents; overlapping paths only external ones; one path inside the other has none. Paths that touch, from outside or from inside, share one tangent there instead: a line centered on the point where they touch and as long as the narrower path is wide along it; paths that meet at a corner or along a shared stretch of outline get one such line, at the middle of the directions that touch both. Paths count as touching when the gap between them is at most a billionth of the larger of their sizes and the distance between their centers. One of the two may be a point (a path of one anchor): the lines then run from the point to where they touch the path, two when the point lies outside it (one that lies along a straight side covers the whole side), one when the point lies on its outline, that is, at most the touching tolerance from it, with the point's distance from the path's center in place of the distance between centers (centered on the point and as long as the path is wide along it, or the whole straight side the point lies on), none when it lies inside; every `tangents` value gives the same lines, counted as internal when `tangents` is \"internal\" and as external otherwise, and the centerline runs from the point to the path's center; two points are refused. When there is no tangent of the kind asked for, nothing changes and the result has a `warning` → {ids, external, internal, centerline (its id or null), warning?}", + "{tangents?: \"external\" (both paths on the same side of each line) | \"internal\" (the lines that run between them) | \"all\" (\"all\"), centerline?: bool (false: true also adds the line joining the two centers, an ellipse's center or a path's center of area), connect?: bool (false: true joins the two tangents of each kind into one closed path, along the chords between where they touch each path; a kind with one tangent stays a line), curved?: bool (false: true joins the selected circles into one outline along concave arcs that touch both, as `addon.pathtools.bridge` does, in place of the external tangents; `tangents` other than \"external\", `centerline` and `connect: false` are then an error), radius?: % 1..1000 (100; with curved, as for `addon.pathtools.bridge`), gap?: pt 0..1000 (with curved, instead of radius), reach?: pt 0..10000 (10; with curved, for three or more circles), keepOriginals?: bool (false; with curved), ids?: [id, id] (default: the selection; with curved, two or more circles)} add the common tangent lines of two convex closed paths (with curved, join circles with a smooth bridge into metaball, aka meatball, shapes instead) as separate open paths, each from where it touches the first path to where it touches the second (the whole stretch where a straight side lies along it), stroked with the current stroke color and weight (black when the stroke is None) and unfilled, directly above the upper of the two, as one undo step; the new lines are selected. An ellipse drawn with the Ellipse tool, turned or scaled, is measured as an exact ellipse; any other path must be closed, have one outline, bend the same way all around and have at most 10000 segments. Separate paths have two external and two internal tangents; overlapping paths only external ones; one path inside the other has none. Paths that touch, from outside or from inside, share one tangent there instead: a line centered on the point where they touch and as long as the narrower path is wide along it; paths that meet at a corner or along a shared stretch of outline get one such line, at the middle of the directions that touch both. Paths count as touching when the gap between them is at most a billionth of the larger of their sizes and the distance between their centers. One of the two may be a point (a path of one anchor): the lines then run from the point to where they touch the path, two when the point lies outside it (one that lies along a straight side covers the whole side), one when the point lies on its outline, that is, at most the touching tolerance from it, with the point's distance from the path's center in place of the distance between centers (centered on the point and as long as the path is wide along it, or the whole straight side the point lies on), none when it lies inside; every `tangents` value gives the same lines, counted as internal when `tangents` is \"internal\" and as external otherwise, and the centerline runs from the point to the path's center; two points are refused. When there is no tangent of the kind asked for, nothing changes and the result has a `warning` → {ids, external, internal, centerline (its id or null), warning?}, or with curved `addon.pathtools.bridge`'s {ids, alone, id?}", has_selection, common_tangents )] @@ -71,9 +71,36 @@ fn refusal(e: pt::OutlineError) -> EngineError { ) } +/// The parameters that shape a curved bridge. +const CURVED_KEYS: [&str; 4] = ["radius", "gap", "reach", "keepOriginals"]; + fn common_tangents(s: &mut Session, p: &Value) -> Result { const C: &str = COMMON_TANGENTS; - let kinds = choice(p, C, "tangents", &KINDS)?.unwrap_or("all"); + let given = |key: &str| p.get(key).is_some_and(|v| !v.is_null()); + let kinds = choice(p, C, "tangents", &KINDS)?; + let connect = if given("connect") { Some(switch_or(p, "connect", false, C)?) } else { None }; + if switch_or(p, "curved", false, C)? { + if kinds.is_some_and(|k| k != "external") { + return Err(bad(C, "`curved` joins the circles along their external tangents: give `tangents` \"external\" or leave it out")); + } + if given("centerline") { + return Err(bad(C, "`centerline` applies to the tangent lines: leave it out with `curved`")); + } + if connect == Some(false) { + return Err(bad(C, "a curved bridge is always connected: leave `connect` out or set it true")); + } + // The outline is Smooth Bridge's. + let mut bridged = serde_json::Map::new(); + for key in CURVED_KEYS.iter().chain(&["ids"]).filter(|k| given(k)) { + bridged.insert((*key).to_owned(), p[*key].clone()); + } + return super::bridge::bridge(s, &Value::Object(bridged)); + } + if let Some(key) = CURVED_KEYS.iter().find(|k| given(k)) { + return Err(bad(C, format!("`{key}` applies to a curved bridge: give `curved` with it"))); + } + let kinds = kinds.unwrap_or("all"); + let connect = connect.unwrap_or(false); let centerline = switch_or(p, "centerline", false, C)?; let roots = checked_ids_or_selection(s, p, C)?; let d = &s.doc()?.doc; @@ -105,6 +132,33 @@ fn common_tangents(s: &mut Session, p: &Value) -> Result { _ => (count(pt::TangentKind::External), count(pt::TangentKind::Internal)), }; let lines: Vec<(Point, Point)> = kept.iter().map(|t| (t.from, t.to)).collect(); + // With `connect`, the two tangents of each kind and the chords between their ends on each path make one closed + // shape; a kind with one tangent (paths that touch) keeps it as a line. A point's lines are all one kind. + let shapes: Vec<(Vec, bool)> = if connect { + let mut out = vec![]; + for kind in [pt::TangentKind::External, pt::TangentKind::Internal] { + let of: Vec<&pt::Tangent> = kept.iter().copied().filter(|t| point || t.kind == kind).collect(); + match of.as_slice() { + [l, m] => { + // A point's two lines share the point, which then closes the ring once. + let same = |q: Point, p: Point| (q - p).hypot() <= 1e-9 * a.size().max(b.size()); + let mut ring = vec![l.from, l.to, m.to, m.from]; + ring.dedup_by(|q, p| same(*q, *p)); + if ring.len() > 2 && same(ring[0], ring[ring.len() - 1]) { + ring.pop(); + } + out.push((ring, true)); + } + _ => out.extend(of.iter().map(|t| (vec![t.from, t.to], false))), + } + if point { + break; + } + } + out + } else { + lines.iter().map(|&(from, to)| (vec![from, to], false)).collect() + }; if lines.is_empty() && point { // Written as `EngineError::Other` so that the i18n message scan finds it. let warning = EngineError::Other("The point lies inside the path, so it has no tangents".into()); @@ -133,13 +187,14 @@ fn common_tangents(s: &mut Session, p: &Value) -> Result { let (parent, idx, _) = d.position(top).ok_or(EngineError::NoNode(top))?; let mut ids = vec![]; let mut center_id = None; - for (k, (from, to)) in lines.iter().copied().chain(center).enumerate() { + let center = center.map(|(from, to)| (vec![from, to], false)); + for (k, (points, closed)) in shapes.iter().cloned().chain(center).enumerate() { let id = d.alloc_id(); - let path = PathData::single(SubPath::polyline(&[from, to], false)); + let path = PathData::single(SubPath::polyline(&points, closed)); let mut n = Node::new(id, NodeKind::Path { path, rule: FillRule::NonZero, live: None, clipping: false, guide: false }); look.apply(d, &mut n); d.insert(parent, idx + 1 + k, n)?; - if k == lines.len() { + if k == shapes.len() { center_id = Some(id); } ids.push(id); diff --git a/crates/engine/src/cmd/addons/pathtools/tangents/tests.rs b/crates/engine/src/cmd/addons/pathtools/tangents/tests.rs index 7ab6b32838..032ef5f377 100644 --- a/crates/engine/src/cmd/addons/pathtools/tangents/tests.rs +++ b/crates/engine/src/cmd/addons/pathtools/tangents/tests.rs @@ -354,3 +354,110 @@ fn bad_selections_and_params_are_refused() { let g = group_of(&mut s, &[b]); assert!(err(&mut s, json!({"ids": [a.0, g.0]})).contains("select two closed paths")); } + +/// The one closed outline of path `id`. +fn outline(s: &Session, id: NodeId) -> vectorcraft_geom::SubPath { + let n = s.doc().unwrap().doc.node(id).unwrap(); + let NodeKind::Path { path, .. } = &n.kind else { panic!("not a path") }; + let [sp] = path.subpaths.as_slice() else { panic!("{} subpaths", path.subpaths.len()) }; + assert!(sp.closed); + sp.clone() +} + +/// The anchors of path `id`'s one closed outline. +fn corners(s: &Session, id: NodeId) -> Vec { + outline(s, id).anchors.iter().map(|a| a.p).collect() +} + +#[test] +fn connect_joins_the_external_tangents_and_the_chords_into_one_closed_shape_in_one_step() { + let mut s = session(); + let (a, b) = (circle(&mut s, 100.0, 100.0, 20.0), circle(&mut s, 200.0, 100.0, 20.0)); + let (before, count) = (steps(&s), s.doc().unwrap().doc.node_count()); + let r = s.execute(C, &json!({"tangents": "external", "connect": true, "ids": [a.0, b.0]})).unwrap(); + assert_eq!(steps(&s), before + 1, "one undo step"); + let ids = r["ids"].as_array().unwrap(); + assert_eq!(ids.len(), 1, "one shape in place of two lines"); + assert_eq!(s.doc().unwrap().doc.node_count(), count + 1, "the circles stay"); + let found = corners(&s, NodeId(ids[0].as_u64().unwrap())); + assert_eq!(found.len(), 4); + // The tangents above and below both circles, joined by each circle's vertical diameter. + for p in [Point::new(100.0, 80.0), Point::new(200.0, 80.0), Point::new(200.0, 120.0), Point::new(100.0, 120.0)] { + assert!(found.iter().any(|&q| near(p, q)), "{p:?} in {found:?}"); + } + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(s.doc().unwrap().doc.node_count(), count); +} + +#[test] +fn connect_with_all_makes_one_shape_of_each_kind_and_a_point_makes_a_triangle() { + let mut s = session(); + let (ca, cb) = ((Point::new(100.0, 100.0), 20.0), (Point::new(220.0, 140.0), 40.0)); + let (a, b) = (circle(&mut s, ca.0.x, ca.0.y, ca.1), circle(&mut s, cb.0.x, cb.0.y, cb.1)); + let r = s.execute(C, &json!({"connect": true, "centerline": true, "ids": [a.0, b.0]})).unwrap(); + let ids: Vec = r["ids"].as_array().unwrap().iter().map(|v| NodeId(v.as_u64().unwrap())).collect(); + assert_eq!(ids.len(), 3, "an external shape, an internal shape and the centerline"); + for &id in &ids[..2] { + let found = corners(&s, id); + assert_eq!(found.len(), 4); + let on = |(c, r): (Point, f64)| found.iter().filter(|p| ((**p - c).hypot() - r).abs() < 1e-6).count(); + assert_eq!((on(ca), on(cb)), (2, 2), "two corners where the tangents touch each circle: {found:?}"); + } + assert_ne!(corners(&s, ids[0]), corners(&s, ids[1])); + assert_eq!(r["centerline"], json!(ids[2].0)); + + let mut s = session(); + let (p, c) = (point(&mut s, 0.0, 100.0), circle(&mut s, 100.0, 100.0, 20.0)); + let r = s.execute(C, &json!({"connect": true, "ids": [p.0, c.0]})).unwrap(); + let ids = r["ids"].as_array().unwrap(); + assert_eq!(ids.len(), 1); + let found = corners(&s, NodeId(ids[0].as_u64().unwrap())); + assert_eq!(found.len(), 3, "the point and where its two lines touch the circle: {found:?}"); + assert!(found.iter().any(|&q| near(q, Point::new(0.0, 100.0)))); +} + +#[test] +fn curved_makes_the_bridge_the_smooth_bridge_command_makes() { + let build = || { + let mut s = session(); + let ids = [circle(&mut s, 100.0, 100.0, 20.0), circle(&mut s, 150.0, 100.0, 20.0), circle(&mut s, 125.0, 140.0, 20.0)]; + select(&mut s, &ids); + s + }; + for (merged, old) in [ + (json!({"curved": true}), json!({})), + ( + json!({"tangents": "external", "connect": true, "curved": true, "gap": 5, "reach": 30, "keepOriginals": true}), + json!({"gap": 5, "reach": 30, "keepOriginals": true}), + ), + ] { + let (mut s, mut t) = (build(), build()); + let r = s.execute(C, &merged).unwrap(); + let q = t.execute("addon.pathtools.bridge", &old).unwrap(); + assert_eq!(r, q, "{merged}"); + let kinds = |s: &Session| s.doc().unwrap().doc.layers[0].children().unwrap().iter().map(|n| n.kind.clone()).collect::>(); + assert_eq!(kinds(&s), kinds(&t), "{merged}"); + } +} + +#[test] +fn options_of_the_other_mode_are_refused() { + let mut s = session(); + let (a, b) = (circle(&mut s, 100.0, 100.0, 20.0), circle(&mut s, 200.0, 100.0, 20.0)); + select(&mut s, &[a, b]); + let before = (steps(&s), s.doc().unwrap().doc.node_count()); + let err = |s: &mut Session, p: Value| s.execute(C, &p).unwrap_err().to_string(); + for (p, says) in [ + (json!({"connect": "yes"}), "connect"), + (json!({"curved": true, "tangents": "all"}), "external"), + (json!({"curved": true, "centerline": true}), "centerline"), + (json!({"curved": true, "connect": false}), "connected"), + (json!({"radius": 50}), "curved"), + (json!({"connect": true, "keepOriginals": true}), "curved"), + (json!({"curved": true, "radius": 50, "gap": 2}), "not both"), + (json!({"curved": true, "radius": 0}), "radius"), + ] { + assert!(err(&mut s, p.clone()).contains(says), "{p}: {}", err(&mut s, p.clone())); + } + assert_eq!((steps(&s), s.doc().unwrap().doc.node_count()), before, "nothing changes"); +} diff --git a/crates/engine/src/cmd/params.rs b/crates/engine/src/cmd/params.rs index 9b498f1ca8..0bfbe7c304 100644 --- a/crates/engine/src/cmd/params.rs +++ b/crates/engine/src/cmd/params.rs @@ -388,6 +388,7 @@ const EXCLUSIVE_KEYS: &[(&str, &str, &str)] = &[ ("addon.pathtools.cornerSet", "items", "ids"), ("addon.pathtools.cornerRemove", "items", "ids"), ("addon.pathtools.bridge", "radius", "gap"), + ("addon.pathtools.commonTangents", "radius", "gap"), ("links.unembed", "id", "ids"), ("links.unembed", "path", "folder"), ]; diff --git a/crates/mcp/src/ui_catalog.rs b/crates/mcp/src/ui_catalog.rs index b29f22395c..1f4ade798a 100644 --- a/crates/mcp/src/ui_catalog.rs +++ b/crates/mcp/src/ui_catalog.rs @@ -1531,7 +1531,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.menuDialog", "Menu Dialog", "", - "{command: object.move|object.rotate|object.scale|object.reflect|object.shear|object.transformEach|path.average|path.averageJoin|object.path.offsetPath|object.path.simplify|object.path.smooth|object.path.splitIntoGrid|object.vectorHalftone|object.stepAndRepeat|artboard.rearrange|artboard.rename|object.envelope.makeWithWarp|object.envelope.resetWithWarp|object.envelope.makeWithMesh|object.envelope.resetWithMesh|object.envelope.options|addon.arrange.grid|addon.arrange.offset|addon.arrange.replace|addon.arrange.size|addon.arrange.match|addon.arrange.groupRows|addon.packaging.setFoldAngle|addon.pathtools.cornerSet|addon.pathtools.divideDashes|addon.pathtools.bridge|addon.pathtools.tangentCircle|addon.type.textTweaker|addon.color.swatchLegend|addon.arrange.randomizeOpacity|addon.arrange.sort|addon.arrange.markBounds|addon.color.applyNearestSwatch|addon.color.randomFill|addon.select.byArtboards|addon.select.editPointsOnly|type.smartPunctuation|variable.define|variable.rename|variable.bind|dataset.new|dataset.set|dataset.rename|dataset.select} open the dialog that command's menu item opens (its `key` in ui.inspect is the command id, except `transformEach` for object.transformEach, `envelopeWarp` for object.envelope.makeWithWarp and object.envelope.resetWithWarp, `envelopeMesh` for object.envelope.makeWithMesh and object.envelope.resetWithMesh, `variables` for variable.define and variable.rename and variable.bind and dataset.new and dataset.set and dataset.rename and dataset.select, `envelopeOptions` for object.envelope.options, `smoothSlider` for object.path.smooth, and `simplifySlider` for object.path.simplify; the dialogs of addon.color.applyNearestSwatch and addon.select.byArtboards have no `key`; smoothSlider and simplifySlider are the sliders over the canvas, with field `level`, and object.path.simplify opens its dialog `object.path.simplify` instead once OK in that dialog keeps the settings (`retain`); Set Fold Angle's `angle` is the selected fold lines' angle, and it is refused while the selection has no fold line it can change; Scale and Transform Each have `corners` and `strokes`, from the preferences, which OK updates; Transform Each opens on the values it was last confirmed with (not `copy`), and its Copy button confirms with `copy: true`; the envelope dialogs start from the selected envelope, Make opens as Reset (`reset: true`) while one is selected; variable.rename opens only while the document has a variable, and dataset.set and dataset.rename only while it has a data set, and otherwise the status bar says why; ui.dialog.set, ui.dialog.confirm and ui.dialog.cancel take the dialog's `id` from ui.inspect, or `top`, not its `key`)", + "{command: object.move|object.rotate|object.scale|object.reflect|object.shear|object.transformEach|path.average|path.averageJoin|object.path.offsetPath|object.path.simplify|object.path.smooth|object.path.splitIntoGrid|object.vectorHalftone|object.stepAndRepeat|artboard.rearrange|artboard.rename|object.envelope.makeWithWarp|object.envelope.resetWithWarp|object.envelope.makeWithMesh|object.envelope.resetWithMesh|object.envelope.options|addon.arrange.grid|addon.arrange.offset|addon.arrange.replace|addon.arrange.size|addon.arrange.match|addon.arrange.groupRows|addon.packaging.setFoldAngle|addon.pathtools.cornerSet|addon.pathtools.divideDashes|addon.pathtools.bridge|addon.pathtools.commonTangents|addon.pathtools.tangentCircle|addon.type.textTweaker|addon.color.swatchLegend|addon.arrange.randomizeOpacity|addon.arrange.sort|addon.arrange.markBounds|addon.color.applyNearestSwatch|addon.color.randomFill|addon.select.byArtboards|addon.select.editPointsOnly|type.smartPunctuation|variable.define|variable.rename|variable.bind|dataset.new|dataset.set|dataset.rename|dataset.select} open the dialog that command's menu item opens (its `key` in ui.inspect is the command id, except `transformEach` for object.transformEach, `envelopeWarp` for object.envelope.makeWithWarp and object.envelope.resetWithWarp, `envelopeMesh` for object.envelope.makeWithMesh and object.envelope.resetWithMesh, `variables` for variable.define and variable.rename and variable.bind and dataset.new and dataset.set and dataset.rename and dataset.select, `envelopeOptions` for object.envelope.options, `addon.pathtools.commonTangents` for addon.pathtools.bridge, `smoothSlider` for object.path.smooth, and `simplifySlider` for object.path.simplify; the dialogs of addon.color.applyNearestSwatch and addon.select.byArtboards have no `key`; smoothSlider and simplifySlider are the sliders over the canvas, with field `level`, and object.path.simplify opens its dialog `object.path.simplify` instead once OK in that dialog keeps the settings (`retain`); Set Fold Angle's `angle` is the selected fold lines' angle, and it is refused while the selection has no fold line it can change; Scale and Transform Each have `corners` and `strokes`, from the preferences, which OK updates; Transform Each opens on the values it was last confirmed with (not `copy`), and its Copy button confirms with `copy: true`; the envelope dialogs start from the selected envelope, Make opens as Reset (`reset: true`) while one is selected; variable.rename opens only while the document has a variable, and dataset.set and dataset.rename only while it has a data set, and otherwise the status bar says why; ui.dialog.set, ui.dialog.confirm and ui.dialog.cancel take the dialog's `id` from ui.inspect, or `top`, not its `key`)", ), ( "ui.widthPointEdit", diff --git a/crates/ui-egui/src/addons/cutting/tests.rs b/crates/ui-egui/src/addons/cutting/tests.rs index b177f72604..a22e907c04 100644 --- a/crates/ui-egui/src/addons/cutting/tests.rs +++ b/crates/ui-egui/src/addons/cutting/tests.rs @@ -35,10 +35,6 @@ fn rect(app: &mut VectorcraftApp, x: f64, y: f64, width: f64, height: f64) -> u6 id_of(app.run("shape.rectangle", json!({"x": x, "y": y, "width": width, "height": height})).unwrap()) } -fn circle(app: &mut VectorcraftApp, cx: f64, cy: f64, r: f64) -> u64 { - id_of(app.run("shape.ellipse", json!({"x": cx - r, "y": cy - r, "width": 2.0 * r, "height": 2.0 * r})).unwrap()) -} - fn select(app: &mut VectorcraftApp, ids: &[u64]) { app.run("select.set", json!({ "ids": ids })).unwrap(); } @@ -224,35 +220,6 @@ fn each_addon_dialog_opens_on_its_items_values_and_runs_its_command() { assert!(b > a, "the second object lies right of the first: {a}, {b}"); }, }, - Row { - name: "common tangents", - menu: "Path Precision Tools", - label: "Common Tangents…", - command: crate::addons::pathtools::COMMON_TANGENTS, - setup: |app| { - let (a, b) = (circle(app, 60.0, 150.0, 20.0), circle(app, 220.0, 150.0, 40.0)); - select(app, &[a, b]); - }, - opens: || json!({"tangents": "all", "centerline": false}), - set: || json!({}), - check: |app, start| { - assert_eq!(nodes(app), start.node_count() + 4, "four tangent lines"); - // Each kind the list offers is one the command takes. - for (_, kind) in crate::addons::pathtools::TANGENT_KINDS { - let params = json!({"tangents": kind}); - assert!(vectorcraft_engine::check_params(crate::addons::pathtools::COMMON_TANGENTS, ¶ms).is_ok(), "{kind}"); - } - // A circle inside another: nothing changes, and a message says why. - let ids = children(start); - let inner = circle(app, 220.0, 150.0, 10.0); - select(app, &[ids[1], inner]); - let (n, count) = (steps(app), nodes(app)); - open_item(app, "Path Precision Tools", "Common Tangents…"); - answer(app, true); - assert_eq!((steps(app), nodes(app)), (n, count)); - assert!(app.ui.status.contains("inside the other"), "{}", app.ui.status); - }, - }, Row { name: "add bounding rectangle", menu: "Path Precision Tools", diff --git a/crates/ui-egui/src/addons/dialogs.rs b/crates/ui-egui/src/addons/dialogs.rs index 4abd73e430..a607911e16 100644 --- a/crates/ui-egui/src/addons/dialogs.rs +++ b/crates/ui-egui/src/addons/dialogs.rs @@ -104,7 +104,8 @@ pub(crate) fn open_from_menu(app: &mut VectorcraftApp, id: &str) -> Option Result = match id { pathtools::set_corners::COMMAND => pathtools::set_corners::open, pathtools::dashes::COMMAND => pathtools::dashes::open, - pathtools::bridge::COMMAND => pathtools::bridge::open, + pathtools::COMMON_TANGENTS => pathtools::tangents::open, + pathtools::tangents::BRIDGE => pathtools::tangents::open_connected, pathtools::tangent_circle::COMMAND => pathtools::tangent_circle::open, typetools::COMMAND => typetools::open, color::legend::COMMAND => color::legend::open, diff --git a/crates/ui-egui/src/addons/dialogs/tests.rs b/crates/ui-egui/src/addons/dialogs/tests.rs index c0d1c572f2..dc2372552e 100644 --- a/crates/ui-egui/src/addons/dialogs/tests.rs +++ b/crates/ui-egui/src/addons/dialogs/tests.rs @@ -183,10 +183,10 @@ fn rows() -> Vec { }, Row { group: "Path Precision Tools", - label: "Smooth Bridge…", + label: "Common Tangents…", setup: two_circles, refused: Vec::new, - values: || vec![("keepOriginals", json!(true))], + values: || vec![("tangents", json!("external")), ("sides", json!("curved")), ("keepOriginals", json!(true))], check: |app| assert_eq!(count(app), 3, "the circles and the outline above them"), }, Row { diff --git a/crates/ui-egui/src/addons/pathtools.rs b/crates/ui-egui/src/addons/pathtools.rs index 324f907615..2cb01c3e29 100644 --- a/crates/ui-egui/src/addons/pathtools.rs +++ b/crates/ui-egui/src/addons/pathtools.rs @@ -1,6 +1,6 @@ //! Path Precision Tools in the interface: its submenu (Object › Plug-ins › Path Precision Tools), //! which selects its tools, opens its panels and runs Split / Add Points at Crossings, Set Corners… ([`set_corners`]), Divide into -//! Dashes ([`dashes`]), Expand Dashes into Paths, Smooth Bridge ([`bridge`]), Convert to Parametric Shape, Tangent Circle… ([`tangent_circle`]), Add Bounding Rectangle…, Add Bounding Circle… and Add Inscribed Circle; the Anchor Inspector panel (the selected +//! Dashes ([`dashes`]), Expand Dashes into Paths, Convert to Parametric Shape, Tangent Circle… ([`tangent_circle`]), Common Tangents… (the tangent lines, or circles connected along them, [`tangents`]), Add Bounding Rectangle…, Add Bounding Circle… and Add Inscribed Circle; the Anchor Inspector panel (the selected //! anchor's position and handles as numbers, the add-on's anchor edits, the Corner Tool's values, //! [`corner`], and the Shared Edge Merge Tool's, [`shared_edge`]); the Parametric Shape panel //! ([`shape`]); its tools' options dialog (a double-click on the tool); and the Tangent Circle Tool's radius dialog @@ -8,7 +8,6 @@ //! dialog draws its circle with `shape.circleThroughPoints`. Canceling an Anchor Inspector field edit restores its //! opening value: an anchor edit is one undo step that the cancel takes back. -pub mod bridge; pub mod corner; pub mod dashes; pub mod set_corners; @@ -16,6 +15,7 @@ pub mod shape; pub mod shared_edge; pub mod tangent_circle; pub mod tangent_circle_radius; +pub mod tangents; use craft::behavior::{ColumnWidth, EditEvents}; use craft::menu::Node; @@ -45,7 +45,7 @@ use crate::{VectorcraftApp, fields}; pub const ID: &str = "anchorInspector"; /// The tools' options dialog. pub const KIND: &str = "pathToolOptions"; -/// Common Tangents' command, whose menu item opens the command dialog with a Preview. +/// Common Tangents' command, whose menu item opens its dialog ([`tangents`]). pub const COMMON_TANGENTS: &str = "addon.pathtools.commonTangents"; /// The kinds of tangent Common Tangents' `tangents` picks, and their labels. pub const TANGENT_KINDS: &[(&str, &str)] = &[("All", "all"), ("External", "external"), ("Internal", "internal")]; @@ -143,10 +143,9 @@ pub fn menu() -> Vec { cp("Split at Crossings", "addon.pathtools.crossings", json!({ "cut": true })), c("Divide into Dashes…", dashes::COMMAND), cp("Expand Dashes into Paths", "addon.pathtools.expandDashes", json!({})), - c("Smooth Bridge…", bridge::COMMAND), cp("Convert to Parametric Shape", "addon.pathtools.shape.convert", json!({})), c("Tangent Circle…", tangent_circle::COMMAND), - cp("Common Tangents…", COMMON_TANGENTS, json!({ "tangents": "all", "centerline": false })), + c("Common Tangents…", COMMON_TANGENTS), cp("Add Bounding Rectangle…", BOUNDING_RECTANGLE, json!({ "offset": 0, "each": false })), cp("Add Bounding Circle…", BOUNDING_CIRCLE, json!({ "offset": 0, "each": false })), cp("Add Inscribed Circle", INSCRIBED_CIRCLE, json!({})), diff --git a/crates/ui-egui/src/addons/pathtools/bridge.rs b/crates/ui-egui/src/addons/pathtools/bridge.rs deleted file mode 100644 index 5ddeee621b..0000000000 --- a/crates/ui-egui/src/addons/pathtools/bridge.rs +++ /dev/null @@ -1,254 +0,0 @@ -//! Smooth Bridge in the interface: its dialog (the arcs' radius as a percentage of the smaller -//! circle's radius, or with Constant Gap that radius plus a gap; the reach, unavailable with two -//! circles selected; Keep Originals), which previews on the canvas and runs -//! `addon.pathtools.bridge` on OK. - -use craft::ui::contract::Bind; -use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue, Param, ParamDialog, ParamKind}; -use craft::ui::runtime::env::UnitKind; -use serde_json::{Value, json}; - -use crate::VectorcraftApp; -use crate::addons::dialogs::{self, Spec}; -use crate::canvas::rulers::general_lengths; - -/// The command. -pub const COMMAND: &str = "addon.pathtools.bridge"; -/// The radius the command takes (%), and its default. -const RADII: std::ops::RangeInclusive = 1.0..=1000.0; -const RADIUS: f64 = 100.0; -/// The gap the command takes (pt), and the dialog's first one. -const GAPS: std::ops::RangeInclusive = 0.0..=1000.0; -const GAP: f64 = 4.0; -/// The reach the command takes (pt), and its default. -const REACHES: std::ops::RangeInclusive = 0.0..=10000.0; -const REACH: f64 = 10.0; - -/// How the dialog's values reach the command. -pub(crate) static SPEC: Spec = Spec { command: COMMAND, params, found: None }; - -/// The command's parameters from the dialog's fields: the radius, or with Constant Gap the gap. -fn params(fields: &DialogFields) -> Value { - let (reach, keep) = (fields.number("reach").unwrap_or(REACH), fields.bool("keepOriginals").unwrap_or(false)); - if fields.bool("constantGap").unwrap_or(false) { - json!({ "gap": fields.number("gap").unwrap_or(GAP), "reach": reach, "keepOriginals": keep }) - } else { - json!({ "radius": fields.number("radius").unwrap_or(RADIUS), "reach": reach, "keepOriginals": keep }) - } -} - -/// Opens Smooth Bridge's dialog on the command's defaults. -pub(crate) fn open(app: &mut VectorcraftApp) -> Result { - // The reach applies to three or more circles; two are bridged at any distance. Counted once, before a preview - // replaces the selection with its result, with a selected group counting the objects inside it. - let many = app.session.doc().map(|doc| members(&doc.doc, &doc.selection.objects) > 2).unwrap_or(true); - let fields = DialogFields::from_pairs([ - ("radius", FieldValue::Number(RADIUS)), - ("constantGap", FieldValue::Bool(false)), - ("gap", FieldValue::Number(GAP)), - ("reach", FieldValue::Number(REACH)), - ("keepOriginals", FieldValue::Bool(false)), - ("many", FieldValue::Bool(many)), - ]); - let lengths = general_lengths(app); - dialogs::open(app, &SPEC, fields, move |fields| { - let rows = vec![ - Param::new("constantGap", tl!("Constant Gap"), ParamKind::bool(false)), - Param::number("gap", tl!("Gap:"), GAP, 1.0, 2) - .length(lengths) - .bounds(Some(*GAPS.start()), Some(*GAPS.end())) - .visible_when("constantGap", FieldValue::Bool(true)), - Param::number("radius", tl!("Radius:"), RADIUS, 1.0, 0) - .unit(UnitKind::Percent) - .bounds(Some(*RADII.start()), Some(*RADII.end())) - .visible_when("constantGap", FieldValue::Bool(false)), - Param::number("reach", tl!("Reach:"), REACH, 1.0, 2) - .length(lengths) - .bounds(Some(*REACHES.start()), Some(*REACHES.end())) - .enabled_when("many", FieldValue::Bool(true)), - Param::new("keepOriginals", tl!("Keep Originals"), ParamKind::bool(false)), - ]; - ParamDialog::new(COMMAND, tl!("Smooth Bridge"), rows).previews(true).values(Bind::bound(fields)) - }) -} - -/// How many objects the command bridges for objects `ids`: each one, or for a group (a clipping group excepted) the -/// objects inside it, at any depth; an object given twice, or with its group, counts once. -fn members(doc: &vectorcraft_doc::Document, ids: &[vectorcraft_doc::NodeId]) -> usize { - fn visit(n: &vectorcraft_doc::Node, out: &mut std::collections::BTreeSet) { - match &n.kind { - vectorcraft_doc::NodeKind::Group { children, clip: false } => children.iter().for_each(|c| visit(c, out)), - _ => { - out.insert(n.id); - } - } - } - let mut out = std::collections::BTreeSet::new(); - for n in ids.iter().filter_map(|&id| doc.node(id)) { - visit(n, &mut out); - } - out.len() -} - -#[cfg(test)] -mod tests { - use serde_json::{Value, json}; - use vectorcraft_engine::Session; - - use crate::addons::dialogs::tests::{confirm, dialog_id, frame, read, set}; - use crate::{VectorcraftApp, menus}; - - fn circle(app: &mut VectorcraftApp, x: f64, r: f64) -> u64 { - app.run("shape.ellipse", json!({"x": x - r, "y": 100.0 - r, "width": 2.0 * r, "height": 2.0 * r})).unwrap()["id"].as_u64().unwrap() - } - - fn bridge_app(xs: &[f64]) -> VectorcraftApp { - let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), Default::default())); - app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); - let ids: Vec = xs.iter().map(|&x| circle(&mut app, x, 10.0)).collect(); - app.run("select.set", json!({"ids": ids})).unwrap(); - app - } - - fn geometry(app: &VectorcraftApp) -> Vec { - app.session.doc().unwrap().doc.layers[0].children().unwrap().iter().map(|node| node.kind.clone()).collect() - } - - fn type_number(panel: &mut crate::tests::panel_harness::Panel, label: &str, text: &str) { - panel.click(label); - panel.key(egui::Key::A, egui::Modifiers::COMMAND); - panel.type_text(text); - panel.key(egui::Key::Tab, egui::Modifiers::NONE); - panel.frame(); - } - - #[test] - fn real_bridge_controls_change_the_preview_and_confirmed_geometry() { - use crate::tests::panel_harness::Panel; - - let mut panel = Panel::new(bridge_app(&[100.0, 124.0]), crate::tests::picks::dialogs); - let before = panel.app().session.doc().unwrap().history.undo.len(); - menus::invoke(&mut panel.app(), super::COMMAND, Value::Null); - panel.frame(); - assert!(!panel.enabled("Reach"), "two circles can be bridged at any distance"); - panel.click("Keep Originals"); - type_number(&mut panel, "Radius", "150"); - let id = dialog_id(&panel.app()); - assert_eq!(read(&panel.app(), id, |f| f.number("radius")), Some(150.0)); - let mut expected = bridge_app(&[100.0, 124.0]); - expected.session.execute(super::COMMAND, &json!({"radius": 150, "keepOriginals": true})).unwrap(); - assert_eq!(geometry(&panel.app()), geometry(&expected)); - assert_eq!(geometry(&panel.app()).len(), 3, "both circles stay beside the bridge"); - - panel.click("Constant Gap"); - type_number(&mut panel, "Gap", "6"); - let params = read(&panel.app(), id, super::params); - assert_eq!(params, json!({"gap": 6.0, "reach": 10.0, "keepOriginals": true})); - let mut expected = bridge_app(&[100.0, 124.0]); - expected.session.execute(super::COMMAND, ¶ms).unwrap(); - let preview = geometry(&panel.app()); - assert_eq!(preview, geometry(&expected)); - panel.click("OK"); - panel.frame(); - assert_eq!(geometry(&panel.app()), preview); - assert_eq!(panel.app().session.doc().unwrap().history.undo.len(), before + 1); - assert!(!panel.app().any_dialog_open()); - } - - #[test] - fn real_bridge_reach_edit_reaches_the_command_and_cancel_restores_the_originals() { - use crate::tests::panel_harness::Panel; - - let mut panel = Panel::new(bridge_app(&[100.0, 124.0, 148.0, 300.0]), crate::tests::picks::dialogs); - let original = geometry(&panel.app()); - menus::invoke(&mut panel.app(), super::COMMAND, Value::Null); - panel.frame(); - assert!(panel.enabled("Reach")); - type_number(&mut panel, "Reach", "5"); - let id = dialog_id(&panel.app()); - let params = read(&panel.app(), id, super::params); - assert_eq!(params["reach"], 5.0); - let mut expected = bridge_app(&[100.0, 124.0, 148.0, 300.0]); - expected.session.execute(super::COMMAND, ¶ms).unwrap(); - assert_eq!(geometry(&panel.app()), geometry(&expected)); - panel.click("Cancel"); - panel.frame(); - assert_eq!(geometry(&panel.app()), original); - } - - #[test] - fn reach_counts_the_circles_inside_a_selected_group() { - use crate::tests::panel_harness::Panel; - - for (xs, many) in [(&[100.0, 124.0][..], false), (&[100.0, 124.0, 148.0][..], true)] { - let mut app = bridge_app(xs); - let ids: Vec = app.session.doc().unwrap().selection.objects.iter().map(|id| id.0).collect(); - let group = app.run("object.group", json!({ "ids": ids })).unwrap()["id"].as_u64().unwrap(); - app.run("select.set", json!({"ids": [group]})).unwrap(); - let mut panel = Panel::new(app, crate::tests::picks::dialogs); - menus::invoke(&mut panel.app(), super::COMMAND, Value::Null); - panel.frame(); - assert_eq!(panel.enabled("Reach"), many, "{} circles in the group", xs.len()); - panel.click("OK"); - panel.frame(); - let inside = panel.app().session.doc().unwrap().doc.node(vectorcraft_doc::NodeId(group)).unwrap().children().unwrap().len(); - assert_eq!(inside, 1, "the circles in the group became one shape"); - } - // A group of two circles selected together with one of them: still two circles. - let mut app = bridge_app(&[100.0, 124.0]); - let ids: Vec = app.session.doc().unwrap().selection.objects.iter().map(|id| id.0).collect(); - let group = app.run("object.group", json!({ "ids": ids })).unwrap()["id"].as_u64().unwrap(); - app.run("select.set", json!({"ids": [group, ids[0]]})).unwrap(); - assert_eq!(app.session.doc().unwrap().selection.objects.len(), 2); - let mut panel = Panel::new(app, crate::tests::picks::dialogs); - menus::invoke(&mut panel.app(), super::COMMAND, Value::Null); - panel.frame(); - assert!(!panel.enabled("Reach"), "a circle selected with its group counts once"); - } - - #[test] - fn constant_gap_shows_the_gap_and_bridges_many_circles_within_reach() { - let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), Default::default())); - app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); - // Three circles 4 apart in a row and one far off. - let ids: Vec = [100.0, 124.0, 148.0, 300.0].iter().map(|&x| circle(&mut app, x, 10.0)).collect(); - app.run("select.set", json!({ "ids": ids })).unwrap(); - menus::invoke(&mut app, super::COMMAND, Value::Null); - let dialog = dialog_id(&app); - set(&app, dialog, "constantGap", json!(true)); - // A preview leaves two objects selected (one shape and the far circle); Reach stays available for the - // four circles the command still bridges. - frame(&mut app); - assert_eq!(app.session.doc().unwrap().selection.objects.len(), 2, "previewed"); - let (many, params) = read(&app, dialog, |fields| (fields.bool("many"), (super::SPEC.params)(fields))); - assert_eq!(many, Some(true), "Reach available for four circles"); - assert_eq!(params, json!({"gap": 4.0, "reach": 10.0, "keepOriginals": false}), "the gap, not the radius"); - assert!(confirm(&app, dialog), "OK is on"); - frame(&mut app); - let top: Vec = app.session.doc().unwrap().doc.layers[0].children().unwrap().iter().map(|n| n.id.0).collect(); - assert_eq!(top, [ids[2], ids[3]], "one shape in the topmost joined circle's place, and the far circle"); - } - - #[test] - fn the_status_line_says_why_an_ellipse_is_refused() { - use crate::tests::panel_harness::Panel; - - let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), Default::default())); - app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); - let a = circle(&mut app, 100.0, 10.0); - let oval = app.run("shape.ellipse", json!({"x": 130, "y": 90, "width": 20, "height": 21})).unwrap()["id"].as_u64().unwrap(); - app.run("select.set", json!({"ids": [a, oval]})).unwrap(); - let original = geometry(&app); - let mut panel = Panel::new(app, crate::tests::picks::dialogs); - let before = panel.app().session.doc().unwrap().history.undo.len(); - menus::invoke(&mut panel.app(), super::COMMAND, Value::Null); - panel.frame(); - let why = "an ellipse whose width and height differ is not a circle"; - assert!(panel.app().ui.status.contains(why), "the preview's refusal: {}", panel.app().ui.status); - panel.click("OK"); - panel.frame(); - assert!(panel.app().ui.status.contains(why), "OK's refusal: {}", panel.app().ui.status); - assert_eq!(geometry(&panel.app()), original); - assert_eq!(panel.app().session.doc().unwrap().history.undo.len(), before, "no undo step"); - } -} diff --git a/crates/ui-egui/src/addons/pathtools/tangents.rs b/crates/ui-egui/src/addons/pathtools/tangents.rs new file mode 100644 index 0000000000..1c1587a0d5 --- /dev/null +++ b/crates/ui-egui/src/addons/pathtools/tangents.rs @@ -0,0 +1,150 @@ +//! Common Tangents in the interface: one dialog for the tangent lines of two shapes and for circles joined by a smooth +//! bridge. It picks the kind of tangent, the centerline and Connect tangents (the two tangents of each kind joined into +//! one closed shape). With External, Straight keeps the tangent lines and Curved joins the circles along concave arcs +//! instead (the arcs' radius as a percentage of the smaller circle's radius, or with Constant Gap that radius plus a +//! gap; the reach, unavailable with two circles selected; Keep Originals), as `addon.pathtools.bridge` does. It +//! previews on the canvas and runs `addon.pathtools.commonTangents` on OK. Smooth Bridge's command id opens the same +//! dialog with External and Curved on. + +use craft::ui::contract::Bind; +use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue, Param, ParamDialog, ParamKind}; +use craft::ui::runtime::env::UnitKind; +use serde_json::{Value, json}; + +use crate::VectorcraftApp; +use crate::addons::dialogs::{self, Spec}; +use crate::canvas::rulers::general_lengths; + +use super::{COMMON_TANGENTS, TANGENT_KINDS}; + +/// Smooth Bridge's command, which opens this dialog with External and Curved on. +pub const BRIDGE: &str = "addon.pathtools.bridge"; +/// The kind of tangent the dialog opens with. +const TANGENTS: &str = "all"; +/// The tangents that Curved replaces with arcs. +const EXTERNAL: &str = "external"; +/// What joins the circles with External, and its labels; the first is the default. +const SIDES: [(&str, &str); 2] = [("straight", "Straight"), ("curved", "Curved")]; +/// The radius the command takes (%), and its default. +const RADII: std::ops::RangeInclusive = 1.0..=1000.0; +const RADIUS: f64 = 100.0; +/// The gap the command takes (pt), and the dialog's first one. +const GAPS: std::ops::RangeInclusive = 0.0..=1000.0; +const GAP: f64 = 4.0; +/// The reach the command takes (pt), and its default. +const REACHES: std::ops::RangeInclusive = 0.0..=10000.0; +const REACH: f64 = 10.0; + +/// How the dialog's values reach the command. +pub(crate) static SPEC: Spec = Spec { command: COMMON_TANGENTS, params, found: None }; + +/// Whether the fields ask for a curved bridge: External with Curved. +fn curved(fields: &DialogFields) -> bool { + fields.text("tangents") == Some(EXTERNAL) && fields.text("sides") == Some("curved") +} + +/// The command's parameters from the dialog's fields: the tangent lines' kind, centerline and Connect tangents, or for +/// a curved bridge the radius (or with Constant Gap the gap), the reach and Keep Originals. +fn params(fields: &DialogFields) -> Value { + if !curved(fields) { + return json!({ + "tangents": fields.text("tangents").unwrap_or(TANGENTS), + "centerline": fields.bool("centerline").unwrap_or(false), + "connect": fields.bool("connect").unwrap_or(false), + }); + } + let (reach, keep) = (fields.number("reach").unwrap_or(REACH), fields.bool("keepOriginals").unwrap_or(false)); + if fields.bool("constantGap").unwrap_or(false) { + json!({ "tangents": EXTERNAL, "curved": true, "gap": fields.number("gap").unwrap_or(GAP), "reach": reach, "keepOriginals": keep }) + } else { + json!({ "tangents": EXTERNAL, "curved": true, "radius": fields.number("radius").unwrap_or(RADIUS), "reach": reach, "keepOriginals": keep }) + } +} + +/// Opens Common Tangents' dialog for the tangent lines. +pub(crate) fn open(app: &mut VectorcraftApp) -> Result { + open_with(app, false) +} + +/// Opens Common Tangents' dialog with External and Curved on, for Smooth Bridge's command. +pub(crate) fn open_connected(app: &mut VectorcraftApp) -> Result { + open_with(app, true) +} + +fn open_with(app: &mut VectorcraftApp, bridge: bool) -> Result { + // The reach applies to three or more circles; two are bridged at any distance. Counted once, before a preview + // replaces the selection with its result, with a selected group counting the objects inside it. + let many = app.session.doc().map(|doc| members(&doc.doc, &doc.selection.objects) > 2).unwrap_or(true); + let fields = DialogFields::from_pairs([ + ("tangents", FieldValue::from(if bridge { EXTERNAL } else { TANGENTS })), + ("centerline", FieldValue::Bool(false)), + ("connect", FieldValue::Bool(bridge)), + ("sides", FieldValue::from(if bridge { "curved" } else { "straight" })), + ("constantGap", FieldValue::Bool(false)), + ("radius", FieldValue::Number(RADIUS)), + ("gap", FieldValue::Number(GAP)), + ("reach", FieldValue::Number(REACH)), + ("keepOriginals", FieldValue::Bool(false)), + ("many", FieldValue::Bool(many)), + ]); + let lengths = general_lengths(app); + dialogs::open(app, &SPEC, fields, move |fields| { + let kinds = TANGENT_KINDS.iter().map(|(label, id)| ((*id).to_owned(), tl!(label).into())).collect(); + let sides = SIDES.iter().map(|(id, label)| ((*id).to_owned(), tl!(label).into())).collect(); + let curved = || ["curved"]; + // Picking another kind of tangent goes back to Straight, so Curved only holds while External does. + let rows = vec![ + Param::new("tangents", tl!("Tangents:"), ParamKind::choice(kinds, Some(TANGENTS.to_owned()))).resets(["sides"]), + Param::new("centerline", tl!("Centerline"), ParamKind::bool(false)).enabled_when("sides", "straight"), + // A curved bridge is always connected. + Param::new("connect", tl!("Connect tangents"), ParamKind::bool(false)).enabled_when("sides", "straight").disabled_value(true), + Param::new("sides", tl!("Sides"), ParamKind::radio(sides, Some(SIDES[0].0.to_owned()))).visible_when("tangents", EXTERNAL), + Param::new("constantGap", tl!("Constant Gap"), ParamKind::bool(false)) + .visible_when("tangents", EXTERNAL) + .enabled_when_in("sides", curved()), + Param::number("gap", tl!("Gap:"), GAP, 1.0, 2) + .length(lengths) + .bounds(Some(*GAPS.start()), Some(*GAPS.end())) + .visible_when("tangents", EXTERNAL) + .visible_when_in("constantGap", [true]) + .enabled_when_in("sides", curved()), + Param::number("radius", tl!("Radius:"), RADIUS, 1.0, 0) + .unit(UnitKind::Percent) + .bounds(Some(*RADII.start()), Some(*RADII.end())) + .visible_when("tangents", EXTERNAL) + .visible_when_in("constantGap", [false]) + .enabled_when_in("sides", curved()), + Param::number("reach", tl!("Reach:"), REACH, 1.0, 2) + .length(lengths) + .bounds(Some(*REACHES.start()), Some(*REACHES.end())) + .visible_when("tangents", EXTERNAL) + .enabled_when_in("sides", curved()) + .and_enabled_when_in("many", [true]), + Param::new("keepOriginals", tl!("Keep Originals"), ParamKind::bool(false)) + .visible_when("tangents", EXTERNAL) + .enabled_when_in("sides", curved()), + ]; + ParamDialog::new(COMMON_TANGENTS, tl!("Common Tangents"), rows).previews(true).values(Bind::bound(fields)) + }) +} + +/// How many objects the command bridges for objects `ids`: each one, or for a group (a clipping group excepted) the +/// objects inside it, at any depth; an object given twice, or with its group, counts once. +fn members(doc: &vectorcraft_doc::Document, ids: &[vectorcraft_doc::NodeId]) -> usize { + fn visit(n: &vectorcraft_doc::Node, out: &mut std::collections::BTreeSet) { + match &n.kind { + vectorcraft_doc::NodeKind::Group { children, clip: false } => children.iter().for_each(|c| visit(c, out)), + _ => { + out.insert(n.id); + } + } + } + let mut out = std::collections::BTreeSet::new(); + for n in ids.iter().filter_map(|&id| doc.node(id)) { + visit(n, &mut out); + } + out.len() +} + +#[cfg(test)] +mod tests; diff --git a/crates/ui-egui/src/addons/pathtools/tangents/tests.rs b/crates/ui-egui/src/addons/pathtools/tangents/tests.rs new file mode 100644 index 0000000000..c3f1b84163 --- /dev/null +++ b/crates/ui-egui/src/addons/pathtools/tangents/tests.rs @@ -0,0 +1,244 @@ +//! Common Tangents' dialog: the tangent lines, Connect tangents, External's Straight or Curved bridge, Smooth +//! Bridge's command opening it curved, the reach's availability, Cancel and the refusals on the status line. + +use serde_json::{Value, json}; +use vectorcraft_engine::Session; + +use super::{BRIDGE, COMMON_TANGENTS}; +use crate::addons::dialogs::tests::{confirm, dialog_id, frame, read, set}; +use crate::tests::panel_harness::Panel; +use crate::{VectorcraftApp, menus}; + +fn circle(app: &mut VectorcraftApp, x: f64, r: f64) -> u64 { + app.run("shape.ellipse", json!({"x": x - r, "y": 100.0 - r, "width": 2.0 * r, "height": 2.0 * r})).unwrap()["id"].as_u64().unwrap() +} + +fn circles_app(xs: &[f64]) -> VectorcraftApp { + let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), Default::default())); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + let ids: Vec = xs.iter().map(|&x| circle(&mut app, x, 10.0)).collect(); + app.run("select.set", json!({"ids": ids})).unwrap(); + app +} + +fn geometry(app: &VectorcraftApp) -> Vec { + app.session.doc().unwrap().doc.layers[0].children().unwrap().iter().map(|node| node.kind.clone()).collect() +} + +fn steps(app: &VectorcraftApp) -> usize { + app.session.doc().unwrap().history.undo.len() +} + +fn type_number(panel: &mut Panel, label: &str, text: &str) { + panel.click(label); + panel.key(egui::Key::A, egui::Modifiers::COMMAND); + panel.type_text(text); + panel.key(egui::Key::Tab, egui::Modifiers::NONE); + panel.frame(); +} + +/// The geometry the command makes on `xs`'s circles with `params`. +fn expected(xs: &[f64], params: &Value) -> Vec { + let mut app = circles_app(xs); + app.session.execute(COMMON_TANGENTS, params).unwrap(); + geometry(&app) +} + +#[test] +fn the_menu_item_adds_the_tangent_lines_and_only_their_options_take_input() { + let xs = [100.0, 200.0]; + let mut panel = Panel::new(circles_app(&xs), crate::tests::picks::dialogs); + let before = steps(&panel.app()); + menus::invoke(&mut panel.app(), COMMON_TANGENTS, Value::Null); + panel.frame(); + assert!(panel.enabled("Centerline") && panel.enabled("Tangents") && panel.enabled("Connect tangents")); + assert!(!panel.shows("Radius") && !panel.shows("Straight"), "the bridge's options wait for External"); + panel.click("Centerline"); + panel.frame(); + let id = dialog_id(&panel.app()); + let params = read(&panel.app(), id, super::params); + assert_eq!(params, json!({"tangents": "all", "centerline": true, "connect": false})); + assert_eq!(geometry(&panel.app()), expected(&xs, ¶ms), "the preview"); + assert_eq!(geometry(&panel.app()).len(), 2 + 5, "four tangents and the centerline beside the circles"); + panel.click("OK"); + panel.frame(); + assert_eq!(steps(&panel.app()), before + 1); + assert!(!panel.app().any_dialog_open()); +} + +#[test] +fn external_shows_straight_or_curved_and_curved_takes_the_bridge_options() { + let xs = [100.0, 124.0]; + let mut panel = Panel::new(circles_app(&xs), crate::tests::picks::dialogs); + let before = steps(&panel.app()); + menus::invoke(&mut panel.app(), COMMON_TANGENTS, Value::Null); + panel.frame(); + let id = dialog_id(&panel.app()); + set(&panel.app(), id, "tangents", json!("external")); + panel.frame(); + assert!(panel.shows("Straight") && panel.shows("Radius"), "External shows the bridge's options"); + assert!(!panel.enabled("Radius") && !panel.enabled("Keep Originals"), "Straight keeps them unavailable"); + panel.click("Connect tangents"); + panel.frame(); + let straight = read(&panel.app(), id, super::params); + assert_eq!(straight, json!({"tangents": "external", "centerline": false, "connect": true})); + assert_eq!(geometry(&panel.app()), expected(&xs, &straight)); + assert_eq!(geometry(&panel.app()).len(), 3, "the circles and one closed shape"); + + panel.click("Curved"); + panel.frame(); + assert!(panel.enabled("Radius") && panel.enabled("Keep Originals") && !panel.enabled("Centerline")); + let curved = read(&panel.app(), id, super::params); + assert_eq!(curved, json!({"tangents": "external", "curved": true, "radius": 100.0, "reach": 10.0, "keepOriginals": false})); + let preview = geometry(&panel.app()); + assert_eq!(preview, expected(&xs, &curved)); + assert_eq!(preview.len(), 1, "the bridge replaces the circles"); + + // Another kind of tangent goes back to Straight and the lines' options. + set(&panel.app(), id, "tangents", json!("internal")); + panel.frame(); + assert!(panel.enabled("Centerline") && !panel.shows("Curved")); + assert_eq!(read(&panel.app(), id, super::params)["tangents"], "internal"); + set(&panel.app(), id, "tangents", json!("external")); + panel.frame(); + panel.click("Curved"); + panel.frame(); + panel.click("OK"); + panel.frame(); + assert_eq!(geometry(&panel.app()), preview); + assert_eq!(steps(&panel.app()), before + 1, "one undo step"); +} + +#[test] +fn the_bridge_command_opens_the_dialog_connected_and_its_controls_reach_the_command() { + let xs = [100.0, 124.0]; + let mut panel = Panel::new(circles_app(&xs), crate::tests::picks::dialogs); + let before = steps(&panel.app()); + menus::invoke(&mut panel.app(), BRIDGE, Value::Null); + panel.frame(); + assert!(panel.enabled("Radius"), "External and Curved are on"); + assert!(!panel.enabled("Reach"), "two circles can be bridged at any distance"); + panel.click("Keep Originals"); + type_number(&mut panel, "Radius", "150"); + let id = dialog_id(&panel.app()); + assert_eq!(read(&panel.app(), id, |f| f.number("radius")), Some(150.0)); + let mut old = circles_app(&xs); + old.session.execute(BRIDGE, &json!({"radius": 150, "keepOriginals": true})).unwrap(); + assert_eq!(geometry(&panel.app()), geometry(&old), "the same outline Smooth Bridge makes"); + assert_eq!(geometry(&panel.app()).len(), 3, "both circles stay beside the bridge"); + + panel.click("Constant Gap"); + type_number(&mut panel, "Gap", "6"); + let params = read(&panel.app(), id, super::params); + assert_eq!(params, json!({"tangents": "external", "curved": true, "gap": 6.0, "reach": 10.0, "keepOriginals": true})); + let preview = geometry(&panel.app()); + assert_eq!(preview, expected(&xs, ¶ms)); + panel.click("OK"); + panel.frame(); + assert_eq!(geometry(&panel.app()), preview); + assert_eq!(steps(&panel.app()), before + 1); + assert!(!panel.app().any_dialog_open()); +} + +#[test] +fn a_reach_edit_reaches_the_command_and_cancel_restores_the_originals() { + let xs = [100.0, 124.0, 148.0, 300.0]; + let mut panel = Panel::new(circles_app(&xs), crate::tests::picks::dialogs); + let original = geometry(&panel.app()); + menus::invoke(&mut panel.app(), BRIDGE, Value::Null); + panel.frame(); + assert!(panel.enabled("Reach")); + type_number(&mut panel, "Reach", "5"); + let id = dialog_id(&panel.app()); + let params = read(&panel.app(), id, super::params); + assert_eq!(params["reach"], 5.0); + assert_eq!(geometry(&panel.app()), expected(&xs, ¶ms)); + panel.click("Cancel"); + panel.frame(); + assert_eq!(geometry(&panel.app()), original); +} + +#[test] +fn reach_counts_the_circles_inside_a_selected_group() { + for (xs, many) in [(&[100.0, 124.0][..], false), (&[100.0, 124.0, 148.0][..], true)] { + let mut app = circles_app(xs); + let ids: Vec = app.session.doc().unwrap().selection.objects.iter().map(|id| id.0).collect(); + let group = app.run("object.group", json!({ "ids": ids })).unwrap()["id"].as_u64().unwrap(); + app.run("select.set", json!({"ids": [group]})).unwrap(); + let mut panel = Panel::new(app, crate::tests::picks::dialogs); + menus::invoke(&mut panel.app(), BRIDGE, Value::Null); + panel.frame(); + assert_eq!(panel.enabled("Reach"), many, "{} circles in the group", xs.len()); + panel.click("OK"); + panel.frame(); + let inside = panel.app().session.doc().unwrap().doc.node(vectorcraft_doc::NodeId(group)).unwrap().children().unwrap().len(); + assert_eq!(inside, 1, "the circles in the group became one shape"); + } + // A group of two circles selected together with one of them: still two circles. + let mut app = circles_app(&[100.0, 124.0]); + let ids: Vec = app.session.doc().unwrap().selection.objects.iter().map(|id| id.0).collect(); + let group = app.run("object.group", json!({ "ids": ids })).unwrap()["id"].as_u64().unwrap(); + app.run("select.set", json!({"ids": [group, ids[0]]})).unwrap(); + let mut panel = Panel::new(app, crate::tests::picks::dialogs); + menus::invoke(&mut panel.app(), BRIDGE, Value::Null); + panel.frame(); + assert!(!panel.enabled("Reach"), "a circle selected with its group counts once"); +} + +#[test] +fn constant_gap_bridges_many_circles_within_reach() { + let mut app = circles_app(&[100.0, 124.0, 148.0, 300.0]); + let ids: Vec = app.session.doc().unwrap().selection.objects.iter().map(|id| id.0).collect(); + menus::invoke(&mut app, BRIDGE, Value::Null); + let dialog = dialog_id(&app); + set(&app, dialog, "constantGap", json!(true)); + // A preview leaves two objects selected (one shape and the far circle); Reach stays available for the four + // circles the command still bridges. + frame(&mut app); + assert_eq!(app.session.doc().unwrap().selection.objects.len(), 2, "previewed"); + let (many, params) = read(&app, dialog, |fields| (fields.bool("many"), (super::SPEC.params)(fields))); + assert_eq!(many, Some(true), "Reach available for four circles"); + assert_eq!(params, json!({"tangents": "external", "curved": true, "gap": 4.0, "reach": 10.0, "keepOriginals": false}), "the gap, not the radius"); + assert!(confirm(&app, dialog), "OK is on"); + frame(&mut app); + let top: Vec = app.session.doc().unwrap().doc.layers[0].children().unwrap().iter().map(|n| n.id.0).collect(); + assert_eq!(top, [ids[2], ids[3]], "one shape in the topmost joined circle's place, and the far circle"); +} + +#[test] +fn the_status_line_says_why_a_selection_is_refused() { + // Connected: an ellipse is not a circle. + let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), Default::default())); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + let a = circle(&mut app, 100.0, 10.0); + let oval = app.run("shape.ellipse", json!({"x": 130, "y": 90, "width": 20, "height": 21})).unwrap()["id"].as_u64().unwrap(); + app.run("select.set", json!({"ids": [a, oval]})).unwrap(); + let original = geometry(&app); + let mut panel = Panel::new(app, crate::tests::picks::dialogs); + let before = steps(&panel.app()); + menus::invoke(&mut panel.app(), BRIDGE, Value::Null); + panel.frame(); + let why = "an ellipse whose width and height differ is not a circle"; + assert!(panel.app().ui.status.contains(why), "the preview's refusal: {}", panel.app().ui.status); + panel.click("OK"); + panel.frame(); + assert!(panel.app().ui.status.contains(why), "OK's refusal: {}", panel.app().ui.status); + assert_eq!(geometry(&panel.app()), original); + assert_eq!(steps(&panel.app()), before, "no undo step"); + + // The lines: a circle inside another has none, and the warning says so. + let mut app = circles_app(&[150.0]); + let outer = app.run("shape.ellipse", json!({"x": 100, "y": 50, "width": 100, "height": 100})).unwrap()["id"].as_u64().unwrap(); + let inner = app.session.doc().unwrap().doc.layers[0].children().unwrap()[0].id.0; + app.run("select.set", json!({"ids": [inner, outer]})).unwrap(); + let mut panel = Panel::new(app, crate::tests::picks::dialogs); + let before = steps(&panel.app()); + let count = geometry(&panel.app()).len(); + menus::invoke(&mut panel.app(), COMMON_TANGENTS, Value::Null); + panel.frame(); + panel.click("OK"); + panel.frame(); + assert_eq!(steps(&panel.app()), before); + assert_eq!(geometry(&panel.app()).len(), count); + assert!(panel.app().ui.status.contains("inside the other"), "{}", panel.app().ui.status); +} diff --git a/crates/ui-egui/src/dialogs/command.rs b/crates/ui-egui/src/dialogs/command.rs index 6d8741d342..6be16732f6 100644 --- a/crates/ui-egui/src/dialogs/command.rs +++ b/crates/ui-egui/src/dialogs/command.rs @@ -349,8 +349,7 @@ fn heading_in(lang: crate::i18n::Lang, label: &str) -> String { /// too (#5360), as public tutorials of the dialog show, and Type Tools › Release Type on a Path /// works the same way (#5532), and so do Image Tools › Remove Background and Color Mask and /// Cutting Tools › Weed Box and Lines, Banner Hems and Grommets and Nest Shapes, and Path -/// Precision Tools › Common Tangents and the bounding shapes (Add Bounding Rectangle… and Add -/// Bounding Circle…). (Cancel rolls a preview back whichever dialog started it.) +/// Precision Tools' bounding shapes (Add Bounding Rectangle… and Add Bounding Circle…). (Cancel rolls a preview back whichever dialog started it.) fn previews(command: &str, opening: &Map) -> bool { match command { "object.repeat.options" => opening.contains_key("gridType"), @@ -361,7 +360,6 @@ fn previews(command: &str, opening: &Map) -> bool { | crate::addons::cutting::WEED | crate::addons::cutting::BANNER | crate::addons::cutting::NEST - | crate::addons::pathtools::COMMON_TANGENTS | crate::addons::pathtools::BOUNDING_RECTANGLE | crate::addons::pathtools::BOUNDING_CIRCLE => true, _ => false, @@ -465,7 +463,6 @@ fn order(command: &str) -> &'static [&'static str] { } crate::addons::cutting::BRIDGES => &["width", "count", "direction", "keepOriginal"], crate::addons::packaging::SET_ROLE_SWATCH => &["role", "swatch"], - crate::addons::pathtools::COMMON_TANGENTS => &["tangents", "centerline"], crate::addons::pathtools::BOUNDING_RECTANGLE | crate::addons::pathtools::BOUNDING_CIRCLE => &["offset", "each"], "object.path.cleanUp" => &["strayPoints", "unpaintedObjects", "emptyTextPaths", "hairlineSlivers", "sliverWidth"], _ => &[], @@ -484,7 +481,6 @@ fn choices(command: &str, key: &str) -> Option { ("text.areaOptions", "firstBaseline") => Some(FIRST_BASELINE), ("text.areaOptions", "verticalAlign") => Some(VERTICAL_ALIGN), (crate::addons::cutting::WEED, "direction") => Some(crate::addons::cutting::WEED_DIRECTIONS), - (crate::addons::pathtools::COMMON_TANGENTS, "tangents") => Some(crate::addons::pathtools::TANGENT_KINDS), (crate::addons::image::REMOVE_BACKGROUND | crate::addons::image::COLOR_MASK, "background") => Some(crate::addons::image::BACKGROUNDS), (crate::addons::image::REMOVE_BACKGROUND | crate::addons::image::COLOR_MASK, "match") => Some(crate::addons::image::MATCHES), ("object.rasterize", "antiAlias") => Some(RASTERIZE_ANTI_ALIAS), diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index 671ebcec8f..0be68e7a2b 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -1532,7 +1532,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.menuDialog", "Menu Dialog", "", - "{command: object.move|object.rotate|object.scale|object.reflect|object.shear|object.transformEach|path.average|path.averageJoin|object.path.offsetPath|object.path.simplify|object.path.smooth|object.path.splitIntoGrid|object.vectorHalftone|object.stepAndRepeat|artboard.rearrange|artboard.rename|object.envelope.makeWithWarp|object.envelope.resetWithWarp|object.envelope.makeWithMesh|object.envelope.resetWithMesh|object.envelope.options|addon.arrange.grid|addon.arrange.offset|addon.arrange.replace|addon.arrange.size|addon.arrange.match|addon.arrange.groupRows|addon.packaging.setFoldAngle|addon.pathtools.cornerSet|addon.pathtools.divideDashes|addon.pathtools.bridge|addon.pathtools.tangentCircle|addon.type.textTweaker|addon.color.swatchLegend|addon.arrange.randomizeOpacity|addon.arrange.sort|addon.arrange.markBounds|addon.color.applyNearestSwatch|addon.color.randomFill|addon.select.byArtboards|addon.select.editPointsOnly|type.smartPunctuation|variable.define|variable.rename|variable.bind|dataset.new|dataset.set|dataset.rename|dataset.select} open the dialog that command's menu item opens (its `key` in ui.inspect is the command id, except `transformEach` for object.transformEach, `envelopeWarp` for object.envelope.makeWithWarp and object.envelope.resetWithWarp, `envelopeMesh` for object.envelope.makeWithMesh and object.envelope.resetWithMesh, `variables` for variable.define and variable.rename and variable.bind and dataset.new and dataset.set and dataset.rename and dataset.select, `envelopeOptions` for object.envelope.options, `smoothSlider` for object.path.smooth, and `simplifySlider` for object.path.simplify; the dialogs of addon.color.applyNearestSwatch and addon.select.byArtboards have no `key`; smoothSlider and simplifySlider are the sliders over the canvas, with field `level`, and object.path.simplify opens its dialog `object.path.simplify` instead once OK in that dialog keeps the settings (`retain`); Set Fold Angle's `angle` is the selected fold lines' angle, and it is refused while the selection has no fold line it can change; Scale and Transform Each have `corners` and `strokes`, from the preferences, which OK updates; Transform Each opens on the values it was last confirmed with (not `copy`), and its Copy button confirms with `copy: true`; the envelope dialogs start from the selected envelope, Make opens as Reset (`reset: true`) while one is selected; variable.rename opens only while the document has a variable, and dataset.set and dataset.rename only while it has a data set, and otherwise the status bar says why; ui.dialog.set, ui.dialog.confirm and ui.dialog.cancel take the dialog's `id` from ui.inspect, or `top`, not its `key`)", + "{command: object.move|object.rotate|object.scale|object.reflect|object.shear|object.transformEach|path.average|path.averageJoin|object.path.offsetPath|object.path.simplify|object.path.smooth|object.path.splitIntoGrid|object.vectorHalftone|object.stepAndRepeat|artboard.rearrange|artboard.rename|object.envelope.makeWithWarp|object.envelope.resetWithWarp|object.envelope.makeWithMesh|object.envelope.resetWithMesh|object.envelope.options|addon.arrange.grid|addon.arrange.offset|addon.arrange.replace|addon.arrange.size|addon.arrange.match|addon.arrange.groupRows|addon.packaging.setFoldAngle|addon.pathtools.cornerSet|addon.pathtools.divideDashes|addon.pathtools.bridge|addon.pathtools.commonTangents|addon.pathtools.tangentCircle|addon.type.textTweaker|addon.color.swatchLegend|addon.arrange.randomizeOpacity|addon.arrange.sort|addon.arrange.markBounds|addon.color.applyNearestSwatch|addon.color.randomFill|addon.select.byArtboards|addon.select.editPointsOnly|type.smartPunctuation|variable.define|variable.rename|variable.bind|dataset.new|dataset.set|dataset.rename|dataset.select} open the dialog that command's menu item opens (its `key` in ui.inspect is the command id, except `transformEach` for object.transformEach, `envelopeWarp` for object.envelope.makeWithWarp and object.envelope.resetWithWarp, `envelopeMesh` for object.envelope.makeWithMesh and object.envelope.resetWithMesh, `variables` for variable.define and variable.rename and variable.bind and dataset.new and dataset.set and dataset.rename and dataset.select, `envelopeOptions` for object.envelope.options, `addon.pathtools.commonTangents` for addon.pathtools.bridge, `smoothSlider` for object.path.smooth, and `simplifySlider` for object.path.simplify; the dialogs of addon.color.applyNearestSwatch and addon.select.byArtboards have no `key`; smoothSlider and simplifySlider are the sliders over the canvas, with field `level`, and object.path.simplify opens its dialog `object.path.simplify` instead once OK in that dialog keeps the settings (`retain`); Set Fold Angle's `angle` is the selected fold lines' angle, and it is refused while the selection has no fold line it can change; Scale and Transform Each have `corners` and `strokes`, from the preferences, which OK updates; Transform Each opens on the values it was last confirmed with (not `copy`), and its Copy button confirms with `copy: true`; the envelope dialogs start from the selected envelope, Make opens as Reset (`reset: true`) while one is selected; variable.rename opens only while the document has a variable, and dataset.set and dataset.rename only while it has a data set, and otherwise the status bar says why; ui.dialog.set, ui.dialog.confirm and ui.dialog.cancel take the dialog's `id` from ui.inspect, or `top`, not its `key`)", ), ( "ui.widthPointEdit", diff --git a/crates/ui-egui/src/palette.rs b/crates/ui-egui/src/palette.rs index 017486e7ad..98f7ac967d 100644 --- a/crates/ui-egui/src/palette.rs +++ b/crates/ui-egui/src/palette.rs @@ -2786,4 +2786,17 @@ mod tests { } } } + + /// Smooth Bridge is part of Common Tangents (#10465): the palette lists Common Tangents once, a search for + /// "metaball" or "smooth bridge" finds it, and Smooth Bridge's own command is no result. + #[test] + fn a_search_for_metaball_finds_common_tangents_and_not_smooth_bridge() { + let app = app_on(Session::new()); + let built = built_for(&app); + assert!(built.entries.iter().all(|e| !e.ids().iter().any(|id| id == "addon.pathtools.bridge")), "Smooth Bridge is no result"); + for query in ["metaball", "smooth bridge"] { + let found = ranked(&built, query); + assert_eq!(found.first().map(String::as_str), Some(crate::addons::pathtools::COMMON_TANGENTS), "{query}: {found:?}"); + } + } } diff --git a/docs/mcp.md b/docs/mcp.md index 5a32fe1e32..ad7c424552 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -16981,7 +16981,7 @@ Commands: - `addon.pathtools.bridge {radius?, gap?, reach?, keepOriginals?, ids?}` joins circles (`ids`, default: the selection, with a group other than a clipping group giving the objects inside it at any depth, which must all be circles; paths whose outline is a circle, not hidden or locked) into metaball (aka meatball) shapes, as one undo step (Object › - Plug-ins › Path Precision Tools › Smooth Bridge…). Two circles become one closed outline that goes around each circle + Plug-ins › Path Precision Tools › Common Tangents… with External and Curved). Two circles become one closed outline that goes around each circle on its side away from the other and along two concave arcs, one on each side of the line through the centers, each touching both circles from outside, so every anchor is smooth. `radius` is the arcs' radius as a percentage of the smaller circle's radius (1 to 1,000, 100 by default): a larger radius makes a wider, gentler bridge. `gap` (0 to 1,000 @@ -17011,10 +17011,11 @@ Commands: other stays as it is. The shapes and the circles left as they are are selected. It is an error when any pair within reach has one circle inside the other, when no pair within reach can be bridged (suggesting a larger radius or gap only when the largest would bridge a pair of them under these rules), when no two circles are within reach, and above 2,000 circles or 8,000 bridges. → `{ids, alone}`: - the shapes and the circles left as they are, with `id` as well for two circles. Smooth Bridge… opens a dialog - (`ui.menuDialog {command}`, key `addon.pathtools.bridge`) with Constant Gap (a Gap field in place of the Radius field in - percent), Reach (unavailable when the selection, a selected group's objects counted, holds two objects), Keep Originals - and Preview. + the shapes and the circles left as they are, with `id` as well for two circles. Opening `addon.pathtools.bridge` + from the menu dialog (`ui.menuDialog {command}`) opens Common Tangents' dialog (key + `addon.pathtools.commonTangents`) with External and Curved on, described under + `addon.pathtools.commonTangents`. No menu item runs `addon.pathtools.bridge`, and the command palette and Keyboard + Shortcuts leave it out; scripts and actions still run it. - `addon.pathtools.tangentCircle {ids?, radius?, circle?}` draws the circles that touch two paths or compound paths and have `radius` (0.01 to 1,000,000 pt, needed with two), or that touch three (which set the radius themselves, so `radius` is then an error), as one undo step (Object › Plug-ins › Path Precision Tools › Tangent Circle…). `ids` @@ -17115,7 +17116,7 @@ Commands: - `addon.pathtools.shape.convert {ids?}` makes the selected plain closed paths that are rectangles, ellipses or polygons with equal sides and corners (stretched along their own axes at most) parametric shapes with the same outline. → `{ids}` (those converted). -- `addon.pathtools.commonTangents {tangents?, centerline?, ids?}` adds the common tangent lines of two convex closed +- `addon.pathtools.commonTangents {tangents?, centerline?, connect?, curved?, radius?, gap?, reach?, keepOriginals?, ids?}` adds the common tangent lines of two convex closed paths (`ids`, or the two selected objects) as separate open paths: lines that touch both paths without crossing into either. `tangents`: `external` (both paths on the same side of the line), `internal` (lines that run between them) or `all` (default). With `centerline: true` it also adds the line joining the two centers: an ellipse's center, or @@ -17140,9 +17141,19 @@ Commands: runs from the point to the path's center. Two points are refused with "select two closed paths". The lines are stroked with the current stroke color and weight (black when the stroke is None), have no fill, go directly above the upper of the two paths and are selected; one undo step. When there is no tangent of the kind asked for, - nothing changes, and the result's `warning` says why. Common Tangents… opens a dialog (Tangents, Centerline) with - Preview; with a point selected, every Tangents choice gives the same lines. → `{ids, external, internal, - centerline, warning?}` (`centerline`: the centerline's id, or null). + nothing changes, and the result's `warning` says why. → `{ids, external, internal, centerline, warning?}` + (`centerline`: the centerline's id, or null). With `connect: true` the two tangents of each kind become one closed + path instead of two lines, joined by the chords between where they touch each path (two internal tangents make a + crossed shape, and a point's two lines make a triangle); a kind with one tangent stays a line, and the centerline + stays a line. With `curved: true` it joins the selected circles into one outline along concave arcs instead, as + `addon.pathtools.bridge` does, taking that command's `radius` or `gap`, `reach`, `keepOriginals` and `ids`, and + the result is that command's. `tangents` other than `external`, `centerline` and `connect: false` with `curved` are + an error, and so are `radius`, `gap`, `reach` and `keepOriginals` without it. Common Tangents… opens a dialog with + Tangents, Centerline and Connect tangents; with External it also shows Straight and Curved (Straight by default) and + the bridge's options: Constant Gap (a Gap field in place of the Radius field in percent), Reach (unavailable when the + selection, a selected group's objects counted, holds two objects) and Keep Originals, which take input only with + Curved. With Curved, Centerline is unavailable and Connect tangents shows on. Choosing another kind of tangent goes + back to Straight. With a point selected, every Tangents choice gives the same lines. - `addon.pathtools.boundingRectangle {each?, offset?}` draws a live rectangle on the geometric bounding box of the selected objects, strokes and effects left out (Object › Plug-ins › Path Precision Tools › Add Bounding Rectangle…, #6966). `addon.pathtools.boundingCircle {each?, offset?}` draws the smallest live circle that holds the outlines of diff --git a/docs/ui-parity.md b/docs/ui-parity.md index fa75b28fb4..2f94f51885 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -592,7 +592,7 @@ next unit in the order a right-click on a ruler lists them, from Feet back to Po | Path Precision Tools add-on (VectorCraft addition): Object › Plug-ins › Path Precision Tools › Trim at Crossings Tool (also in the Scissors tool's group in both shipped toolbars, after the Knife, and listed there in the All Tools drawer; a toolbar edited before keeps its saved layout until Reset Toolbar; no shortcut until one is set in Edit › Keyboard Shortcuts › Tools; the Knife's cursor, drawn as a knife with the blade's point on the hotspot) removes stretches of paths between the places where they are crossed, on any editable path, selected or not: a click removes the stretch under the pointer, a drag removes every stretch its rectangle touches, and an Alt-drag removes every stretch its freehand line crosses; one undo step each; Escape during a drag removes nothing; hovering shows in red the stretch a click would remove, and a drag that reaches few paths shows what its release would remove | done | `addon.pathtools.trim` (in `crates/engine/src/cmd/addons/pathtools/trim.rs`), `crates/tools/src/addons/trim.rs` and their tests; not a feature of the reference app, so it is not scored | | Path Precision Tools add-on (VectorCraft addition): Object › Plug-ins › Path Precision Tools › Tangent Circle Tool (also in the All Tools drawer): a click on a path segment, then on another, draws the circle tangent to the first at the point clicked that touches the second or a segment beside it; Shift uses the tool's radius (36 pt to start, set in its options) and a drag from the second segment sets the radius (Shift in round steps, Cmd/Ctrl slowly), the circle then touching the first segment anywhere along it; the circle shows with its center and radii first, or a note when there is none (its options show or hide the center cross and the radii, set their color, and set how near a segment is picked with Smart Guides on or off); Add Points to Existing Paths (in its options; Alt at the release turns it the other way, a dot beside the pointer while it is in effect) also adds an anchor point where the circle touches each segment; one undo step | done | tool `tangentCircle` (in `crates/tools/src/addons/tangent_circle.rs`, geometry in `crates/pathops/src/addons/pathtools/tangent_circle/on_segments.rs`) and its tests; a VectorCraft addition, so it is not scored | | Path Precision Tools add-on (VectorCraft addition): Object › Plug-ins › Path Precision Tools › Expand Dashes into Paths turns each selected path's dashed stroke into separate open paths, one per dash, laid out as the stroke draws them (pattern, offset, Align Dashes to Corners and Path Ends), each keeping the stroke with the dashes off; one undo step | done | #4922; `addon.pathtools.expandDashes` (in `crates/engine/src/cmd/addons/pathtools.rs`, using the renderer's dash layout) and its tests; not a feature of the reference app, so it is not scored | -| Path Precision Tools add-on (VectorCraft addition): Object › Plug-ins › Path Precision Tools › Smooth Bridge… (Radius as a percentage of the smaller circle's radius, or with Constant Gap that radius plus a gap; Reach; Keep Originals; Preview) joins two selected circles into one outline with two concave arcs that touch both circles, or three or more each to the others within reach, united where the bridges connect, in place of the circles or above them (a pair within reach gets no bridge when its arcs would not reach both circles or would cross, or when its neck would be thinner than the precision its shape is united at; a circle bridged to no other stays as it is); one undo step | done | `addon.pathtools.bridge`, `crates/pathops/src/addons/pathtools/bridge.rs`, `crates/ui-egui/src/addons/pathtools/bridge.rs` and their tests; a VectorCraft addition, so it is not scored | +| Path Precision Tools add-on (VectorCraft addition): Object › Plug-ins › Path Precision Tools › Common Tangents… with External and Curved (Radius as a percentage of the smaller circle's radius, or with Constant Gap that radius plus a gap; Reach; Keep Originals; Preview) joins two selected circles into one outline with two concave arcs that touch both circles, or three or more each to the others within reach, united where the bridges connect, in place of the circles or above them (a pair within reach gets no bridge when its arcs would not reach both circles or would cross, or when its neck would be thinner than the precision its shape is united at; a circle bridged to no other stays as it is); one undo step | done | `addon.pathtools.bridge`, `crates/pathops/src/addons/pathtools/bridge.rs`, `crates/ui-egui/src/addons/pathtools/tangents.rs` and their tests; a VectorCraft addition, so it is not scored | | Path Precision Tools add-on (VectorCraft addition): Object › Plug-ins › Path Precision Tools › Tangent Circle… draws the circles that touch two selected paths or compound paths at a radius, or three of them, each touching the outlines without crossing them; Radius (two shapes), a Circle menu (All or one by number) and Preview; one undo step | done | `addon.pathtools.tangentCircle` (in `crates/engine/src/cmd/addons/pathtools/tangent_circle.rs`, geometry in `crates/pathops/src/addons/pathtools/tangent_circle.rs`) and its tests; a VectorCraft addition, so it is not scored | | Path Precision Tools add-on (VectorCraft addition): Object › Plug-ins › Path Precision Tools › Add Bounding Rectangle… and Add Bounding Circle… draw a live rectangle on the selection's geometric bounding box, or the smallest live circle that holds its outlines, from a dialog with Offset, One per Object (a shape around each object instead of one around the whole selection) and Preview; one undo step | done | `addon.pathtools.boundingRectangle` and `addon.pathtools.boundingCircle` (in `crates/engine/src/cmd/addons/pathtools/bounding.rs`, the circle in `crates/geom/src/shapes.rs`, `enclosing_circle`; the dialog is the command dialog, `crates/ui-egui/src/dialogs/command.rs`) and their tests, with the menu items' test `add_bounding_rectangle_and_circle_open_a_dialog_with_offset_and_one_per_object` in `crates/ui-egui/src/addons/pathtools/tests.rs`; a VectorCraft addition, so it is not scored | | Path Precision Tools add-on (VectorCraft addition): Object › Plug-ins › Path Precision Tools › Add Inscribed Circle draws the largest live circle inside each selected closed path or compound path, in the area it fills under its fill rule; one undo step | done | `addon.pathtools.inscribedCircle` (in `crates/engine/src/cmd/addons/pathtools/inscribed.rs`, geometry in `crates/pathops/src/addons/pathtools/inscribed.rs`) and its tests, with the menu item's test `add_inscribed_circle_draws_its_circles_without_a_dialog` in `crates/ui-egui/src/addons/pathtools/tests.rs`; a VectorCraft addition, so it is not scored | From 5d494db4d99dd45ab9657fc9a5a1168c2cd8173f Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 1 Dec 2026 14:16:38 -0800 Subject: [PATCH 2/2] Tests: Connect tangents' external shape does not cross itself The test checked only which corners the shape has, so corners joined in the wrong order passed. It now also checks the shape's area. --- crates/engine/src/cmd/addons/pathtools/tangents/tests.rs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/crates/engine/src/cmd/addons/pathtools/tangents/tests.rs b/crates/engine/src/cmd/addons/pathtools/tangents/tests.rs index 032ef5f377..1653089520 100644 --- a/crates/engine/src/cmd/addons/pathtools/tangents/tests.rs +++ b/crates/engine/src/cmd/addons/pathtools/tangents/tests.rs @@ -385,6 +385,9 @@ fn connect_joins_the_external_tangents_and_the_chords_into_one_closed_shape_in_o for p in [Point::new(100.0, 80.0), Point::new(200.0, 80.0), Point::new(200.0, 120.0), Point::new(100.0, 120.0)] { assert!(found.iter().any(|&q| near(p, q)), "{p:?} in {found:?}"); } + // In order around the band, not crossing itself: the area is the 100 by 40 rectangle's. + let area = found.iter().zip(found.iter().cycle().skip(1)).map(|(p, q)| p.x * q.y - q.x * p.y).sum::() / 2.0; + assert!((area.abs() - 4000.0).abs() < 1e-6, "area {area} of {found:?}"); s.execute("edit.undo", &json!({})).unwrap(); assert_eq!(s.doc().unwrap().doc.node_count(), count); }