mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-27 16:59:43 +01:00
Merge pull request #9006 from dotCooCoo/feat/tangent-circle-add-points
Tangent Circle Tool: Add Points to Existing Paths adds anchors where the circle touches
This commit is contained in:
8 files changed
+323
-19
No files matched your search
@@ -1172,6 +1172,64 @@ fn the_tangent_circle_tool_keeps_its_first_segment_when_drawing_fails() {
|
||||
assert!(!shown(&mut s), "the first segment is forgotten once the circle is drawn");
|
||||
}
|
||||
|
||||
/// With Add Points to Existing Paths on, the Tangent Circle tool's circle and an anchor point where
|
||||
/// it touches each line are one undo step; the lines keep their shape, and one Undo takes all of it
|
||||
/// back.
|
||||
#[test]
|
||||
fn the_tangent_circle_tool_adds_points_where_the_circle_touches_in_one_step() {
|
||||
let mut s = session();
|
||||
let a = line(&mut s, &[(100.0, 100.0), (300.0, 100.0)], false);
|
||||
let b = line(&mut s, &[(100.0, 140.0), (300.0, 140.0)], false);
|
||||
let view = ViewInfo { smart_guides: false, ..ViewInfo::default() };
|
||||
s.select_tool("tangentCircle", view).unwrap();
|
||||
s.set_tool_option("addPoints", &json!(true));
|
||||
let n = steps(&s);
|
||||
for (kind, x, y) in
|
||||
[(PointerKind::Down, 150.0, 101.0), (PointerKind::Up, 150.0, 101.0), (PointerKind::Down, 200.0, 139.0), (PointerKind::Up, 200.0, 139.0)]
|
||||
{
|
||||
s.pointer(&PointerEvent::new(kind, x, y), view).unwrap();
|
||||
}
|
||||
assert_eq!(steps(&s), n + 1, "one undo step");
|
||||
let points = |s: &Session, id| path(s, id).subpaths[0].anchors.iter().map(|a| (a.p.x, a.p.y)).collect::<Vec<_>>();
|
||||
let near = |got: Vec<(f64, f64)>, want: &[(f64, f64)]| {
|
||||
got.len() == want.len() && got.iter().zip(want).all(|(g, w)| (g.0 - w.0).abs() < 1e-6 && (g.1 - w.1).abs() < 1e-6)
|
||||
};
|
||||
assert!(near(points(&s, a), &[(100.0, 100.0), (150.0, 100.0), (300.0, 100.0)]), "{:?}", points(&s, a));
|
||||
assert!(near(points(&s, b), &[(100.0, 140.0), (150.0, 140.0), (300.0, 140.0)]), "{:?}", points(&s, b));
|
||||
let st = s.doc().unwrap();
|
||||
let [circle] = st.selection.objects[..] else { panic!("{:?}", st.selection.objects) };
|
||||
let r = st.doc.node(circle).and_then(|c| c.path_data()).and_then(|pd| pd.bounds()).unwrap();
|
||||
assert!((r.x0 - 130.0).abs() < 1e-6 && (r.y0 - 100.0).abs() < 1e-6 && (r.width() - 40.0).abs() < 1e-6, "{r:?}");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!((steps(&s), points(&s, a).len(), points(&s, b).len()), (n, 2, 2));
|
||||
assert!(s.doc().unwrap().doc.node(circle).is_none(), "the circle is gone too");
|
||||
}
|
||||
|
||||
/// In Draw Behind, the Tangent Circle tool's circle goes behind the object selected before the
|
||||
/// clicks, also when Add Points to Existing Paths adds anchors to lines that were not selected.
|
||||
#[test]
|
||||
fn the_tangent_circle_tool_adding_points_draws_behind_the_selection() {
|
||||
let mut s = session();
|
||||
line(&mut s, &[(100.0, 100.0), (300.0, 100.0)], false);
|
||||
line(&mut s, &[(100.0, 140.0), (300.0, 140.0)], false);
|
||||
let other = line(&mut s, &[(100.0, 400.0), (300.0, 400.0)], false);
|
||||
select(&mut s, &[other]);
|
||||
s.execute("view.drawMode", &json!({"mode": "behind"})).unwrap();
|
||||
let view = ViewInfo { smart_guides: false, ..ViewInfo::default() };
|
||||
s.select_tool("tangentCircle", view).unwrap();
|
||||
s.set_tool_option("addPoints", &json!(true));
|
||||
for (kind, x, y) in
|
||||
[(PointerKind::Down, 150.0, 101.0), (PointerKind::Up, 150.0, 101.0), (PointerKind::Down, 200.0, 139.0), (PointerKind::Up, 200.0, 139.0)]
|
||||
{
|
||||
s.pointer(&PointerEvent::new(kind, x, y), view).unwrap();
|
||||
}
|
||||
let st = s.doc().unwrap();
|
||||
let [circle] = st.selection.objects[..] else { panic!("{:?}", st.selection.objects) };
|
||||
let at = |id| st.doc.position(id).map(|(parent, index, _)| (parent, index));
|
||||
let (Some((p, c)), Some((q, o))) = (at(circle), at(other)) else { panic!("not placed") };
|
||||
assert!(p == q && c + 1 == o, "the circle is right behind the selected line: {c} and {o}");
|
||||
}
|
||||
|
||||
fn ids(v: &Value) -> Vec<NodeId> {
|
||||
v["ids"].as_array().unwrap().iter().map(|i| NodeId(i.as_u64().unwrap())).collect()
|
||||
}
|
||||
|
||||
@@ -15,19 +15,23 @@
|
||||
//! press on the second segment is dropped. Escape, an edit or Undo outside the tool, another
|
||||
//! document, or a change to the first segment that leaves no undo step (a live preview, or one that
|
||||
//! was canceled) forgets the first segment. The circles are looked for again whenever either
|
||||
//! segment's shape differs from the one they were found on.
|
||||
//! 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.
|
||||
//!
|
||||
//! The tool's options (its options dialog, `tool.setOption`; kept with the preferences): `radius`;
|
||||
//! `center` and `radii` show or hide the circle's center cross and the lines from its center to the
|
||||
//! `addPoints`; `center` and `radii` show or hide the circle's center cross and the lines from its center to the
|
||||
//! two points it touches; `color` is the color of the circle, the cross, those lines and the note
|
||||
//! (one of [`COLORS`]); `snapTolerance` is how near (screen pixels) the pointer picks a segment
|
||||
//! with Smart Guides on, where Smart Guides' Snapping Tolerance counts instead when it is larger,
|
||||
//! or with Smart Guides off while `snapWithoutGuides` is on. Without snapping a segment is picked
|
||||
//! 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 the
|
||||
//! cross and the lines show, the color is red, the tolerance is 3 px and `snapWithoutGuides` is on.
|
||||
//! 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.
|
||||
|
||||
use kurbo::{CubicBez, Shape};
|
||||
use kurbo::{CubicBez, ParamCurveNearest, Shape};
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::NodeId;
|
||||
use vectorcraft_geom::{BezPath, ParamCurve, Point};
|
||||
@@ -52,6 +56,12 @@ pub const NO_CIRCLE: &str = "No tangent circle here";
|
||||
const BLUE: [u8; 3] = [0x4f, 0x9d, 0xff];
|
||||
const RED: [u8; 3] = [0xe0, 0x3c, 0x3c];
|
||||
const GREY: [u8; 3] = [0x80, 0x80, 0x80];
|
||||
/// The label of the `addPoints` option in the tool's options.
|
||||
pub const ADD_POINTS: &str = "Add Points to Existing Paths";
|
||||
/// How far (screen pixels) right of and below the pointer the dot shows while `addPoints` is in
|
||||
/// effect, and its size.
|
||||
const DOT_PX: f64 = 10.0;
|
||||
const DOT_SIZE: f32 = 4.0;
|
||||
/// The colors the `color` option takes, by option value, with the color the circle, its center
|
||||
/// cross, its radii and the note are drawn in. Red is the first.
|
||||
pub const COLORS: &[(&str, [u8; 3])] = &[
|
||||
@@ -67,7 +77,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] = &["center", "radii", "snapWithoutGuides"];
|
||||
const SWITCHES: &[&str] = &["addPoints", "center", "radii", "snapWithoutGuides"];
|
||||
|
||||
/// A segment under the pointer: where on it, and the segment itself.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
@@ -101,6 +111,11 @@ struct Press {
|
||||
|
||||
pub struct TangentCircleTool {
|
||||
radius: f64,
|
||||
/// Whether drawing a circle adds anchor points where it touches the segments.
|
||||
add_points: bool,
|
||||
/// The keys held at the last pointer event, and whether the pointer is over the canvas.
|
||||
mods: Mods,
|
||||
over: bool,
|
||||
/// Whether the preview shows the center cross and the radii.
|
||||
center: bool,
|
||||
radii: bool,
|
||||
@@ -130,6 +145,9 @@ impl Default for TangentCircleTool {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
radius: RADIUS,
|
||||
add_points: false,
|
||||
mods: Mods::default(),
|
||||
over: false,
|
||||
center: true,
|
||||
radii: true,
|
||||
color: 0,
|
||||
@@ -189,6 +207,11 @@ 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`] 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) {
|
||||
return vec![];
|
||||
}
|
||||
@@ -205,7 +228,36 @@ fn second_set(cx: &ToolContext, first: &Pick, second: &Pick) -> Vec<CubicBez> {
|
||||
indices.sort_unstable();
|
||||
indices.dedup();
|
||||
let is_first = |k: usize| first.id == second.id && first.subpath == second.subpath && first.segment == k;
|
||||
indices.into_iter().filter(|k| *k < n && !is_first(*k)).map(|k| sp.segment(k)).collect()
|
||||
indices.into_iter().filter(|k| *k < n && !is_first(*k)).map(|k| (k, sp.segment(k))).collect()
|
||||
}
|
||||
|
||||
/// Where on `curve` the point `p` lies: its parameter, or none when `p` is within `tol` of either
|
||||
/// end, where the segment already has an anchor point.
|
||||
fn split_at(curve: &CubicBez, p: Point, tol: f64) -> Option<f64> {
|
||||
if p.distance(curve.p0) <= tol || p.distance(curve.p3) <= tol {
|
||||
return None;
|
||||
}
|
||||
let t = curve.nearest(p, 1e-12).t;
|
||||
(t > 0.0 && t < 1.0).then_some(t)
|
||||
}
|
||||
|
||||
/// The `path.insertAnchor` steps that add an anchor point where circle `c` touches the first segment
|
||||
/// and the segment of `second` (the segments a circle may touch, with their indices, on the subpath
|
||||
/// of `pick`) nearest its second touch. On one subpath the later segment comes first, so that the
|
||||
/// anchor added before it does not move it along.
|
||||
fn anchor_steps(first: &Pick, pick: &Pick, second: &[(usize, CubicBez)], c: &SegmentCircle, tol: f64) -> Vec<Value> {
|
||||
let mut at: Vec<(NodeId, usize, usize, f64)> = vec![];
|
||||
if let Some(t) = split_at(&first.curve, c.first, tol) {
|
||||
at.push((first.id, first.subpath, first.segment, t));
|
||||
}
|
||||
let nearest = second.iter().min_by(|(_, a), (_, b)| a.nearest(c.second, 1e-12).distance_sq.total_cmp(&b.nearest(c.second, 1e-12).distance_sq));
|
||||
if let Some((k, curve)) = nearest
|
||||
&& let Some(t) = split_at(curve, c.second, tol)
|
||||
{
|
||||
at.push((pick.id, pick.subpath, *k, t));
|
||||
}
|
||||
at.sort_by_key(|a| std::cmp::Reverse((a.0, a.1, a.2)));
|
||||
at.into_iter().map(|(id, subpath, segment, t)| json!({ "command": "path.insertAnchor", "params": { "id": id.0, "subpath": subpath, "segment": segment, "t": t } })).collect()
|
||||
}
|
||||
|
||||
/// Of `circles`, the one touching the second segments nearest `at`, leaving out those [`draw`] cannot
|
||||
@@ -242,6 +294,14 @@ fn round_step(least: f64) -> f64 {
|
||||
/// distance from the origin, or too large, in floating point), or when the circle would reach past
|
||||
/// the canvas ([`crate::circle::circle_of`]), which the command refuses.
|
||||
fn draw(c: &SegmentCircle, tol: f64) -> Option<Action> {
|
||||
circle_params(c, tol).map(|p| Action::Exec(CIRCLE.into(), p))
|
||||
}
|
||||
|
||||
/// The command [`draw`] runs.
|
||||
const CIRCLE: &str = "shape.circleThroughPoints";
|
||||
|
||||
/// The params of the [`CIRCLE`] command that [`draw`] runs.
|
||||
fn circle_params(c: &SegmentCircle, tol: f64) -> Option<Value> {
|
||||
let (at, r) = (c.circle.center, c.circle.radius);
|
||||
let points: Vec<Point> = [90.0f64, 210.0, 330.0]
|
||||
.iter()
|
||||
@@ -255,7 +315,7 @@ fn draw(c: &SegmentCircle, tol: f64) -> Option<Action> {
|
||||
return None;
|
||||
}
|
||||
let points: Vec<[f64; 2]> = points.iter().map(|p| [p.x, p.y]).collect();
|
||||
Some(Action::Exec("shape.circleThroughPoints".into(), json!({ "points": points })))
|
||||
Some(json!({ "points": points }))
|
||||
}
|
||||
|
||||
fn segment_path(c: &CubicBez) -> BezPath {
|
||||
@@ -391,6 +451,8 @@ impl Tool for TangentCircleTool {
|
||||
|
||||
fn pointer(&mut self, cx: &ToolContext, ev: &PointerEvent) -> Vec<Action> {
|
||||
self.pointer = ev.pos;
|
||||
self.mods = ev.mods;
|
||||
self.over = true;
|
||||
match ev.kind {
|
||||
PointerKind::Move => {
|
||||
self.hover = pick_at(cx, ev.pos, self.reach(cx));
|
||||
@@ -424,15 +486,34 @@ impl Tool for TangentCircleTool {
|
||||
// The release's own position and keys set the radius of a drag.
|
||||
self.drag_to(cx, ev);
|
||||
self.picking = false;
|
||||
if self.press.take().is_none() {
|
||||
return vec![];
|
||||
}
|
||||
let Some(press) = self.press.take() else { return vec![] };
|
||||
// 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 Some(action) = self.found.take().and_then(|c| draw(&c, cx.tol(DRAW_PX))) else { return vec![] };
|
||||
let Some(c) = self.found.take() else { return vec![] };
|
||||
let Some(params) = circle_params(&c, cx.tol(DRAW_PX)) else { return vec![] };
|
||||
self.looked = false;
|
||||
vec![action, Action::Notify(DRAWN.into())]
|
||||
// Alt at the release turns `addPoints` the other way.
|
||||
let steps = match &self.first {
|
||||
Some(first) if self.add_points != ev.mods.alt => {
|
||||
let second = if segment_now(cx, &press.pick).is_some() { second_segments(cx, first, &press.pick) } else { vec![] };
|
||||
anchor_steps(first, &press.pick, &second, &c, cx.tol(DRAW_PX))
|
||||
}
|
||||
_ => vec![],
|
||||
};
|
||||
if steps.is_empty() {
|
||||
return vec![Action::Exec(CIRCLE.into(), params), Action::Notify(DRAWN.into())];
|
||||
}
|
||||
let mut commands = steps;
|
||||
// A path that was not selected becomes the selection when it gets an anchor; the
|
||||
// selection is put back before the circle, which Draw Behind places behind it.
|
||||
if commands.iter().any(|s| s["params"]["id"].as_u64().is_some_and(|id| !cx.selection.contains(NodeId(id)))) {
|
||||
let ids: Vec<u64> = cx.selection.objects.iter().map(|id| id.0).collect();
|
||||
commands.push(json!({ "command": "select.set", "params": { "ids": ids } }));
|
||||
}
|
||||
commands.push(json!({ "command": CIRCLE, "params": params }));
|
||||
// One undo step for the anchors and the circle, and none of them when a step fails.
|
||||
vec![Action::Exec("command.batch".into(), json!({ "label": "Ellipse", "commands": commands })), Action::Notify(DRAWN.into())]
|
||||
}
|
||||
// The canvas sends a double-click after the second click's `Up`, which drew the circle.
|
||||
PointerKind::DoubleClick | PointerKind::TripleClick => vec![],
|
||||
@@ -483,6 +564,7 @@ impl Tool for TangentCircleTool {
|
||||
|
||||
fn hover_ended(&mut self, _cx: &ToolContext) {
|
||||
self.hover = None;
|
||||
self.over = false;
|
||||
if self.press.is_none() {
|
||||
self.found = None;
|
||||
self.looked = false;
|
||||
@@ -525,6 +607,11 @@ impl Tool for TangentCircleTool {
|
||||
// A label, which the canvas shows in the interface language.
|
||||
out.push(Overlay::Label { p: self.pointer, text: NO_CIRCLE.into(), color });
|
||||
}
|
||||
// `addPoints` in effect, with Alt as it is now.
|
||||
if (self.over || self.press.is_some()) && self.add_points != self.mods.alt {
|
||||
let off = cx.tol(DOT_PX);
|
||||
out.push(Overlay::CurvePoint { p: self.pointer + kurbo::Vec2::new(off, off), color: BLUE, filled: true, size: DOT_SIZE });
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
@@ -535,6 +622,7 @@ impl Tool for TangentCircleTool {
|
||||
fn options(&self) -> Value {
|
||||
json!({
|
||||
"radius": self.radius,
|
||||
"addPoints": self.add_points,
|
||||
"center": self.center,
|
||||
"radii": self.radii,
|
||||
"color": COLORS.get(self.color).map_or("red", |(name, _)| *name),
|
||||
@@ -550,6 +638,7 @@ impl Tool for TangentCircleTool {
|
||||
}
|
||||
match key {
|
||||
"radius" => self.radius = v.as_f64().unwrap_or(self.radius),
|
||||
"addPoints" => self.add_points = v.as_bool().unwrap_or(self.add_points),
|
||||
"center" => self.center = v.as_bool().unwrap_or(self.center),
|
||||
"radii" => self.radii = v.as_bool().unwrap_or(self.radii),
|
||||
"color" => self.color = v.as_str().and_then(|s| COLORS.iter().position(|(name, _)| *name == s)).unwrap_or(self.color),
|
||||
@@ -1059,6 +1148,144 @@ mod tests {
|
||||
assert!(matches!(segments[..], [n] if n < 100), "{segments:?}");
|
||||
}
|
||||
|
||||
/// The steps of the `command.batch` an action list runs: (command, params) each.
|
||||
fn batch_steps(actions: &[Action]) -> Vec<(String, Value)> {
|
||||
let [Action::Exec(cmd, p), Action::Notify(what)] = actions else { panic!("{actions:?}") };
|
||||
assert_eq!((cmd.as_str(), what.as_str()), ("command.batch", DRAWN));
|
||||
p["commands"].as_array().unwrap().iter().map(|s| (s["command"].as_str().unwrap().to_string(), s["params"].clone())).collect()
|
||||
}
|
||||
|
||||
/// An inserted anchor's place: (path, subpath, segment) and the point at its `t` on that segment.
|
||||
fn inserted(cx: &ToolContext, params: &Value) -> (u64, u64, u64, Point) {
|
||||
let (id, sub, seg) = (params["id"].as_u64().unwrap(), params["subpath"].as_u64().unwrap(), params["segment"].as_u64().unwrap());
|
||||
let sp = &cx.doc.node(NodeId(id)).unwrap().path_data().unwrap().subpaths[sub as usize];
|
||||
(id, sub, seg, sp.segment(seg as usize).eval(params["t"].as_f64().unwrap()))
|
||||
}
|
||||
|
||||
fn alt(mut e: PointerEvent) -> PointerEvent {
|
||||
e.mods.alt = true;
|
||||
e
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn add_points_adds_an_anchor_where_the_circle_touches_each_segment() {
|
||||
let d = doc();
|
||||
let (sel, p) = (Selection::default(), paint());
|
||||
let cx = cx(&d, &sel, &p);
|
||||
let line_at = |y: f64| pick_at(&cx, Point::new(150.0, y), cx.pick_tol()).map(|p| p.id.0).unwrap();
|
||||
let (top, below) = (line_at(100.0), line_at(140.0));
|
||||
let mut t = TangentCircleTool::default();
|
||||
t.set_option("addPoints", &json!(true));
|
||||
assert_eq!(t.options()["addPoints"], json!(true));
|
||||
// The circle through (150, 100) touching the line below at (150, 140): an anchor a quarter
|
||||
// along each line, then the circle, in one batch.
|
||||
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 steps = batch_steps(&up(&mut t, &cx, &ev(PointerKind::Up, 200.0, 139.0)));
|
||||
assert_eq!(steps.len(), 4, "{steps:?}");
|
||||
assert!(steps[..2].iter().all(|(c, _)| c == "path.insertAnchor"), "{steps:?}");
|
||||
let mut anchors: Vec<(u64, u64, u64, Point)> = steps[..2].iter().map(|(_, p)| inserted(&cx, p)).collect();
|
||||
anchors.sort_by_key(|a| a.0);
|
||||
let mut want = [(top, 0, 0, Point::new(150.0, 100.0)), (below, 0, 0, Point::new(150.0, 140.0))];
|
||||
want.sort_by_key(|a| a.0);
|
||||
assert!(top != below && anchors.iter().zip(want).all(|(a, b)| (a.0, a.1, a.2) == (b.0, b.1, b.2) && a.3.distance(b.3) < 1e-6), "{anchors:?}");
|
||||
// The lines were not selected, so the selection (none) is put back before the circle.
|
||||
assert_eq!(steps[2], ("select.set".to_string(), json!({ "ids": [] })), "{steps:?}");
|
||||
let (cmd, params) = &steps[3];
|
||||
let circle = drawn(&[Action::Exec(cmd.clone(), params.clone()), Action::Notify(DRAWN.into())]);
|
||||
assert!(close(circle, (130.0, 100.0, 40.0, 40.0)), "{steps:?}");
|
||||
assert!(t.first.is_none(), "ready for the next circle");
|
||||
// With both lines selected, the anchors leave the selection as it is: no step puts it back.
|
||||
let mut both = Selection::default();
|
||||
both.add(NodeId(top));
|
||||
both.add(NodeId(below));
|
||||
let selected = self::cx(&d, &both, &p);
|
||||
t.pointer(&selected, &ev(PointerKind::Down, 150.0, 101.0));
|
||||
t.pointer(&selected, &ev(PointerKind::Up, 150.0, 101.0));
|
||||
t.pointer(&selected, &ev(PointerKind::Down, 200.0, 139.0));
|
||||
let steps = batch_steps(&up(&mut t, &selected, &ev(PointerKind::Up, 200.0, 139.0)));
|
||||
assert!(steps.len() == 3 && steps[2].0 == CIRCLE, "{steps:?}");
|
||||
// Alt at the release turns it off for that circle, and with the option off turns it on.
|
||||
for (on, alt_up, adds) in [(true, true, false), (false, true, true), (false, false, false)] {
|
||||
t.set_option("addPoints", &json!(on));
|
||||
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));
|
||||
t.pointer(&cx, &alt(ev(PointerKind::Drag, 200.0, 139.0)));
|
||||
let release = if alt_up { alt(ev(PointerKind::Up, 200.0, 139.0)) } else { ev(PointerKind::Up, 200.0, 139.0) };
|
||||
let released = up(&mut t, &cx, &release);
|
||||
if adds {
|
||||
assert_eq!(batch_steps(&released).len(), 4, "on {on}, Alt {alt_up}: {released:?}");
|
||||
} else {
|
||||
assert!(close(drawn(&released), (130.0, 100.0, 40.0, 40.0)), "on {on}, Alt {alt_up}: {released:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn add_points_on_one_path_adds_the_later_anchor_first_and_none_at_an_anchor() {
|
||||
let d = doc();
|
||||
let (sel, p) = (Selection::default(), paint());
|
||||
let cx = cx(&d, &sel, &p);
|
||||
let mut t = TangentCircleTool::default();
|
||||
t.set_option("addPoints", &json!(true));
|
||||
t.set_option("radius", &json!(10));
|
||||
// The L's corner circle of radius 10 touches (290, 300) on its first segment and (300, 310)
|
||||
// on its second: the second segment's anchor comes first, so the first one's index holds.
|
||||
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 steps = batch_steps(&up(&mut t, &cx, &shifted(PointerKind::Up, 300.0, 350.0)));
|
||||
assert_eq!(steps.len(), 4, "{steps:?}");
|
||||
let l = pick_at(&cx, Point::new(300.0, 350.0), cx.pick_tol()).map(|p| p.id.0);
|
||||
let anchors: Vec<(u64, u64, u64, Point)> = steps[..2].iter().map(|(_, p)| inserted(&cx, p)).collect();
|
||||
let want = [(1, Point::new(300.0, 310.0)), (0, Point::new(290.0, 300.0))];
|
||||
assert!(anchors.iter().zip(want).all(|(a, (seg, at))| Some(a.0) == l && a.1 == 0 && a.2 == seg && a.3.distance(at) < 1e-6), "{anchors:?}");
|
||||
assert_eq!((steps[2].0.as_str(), steps[3].0.as_str()), ("select.set", CIRCLE));
|
||||
// A circle touching both lines at their right ends: no anchor is added on top of an anchor,
|
||||
// so only the circle is drawn, as without the option.
|
||||
t.set_option("radius", &json!(36));
|
||||
t.pointer(&cx, &ev(PointerKind::Down, 300.0, 101.0));
|
||||
t.pointer(&cx, &ev(PointerKind::Up, 300.0, 101.0));
|
||||
t.pointer(&cx, &ev(PointerKind::Down, 299.0, 139.0));
|
||||
let released = up(&mut t, &cx, &ev(PointerKind::Up, 299.0, 139.0));
|
||||
assert!(close(drawn(&released), (280.0, 100.0, 40.0, 40.0)), "{released:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn add_points_shows_a_dot_and_is_an_option_that_refuses_other_values() {
|
||||
let d = doc();
|
||||
let (sel, p) = (Selection::default(), paint());
|
||||
let cx = cx(&d, &sel, &p);
|
||||
let mut t = TangentCircleTool::default();
|
||||
assert_eq!(t.options()["addPoints"], json!(false), "off to start");
|
||||
let dot =
|
||||
|t: &TangentCircleTool| t.overlays(&cx).iter().any(|o| matches!(o, Overlay::CurvePoint { filled: true, color, .. } if *color == BLUE));
|
||||
t.pointer(&cx, &ev(PointerKind::Move, 50.0, 50.0));
|
||||
assert!(!dot(&t));
|
||||
// Alt turns it on while held, and back off with the option on.
|
||||
t.pointer(&cx, &alt(ev(PointerKind::Move, 50.0, 50.0)));
|
||||
assert!(dot(&t));
|
||||
t.set_option("addPoints", &json!(true));
|
||||
assert!(!dot(&t));
|
||||
t.pointer(&cx, &ev(PointerKind::Move, 50.0, 50.0));
|
||||
assert!(dot(&t));
|
||||
let Some(Overlay::CurvePoint { p, .. }) = t.overlays(&cx).into_iter().find(|o| matches!(o, Overlay::CurvePoint { .. })) else {
|
||||
panic!("no dot")
|
||||
};
|
||||
assert!(p.x > 50.0 && p.y > 50.0, "beside the pointer: {p:?}");
|
||||
// The pointer off the canvas: no dot left behind.
|
||||
t.hover_ended(&cx);
|
||||
assert!(!dot(&t));
|
||||
for bad in [json!(1), json!("true"), Value::Null] {
|
||||
assert_eq!(t.check_option("addPoints", &bad), Err("`addPoints` must be true or false".into()), "{bad}");
|
||||
t.set_option("addPoints", &bad);
|
||||
assert_eq!(t.options()["addPoints"], json!(true), "{bad}");
|
||||
}
|
||||
assert_eq!(t.check_option("addPoints", &json!(false)), Ok(()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_circle_that_would_reach_past_the_canvas_is_not_offered() {
|
||||
// Two lines 40 pt apart ending at the canvas edge, x = 4,000,000: a click at x the first gives
|
||||
|
||||
@@ -108,7 +108,7 @@ 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", "center", "radii", "color", "snapTolerance", "snapWithoutGuides"]),
|
||||
(&[crate::addons::tangent_circle::ID], None, &["radius", "addPoints", "center", "radii", "color", "snapTolerance", "snapWithoutGuides"]),
|
||||
(&[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"]),
|
||||
|
||||
@@ -307,6 +307,7 @@ fn options_params(tool: &str, lengths: LengthUnits) -> Vec<Param> {
|
||||
let snap = ParamKind::number(Some(snap_lo), Some(snap_hi), tangent_circle_tool::SNAP_PX, 1.0, 2);
|
||||
return vec![
|
||||
Param::new("radius", tl!("Radius"), kind).length(lengths),
|
||||
Param::new("addPoints", tl!(tangent_circle_tool::ADD_POINTS), ParamKind::bool(false)),
|
||||
Param::new("center", tl!("Circle Center"), ParamKind::bool(true)),
|
||||
Param::new("radii", tl!("Circle Radii Lines"), ParamKind::bool(true)),
|
||||
Param::new("color", tl!("Color"), ParamKind::choice(colors, Some("red".into()))),
|
||||
|
||||
@@ -84,11 +84,18 @@ 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.
|
||||
// The Tangent Circle tool's radius for Shift, and Add Points to Existing Paths (off to start).
|
||||
app.run("tool.options", json!({"tool": "tangentCircle"})).unwrap();
|
||||
assert_eq!(held(&app, |d| d.expect("the held dialog").fields().number("radius")), Some(36.0));
|
||||
ok(&mut app, &[("radius", FieldValue::Number(12.5))]);
|
||||
let shown = held(&app, |d| {
|
||||
let f = d.expect("the held dialog").fields();
|
||||
(f.number("radius"), f.bool("addPoints"))
|
||||
});
|
||||
assert_eq!(shown, (Some(36.0), 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));
|
||||
assert!(app.run("tool.options", json!({"tool": "measureInspect"})).is_err());
|
||||
assert_eq!(KIND, "pathToolOptions");
|
||||
}
|
||||
@@ -150,6 +157,7 @@ fn the_tangent_circle_options_have_their_rows_and_a_fractional_tolerance() {
|
||||
rows,
|
||||
[
|
||||
("radius", "Radius"),
|
||||
("addPoints", "Add Points to Existing Paths"),
|
||||
("center", "Circle Center"),
|
||||
("radii", "Circle Radii Lines"),
|
||||
("color", "Color"),
|
||||
|
||||
+9
-1
@@ -15374,8 +15374,16 @@ Tools:
|
||||
change to the first segment that makes no undo step (a live preview, or one that was canceled) forgets the first
|
||||
segment. The circle is looked for again whenever either segment no longer has the shape it was found on, so a
|
||||
canceled preview does not leave a circle worked out on the previewed paths.
|
||||
With `addPoints` on, the circle also adds an anchor point to the first segment and to the second segment (or the
|
||||
one beside it) where it touches them, with `path.insertAnchor` at that point, so the segments are split without
|
||||
changing their shape; the anchors and the circle are one `command.batch` undo step, and one Undo removes all of them.
|
||||
When a touched path was not selected, a `select.set` step puts the selection back before the circle is drawn, so
|
||||
Draw Behind places the circle behind the objects that were selected.
|
||||
A touch within 0.05 screen pixels of an existing anchor adds no anchor there; when neither touch adds one, only the
|
||||
circle is drawn. Alt (Option on macOS) held at the release turns `addPoints` the other way for that circle, and a
|
||||
dot right of and below the pointer shows while it is in effect, following Alt as it is pressed and let go.
|
||||
Options (`tool.setOption`, or a double-click on the tool; kept with the preferences): `radius` (pt, 0.01 to
|
||||
1000000, 36); `center` and `radii` (true or false, both true) show the center cross and the radii; `color` (`red`,
|
||||
1000000, 36); `addPoints` (Add Points to Existing Paths, true or false, false); `center` and `radii` (true or false, both true) show the center cross and the radii; `color` (`red`,
|
||||
`blue`, `magenta`, `green`, `black` or `gray`; `red`) is the color of the circle, the cross, the radii and the note;
|
||||
`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
|
||||
|
||||
@@ -3097,6 +3097,8 @@ A VectorCraft addition, not a feature of the reference app, so no area score mov
|
||||
|
||||
A VectorCraft addition, so no area score moves. The Tangent Circle Tool (`tangentCircle`; Object › Plug-ins › Path Precision Tools and the All Tools drawer) draws a circle on two clicked path segments: tangent to the first at the point clicked (its center on the normal there) and touching the second segment or one beside it on its subpath, the touch nearest the pointer winning. Shift gives the circle the tool's radius, and a drag from the second segment sets the radius to the drag's length (Shift: steps of 1, 2 or 5 times a power of 10 pt, at least 4 screen pixels; Cmd/Ctrl: a tenth of the movement); with a radius the circle may touch the first segment anywhere along it. Before the click the circle shows with its center, radii and radius, or a note says there is none. The circles are found by sampling the distance to the second segments along the first segment's normal (or along the first segment, for a radius) and taking the places where it equals the radius (samples, bisection where it crosses, and a search where it only touches). Left out are circles whose nearest point of the second segments is not on the circle (within a millionth of the radius: where the first segment turns back on itself the distance jumps past the radius without a touch), circles that cross the first segment, circles that touch both segments at one point, circles without a finite radius above 0, circles too small or too large for three of their points to give them back in floating point, and circles that would reach past the canvas; a circle found twice (the same center, touching the first segment at the same point) is kept once. The circle is a new ellipse with the current paint, one undo step; the first segment stays picked until it is drawn, also when drawing fails or the press is canceled, and the circles are looked for again when a live preview, or one that was canceled, changes either segment without an undo step (a changed first segment is forgotten). Tests: `tangent_circle::tests` in `vectorcraft-pathops` (parallel and crossing lines, a curved second segment, a corner's fillet, lines twice the radius apart, a touch between the places tried, the ends of a line with its handles on its anchors, a circle that crosses the first segment, a first segment that turns back, no circle), `addons::tangent_circle::tests` in `vectorcraft-tools` (two clicks, Shift and the radius option, a drag with Shift and Cmd/Ctrl, no circle and Escape, a canceled press, a canceled preview, a circle its three points cannot draw, a circle past the canvas), the session test for a failed draw in `vectorcraft-engine` and the Path Precision Tools menu, options, drawer and catalog tests in `vectorcraft-ui-egui`. Commands: `docs/mcp.md` › Path Precision Tools add-on.
|
||||
|
||||
Add Points to Existing Paths (2026-11-20): the tool's `addPoints` option (in its options, off to start) also adds an anchor point where the circle touches each of the two segments, splitting them without changing their shape, in the circle's undo step; a touch at an existing anchor adds none. Alt held at the release turns the option the other way for that circle, and a dot beside the pointer shows while it is in effect. Tests: `addons::tangent_circle::tests::add_points_*` in `vectorcraft-tools`, `the_tangent_circle_tool_adds_points_where_the_circle_touches_in_one_step` in `vectorcraft-engine`, and the options dialog test in `vectorcraft-ui-egui`.
|
||||
|
||||
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`.
|
||||
|
||||
## Path Precision Tools add-on: Trim at Crossings (2026-11-13)
|
||||
|
||||
+1
-1
@@ -561,7 +561,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 › Divide into Dashes… (Dash and Gap in any unit, Fit to Corners and Ends, Remove Gaps; Preview) cuts the selected paths, or only their direct-selected segments, into open pieces along the curve, keeping their appearance, one undo step | done | #4950; `addon.pathtools.divideDashes`, `crates/pathops/src/addons/pathtools/dashes.rs`, `crates/ui-egui/src/addons/pathtools/dashes.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 › Set Corners… (also a button in the Anchor Inspector's Corners section: Radius in any unit, Corner kind, Anchors: All, Odd-Numbered or Even-Numbered, counted from each path's first anchor; Angle: from … to …°, only the corners whose sides meet at an angle in that range; Preview) cuts corners on the chosen anchors of every selected path, one undo step | done | #5546, #5545; `addon.pathtools.cornerSet` (`every`, `minAngle`, `maxAngle`), `crates/ui-egui/src/addons/pathtools/set_corners.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 › 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); 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 › 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 › 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 |
|
||||
|
||||
Reference in new issue
Block a user