Merge pull request #9000 from dotCooCoo/feat/tangent-circle-ask-radius

Tangent Circle Tool: Ask For Circle Radius asks for the radius after a click
This commit is contained in:
.CooCoo authored and GitHub committed 2026-11-28 01:40:20 -08:00
commit 13fc74e4fd
37 files changed
+922 -22

No files matched your search

+272 -12
View File
@@ -18,7 +18,12 @@
//! segment's shape differs from the one they were found on. With the `addPoints` option on (Alt at
//! the release turns it the other way, and a dot beside the pointer shows when it is in effect), the
//! segments the circle touches get an anchor point at each touch, which splits them without changing
//! their shape, in the same undo step as the circle; a touch at an existing anchor adds none.
//! their shape, in the same undo step as the circle; a touch at an existing anchor adds none. With the
//! `askRadius` option on, a click on the second segment (not a drag, which sets the radius itself)
//! opens the [`RADIUS_DIALOG`] instead of drawing: it starts at the radius of the circle found and
//! draws the circle of the radius typed ([`radius_circle`]); the first segment stays picked until it
//! does. While the dialog is open, an edit to either segment leaves it without a circle
//! ([`segments_unchanged`]).
//!
//! The tool's options (its options dialog, `tool.setOption`; kept with the preferences): `radius`;
//! `addPoints`; `center` and `radii` show or hide the circle's center cross and the lines from its center to the
@@ -29,11 +34,12 @@
//! within the selection tolerance, as a click on a path picks it, and that is also the least reach
//! snapping has. Of the segments within reach the nearest is picked ([`pick_at`]). By default
//! `addPoints` is off, the cross and the lines show, the color is red, the tolerance is 3 px and
//! `snapWithoutGuides` is on.
//! `snapWithoutGuides` is on. `askRadius` (above) and `autoUpdateDefault`, which makes the radius
//! given in the dialog the tool's `radius`, are off by default.
use kurbo::{CubicBez, ParamCurveNearest, Shape};
use serde_json::{Value, json};
use vectorcraft_doc::NodeId;
use vectorcraft_doc::{Document, NodeId};
use vectorcraft_geom::{BezPath, ParamCurve, Point};
use vectorcraft_pathops::addons::pathtools::{SegmentCircle, circles_of_radius, circles_through};
@@ -53,6 +59,9 @@ const STEP_PX: f64 = 4.0;
const SLOW: f64 = 0.1;
/// The note shown over a second segment that gives no circle.
pub const NO_CIRCLE: &str = "No tangent circle here";
/// The dialog a click on the second segment opens with `askRadius` on: its parameters hold the two
/// segments, the click and the circle found ([`radius_circle`]).
pub const RADIUS_DIALOG: &str = "tangentCircleRadius";
const BLUE: [u8; 3] = [0x4f, 0x9d, 0xff];
const RED: [u8; 3] = [0xe0, 0x3c, 0x3c];
const GREY: [u8; 3] = [0x80, 0x80, 0x80];
@@ -77,7 +86,7 @@ pub const SNAP_PX: f64 = 3.0;
/// The snapping tolerance the `snapTolerance` option takes (screen pixels).
pub const SNAP_RANGE: (f64, f64) = (0.0, 25.0);
/// The option keys that are true or false.
const SWITCHES: &[&str] = &["addPoints", "center", "radii", "snapWithoutGuides"];
const SWITCHES: &[&str] = &["addPoints", "center", "radii", "snapWithoutGuides", "askRadius", "autoUpdateDefault"];
/// A segment under the pointer: where on it, and the segment itself.
#[derive(Clone, Debug, PartialEq)]
@@ -124,6 +133,10 @@ pub struct TangentCircleTool {
/// The snapping tolerance (screen pixels), and whether the tool snaps with Smart Guides off.
snap_px: f64,
snap_without_guides: bool,
/// Whether a click on the second segment asks for the radius (`askRadius`), and whether the
/// radius given there becomes `radius` (`autoUpdateDefault`, which the dialog reads).
ask_radius: bool,
auto_update: bool,
first: Option<Pick>,
hover: Option<Pick>,
press: Option<Press>,
@@ -153,6 +166,8 @@ impl Default for TangentCircleTool {
color: 0,
snap_px: SNAP_PX,
snap_without_guides: true,
ask_radius: false,
auto_update: false,
first: None,
hover: None,
press: None,
@@ -193,10 +208,24 @@ fn pick_at(cx: &ToolContext, p: Point, reach: f64) -> Option<Pick> {
Some(Pick { id, subpath, segment, t, p: curve.eval(t), curve })
}
/// A segment's place in the document: its path, subpath and index.
type Place = (NodeId, usize, usize);
impl Pick {
fn place(&self) -> Place {
(self.id, self.subpath, self.segment)
}
}
/// The document's segment at `pick` as it is now: none when its path, subpath or segment is gone.
fn segment_now(cx: &ToolContext, pick: &Pick) -> Option<CubicBez> {
let sp = cx.doc.node(pick.id)?.path_data()?.subpaths.get(pick.subpath)?;
(pick.segment < sp.segment_count()).then(|| sp.segment(pick.segment))
segment_at(cx.doc, pick.place())
}
/// The segment of `doc` at `place`: none when its path, subpath or segment is gone.
fn segment_at(doc: &Document, (id, subpath, segment): Place) -> Option<CubicBez> {
let sp = doc.node(id)?.path_data()?.subpaths.get(subpath)?;
(segment < sp.segment_count()).then(|| sp.segment(segment))
}
/// Whether the document's segment at `pick` still has the shape it had when it was picked.
@@ -207,17 +236,31 @@ fn unchanged(cx: &ToolContext, pick: &Pick) -> bool {
/// The segments a circle may touch when `second` is picked: it and the segments on either side of
/// it, without `first`. None when `second` is the first segment again.
fn second_set(cx: &ToolContext, first: &Pick, second: &Pick) -> Vec<CubicBez> {
second_segments(cx, first, second).into_iter().map(|(_, c)| c).collect()
second_set_at(cx.doc, first.place(), second.place())
}
/// [`second_set`] for the segments of `doc` at `first` and `second`.
fn second_set_at(doc: &Document, first: Place, second: Place) -> Vec<CubicBez> {
second_segments_at(doc, first, second).into_iter().map(|(_, c)| c).collect()
}
/// [`second_set`] with each segment's index on the second pick's subpath.
fn second_segments(cx: &ToolContext, first: &Pick, second: &Pick) -> Vec<(usize, CubicBez)> {
if (first.id, first.subpath, first.segment) == (second.id, second.subpath, second.segment) {
second_segments_at(cx.doc, first.place(), second.place())
}
/// [`second_segments`] for the segments of `doc` at `first` and `second`.
fn second_segments_at(doc: &Document, first: Place, second: Place) -> Vec<(usize, CubicBez)> {
if first == second {
return vec![];
}
let Some(sp) = cx.doc.node(second.id).and_then(|n| n.path_data()).and_then(|p| p.subpaths.get(second.subpath)) else { return vec![] };
let (id, subpath, i) = second;
let Some(sp) = doc.node(id).and_then(|n| n.path_data()).and_then(|p| p.subpaths.get(subpath)) else { return vec![] };
// A subpath edited down to no segments (while the radius dialog is open) has nothing to touch.
let n = sp.segment_count();
let i = second.segment;
if n == 0 {
return vec![];
}
let mut indices = vec![i];
if i > 0 || sp.closed {
indices.push((i + n - 1) % n);
@@ -227,7 +270,7 @@ fn second_segments(cx: &ToolContext, first: &Pick, second: &Pick) -> Vec<(usize,
}
indices.sort_unstable();
indices.dedup();
let is_first = |k: usize| first.id == second.id && first.subpath == second.subpath && first.segment == k;
let is_first = |k: usize| first == (id, subpath, k);
indices.into_iter().filter(|k| *k < n && !is_first(*k)).map(|k| (k, sp.segment(k))).collect()
}
@@ -325,6 +368,93 @@ fn segment_path(c: &CubicBez) -> BezPath {
bp
}
fn point_json(p: Point) -> Value {
json!([p.x, p.y])
}
fn curve_json(c: &CubicBez) -> Value {
json!([point_json(c.p0), point_json(c.p1), point_json(c.p2), point_json(c.p3)])
}
/// A finite point written by [`point_json`].
fn point_of(v: &Value) -> Option<Point> {
let [x, y] = v.as_array()?.as_slice() else { return None };
let p = Point::new(x.as_f64()?, y.as_f64()?);
(p.x.is_finite() && p.y.is_finite()).then_some(p)
}
/// A segment written by [`curve_json`].
fn curve_of(v: &Value) -> Option<CubicBez> {
let [a, b, c, d] = v.as_array()?.as_slice() else { return None };
Some(CubicBez::new(point_of(a)?, point_of(b)?, point_of(c)?, point_of(d)?))
}
fn place_json((id, subpath, segment): Place) -> Value {
json!([id.0, subpath, segment])
}
/// A place written by [`place_json`].
fn place_of(v: &Value) -> Option<Place> {
let [id, subpath, segment] = v.as_array()?.as_slice() else { return None };
let index = |v: &Value| v.as_u64().and_then(|i| usize::try_from(i).ok());
Some((NodeId(id.as_u64()?), index(subpath)?, index(segment)?))
}
/// The [`RADIUS_DIALOG`]'s parameters for circle `c`, found by a click at `at` on `first` and on
/// `picked`, whose segments a circle may touch are `second`, which `points` (from [`draw`]) draws:
/// the segments and their places, the click, the circle's radius and points, and the tolerance
/// [`draw`] checked them with.
fn dialog_params(first: &Pick, picked: &Pick, second: &[CubicBez], at: Point, c: &SegmentCircle, points: &Value, tol: f64) -> Value {
json!({
"first": curve_json(&first.curve),
"second": second.iter().map(curve_json).collect::<Vec<_>>(),
"places": [place_json(first.place()), place_json(picked.place())],
"at": point_json(at),
"radius": c.circle.radius,
"points": points,
"tol": tol,
})
}
/// Whether the segments the [`RADIUS_DIALOG`] opened with parameters `p` holds are still those of
/// `doc`: false when a path was edited or removed since the click, in another document, or for
/// parameters the tool did not write.
pub fn segments_unchanged(doc: &Document, p: &Value) -> bool {
let check = || -> Option<bool> {
let [first, second] = p.get("places")?.as_array()?.as_slice() else { return None };
let (first, second) = (place_of(first)?, place_of(second)?);
let second_then: Vec<CubicBez> = p.get("second")?.as_array()?.iter().map(curve_of).collect::<Option<_>>()?;
Some(segment_at(doc, first)? == curve_of(p.get("first")?)? && second_then == second_set_at(doc, first, second))
};
check() == Some(true)
}
/// The `shape.circleThroughPoints` parameters that draw the circle of `radius` the [`RADIUS_DIALOG`]
/// opened with parameters `p` gives: at the radius the click found, the circle found; at any other,
/// the circle of `radius` touching the second segments nearest the click, anywhere along the first
/// segment (as with Shift). None for a radius that is not a finite number above 0, when no circle of
/// that radius can be drawn there, or for parameters the tool did not write.
pub fn radius_circle(p: &Value, radius: f64) -> Option<Value> {
if !(radius.is_finite() && radius > 0.0) {
return None;
}
if p.get("radius").and_then(Value::as_f64) == Some(radius) {
let points = p.get("points")?;
let [a, b, c] = points.as_array()?.as_slice() else { return None };
return [a, b, c].into_iter().all(|q| point_of(q).is_some()).then(|| json!({ "points": points }));
}
let first = curve_of(p.get("first")?)?;
// The second segment and at most one on either side of it.
let second: Vec<CubicBez> = p.get("second")?.as_array().filter(|s| (1..=3).contains(&s.len()))?.iter().map(curve_of).collect::<Option<_>>()?;
let at = point_of(p.get("at")?)?;
let tol = p.get("tol").and_then(Value::as_f64).filter(|t| t.is_finite() && *t > 0.0)?;
let c = nearest_to(circles_of_radius(first, &second, radius), at, tol)?;
match draw(&c, tol)? {
Action::Exec(_, params) => Some(params),
_ => None,
}
}
impl TangentCircleTool {
/// How near (document units) the pointer picks a segment: with Smart Guides on, the snapping
/// tolerance or Smart Guides' Snapping Tolerance, whichever is larger; with them off, the
@@ -490,9 +620,20 @@ impl Tool for TangentCircleTool {
// No circle, or one the three points cannot draw: the first segment stays picked,
// for another try. It also stays when the command fails: only a drawn circle tells
// the tool (`notify`) to forget it.
let tol = cx.tol(DRAW_PX);
let Some(c) = self.found.take() else { return vec![] };
let Some(params) = circle_params(&c, cx.tol(DRAW_PX)) else { return vec![] };
let Some(params) = circle_params(&c, tol) else { return vec![] };
self.looked = false;
// Asked for: a click, not a drag (which set the radius), opens the radius dialog,
// which draws the circle. Until then the first segment stays picked, so Cancel
// leaves it for another try.
if self.ask_radius
&& press.radius.is_none()
&& let Some(first) = &self.first
{
let params = dialog_params(first, &press.pick, &press.second, press.at, &c, &params["points"], tol);
return vec![Action::Dialog(RADIUS_DIALOG.into(), params)];
}
// Alt at the release turns `addPoints` the other way.
let steps = match &self.first {
Some(first) if self.add_points != ev.mods.alt => {
@@ -628,6 +769,8 @@ impl Tool for TangentCircleTool {
"color": COLORS.get(self.color).map_or("red", |(name, _)| *name),
"snapTolerance": self.snap_px,
"snapWithoutGuides": self.snap_without_guides,
"askRadius": self.ask_radius,
"autoUpdateDefault": self.auto_update,
})
}
@@ -644,6 +787,8 @@ impl Tool for TangentCircleTool {
"color" => self.color = v.as_str().and_then(|s| COLORS.iter().position(|(name, _)| *name == s)).unwrap_or(self.color),
"snapTolerance" => self.snap_px = v.as_f64().unwrap_or(self.snap_px),
"snapWithoutGuides" => self.snap_without_guides = v.as_bool().unwrap_or(self.snap_without_guides),
"askRadius" => self.ask_radius = v.as_bool().unwrap_or(self.ask_radius),
"autoUpdateDefault" => self.auto_update = v.as_bool().unwrap_or(self.auto_update),
_ => {}
}
}
@@ -721,6 +866,121 @@ mod tests {
[(a.0, b.0), (a.1, b.1), (a.2, b.2), (a.3, b.3)].iter().all(|(x, y)| (x - y).abs() < 1e-4)
}
/// The circle `shape.circleThroughPoints` parameters `p` draw, as [`drawn`] gives it.
fn boxed(p: &Value) -> (f64, f64, f64, f64) {
drawn(&[Action::Exec("shape.circleThroughPoints".into(), p.clone()), Action::Notify(DRAWN.into())])
}
/// The radius dialog's parameters in `actions`, which hold nothing else.
fn asked(actions: &[Action]) -> Value {
let [Action::Dialog(kind, p)] = actions else { panic!("{actions:?}") };
assert_eq!(kind, RADIUS_DIALOG);
p.clone()
}
#[test]
fn ask_for_circle_radius_opens_the_dialog_after_a_click_but_not_after_a_drag() {
let d = doc();
let (sel, p) = (Selection::default(), paint());
let cx = cx(&d, &sel, &p);
let mut t = TangentCircleTool::default();
assert_eq!((t.options()["askRadius"].clone(), t.options()["autoUpdateDefault"].clone()), (json!(false), json!(false)));
for key in ["askRadius", "autoUpdateDefault"] {
assert_eq!(t.check_option(key, &json!(true)), Ok(()));
for bad in [json!(1), json!("true"), Value::Null] {
assert_eq!(t.check_option(key, &bad), Err(format!("`{key}` must be true or false")), "{bad}");
t.set_option(key, &bad);
assert_eq!(t.options()[key], json!(false), "{bad}");
}
t.set_option(key, &json!(true));
assert_eq!(t.options()[key], json!(true));
}
// A click on the second line: the dialog, at the click's circle (radius 20), and nothing
// drawn yet; the first segment stays picked.
t.pointer(&cx, &ev(PointerKind::Down, 150.0, 101.0));
t.pointer(&cx, &ev(PointerKind::Up, 150.0, 101.0));
t.pointer(&cx, &ev(PointerKind::Down, 200.0, 139.0));
let p = asked(&up(&mut t, &cx, &ev(PointerKind::Up, 200.0, 139.0)));
assert!((p["radius"].as_f64().unwrap() - 20.0).abs() < 1e-6, "{p}");
assert!(t.first.is_some() && !t.busy());
let r = p["radius"].as_f64().unwrap();
assert!(close(boxed(&radius_circle(&p, r).unwrap()), (130.0, 100.0, 40.0, 40.0)), "{p}");
// Lines 40 pt apart take no other radius; nor is there a circle without a radius above 0.
for no in [25.0, 0.0, -20.0, f64::NAN, f64::INFINITY] {
assert_eq!(radius_circle(&p, no), None, "{no}");
}
// Shift on the L's corner: the dialog at the tool's radius, and another radius gives that
// radius's fillet.
t.key(&cx, ToolKey::Escape, Mods::default());
t.pointer(&cx, &ev(PointerKind::Down, 150.0, 300.0));
t.pointer(&cx, &ev(PointerKind::Up, 150.0, 300.0));
t.pointer(&cx, &shifted(PointerKind::Down, 300.0, 350.0));
let p = asked(&up(&mut t, &cx, &shifted(PointerKind::Up, 300.0, 350.0)));
assert_eq!(p["radius"], json!(RADIUS));
assert!(close(boxed(&radius_circle(&p, RADIUS).unwrap()), (300.0 - 72.0, 300.0, 72.0, 72.0)), "{p}");
assert!(close(boxed(&radius_circle(&p, 10.0).unwrap()), (280.0, 300.0, 20.0, 20.0)), "{p}");
// Parameters the tool did not write give no circle.
assert_eq!(radius_circle(&json!({}), 10.0), None);
let second = p["second"].as_array().unwrap()[0].clone();
for (key, bad) in [
("second", json!([])),
("second", json!([second, second, second, second])),
("at", json!([1.0])),
("tol", json!(0)),
("first", json!("x")),
("points", json!([[0, 0]])),
] {
let mut q = p.clone();
q[key] = bad;
let r = if key == "points" { RADIUS } else { 10.0 };
assert_eq!(radius_circle(&q, r), None, "{key}");
}
// A drag sets the radius itself: drawn at once, with no dialog.
t.pointer(&cx, &ev(PointerKind::Down, 300.0, 350.0));
t.pointer(&cx, &ev(PointerKind::Drag, 300.0, 365.0));
let released = up(&mut t, &cx, &ev(PointerKind::Up, 300.0, 365.0));
assert!(close(drawn(&released), (300.0 - 30.0, 300.0, 30.0, 30.0)), "{released:?}");
assert!(t.first.is_none());
// A click that finds no circle opens no dialog.
t.set_option("radius", &json!(5));
t.pointer(&cx, &ev(PointerKind::Down, 150.0, 101.0));
t.pointer(&cx, &ev(PointerKind::Up, 150.0, 101.0));
t.pointer(&cx, &shifted(PointerKind::Down, 200.0, 139.0));
assert!(t.pointer(&cx, &shifted(PointerKind::Up, 200.0, 139.0)).is_empty());
assert!(t.first.is_some());
}
#[test]
fn the_radius_dialog_knows_when_its_segments_changed() {
let d = doc();
let (sel, p) = (Selection::default(), paint());
let cx = cx(&d, &sel, &p);
let mut t = TangentCircleTool::default();
t.set_option("askRadius", &json!(true));
t.pointer(&cx, &ev(PointerKind::Down, 150.0, 101.0));
t.pointer(&cx, &ev(PointerKind::Up, 150.0, 101.0));
t.pointer(&cx, &ev(PointerKind::Down, 200.0, 139.0));
let p = asked(&up(&mut t, &cx, &ev(PointerKind::Up, 200.0, 139.0)));
assert!(segments_unchanged(&d, &p));
assert!(segments_unchanged(&doc_at(100.0, 140.0), &p), "the same paths");
// Either line moved, or another document: changed.
for (a, b) in [(100.0, 150.0), (110.0, 140.0)] {
assert!(!segments_unchanged(&doc_at(a, b), &p), "{a} {b}");
}
assert!(!segments_unchanged(&Document::new(500.0, 500.0), &p));
// The second line edited down to a closed subpath without segments: changed.
let mut emptied = d.clone();
let (second, ..) = place_of(&p["places"][1]).unwrap();
emptied.node_mut(second).and_then(|n| n.path_data_mut()).unwrap().subpaths[0] = SubPath::polyline(&[], true);
assert!(!segments_unchanged(&emptied, &p));
// Parameters the tool did not write.
for key in ["places", "first", "second"] {
let mut q = p.clone();
q[key] = json!("x");
assert!(!segments_unchanged(&d, &q), "{key}");
}
}
#[test]
fn two_clicks_draw_the_circle_tangent_at_the_first_click() {
let d = doc();
+5 -1
View File
@@ -110,7 +110,11 @@ const ROWS: &[Row] = &[
(&[crate::addons::extend_path::ID], None, &["mode"]),
(&[crate::addons::corner_tool::ID], None, &["radius", "kind"]),
(&[crate::addons::shared_edge::ID], None, &["diameter", "tolerance", "together"]),
(&[crate::addons::tangent_circle::ID], None, &["radius", "addPoints", "center", "radii", "color", "snapTolerance", "snapWithoutGuides"]),
(
&[crate::addons::tangent_circle::ID],
None,
&["radius", "addPoints", "center", "radii", "color", "snapTolerance", "snapWithoutGuides", "askRadius", "autoUpdateDefault"],
),
(&[crate::addons::smart_pen::ID], None, &["next"]),
// The kind first: a new kind resets the values after it.
(&[crate::addons::parametric_shape::ID], None, &["kind", "count", "a", "b", "radius", "width", "height", "rotation"]),
+3
View File
@@ -34,6 +34,8 @@ pub(crate) struct Spec {
pub(crate) struct AddonDialogs {
open: Option<Open>,
preview: LivePreview,
/// The open Tangent Circle Tool radius dialog.
pub(crate) tangent_radius: Option<super::pathtools::tangent_circle_radius::Open>,
}
#[derive(Clone, Copy)]
@@ -105,6 +107,7 @@ pub(crate) fn open_from_menu(app: &mut VectorcraftApp, id: &str) -> Option<Resul
/// by type: two hosted parameter dialogs would take each other's answers.
pub(crate) fn pump(app: &mut VectorcraftApp, ctx: &Context) {
pump_commit(app);
super::pathtools::tangent_circle_radius::pump(app, ctx);
super::color::nearest::pump(app, ctx);
super::select::pump(app, ctx);
super::select::link_status::pump(app, ctx);
+6 -2
View File
@@ -3,8 +3,9 @@
//! 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
//! 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`]); and its tools' options dialog (a double-click on the tool). Everything acts through `addon.pathtools.*` and
//! `tool.setOption`.
//! ([`shape`]); its tools' options dialog (a double-click on the tool); and the Tangent Circle Tool's radius dialog
//! ([`tangent_circle_radius`]). Everything acts through `addon.pathtools.*` and `tool.setOption`, except that the radius
//! dialog draws its circle with `shape.circleThroughPoints`.
pub mod bridge;
pub mod corner;
@@ -13,6 +14,7 @@ pub mod set_corners;
pub mod shape;
pub mod shared_edge;
pub mod tangent_circle;
pub mod tangent_circle_radius;
use craft::behavior::ColumnWidth;
use craft::menu::Node;
@@ -317,6 +319,8 @@ fn options_params(tool: &str, lengths: LengthUnits) -> Vec<Param> {
Param::new("color", tl!("Color"), ParamKind::choice(colors, Some("red".into()))),
Param::new("snapTolerance", tl!("Snap Tolerance"), snap).unit(UnitKind::Pixels),
Param::new("snapWithoutGuides", tl!("Snap When Smart Guides Are Off"), ParamKind::bool(true)),
Param::new("askRadius", tl!("Ask For Circle Radius"), ParamKind::bool(false)),
Param::new("autoUpdateDefault", tl!("Auto-Update Default"), ParamKind::bool(false)),
];
}
let (size, tolerance) = (anchor_eraser::SIZE_RANGE, anchor_eraser::TOLERANCE_RANGE);
@@ -0,0 +1,551 @@
//! The Tangent Circle Tool's radius dialog, which a click on the second segment opens when the
//! tool's Ask For Circle Radius option is on. It starts at the radius of the circle the click found,
//! and each radius previews on the canvas the circle of that radius touching the two segments
//! nearest the click ([`tangent_circle::radius_circle`]). A radius that gives no circle there shows
//! the tool's note and leaves OK off, as does an edit to either segment after the click. OK draws
//! the circle with `shape.circleThroughPoints` in one undo step, and with Auto-Update Default on
//! also sets the tool's `radius` to the one given when it is in the tool's range; Cancel draws nothing.
use craft::ui::contract::Bind;
use craft::ui::dialog::DialogId;
use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue, HostedParamDialog, Param, ParamDialog, ParamResult};
use craft::ui::runtime::env::Label;
use serde_json::{Value, json};
use vectorcraft_doc::Document;
use vectorcraft_tools::addons::tangent_circle;
use crate::VectorcraftApp;
use crate::canvas::rulers::general_lengths;
use crate::dialogs::host::{HeldOptions, open_held_with};
use crate::dialogs::preview::LivePreview;
/// The dialog's kind.
pub const KIND: &str = tangent_circle::RADIUS_DIALOG;
/// The command that draws the circle.
const DRAW: &str = "shape.circleThroughPoints";
/// The error for a radius outside the tool's range.
const RADIUS_RANGE: &str = "`radius` must be from 0.01 to 1000000 pt";
/// The open radius dialog: the dialog, what the tool found (the segments, the click and its circle), the id of the
/// document the click was in (`DocState::uid`), the circle last looked for and the live preview.
pub(crate) struct Open {
id: DialogId,
click: Value,
doc: Option<u64>,
/// The radius the circle was last looked for at, and the circle's parameters for [`DRAW`] (`None`: no circle).
tried: Option<(f64, Option<Value>)>,
/// Why there is no circle at the radius the dialog held at the last frame (in English), which the dialog shows
/// under its rows with OK off; `None` while there is one.
note: Option<String>,
preview: LivePreview,
/// The document that was active when the preview last ran (`DocState::uid`).
shown_in: Option<u64>,
}
/// Open the dialog on what the tool found (its [`tangent_circle::RADIUS_DIALOG`] parameters).
pub(crate) fn open(app: &mut VectorcraftApp, p: &Value) {
let radius = p.get("radius").and_then(Value::as_f64).unwrap_or(tangent_circle::RADIUS);
let doc = app.session.doc().ok().map(|s| s.uid);
let Some(ctx) = app.ui_ctx.clone() else {
app.status("no window");
return;
};
// A dialog still open from an earlier click closes without an answer, and its preview is rolled back. The new
// dialog has the same id (the dialog's kind), and its own held answer and cancel hook replace the earlier ones.
if let Some(mut old) = app.addon_dialogs.tangent_radius.take() {
if let Some(host) = app.dialogs() {
host.with(|h| {
h.cancel_by_id(&ctx, old.id);
let _ = h.take_by_id::<HostedParamDialog>(old.id);
});
}
take_preview(app, &mut old).cancel(app);
}
let lengths = general_lengths(app);
let fields = DialogFields::from_pairs([("radius", FieldValue::Number(radius))]);
// The field has no bounds: a radius typed outside the tool's range is kept as typed and shows [`RADIUS_RANGE`].
let dialog = HostedParamDialog::new(&ctx, KIND, fields, move |fields| {
let rows = vec![Param::number("radius", tl!("Radius:"), radius, 1.0, 2).length(lengths)];
ParamDialog::new(KIND, tl!("Tangent Circle"), rows).values(Bind::bound(fields)).previews(true)
});
let cancel: Box<dyn FnOnce(&mut VectorcraftApp)> = Box::new(|app| {
if let Some(mut open) = app.addon_dialogs.tangent_radius.take() {
take_preview(app, &mut open).cancel(app);
}
});
match open_held_with(app, dialog, ok, HeldOptions { parent: None, cancel: Some(cancel) }) {
Some(id) => {
app.addon_dialogs.tangent_radius =
Some(Open { id, click: p.clone(), doc, tried: None, note: None, preview: LivePreview::default(), shown_in: doc });
}
None => app.status("no window"),
}
}
/// The document the click was in, while it is the active one. A preview adds the circle to it and
/// leaves the two segments as they are.
fn doc<'a>(app: &'a VectorcraftApp, open: &Open) -> Option<&'a Document> {
let clicked = open.doc?;
app.session.doc().ok().filter(|s| s.uid == clicked).map(|s| &*s.doc)
}
/// The id of the active document (`DocState::uid`).
fn active_uid(app: &VectorcraftApp) -> Option<u64> {
app.session.doc().ok().map(|s| s.uid)
}
/// The dialog's live preview, taken out of `open`. With another document active than the one it previewed in, the
/// preview is forgotten instead: the switch already rolled it back there, and rolling back here would cancel an
/// interaction of the document now active.
fn take_preview(app: &VectorcraftApp, open: &mut Open) -> LivePreview {
let preview = std::mem::take(&mut open.preview);
if open.shown_in == active_uid(app) { preview } else { LivePreview::default() }
}
/// Whether `r` is in the tool's radius range.
fn in_range(r: f64) -> bool {
let (lo, hi) = tangent_circle::RADIUS_RANGE;
(lo..=hi).contains(&r)
}
/// The radius `fields` hold, when it is in the tool's range or is the radius of the circle the click found
/// (which a click without Shift may find outside that range).
fn radius(open: &Open, fields: &DialogFields) -> Result<f64, String> {
let found = open.click.get("radius").and_then(Value::as_f64);
fields.number("radius").filter(|r| in_range(*r) || Some(*r) == found).ok_or_else(|| RADIUS_RANGE.to_string())
}
/// The radius `fields` hold and the circle of that radius, as [`DRAW`]'s parameters. `Err` says why there is none:
/// a radius outside the tool's range, no document clicked in, either segment in it no longer the one clicked (a
/// control request edited or removed its path), or no circle of that radius there. The circle is looked for again
/// only when the radius changed.
fn circle(app: &VectorcraftApp, open: &mut Open, fields: &DialogFields) -> Result<(f64, Value), String> {
let r = radius(open, fields)?;
let no_circle = || tangent_circle::NO_CIRCLE.to_string();
if !doc(app, open).is_some_and(|doc| tangent_circle::segments_unchanged(doc, &open.click)) {
return Err(no_circle());
}
let found = match &open.tried {
Some((tried, found)) if *tried == r => found.clone(),
_ => {
let found = tangent_circle::radius_circle(&open.click, r);
open.tried = Some((r, found.clone()));
found
}
};
found.map(|points| (r, points)).ok_or_else(no_circle)
}
/// Why the active document cannot take a new circle now: its target layer is locked or hidden. The draw would be
/// refused, with or without a preview.
fn target_refusal(app: &VectorcraftApp) -> Option<String> {
app.session.doc().ok()?.target_parent().err().map(|e| e.to_string())
}
/// The words the dialog shows for `why` ([`circle`]'s error), in the interface's language.
fn shown(why: &str) -> String {
if why == tangent_circle::NO_CIRCLE { tl!(tangent_circle::NO_CIRCLE).to_string() } else { crate::i18n::msg(why) }
}
/// Once a frame: previews the circle of the radius the dialog holds, or rolls the preview back and shows why there
/// is none, with OK off.
pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) {
let Some(mut open) = app.addon_dialogs.tangent_radius.take() else { return };
let Some(host) = app.dialogs() else {
app.addon_dialogs.tangent_radius = Some(open);
return;
};
let id = open.id;
let Some((previewing, fields)) = host.with(|h| h.get_by_id::<HostedParamDialog>(id).map(|d| (d.is_previewing(), d.fields().clone()))) else {
app.addon_dialogs.tangent_radius = Some(open);
return;
};
let mut preview = take_preview(app, &mut open);
let found = circle(app, &mut open, &fields);
// Without a circle the preview rolls back; the preview reports its own failures on the status line.
let previewed = match &found {
Ok((_, points)) => (previewing, points.clone()),
Err(_) => (false, Value::Null),
};
let _ = preview.run(app, previewed.0, "Tangent Circle", DRAW, &previewed.1);
open.preview = preview;
open.shown_in = active_uid(app);
// A target layer locked or hidden after the circle previewed refuses the draw: OK stays off. The preview stays,
// since rolling it back would also roll back the edit that locked or hid the layer.
open.note = found.err().or_else(|| target_refusal(app));
let ready = open.note.as_deref().map_or(Ok(()), |why| Err(Label::from(shown(why))));
app.addon_dialogs.tangent_radius = Some(open);
host.with(|h| {
if let Some(d) = h.get_mut_by_id::<HostedParamDialog>(id) {
d.set_notes(ready.as_ref().err().cloned().into_iter().collect());
d.set_ready(ready);
}
});
}
/// OK: draw the circle (keeping its preview) and close; with Auto-Update Default on, the radius
/// becomes the tool's when it is in the tool's range. Without a circle the dialog stays open.
fn ok(app: &mut VectorcraftApp, result: &ParamResult) -> Result<(), String> {
let Some(mut open) = app.addon_dialogs.tangent_radius.take() else { return Err(shown(tangent_circle::NO_CIRCLE)) };
let (r, points) = match circle(app, &mut open, &result.fields) {
Ok(found) => found,
Err(why) => {
app.addon_dialogs.tangent_radius = Some(open);
return Err(shown(&why));
}
};
let auto = app.session.tool_options_of(tangent_circle::ID).get("autoUpdateDefault").and_then(Value::as_bool) == Some(true);
// A failed commit leaves the interaction running: the dialog keeps its preview, so Cancel still ends it.
if let Err(e) = open.preview.clone().commit(app, DRAW, points) {
app.addon_dialogs.tangent_radius = Some(open);
return Err(e);
}
if auto && in_range(r) {
app.run("tool.setOption", json!({ "tool": tangent_circle::ID, "key": "radius", "value": r }))?;
}
Ok(())
}
#[cfg(test)]
mod tests {
use serde_json::{Value, json};
use vectorcraft_engine::{Session, ViewInfo};
use vectorcraft_tools::addons::tangent_circle as tool;
use vectorcraft_tools::{PointerEvent, PointerKind};
use crate::VectorcraftApp;
use crate::addons::dialogs::tests::{cancel, confirm, dialog_id, frame, read, set};
fn count(app: &VectorcraftApp) -> usize {
app.session.doc().unwrap().doc.layers[0].children().unwrap().len()
}
fn undo_steps(app: &VectorcraftApp) -> usize {
app.session.doc().unwrap().history.undo.len()
}
/// A test window with a 500 pt document, the lines `ys` from x 100 to 300, and the tool with Ask For Circle
/// Radius on.
fn app_with_lines(ys: &[i64]) -> VectorcraftApp {
let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), Default::default()));
app.run("file.new", json!({"width": 500, "height": 500})).unwrap();
for y in ys {
app.run("path.create", json!({"anchors": [{"x": 100, "y": y}, {"x": 300, "y": y}]})).unwrap();
}
app.session.select_tool(tool::ID, ViewInfo::default()).unwrap();
app.run("tool.setOption", json!({"tool": tool::ID, "key": "askRadius", "value": true})).unwrap();
app
}
/// A click with the active tool at (`x`, `y`), Shift held when `shift`, with what it asks the
/// interface for done.
fn click(app: &mut VectorcraftApp, x: f64, y: f64, shift: bool) {
for kind in [PointerKind::Down, PointerKind::Up] {
let mut ev = PointerEvent::new(kind, x, y);
ev.mods.shift = shift;
let r = app.session.pointer(&ev, ViewInfo::default());
crate::canvas::apply_requests(app, r);
}
}
fn is_open(app: &VectorcraftApp) -> bool {
app.addon_dialogs.tangent_radius.is_some()
}
/// Why the dialog shows no circle and leaves OK off, at the last frame.
fn note(app: &VectorcraftApp) -> Option<String> {
app.addon_dialogs.tangent_radius.as_ref()?.note.clone()
}
/// Presses OK and lets the held answer through: whether the dialog closed.
fn press_ok(app: &mut VectorcraftApp) -> bool {
let id = dialog_id(app);
let enabled = confirm(app, id);
frame(app);
frame(app);
enabled && !is_open(app)
}
/// Presses OK while it is off: it takes no press, and the dialog stays open.
fn press_ok_while_off(app: &mut VectorcraftApp) {
let id = dialog_id(app);
assert!(!confirm(app, id), "OK is off");
frame(app);
assert!(is_open(app));
}
#[test]
fn the_radius_dialog_previews_says_when_there_is_none_cancels_and_draws_on_ok() {
let mut app = app_with_lines(&[100, 140]);
app.run("path.create", json!({"anchors": [{"x": 100, "y": 300}, {"x": 300, "y": 300}, {"x": 300, "y": 400}]})).unwrap();
let (paths, steps) = (count(&app), undo_steps(&app));
// A click on each line: the dialog at the click's circle (radius 20), previewed.
click(&mut app, 150.0, 100.0, false);
click(&mut app, 200.0, 140.0, false);
assert!(is_open(&app), "{}", app.ui.status);
let id = dialog_id(&app);
assert!((read(&app, id, |f| f.number("radius")).unwrap() - 20.0).abs() < 1e-6);
frame(&mut app);
assert_eq!(count(&app), paths + 1, "previewed: {}", app.ui.status);
assert_eq!(note(&app), None);
// Lines 40 pt apart take no other radius: the note, nothing previewed, and OK off.
set(&app, id, "radius", json!(25));
frame(&mut app);
assert_eq!(note(&app).as_deref(), Some(tool::NO_CIRCLE));
assert_eq!(count(&app), paths);
press_ok_while_off(&mut app);
assert_eq!(count(&app), paths);
// A radius outside the tool's range (as a control request can set it) is an error.
for bad in [json!(0), json!(-20), json!(2e6)] {
set(&app, id, "radius", bad.clone());
frame(&mut app);
assert_eq!(note(&app).as_deref(), Some(super::RADIUS_RANGE), "{bad}");
press_ok_while_off(&mut app);
assert_eq!(count(&app), paths, "{bad}");
}
// Back at 20, previewed again; Cancel draws nothing and leaves no undo step.
set(&app, id, "radius", json!(20));
frame(&mut app);
assert_eq!(count(&app), paths + 1);
cancel(&app, id);
frame(&mut app);
assert!(!is_open(&app));
assert_eq!((count(&app), undo_steps(&app)), (paths, steps));
// The first line stays picked: a click on the second asks again, and OK draws the circle in
// one undo step; the tool's radius stays.
click(&mut app, 200.0, 140.0, false);
frame(&mut app);
assert!(press_ok(&mut app), "{}", app.ui.status);
assert_eq!((count(&app), undo_steps(&app)), (paths + 1, steps + 1));
let st = app.session.doc().unwrap();
let b = st.doc.bounds_of(&[st.doc.layers[0].children().unwrap()[paths].id], false).unwrap();
assert!((b.x0 - 130.0).abs() < 1e-3 && (b.y0 - 100.0).abs() < 1e-3 && (b.width() - 40.0).abs() < 1e-3, "{b:?}");
assert_eq!(app.session.tool_options_of(tool::ID)["radius"], json!(tool::RADIUS));
// Auto-Update Default: Shift in the L's corner asks at the tool's radius; Cancel keeps the
// tool's radius, and OK with another radius draws that fillet and makes it the tool's.
app.run("tool.setOption", json!({"tool": tool::ID, "key": "autoUpdateDefault", "value": true})).unwrap();
click(&mut app, 150.0, 300.0, false);
click(&mut app, 300.0, 350.0, true);
let id = dialog_id(&app);
assert_eq!(read(&app, id, |f| f.number("radius")), Some(tool::RADIUS));
set(&app, id, "radius", json!(12));
frame(&mut app);
cancel(&app, id);
frame(&mut app);
assert_eq!(app.session.tool_options_of(tool::ID)["radius"], json!(tool::RADIUS));
click(&mut app, 300.0, 350.0, true);
let id = dialog_id(&app);
set(&app, id, "radius", json!(10));
frame(&mut app);
assert!(press_ok(&mut app), "{}", app.ui.status);
assert_eq!((count(&app), undo_steps(&app)), (paths + 2, steps + 2));
assert_eq!(app.session.tool_options_of(tool::ID)["radius"], json!(10.0));
}
#[test]
fn another_document_or_a_segment_changed_after_the_click_gives_no_circle() {
let mut app = app_with_lines(&[100, 140]);
let paths = count(&app);
click(&mut app, 150.0, 100.0, false);
click(&mut app, 200.0, 140.0, false);
frame(&mut app);
assert_eq!(note(&app), None);
assert_eq!(count(&app), paths + 1);
// Clicked in another document than the active one: no circle and OK off, until that one is
// active again.
let clicked = app.addon_dialogs.tangent_radius.as_ref().and_then(|o| o.doc);
assert_eq!(clicked, Some(app.session.doc().unwrap().uid));
let set_doc = |app: &mut VectorcraftApp, doc: Option<u64>| app.addon_dialogs.tangent_radius.as_mut().unwrap().doc = doc;
set_doc(&mut app, clicked.map(|d| d + 1));
frame(&mut app);
assert_eq!(note(&app).as_deref(), Some(tool::NO_CIRCLE));
assert_eq!(count(&app), paths);
press_ok_while_off(&mut app);
set_doc(&mut app, clicked);
frame(&mut app);
assert_eq!(note(&app), None);
assert_eq!(count(&app), paths + 1);
// The dialog holds a first segment the document no longer has (as when a control request
// moves that line): no circle, nothing previewed, and OK refused.
app.addon_dialogs.tangent_radius.as_mut().unwrap().click["first"] = json!([[100.0, 110.0], [100.0, 110.0], [300.0, 110.0], [300.0, 110.0]]);
frame(&mut app);
assert_eq!(note(&app).as_deref(), Some(tool::NO_CIRCLE));
assert_eq!(count(&app), paths);
press_ok_while_off(&mut app);
assert_eq!(count(&app), paths);
}
#[test]
fn a_failed_ok_keeps_the_preview_for_cancel() {
let mut app = app_with_lines(&[100, 140]);
let (paths, steps) = (count(&app), undo_steps(&app));
click(&mut app, 150.0, 100.0, false);
click(&mut app, 200.0, 140.0, false);
frame(&mut app);
assert_eq!(count(&app), paths + 1);
// The layer the preview started from is locked before OK, so OK's draw is refused and the dialog stays open.
{
let st = app.session.doc_mut().unwrap();
let layer = st.doc.layers[0].id;
let it = st.interaction.as_mut().unwrap();
std::sync::Arc::make_mut(&mut it.doc).node_mut(layer).unwrap().locked = true;
}
let id = dialog_id(&app);
assert!(confirm(&app, id), "OK is on");
frame(&mut app);
assert!(is_open(&app));
assert!(app.session.in_interaction());
// The dialog still owns the interaction: a radius with no circle there ends it.
set(&app, id, "radius", json!(25));
frame(&mut app);
assert_eq!(note(&app).as_deref(), Some(tool::NO_CIRCLE));
assert!(!app.session.in_interaction());
// Cancel closes it with nothing drawn and no undo step.
cancel(&app, id);
frame(&mut app);
assert!(!is_open(&app));
assert!(!app.session.in_interaction());
assert_eq!((count(&app), undo_steps(&app)), (paths, steps));
}
#[test]
fn cancel_right_after_a_failed_ok_rolls_the_preview_back() {
let mut app = app_with_lines(&[100, 140]);
let (paths, steps) = (count(&app), undo_steps(&app));
click(&mut app, 150.0, 100.0, false);
click(&mut app, 200.0, 140.0, false);
frame(&mut app);
assert_eq!(count(&app), paths + 1);
{
let st = app.session.doc_mut().unwrap();
let layer = st.doc.layers[0].id;
let it = st.interaction.as_mut().unwrap();
std::sync::Arc::make_mut(&mut it.doc).node_mut(layer).unwrap().locked = true;
}
let id = dialog_id(&app);
assert!(confirm(&app, id), "OK is on");
frame(&mut app);
assert!(is_open(&app));
assert!(app.session.in_interaction());
// Cancel is the next press after the refused OK, with no radius change or other frame in between.
cancel(&app, id);
frame(&mut app);
assert!(!is_open(&app));
assert!(!app.session.in_interaction());
assert_eq!((count(&app), undo_steps(&app)), (paths, steps));
}
#[test]
fn a_click_found_radius_outside_the_tool_range_can_be_drawn() {
// Lines 2,400,000 pt apart: a click on each finds the circle of radius 1,200,000, past the
// largest radius the tool takes.
let mut app = app_with_lines(&[100, 2_400_100]);
app.run("tool.setOption", json!({"tool": tool::ID, "key": "autoUpdateDefault", "value": true})).unwrap();
let (paths, steps) = (count(&app), undo_steps(&app));
click(&mut app, 150.0, 100.0, false);
click(&mut app, 200.0, 2_400_100.0, false);
let id = dialog_id(&app);
assert!((read(&app, id, |f| f.number("radius")).unwrap() - 1_200_000.0).abs() < 1e-3, "{}", app.ui.status);
frame(&mut app);
assert_eq!(note(&app), None);
// OK draws it; the tool's radius stays, since the tool does not take that radius.
assert!(press_ok(&mut app), "{}", app.ui.status);
assert_eq!((count(&app), undo_steps(&app)), (paths + 1, steps + 1));
assert_eq!(app.session.tool_options_of(tool::ID)["radius"], json!(tool::RADIUS));
}
#[test]
fn a_second_click_replaces_the_open_dialog() {
let mut app = app_with_lines(&[100, 140]);
let (paths, steps) = (count(&app), undo_steps(&app));
let open_ids = |app: &VectorcraftApp| app.dialogs().unwrap().with(|h| h.open_dialogs().iter().map(|d| d.id).collect::<Vec<_>>());
click(&mut app, 150.0, 100.0, false);
click(&mut app, 200.0, 140.0, false);
frame(&mut app);
assert_eq!(count(&app), paths + 1);
// The first line stays picked: another click on the second (as a control request can send while the dialog
// is open) asks again in one dialog, previewing one circle.
click(&mut app, 200.0, 140.0, false);
frame(&mut app);
assert_eq!(open_ids(&app).len(), 1);
assert!(is_open(&app));
assert_eq!(count(&app), paths + 1);
// Cancel closes it and rolls its preview back, with no undo step.
cancel(&app, dialog_id(&app));
frame(&mut app);
assert!(!is_open(&app));
assert!(open_ids(&app).is_empty());
assert_eq!((count(&app), undo_steps(&app)), (paths, steps));
// Asked again, OK draws one circle in one undo step.
click(&mut app, 200.0, 140.0, false);
frame(&mut app);
assert!(press_ok(&mut app), "{}", app.ui.status);
assert_eq!((count(&app), undo_steps(&app)), (paths + 1, steps + 1));
}
#[test]
fn a_switch_to_another_document_leaves_its_interaction_alone() {
let mut app = app_with_lines(&[100, 140]);
let paths = count(&app);
click(&mut app, 150.0, 100.0, false);
click(&mut app, 200.0, 140.0, false);
frame(&mut app);
assert_eq!(count(&app), paths + 1);
// Another document comes to the front (which rolls the preview back in the first) and starts an interaction
// of its own before the dialog's next frame: the dialog leaves that interaction running.
app.run("file.new", json!({"width": 300, "height": 300})).unwrap();
app.begin_interaction("Other").unwrap();
app.session.preview("path.create", &json!({"anchors": [{"x": 10, "y": 10}, {"x": 50, "y": 10}]})).unwrap();
frame(&mut app);
assert_eq!(note(&app).as_deref(), Some(tool::NO_CIRCLE));
assert!(app.session.in_interaction());
assert_eq!(count(&app), 1);
// Cancel leaves it running too.
cancel(&app, dialog_id(&app));
frame(&mut app);
assert!(!is_open(&app));
assert!(app.session.in_interaction());
assert_eq!(count(&app), 1);
}
#[test]
fn a_circle_the_target_layer_cannot_take_shows_why_and_leaves_ok_off() {
let mut app = app_with_lines(&[100, 140]);
let paths = count(&app);
click(&mut app, 150.0, 100.0, false);
click(&mut app, 200.0, 140.0, false);
frame(&mut app);
assert_eq!(note(&app), None);
assert_eq!(count(&app), paths + 1);
// A control request locks the only layer while the dialog is open: no layer takes the circle, and OK is off.
app.run("layer.setProps", json!({"locked": true})).unwrap();
let steps = undo_steps(&app);
frame(&mut app);
assert!(note(&app).is_some_and(|n| n.contains("locked")), "{:?}", note(&app));
press_ok_while_off(&mut app);
assert_eq!((count(&app), undo_steps(&app)), (paths + 1, steps));
// Unlocked again at the same radius: previewed, and OK draws the circle.
app.run("layer.setProps", json!({"locked": false})).unwrap();
frame(&mut app);
assert_eq!(note(&app), None);
assert_eq!(count(&app), paths + 1);
assert!(press_ok(&mut app), "{}", app.ui.status);
assert_eq!(count(&app), paths + 1);
}
#[test]
fn a_radius_that_is_not_a_number_is_refused_and_keeps_the_circle() {
let mut app = app_with_lines(&[100, 140]);
let paths = count(&app);
click(&mut app, 150.0, 100.0, false);
click(&mut app, 200.0, 140.0, false);
let id = dialog_id(&app);
let ctx = crate::addons::dialogs::tests::ctx(&app);
for bad in [json!("x"), Value::Null] {
assert!(app.dialogs().unwrap().with(|h| h.set_json_field(&ctx, id, "radius", bad.clone())).is_err(), "{bad}");
frame(&mut app);
assert_eq!(note(&app), None, "{bad}");
assert_eq!(count(&app), paths + 1, "{bad}");
}
}
}
+12 -6
View File
@@ -110,18 +110,22 @@ fn double_clicking_the_brush_opens_its_options_and_ok_sets_them() {
assert_eq!(app.session.tool_options_of("extendPath")["mode"], json!("straight"));
ok(&mut app, &[("mode", FieldValue::Text("arc".into()))]);
assert_eq!(app.session.tool_options_of("extendPath")["mode"], json!("arc"));
// The Tangent Circle tool's radius for Shift, and Add Points to Existing Paths (off to start).
// The Tangent Circle tool's radius for Shift, Add Points to Existing Paths (off to start), Ask For
// Circle Radius and Auto-Update Default.
app.run("tool.options", json!({"tool": "tangentCircle"})).unwrap();
let shown = held(&app, |d| {
let f = d.expect("the held dialog").fields();
(f.number("radius"), f.bool("addPoints"))
(f.number("radius"), f.bool("addPoints"), f.bool("askRadius"), f.bool("autoUpdateDefault"))
});
assert_eq!(shown, (Some(36.0), Some(false)));
assert_eq!(shown, (Some(36.0), Some(false), Some(false), Some(false)));
let rows = super::options_params("tangentCircle", crate::canvas::rulers::general_lengths(&app));
assert!(rows.iter().any(|p| p.key == "addPoints" && p.label.as_str() == "Add Points to Existing Paths"), "the option has a row");
ok(&mut app, &[("radius", FieldValue::Number(12.5)), ("addPoints", FieldValue::Bool(true))]);
assert_eq!(app.session.tool_options_of("tangentCircle")["radius"], json!(12.5));
assert_eq!(app.session.tool_options_of("tangentCircle")["addPoints"], json!(true));
ok(&mut app, &[("radius", FieldValue::Number(12.5)), ("addPoints", FieldValue::Bool(true)), ("askRadius", FieldValue::Bool(true))]);
let o = app.session.tool_options_of("tangentCircle");
assert_eq!(
(o["radius"].clone(), o["addPoints"].clone(), o["askRadius"].clone(), o["autoUpdateDefault"].clone()),
(json!(12.5), json!(true), json!(true), json!(false))
);
assert!(app.run("tool.options", json!({"tool": "measureInspect"})).is_err());
assert_eq!(KIND, "pathToolOptions");
}
@@ -189,6 +193,8 @@ fn the_tangent_circle_options_have_their_rows_and_a_fractional_tolerance() {
("color", "Color"),
("snapTolerance", "Snap Tolerance"),
("snapWithoutGuides", "Snap When Smart Guides Are Off"),
("askRadius", "Ask For Circle Radius"),
("autoUpdateDefault", "Auto-Update Default"),
]
);
let colors = params.iter().find_map(|p| match &p.kind {
+2
View File
@@ -105,6 +105,8 @@ pub fn open_tool_dialog(app: &mut VectorcraftApp, kind: &str, p: Value) {
let r = super::slices::open_options(app);
reported(app, r);
}
// A Tangent Circle Tool click with Ask For Circle Radius on: the circle's radius.
crate::addons::pathtools::tangent_circle_radius::KIND => crate::addons::pathtools::tangent_circle_radius::open(app, &p),
// A click or double-click that would edit type set in fonts that aren't available.
vectorcraft_tools::text::MISSING_FONT_EDIT => super::confirm::ask_missing_font_edit(app, &p),
_ => {}
+2
View File
@@ -8297,6 +8297,8 @@ breakText Glyphs Глифи
Tangent Circle Допирателна окръжност
Tangent Circle Tool Инструмент „Допирателна окръжност“
No tangent circle here Тук няма допирателна окръжност
Ask For Circle Radius Питане за радиуса на окръжността
Auto-Update Default Автоматично обновяване на стойността по подразбиране
Circle: Окръжност:
@msg `ids` names an object twice `ids` посочва обект два пъти
@msg select two or three paths or compound paths изберете два или три пътя или съставни пътя
Can't render this file because it is too large.
+2
View File
@@ -7675,6 +7675,8 @@ shape Open Otvoren
Tangent Circle Tangentna kružnica
Tangent Circle Tool Alat tangentna kružnica
No tangent circle here Ovdje nema tangentne kružnice
Ask For Circle Radius Pitaj za poluprečnik kružnice
Auto-Update Default Automatski ažuriraj zadanu vrijednost
Circle: Kružnica:
@msg `ids` names an object twice `ids` navodi objekat dvaput
@msg select two or three paths or compound paths odaberite dvije ili tri putanje ili složene putanje
Can't render this file because it contains an unexpected character in line 2 and column 73.
+2
View File
@@ -8594,6 +8594,8 @@ breakText Glyphs Glifs
Tangent Circle Cercle tangent
Tangent Circle Tool Eina de cercle tangent
No tangent circle here Aquí no hi ha cap cercle tangent
Ask For Circle Radius Demana el radi del cercle
Auto-Update Default Actualitza automàticament el valor predeterminat
Circle: Cercle:
@msg `ids` names an object twice `ids` indica un objecte dues vegades
@msg select two or three paths or compound paths seleccioneu dos o tres camins o camins compostos
Can't render this file because it is too large.
+2
View File
@@ -8575,6 +8575,8 @@ breakText Glyphs Glyfy
Tangent Circle Tečná kružnice
Tangent Circle Tool Nástroj Tečná kružnice
No tangent circle here Zde není žádná tečná kružnice
Ask For Circle Radius Ptát se na poloměr kružnice
Auto-Update Default Automaticky aktualizovat výchozí hodnotu
Circle: Kružnice:
@msg `ids` names an object twice `ids` uvádí některý objekt dvakrát
@msg select two or three paths or compound paths vyberte dvě nebo tři cesty nebo složené cesty
Can't render this file because it is too large.
+2
View File
@@ -10627,6 +10627,8 @@ breakText Glyphs Glyffer
Tangent Circle Tangentcirkel
Tangent Circle Tool Tangentcirkel-værktøj
No tangent circle here Ingen tangentcirkel her
Ask For Circle Radius Spørg om cirklens radius
Auto-Update Default Opdater standard automatisk
Circle: Cirkel:
@msg `ids` names an object twice `ids` nævner et objekt to gange
@msg select two or three paths or compound paths vælg to eller tre stier eller sammensatte stier
Can't render this file because it is too large.
+2
View File
@@ -8198,6 +8198,8 @@ breakText Glyphs Glyphen
Tangent Circle Tangentialkreis
Tangent Circle Tool Tangentialkreis-Werkzeug
No tangent circle here Hier kein Tangentialkreis
Ask For Circle Radius Nach Kreisradius fragen
Auto-Update Default Standardwert automatisch aktualisieren
Circle: Kreis:
@msg `ids` names an object twice `ids` nennt ein Objekt zweimal
@msg select two or three paths or compound paths wählen Sie zwei oder drei Pfade oder zusammengesetzte Pfade aus
Can't render this file because it is too large.
+2
View File
@@ -8566,6 +8566,8 @@ breakText Glyphs Γλύφοι
Tangent Circle Εφαπτόμενος κύκλος
Tangent Circle Tool Εφαπτόμενος κύκλος (Tangent Circle Tool)
No tangent circle here Δεν υπάρχει εφαπτόμενος κύκλος εδώ
Ask For Circle Radius Ερώτηση για την ακτίνα του κύκλου
Auto-Update Default Αυτόματη ενημέρωση προεπιλογής
Circle: Κύκλος:
@msg `ids` names an object twice το `ids` αναφέρει ένα αντικείμενο δύο φορές
@msg select two or three paths or compound paths επιλέξτε δύο ή τρεις διαδρομές ή σύνθετες διαδρομές
Can't render this file because it is too large.
+2
View File
@@ -8552,6 +8552,8 @@ breakText Glyphs Glifos
Tangent Circle Círculo tangente
Tangent Circle Tool Herramienta Círculo tangente
No tangent circle here No hay círculo tangente aquí
Ask For Circle Radius Preguntar el radio del círculo
Auto-Update Default Actualizar automáticamente el valor predeterminado
Circle: Círculo:
@msg `ids` names an object twice `ids` indica un objeto dos veces
@msg select two or three paths or compound paths seleccione dos o tres trazados o trazados compuestos
Can't render this file because it is too large.
+2
View File
@@ -8642,6 +8642,8 @@ breakText Glyphs Merkit
Tangent Circle Sivuava ympyrä
Tangent Circle Tool Sivuava ympyrä -työkalu
No tangent circle here Tässä ei ole sivuavaa ympyrää
Ask For Circle Radius Kysy ympyrän säde
Auto-Update Default Päivitä oletus automaattisesti
Circle: Ympyrä:
@msg `ids` names an object twice `ids` mainitsee saman objektin kahdesti
@msg select two or three paths or compound paths valitse kaksi tai kolme polkua tai yhdistelmäpolkua
Can't render this file because it is too large.
+2
View File
@@ -8571,6 +8571,8 @@ breakText Glyphs Glyphes
Tangent Circle Cercle tangent
Tangent Circle Tool Outil Cercle tangent
No tangent circle here Aucun cercle tangent ici
Ask For Circle Radius Demander le rayon du cercle
Auto-Update Default Mettre à jour automatiquement la valeur par défaut
Circle: Cercle :
@msg `ids` names an object twice `ids` désigne deux fois le même objet
@msg select two or three paths or compound paths sélectionnez deux ou trois tracés ou tracés transparents
Can't render this file because it is too large.
+2
View File
@@ -4365,6 +4365,8 @@ arrowhead Feather પીંછું
Tangent Circle સ્પર્શક વર્તુળ
Tangent Circle Tool સ્પર્શક વર્તુળ ટૂલ
No tangent circle here અહીં કોઈ સ્પર્શક વર્તુળ નથી
Ask For Circle Radius વર્તુળની ત્રિજ્યા પૂછો
Auto-Update Default ડિફૉલ્ટ આપમેળે અપડેટ કરો
Tangent Circle… સ્પર્શક વર્તુળ…
Taper ટેપર
Target લક્ષ્ય
Can't render this file because it contains an unexpected character in line 72 and column 5.
+2
View File
@@ -5914,6 +5914,8 @@ arrowhead Feather पंख
Tangent Circle स्पर्शी वृत्त
Tangent Circle Tool स्पर्शी वृत्त टूल
No tangent circle here यहाँ कोई स्पर्शी वृत्त नहीं है
Ask For Circle Radius वृत्त की त्रिज्या पूछें
Auto-Update Default डिफ़ॉल्ट स्वचालित रूप से अपडेट करें
Tangent Circle… स्पर्शी वृत्त…
Taper टेपर
Target लक्ष्य
Can't render this file because it is too large.
+2
View File
@@ -8561,6 +8561,8 @@ breakText Glyphs Glifák
Tangent Circle Érintőkör
Tangent Circle Tool Érintőkör eszköz
No tangent circle here Itt nincs érintőkör
Ask For Circle Radius Kérdés a kör sugaráról
Auto-Update Default Alapértelmezett érték automatikus frissítése
Circle: Kör:
@msg `ids` names an object twice `ids`: egy objektumot kétszer nevez meg
@msg select two or three paths or compound paths jelölj ki két vagy három útvonalat vagy összetett útvonalat
Can't render this file because it is too large.
+2
View File
@@ -8409,6 +8409,8 @@ breakText Glyphs Glif
Tangent Circle Lingkaran singgung
Tangent Circle Tool Alat lingkaran singgung
No tangent circle here Tidak ada lingkaran singgung di sini
Ask For Circle Radius Tanyakan Radius Lingkaran
Auto-Update Default Perbarui Default Otomatis
Circle: Lingkaran:
@msg `ids` names an object twice `ids` menyebut satu objek dua kali
@msg select two or three paths or compound paths pilih dua atau tiga jalur atau jalur gabungan
Can't render this file because it is too large.
+2
View File
@@ -8236,6 +8236,8 @@ breakText Glyphs Glifi
Tangent Circle Cerchio tangente
Tangent Circle Tool Strumento Cerchio tangente
No tangent circle here Nessun cerchio tangente qui
Ask For Circle Radius Chiedi il raggio del cerchio
Auto-Update Default Aggiorna automaticamente il valore predefinito
Circle: Cerchio:
@msg `ids` names an object twice `ids` indica due volte lo stesso oggetto
@msg select two or three paths or compound paths seleziona due o tre tracciati o tracciati composti
Can't render this file because it is too large.
+2
View File
@@ -10127,6 +10127,8 @@ breakText Glyphs 字形
Tangent Circle 接円
Tangent Circle Tool 接円ツール
No tangent circle here ここに接円はありません
Ask For Circle Radius 円の半径を確認
Auto-Update Default デフォルトを自動更新
Circle: 円:
@msg `ids` names an object twice `ids` に同じオブジェクトが 2 回指定されています
@msg select two or three paths or compound paths パスまたは複合パスを 2 つか 3 つ選択してください
Can't render this file because it is too large.
+2
View File
@@ -10751,6 +10751,8 @@ breakText Glyphs გლიფები
Tangent Circle მხები წრე
Tangent Circle Tool მხები წრის ხელსაწყო
No tangent circle here აქ მხები წრე არ არის
Ask For Circle Radius წრის რადიუსის კითხვა
Auto-Update Default ნაგულისხმევის ავტომატური განახლება
Circle: წრე:
@msg `ids` names an object twice `ids` ერთსა და იმავე ობიექტს ორჯერ მიუთითებს
@msg select two or three paths or compound paths მონიშნეთ ორი ან სამი ტრაექტორია ან შედგენილი ტრაექტორია
Can't render this file because it is too large.
+2
View File
@@ -8208,6 +8208,8 @@ breakText Glyphs 글리프
Tangent Circle 접원
Tangent Circle Tool 접원 도구
No tangent circle here 여기에는 접원이 없음
Ask For Circle Radius 원 반지름 묻기
Auto-Update Default 기본값 자동 업데이트
Circle: 원:
@msg `ids` names an object twice `ids`에 같은 오브젝트가 두 번 있습니다
@msg select two or three paths or compound paths 패스나 컴파운드 패스를 두 개 또는 세 개 선택하세요
Can't render this file because it is too large.
+2
View File
@@ -10471,6 +10471,8 @@ breakText Glyphs Glyphs
Tangent Circle Raakcirkel
Tangent Circle Tool Raakcirkel-gereedschap
No tangent circle here Hier geen raakcirkel
Ask For Circle Radius Vragen naar cirkelradius
Auto-Update Default Standaard automatisch bijwerken
Circle: Cirkel:
@msg `ids` names an object twice `ids` noemt een object twee keer
@msg select two or three paths or compound paths selecteer twee of drie paden of samengestelde paden
Can't render this file because it is too large.
+2
View File
@@ -8432,6 +8432,8 @@ breakText Glyphs Glify
Tangent Circle Okrąg styczny
Tangent Circle Tool Narzędzie Okrąg styczny
No tangent circle here Brak okręgu stycznego w tym miejscu
Ask For Circle Radius Pytaj o promień okręgu
Auto-Update Default Automatycznie aktualizuj wartość domyślną
Circle: Okrąg:
@msg `ids` names an object twice `ids` wskazuje ten sam obiekt dwa razy
@msg select two or three paths or compound paths zaznacz dwie lub trzy ścieżki lub ścieżki złożone
Can't render this file because it is too large.
+2
View File
@@ -8594,6 +8594,8 @@ breakText Glyphs Glifos
Tangent Circle Círculo tangente
Tangent Circle Tool Ferramenta Círculo tangente
No tangent circle here Nenhum círculo tangente aqui
Ask For Circle Radius Perguntar o Raio do Círculo
Auto-Update Default Atualizar o Padrão Automaticamente
Circle: Círculo:
@msg `ids` names an object twice `ids` indica um objeto duas vezes
@msg select two or three paths or compound paths selecione dois ou três caminhos ou caminhos compostos
Can't render this file because it is too large.
+2
View File
@@ -8566,6 +8566,8 @@ breakText Glyphs Глифы
Tangent Circle Касательная окружность
Tangent Circle Tool Инструмент «Касательная окружность»
No tangent circle here Здесь нет касательной окружности
Ask For Circle Radius Запрашивать радиус окружности
Auto-Update Default Автоматически обновлять значение по умолчанию
Circle: Окружность:
@msg `ids` names an object twice `ids` указывает объект дважды
@msg select two or three paths or compound paths выделите два или три контура или составных контура
Can't render this file because it is too large.
+2
View File
@@ -8583,6 +8583,8 @@ breakText Glyphs Glyfer
Tangent Circle Tangentcirkel
Tangent Circle Tool Tangentcirkelverktyget
No tangent circle here Ingen tangentcirkel här
Ask For Circle Radius Fråga efter cirkelradie
Auto-Update Default Uppdatera standard automatiskt
Circle: Cirkel:
@msg `ids` names an object twice `ids` anger ett objekt två gånger
@msg select two or three paths or compound paths markera två eller tre banor eller sammansatta banor
Can't render this file because it is too large.
+2
View File
@@ -10467,6 +10467,8 @@ breakText Glyphs Glifler
Tangent Circle Teğet Daire
Tangent Circle Tool Teğet Daire Aracı
No tangent circle here Burada teğet daire yok
Ask For Circle Radius Daire Yarıçapını Sor
Auto-Update Default Varsayılanı Otomatik Güncelle
Circle: Daire:
@msg `ids` names an object twice `ids` bir nesneyi iki kez belirtiyor
@msg select two or three paths or compound paths iki veya üç yol ya da bileşik yol seçin
Can't render this file because it is too large.
+2
View File
@@ -8218,6 +8218,8 @@ breakText Glyphs Гліфи
Tangent Circle Дотичне коло
Tangent Circle Tool Інструмент «Дотичне коло»
No tangent circle here Тут немає дотичного кола
Ask For Circle Radius Запитувати радіус кола
Auto-Update Default Автоматично оновлювати значення за замовчуванням
Circle: Коло:
@msg `ids` names an object twice `ids` указує об’єкт двічі
@msg select two or three paths or compound paths виділіть два або три контури чи складені контури
Can't render this file because it is too large.
+2
View File
@@ -8264,6 +8264,8 @@ breakText Glyphs Glyph
Tangent Circle Đường tròn tiếp xúc
Tangent Circle Tool Công cụ Đường tròn tiếp xúc
No tangent circle here Không có đường tròn tiếp xúc ở đây
Ask For Circle Radius Hỏi bán kính đường tròn
Auto-Update Default Tự động cập nhật mặc định
Circle: Đường tròn:
@msg `ids` names an object twice `ids` nêu một đối tượng hai lần
@msg select two or three paths or compound paths chọn hai hoặc ba đường dẫn hoặc đường dẫn phức hợp
Can't render this file because it is too large.
+2
View File
@@ -8444,6 +8444,8 @@ breakText Glyphs 字形
Tangent Circle 相切圆
Tangent Circle Tool 相切圆工具
No tangent circle here 此处没有相切圆
Ask For Circle Radius 询问圆半径
Auto-Update Default 自动更新默认值
Circle: 圆:
@msg `ids` names an object twice `ids` 重复指定了同一个对象
@msg select two or three paths or compound paths 请选择两个或三个路径或复合路径
Can't render this file because it is too large.
+2
View File
@@ -8266,6 +8266,8 @@ breakText Glyphs 字符
Tangent Circle 相切圓
Tangent Circle Tool 相切圓工具
No tangent circle here 此處沒有相切圓
Ask For Circle Radius 詢問圓半徑
Auto-Update Default 自動更新預設值
Circle: 圓:
@msg `ids` names an object twice `ids` 將同一個物件指定了兩次
@msg select two or three paths or compound paths 請選取兩個或三個路徑或複合路徑
Can't render this file because it is too large.
+13 -1
View File
@@ -15920,8 +15920,20 @@ Tools:
`snapTolerance` (screen pixels, 0 to 25, 3; VectorCraft's own range and default) is how near the pointer picks a
segment while Smart Guides are on (their Snapping Tolerance counts instead when it is larger) or while they are off
with `snapWithoutGuides` (true or false, true) on. Otherwise a segment is picked within the Selection Tolerance, which is also the least reach with snapping.
`askRadius` (Ask For Circle Radius) and `autoUpdateDefault` (Auto-Update Default) are true or false, both false.
`tool.setOption` gives an error for a value outside an option's range, of the wrong type, or a color not listed, and
for any other option, and then sets none of the values.
for any other option, and then sets none of the values. With `askRadius` on, a click on the second segment that finds
a circle (with or without Shift) opens the Tangent Circle dialog (`tangentCircleRadius`) instead of drawing; a drag,
which sets the radius, draws at once. The dialog's Radius starts at the radius of the circle found, and each radius
previews the circle of that radius touching the second segments nearest the click, anywhere along the first segment
(at the radius it opened with, the circle found). A radius that gives no circle there shows the note and leaves OK
off, as do an edit to either segment's path after the click and another active document; a circle the target layer
cannot take (locked or hidden) shows why and leaves OK off; a radius outside 0.01 to
1000000 pt, typed or set, shows the radius error and leaves OK off, except the radius the dialog opened with.
`ui.dialog.set` gives an error for a radius that is not a number. OK draws the circle in one undo
step, with `shape.circleThroughPoints`, and with `autoUpdateDefault` on also sets `radius` to the radius given when
it is in that range. Cancel draws nothing, leaves no undo step and
keeps the first segment picked.
- **Trim at Crossings Tool** (`trimAtCrossings`): removes stretches of paths between the places where they are crossed,
on any path that can be edited, selected or not. A click runs `addon.pathtools.trim` with `at`, for the path within 4
screen pixels of the pointer. A drag draws a rectangle and runs it with `rect` on release; once the pointer has
+2
View File
@@ -3167,6 +3167,8 @@ Add Points to Existing Paths (2026-11-20): the tool's `addPoints` option (in its
The tool's options dialog also sets the preview and how a segment is picked, the options the help page lists (https://docs.astutegraphics.com/subscribe/tangent-circle-tool): Circle Center and Circle Radii Lines (`center`, `radii`) show or hide the center cross and the radii, Color (`color`: red, blue, magenta, green, black or gray) colors the circle, the cross, the radii and the note, Snap Tolerance (`snapTolerance`, screen pixels) is how near the pointer picks a segment with Smart Guides on, the Smart Guides Snapping Tolerance counting when it is larger, and Snap When Smart Guides Are Off (`snapWithoutGuides`) keeps that reach with Smart Guides off; without it the Selection Tolerance applies. Of the segments within reach the nearest is picked. The defaults (both shown, red, 3 px, snapping on) and the 0 to 25 px range are VectorCraft's own; they are kept with the preferences, and `tool.setOption` gives an error for a value an option does not take. Tests: `addons::tangent_circle::tests` in `vectorcraft-tools` (the preview options, the snapping reach, the options' values) and `the_tangent_circle_options_set_the_preview_and_snapping` in `vectorcraft-ui-egui`.
Ask For Circle Radius and Auto-Update Default (2026-11-20): two options of the tool (`askRadius`, `autoUpdateDefault`, both off to start with). With Ask For Circle Radius on, a click on the second segment that finds a circle, with or without Shift, opens a Tangent Circle dialog at that circle's radius instead of drawing; a drag draws at once. Each radius typed previews the circle of that radius nearest the click, a radius with no circle there, an edit to either segment after the click, or another active document, shows the note and leaves OK off, a target layer that is locked or hidden says so and leaves OK off, a radius typed outside 0.01 to 1,000,000 pt (other than the click's own) shows an error and leaves OK off, OK draws the circle in one undo step, and Cancel draws nothing and keeps the first segment picked. With Auto-Update Default on, OK also makes the radius given the tool's Shift radius when it is from 0.01 to 1,000,000 pt. Tests: `ask_for_circle_radius_opens_the_dialog_after_a_click_but_not_after_a_drag` and `the_radius_dialog_knows_when_its_segments_changed` in `vectorcraft-tools`, and `the_radius_dialog_previews_says_when_there_is_none_cancels_and_draws_on_ok`, `another_document_or_a_segment_changed_after_the_click_gives_no_circle`, `a_failed_ok_keeps_the_preview_for_cancel`, `a_click_found_radius_outside_the_tool_range_can_be_drawn`, `a_circle_the_target_layer_cannot_take_shows_why_and_leaves_ok_off`, `a_switch_to_another_document_leaves_its_interaction_alone`, `a_second_click_replaces_the_open_dialog` and `a_radius_that_is_not_a_number_is_refused_and_keeps_the_circle` in `vectorcraft-ui-egui`.
## Path Precision Tools add-on: Trim at Crossings (2026-11-13)
A VectorCraft addition, not a feature of the reference app, so no area score moves. Object › Plug-ins › Path Precision Tools › Trim at Crossings Tool (also in the Scissors tool's group in both shipped toolbars, after the Knife, since 2026-11-16; a toolbar edited before keeps its saved layout until Reset Toolbar; no shortcut) removes stretches of paths between the places where they are crossed by another path or by themselves, on any path that can be edited, 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; each is one undo step, and Escape during a drag removes nothing. A closed path that loses a stretch becomes open, an open path that loses a middle stretch becomes two paths with its appearance in its place in the stacking order, a path that nothing crosses is removed whole, and the stretches that stay get no new anchors. Hidden and locked paths, guides and clipping paths are not trimmed and do not count as crossing. Add Points at / Split at Crossings share the crossing search: segments that meet at an anchor now count where they cross again elsewhere, and with Self Crossings a curved segment that loops over itself crosses itself. Command `addon.pathtools.trim`; `vectorcraft_pathops::addons::pathtools::{crossings_on, spans, without_spans}`. Hovering shows in red the stretch a click would remove, worked out by the same code the command uses (`vectorcraft_tools::addons::trim::plan`), and a drag that reaches at most 32 paths shows what its release would remove; a preview spends at most a twentieth of the crossing work a click may (2026-11-15; tests `hovering_*`, `in_isolation_mode_*`, `a_path_whose_crossings_*` and `a_small_drag_*` in `addons::trim` in `vectorcraft-tools`, `hovering_with_the_tool_shows_the_stretch_its_click_removes` and `what_the_tool_shows_*` in `vectorcraft-engine`). Not yet: crossings with type, images and symbol instances. Tests: `crossings_on_*`, `segments_*`, `a_segment_that_loops_over_itself_crosses_itself`, `one_work_budget_*`, `spans_divide_*`, `a_subpath_without_*` and `a_slice_*` in `addons::pathtools::tests` in `vectorcraft-pathops`, `addons::trim` in `vectorcraft-tools` (click, rectangle, freehand line, Escape), `cmd::addons::pathtools::trim::tests` in `vectorcraft-engine` (a middle and an end stretch, a closed path opening, a rectangle and a line as one undo step, locked and hidden paths, guides and clipping paths, paths nothing crosses, compound path members, the selection, 3,000 other paths, a path too large to search left alone until touched, bad params refused), `the_plugins_submenu_selects_the_tools_and_opens_the_anchor_inspector` in `vectorcraft-ui-egui`, `edit_toolbar::tests` and `command_sweep`. Commands: `docs/mcp.md` › Path Precision Tools add-on. The tool shows the Knife's cursor, now drawn as a knife with the blade's point on the hotspot (2026-11-16; tests `trim_at_crossings_is_in_the_scissors_flyout` and `a_saved_toolbar_without_trim_at_crossings_keeps_its_layout` in `edit_toolbar::tests`, `trim_at_crossings_is_in_the_scissors_group_once` in `addons::tests`, `headless_backend_methods` in `vectorcraft-mcp`, `the_knife_shows_a_knife_with_its_point_on_the_hotspot` in `cursors::tests` and `drawing_tools_show_their_own_cursor` in `vectorcraft-tools`).