From 81c7578cf01626292cd481f9d1ba7659c1c71732 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 08:02:16 -0800 Subject: [PATCH] Pen: Quick Pen shows a protractor around an arc's center and snaps to its ticks MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit While an arc is drawn, by a drag or as the piece the next click adds, the Quick Pen tool shows a protractor around the arc's center: a tick every 15° from where the arc starts, a longer one every 90°, and one where it ends. The piece the next click adds shows its protractor only while Enable Rubber Band for the Pen tool shows that piece. With Smart Guides on, the end of a continuous arc snaps onto the nearest tick of its protractor, on the same circle, when the tick lies within the snapping tolerance of the pointer, no other Smart Guide snaps the point, and neither Snap to Grid nor Snap to Pixel snaps drawn points. A sharp-corner arc sweeps its arc size, so its end does not snap. Shift does not constrain Quick Pen points, so it does not change the snapping. The protractor, its 15° step and the snapping are VectorCraft's own behavior. The Smart Guides targets now also report whether a point landed on one of them (`Targets::snap_hit`), so a target whose label or line is hidden still takes precedence over a tick. Adds tests for the arc's circle, the tick snapping by drag and by click and its precedence, and the protractor during a drag and while hovering. Also adds tests of existing Quick Pen behavior: a point snapping to a Smart Guide, and the distance label shown while hovering. --- crates/engine/src/tests/quickpen.rs | 205 +++++++++++++++++++++++++++- crates/tools/src/guides/snap.rs | 8 ++ crates/tools/src/guides/targets.rs | 26 ++-- crates/tools/src/quickpen.rs | 168 +++++++++++++++++++++-- crates/tools/src/quickpen/tests.rs | 90 +++++++++++- docs/mcp.md | 9 ++ docs/target-app-parity.md | 1 + 7 files changed, 483 insertions(+), 24 deletions(-) diff --git a/crates/engine/src/tests/quickpen.rs b/crates/engine/src/tests/quickpen.rs index f14be809b4..c6174aa19f 100644 --- a/crates/engine/src/tests/quickpen.rs +++ b/crates/engine/src/tests/quickpen.rs @@ -3,7 +3,7 @@ use serde_json::{Value, json}; use vectorcraft_doc::{NodeId, NodeKind}; use vectorcraft_geom::{PathData, Point, SubPath}; -use vectorcraft_tools::{Mods, PointerEvent, PointerKind, ToolKey}; +use vectorcraft_tools::{Mods, Overlay, PointerEvent, PointerKind, ToolKey}; use crate::tooling::ViewInfo; use crate::*; @@ -43,13 +43,20 @@ fn pt(x: f64, y: f64) -> Point { } fn press(s: &mut Session, pts: &[(f64, f64)]) { - let v = view(); - s.pointer(&PointerEvent::new(PointerKind::Down, pts[0].0, pts[0].1), v).unwrap(); + press_in(s, pts, view()); +} + +fn press_in(s: &mut Session, pts: &[(f64, f64)], v: ViewInfo) { + press_with(s, pts, v, Mods::default()); +} + +fn press_with(s: &mut Session, pts: &[(f64, f64)], v: ViewInfo, m: Mods) { + s.pointer(&PointerEvent::new(PointerKind::Down, pts[0].0, pts[0].1).with_mods(m), v).unwrap(); for &(x, y) in &pts[1..] { - s.pointer(&PointerEvent::new(PointerKind::Drag, x, y), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Drag, x, y).with_mods(m), v).unwrap(); } let l = pts[pts.len() - 1]; - s.pointer(&PointerEvent::new(PointerKind::Up, l.0, l.1), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Up, l.0, l.1).with_mods(m), v).unwrap(); } fn click(s: &mut Session, x: f64, y: f64) { @@ -505,6 +512,194 @@ fn a_click_on_an_open_end_continues_the_path() { assert_eq!(ends, [pt(200.0, 100.0), pt(100.0, 100.0), pt(100.0, 200.0)]); } +/// With Smart Guides on, a click near another path's anchor puts the point on that anchor; with +/// them off, the point stays where the click was. +#[test] +fn a_point_snaps_to_a_smart_guide() { + for (guides, want) in [(true, pt(300.0, 300.0)), (false, pt(302.0, 301.0))] { + let mut s = session(); + s.execute("shape.line", &json!({"x1": 300, "y1": 300, "x2": 500, "y2": 450})).unwrap(); + s.execute("select.set", &json!({"ids": []})).unwrap(); + quick_pen(&mut s); + let v = ViewInfo { smart_guides: guides, ..Default::default() }; + press_in(&mut s, &[(100.0, 100.0)], v); + press_in(&mut s, &[(302.0, 301.0)], v); + let drawn = paths(&s).into_iter().find(|(_, p)| p.subpaths[0].anchors.first().is_some_and(|a| a.p == pt(100.0, 100.0))).unwrap(); + assert!(drawn.1.subpaths[0].anchors.last().unwrap().p.distance(want) < 1e-9, "{guides}"); + } +} + +/// A point 100 pt from (200, 100) and 30.5° below the +x direction a path from (100, 100) ends in: +/// a continuous arc to it sweeps 61°. +fn arc_end_61() -> Point { + let half = 30.5f64.to_radians(); + pt(200.0 + 100.0 * half.cos(), 100.0 + 100.0 * half.sin()) +} + +/// The protractor's 60° tick for the arc to [`arc_end_61`]: on the same circle, a 60° sweep. +fn tick_60() -> Point { + let r = 50.0 / 30.5f64.to_radians().sin(); + pt(200.0 + r * 30f64.to_radians().cos(), 100.0 + r * 30f64.to_radians().sin()) +} + +/// A path from (100, 100) to (200, 100) drawn with Quick Pen, the action then a continuous arc. +fn continuous_arc_after_a_line(s: &mut Session, v: ViewInfo) { + quick_pen(s); + press_in(s, &[(100.0, 100.0)], v); + press_in(s, &[(200.0, 100.0)], v); + key(s, ToolKey::AltTap); +} + +/// The last point of the path the tool drew (any other path is a two-point line). +fn drawn_end(s: &Session) -> Point { + let drawn = paths(s).into_iter().find(|(_, p)| p.subpaths[0].anchors.len() >= 3).unwrap(); + drawn.1.subpaths[0].anchors.last().unwrap().p +} + +/// A continuous arc dragged to end 61° round goes onto the protractor's 60° tick with Smart Guides +/// on, also with Shift held, which does not constrain Quick Pen points; with them off it ends at +/// the pointer. A Smart Guide in reach (another path's anchor) wins over the tick, also with its +/// label hidden, and so do Snap to Grid and Snap to Pixel. +#[test] +fn a_continuous_arc_end_snaps_to_the_protractor() { + let at = arc_end_61(); + let anchor = pt(at.x + 0.2, at.y + 0.15); + let fresh = session(); + let g = &fresh.doc().unwrap().doc.grid; + let step = g.spacing / g.subdivisions.max(1) as f64; + let on_grid = pt((at.x / step).round() * step, (at.y / step).round() * step); + let on_pixel = pt(at.x.round(), at.y.round()); + let shift = Mods { shift: true, ..Default::default() }; + // (Smart Guides, the other path, Snap to Grid, Snap to Pixel, Anchor/Path Labels, mods, where + // the end goes, the pointer) + let cases = [ + (true, false, false, false, true, Mods::default(), tick_60(), at), + (true, false, false, false, true, shift, tick_60(), at), + (false, false, false, false, true, Mods::default(), at, at), + (true, true, false, false, true, Mods::default(), anchor, at), + (true, false, true, false, true, Mods::default(), on_grid, on_grid), + (true, false, false, true, true, Mods::default(), on_pixel, on_pixel), + // Exactly on the anchor, which shows no guide with the labels off. + (true, true, false, false, false, Mods::default(), anchor, anchor), + ]; + for (guides, other, grid, pixel, labels, m, want, pointer) in cases { + let mut s = session(); + s.prefs.anchor_path_labels = labels; + if other { + s.execute("shape.line", &json!({"x1": anchor.x, "y1": anchor.y, "x2": 600, "y2": anchor.y})).unwrap(); + s.execute("select.set", &json!({"ids": []})).unwrap(); + } + let v = ViewInfo { smart_guides: guides, snap_to_grid: grid, snap_to_pixel: pixel, ..Default::default() }; + continuous_arc_after_a_line(&mut s, v); + press_with(&mut s, &[(280.0, 140.0), (pointer.x, pointer.y)], v, m); + let end = drawn_end(&s); + assert!(end.distance(want) < 1e-6, "{guides} {other} {grid} {pixel} {labels} {m:?}: {end:?}"); + } +} + +/// With Smart Guides on, a click without a drag puts a continuous arc's end on the protractor's +/// tick; after Alt switches to a sharp-corner arc, a click at the same place puts the end at the +/// pointer. +#[test] +fn a_click_puts_a_continuous_arc_end_on_a_tick() { + let at = arc_end_61(); + let v = ViewInfo::default(); + for (taps, want) in [(0, tick_60()), (1, at)] { + let mut s = session(); + continuous_arc_after_a_line(&mut s, v); + for _ in 0..taps { + key(&mut s, ToolKey::AltTap); + } + press_in(&mut s, &[(at.x, at.y)], v); + let end = drawn_end(&s); + assert!(end.distance(want) < 1e-6, "{taps}: {end:?}"); + } +} + +/// Hovering near a tick as a continuous arc puts the distance label beside the tick; after Alt +/// switches the action, the same hover puts it beside the pointer. +#[test] +fn a_hover_snaps_to_a_tick_only_for_a_continuous_arc() { + let at = arc_end_61(); + let tick = tick_60(); + let v = ViewInfo::default(); + let mut s = session(); + continuous_arc_after_a_line(&mut s, v); + s.pointer(&PointerEvent::new(PointerKind::Move, at.x, at.y), v).unwrap(); + let label = |s: &mut Session| { + s.overlays(v).iter().find_map(|o| match o { + Overlay::Measure { p, .. } => Some(*p), + _ => None, + }) + }; + let off = label(&mut s).unwrap() - tick; + assert!(off.x > 0.0 && (off.x - off.y).abs() < 1e-9, "the label sits diagonally off the tick: {off:?}"); + for _ in 0..2 { + key(&mut s, ToolKey::AltTap); + assert!((label(&mut s).unwrap() - off).distance(at) < 1e-9, "{:?}", s.tool_options()["action"]); + } +} + +/// While a press drags an arc, the tool shows its protractor; while it drags a line, it shows none. +#[test] +fn an_arc_drag_shows_the_protractor() { + let mut s = session(); + quick_pen(&mut s); + let protractors = |s: &mut Session| s.overlays(view()).iter().filter(|o| matches!(o, Overlay::Path { .. })).count(); + for (action, shown) in [("line", 0), ("continuousArc", 1), ("sharpArc", 1)] { + key(&mut s, ToolKey::Escape); + s.set_tool_option_cmd(&json!({"tool": "quickPen", "key": "action", "value": "line"})).unwrap(); + click(&mut s, 100.0, 100.0); + click(&mut s, 200.0, 100.0); + s.set_tool_option_cmd(&json!({"tool": "quickPen", "key": "action", "value": action})).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Down, 250.0, 150.0), view()).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Drag, 280.0, 180.0), view()).unwrap(); + assert_eq!(protractors(&mut s), shown, "{action}"); + s.pointer(&PointerEvent::new(PointerKind::Up, 280.0, 180.0), view()).unwrap(); + } +} + +/// While hovering, the piece the next click adds shows its protractor beside the rubber band, and +/// neither shows with the Pen tool's rubber band preference off; a line has no protractor. (Smart +/// Guides are off, so no guide paths show.) +#[test] +fn a_hovered_arc_shows_the_protractor_with_the_rubber_band() { + for (rubber_band, action, paths) in [(true, "continuousArc", 2), (true, "line", 1), (false, "continuousArc", 0)] { + let mut s = session(); + s.prefs.pen_rubber_band = rubber_band; + quick_pen(&mut s); + click(&mut s, 100.0, 100.0); + click(&mut s, 200.0, 100.0); + s.set_tool_option_cmd(&json!({"tool": "quickPen", "key": "action", "value": action})).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Move, 280.0, 180.0), view()).unwrap(); + let shown = s.overlays(view()).iter().filter(|o| matches!(o, Overlay::Path { .. })).count(); + assert_eq!(shown, paths, "{rubber_band} {action}"); + } +} + +/// With Measurement Labels on, hovering after the path's last point shows the distance label +/// beside the pointer; with them off, no label shows. +#[test] +fn hovering_shows_the_distance_label() { + for labels in [true, false] { + let mut s = session(); + s.prefs.measurement_labels = labels; + quick_pen(&mut s); + click(&mut s, 100.0, 100.0); + click(&mut s, 200.0, 100.0); + s.pointer(&PointerEvent::new(PointerKind::Move, 300.0, 200.0), view()).unwrap(); + let o = s.overlays(view()); + let label = o.iter().find_map(|o| match o { + Overlay::Measure { p, .. } => Some(*p), + _ => None, + }); + assert_eq!(label.is_some(), labels); + if let Some(p) = label { + assert!(p.x > 300.0 && p.y > 200.0, "beside the pointer: {p:?}"); + } + } +} + /// `path.quickPen` makes a new path with the current paint, or a black stroke without any. #[test] fn path_quick_pen_makes_a_stroked_path() { diff --git a/crates/tools/src/guides/snap.rs b/crates/tools/src/guides/snap.rs index de09341bc7..948f5668b9 100644 --- a/crates/tools/src/guides/snap.rs +++ b/crates/tools/src/guides/snap.rs @@ -493,6 +493,14 @@ impl DrawSnap { t.nearest_point(p, tol).is_some_and(|(a, _)| at(a)) || t.crossing(p, tol).is_some_and(at) } + /// Whether a point at `p` leaving `from` lands on one of the targets the last hover or press + /// gathered ([`Targets::snap_hit`]), whether or not its guides show. False with Smart Guides + /// off, with no targets, and while pixels or the grid snap instead. + pub(crate) fn lands_on_target(&self, cx: &ToolContext, p: Point, from: Option<&Leave>) -> bool { + let Some((_, PointSnap { targets: Some((t, tol)), op })) = &self.targets else { return false }; + cx.smart_guides && !cx.snaps_to_pixel(*op) && !cx.snap_to_grid && t.snap_hit(p, from, cx.tol(*tol)).2 + } + /// The guides of the last snap. pub fn guides(&self) -> &[Overlay] { &self.guides diff --git a/crates/tools/src/guides/targets.rs b/crates/tools/src/guides/targets.rs index 94344aab2c..5f30ce3a7c 100644 --- a/crates/tools/src/guides/targets.rs +++ b/crates/tools/src/guides/targets.rs @@ -778,27 +778,35 @@ impl Targets { /// that way into line with the nearest target; else, before lining up, it lands on a /// construction guide through it, where a target's line crosses the guide if one does nearby. pub fn snap_from(&self, p: Point, from: Option<&Leave>, tol: f64) -> (Point, Vec) { + let (q, guides, _) = self.snap_hit(p, from, tol); + (q, guides) + } + + /// [`Self::snap_from`], and whether `p` landed on a target (an anchor or center, a crossing, + /// a segment, a construction guide or a target's line), whether or not its guides show. A + /// point Shift kept to its angle without lining up with a target landed on none. + pub(crate) fn snap_hit(&self, p: Point, from: Option<&Leave>, tol: f64) -> (Point, Vec, bool) { if let Some(f) = from && let Some(q) = f.constrained(p) { return match self.slide(f.at, q - f.at, q, tol, true) { - Some((q, target)) => (q, self.lined_up(q, target)), - None => (q, vec![]), + Some((q, target)) => (q, self.lined_up(q, target), true), + None => (q, vec![], false), }; } if let Some((q, k)) = self.nearest_point(p, tol) { - return (q, self.label(q, k.label()).into_iter().collect()); + return (q, self.label(q, k.label()).into_iter().collect(), true); } if let Some(q) = self.crossing(p, tol) { - return (q, self.label(q, "intersect").into_iter().collect()); + return (q, self.label(q, "intersect").into_iter().collect(), true); } if let Some(f) = from.filter(|f| f.contact) && let Some((q, perpendicular, dir)) = self.touching(f.at, p, tol) { - return (q, self.touch_guides(f.at, q, perpendicular, dir, tol)); + return (q, self.touch_guides(f.at, q, perpendicular, dir, tol), true); } if let Some(q) = self.on_segment(p, tol) { - return (q, self.label(q, Kind::Edge.label()).into_iter().collect()); + return (q, self.label(q, Kind::Edge.label()).into_iter().collect(), true); } // A construction guide through the point it leaves, else a dragged segment's extension: // it lands on the guide, sliding into line with a target crossing it nearby. @@ -809,8 +817,8 @@ impl Targets { { let construction = |q: Point| Overlay::Line { a: at, b: q, color: self.style.color, dashed: false }; return match self.slide(at, dir, q, tol, false) { - Some((q, target)) => (q, std::iter::once(construction(q)).chain(self.lined_up(q, target)).collect()), - None => (q, vec![construction(q)]), + Some((q, target)) => (q, std::iter::once(construction(q)).chain(self.lined_up(q, target)).collect(), true), + None => (q, vec![construction(q)], true), }; } let mut out = p; @@ -840,7 +848,7 @@ impl Targets { if aligned { ov.extend(self.label(out, "align")); } - (out, ov) + (out, ov, aligned) } /// Where a line from `at` through a point near `p` touches a target segment: square to it diff --git a/crates/tools/src/quickpen.rs b/crates/tools/src/quickpen.rs index 6368ba160b..d542af832c 100644 --- a/crates/tools/src/quickpen.rs +++ b/crates/tools/src/quickpen.rs @@ -12,18 +12,27 @@ //! point closes the path, a click on an end of an open path goes on drawing from it, and Escape //! or Enter ends the path. The path's points show as circles, without handles, and a preview //! shows the piece the next click adds. Points snap to Smart Guides. Each piece is one undo step. +//! +//! While an arc is drawn, by a drag or as the piece the next click adds, the tool shows a +//! protractor around the arc's center: a tick across its circle every 15° from where the arc +//! starts, a longer one every 90°, and one where it ends. The piece the next click adds shows its +//! protractor only while the Pen tool's rubber band preference shows that piece. With Smart Guides +//! on, the end of a continuous arc goes onto the nearest tick of that protractor when the tick lies +//! within the snapping tolerance of the pointer, no other Smart Guide snaps the point, and neither +//! the grid nor pixels snap drawn points. A sharp-corner arc sweeps its arc size, so its end is not +//! snapped to a tick. Shift does not constrain Quick Pen points, so it does not change the snapping. use std::f64::consts::{FRAC_PI_2, PI}; use std::sync::Arc; use serde_json::{Value, json}; -use vectorcraft_doc::{Document, Node, NodeId, NodeKind}; +use vectorcraft_doc::{Document, MAX_COORD, Node, NodeId, NodeKind}; use vectorcraft_geom::{Anchor, AnchorKind, BezPath, Point, SubPath, Vec2}; use crate::draw2::FEEDBACK; use crate::guides::{DrawSnap, Leave}; use crate::pen::{continue_from, open_end_at}; -use crate::{Action, Cursor, Mods, Overlay, PointerEvent, PointerKind, Tool, ToolContext, ToolKey}; +use crate::{Action, Cursor, Mods, Overlay, PixelOp, PointerEvent, PointerKind, Tool, ToolContext, ToolKey}; /// The tool's id. pub const ID: &str = "quickPen"; @@ -36,6 +45,10 @@ pub const TURN_STEP: f64 = 15.0; /// The smallest and largest arc size (degrees). pub const MIN_TURN: f64 = 1.0; pub const MAX_TURN: f64 = 359.0; +/// Degrees between the protractor's ticks, and the steps a continuous arc's sweep snaps to. +pub const TICK_STEP: f64 = 15.0; +/// Half the length (screen points) of a protractor tick; the ticks every 90° are twice as long. +const TICK_PX: f64 = 4.0; /// Screen points the pointer moves after a press before the press drags. const DRAG_PX: f64 = 3.0; /// A continuous arc whose end lies within this angle (radians) of straight ahead, or of straight @@ -190,6 +203,80 @@ pub fn append(sp: &mut SubPath, piece: &Piece) -> bool { true } +/// The circle an arc piece lies on: its center and radius, the point the arc starts from, and the +/// arc's signed sweep (radians; positive bulges to the left of the direction drawn). +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct ArcCircle { + pub center: Point, + pub radius: f64, + pub start: Point, + pub sweep: f64, +} + +/// The circle of the arc `piece` adds at the end of `sp`, as [`append`] draws it. None for a line, +/// a piece that ends where `sp` does, and a circle whose center or radius is past the document's +/// coordinate limit. +pub fn arc_circle(sp: &SubPath, piece: &Piece) -> Option { + let a = sp.anchors.last()?.p; + let c = piece.to - a; + let l = c.hypot(); + if l <= 1e-9 || !l.is_finite() { + return None; + } + let s = turn_of(sp, piece, a, piece.to)?; + let half = s.abs() / 2.0; + let radius = l / (2.0 * half.sin()); + // The center lies on the chord's perpendicular bisector, on the side away from the bulge for + // less than a half circle and on the bulge's side for more. + let center = a + c / 2.0 + rot(c / l, FRAC_PI_2) * (radius * half.cos() * s.signum()); + (radius <= MAX_COORD && center.x.abs() <= MAX_COORD && center.y.abs() <= MAX_COORD).then_some(ArcCircle { center, radius, start: a, sweep: s }) +} + +/// The protractor tick nearest the end of a continuous arc ending at `piece.to`: the point on the +/// arc's circle ([`arc_circle`]) where the sweep is a whole number of [`TICK_STEP`]s. None for +/// other pieces, an arc without a circle, a sweep that rounds to nothing or to a whole circle, and +/// a tick past the document's coordinate limit. +pub fn tick_end(sp: &SubPath, piece: &Piece) -> Option { + if piece.stroke != Stroke::ContinuousArc { + return None; + } + let arc = arc_circle(sp, piece)?; + let step = TICK_STEP.to_radians(); + let s = (arc.sweep / step).round() * step; + (s.abs() > step / 2.0 && s.abs() < 2.0 * PI - step / 2.0) + .then(|| arc.center + rot(arc.start - arc.center, s)) + .filter(|b| b.x.abs() <= MAX_COORD && b.y.abs() <= MAX_COORD) +} + +/// The protractor around `arc`'s center: a tick across its circle every [`TICK_STEP`] from where +/// the arc starts, twice as long every 90°, and one where the arc ends. +fn protractor(cx: &ToolContext, arc: &ArcCircle) -> BezPath { + let step = TICK_STEP.to_radians(); + let out = (arc.start - arc.center) / arc.radius; + let ticks = (arc.sweep.abs() / step + 1e-9).floor() as usize; + let mut bp = BezPath::new(); + let mut tick = |angle: f64, long: bool| { + let d = rot(out, angle); + let half = cx.tol(if long { 2.0 * TICK_PX } else { TICK_PX }); + bp.move_to(arc.center + d * (arc.radius - half)); + bp.line_to(arc.center + d * (arc.radius + half)); + }; + let per_right_angle = (90.0 / TICK_STEP).round() as usize; + for k in 0..=ticks { + tick(arc.sweep.signum() * k as f64 * step, k % per_right_angle == 0); + } + if arc.sweep.abs() - ticks as f64 * step > 1e-6 { + tick(arc.sweep, false); + } + bp +} + +/// The last two of the first `kept` points of `sp`: where the piece after them starts, and the +/// direction it arrives in. +fn tail(sp: &SubPath, kept: usize) -> Option { + Some(SubPath::new(sp.anchors.get_range(kept.saturating_sub(2)..kept)?, false)) +} + /// Closes `sp`: a last point that lies on the first joins it (the first point takes its incoming /// handle); otherwise a straight segment closes the path. Fewer than two points stay open. pub fn close(sp: &mut SubPath) { @@ -284,11 +371,15 @@ pub struct QuickPenTool { press: Option, hover: Option, snap: DrawSnap, + /// The pointer while it hovers, and whether it lies on a Smart Guide target ([`Self::landed`]); + /// `hover` is where Smart Guides put it. The protractor's tick is applied when the point is + /// used ([`Self::hover_end`]), for the action chosen then. A press clears it. + pointer: Option<(Point, bool)>, } impl Default for QuickPenTool { fn default() -> Self { - Self { action: Stroke::Line, turn: DEFAULT_TURN, drawing: None, press: None, hover: None, snap: DrawSnap::default() } + Self { action: Stroke::Line, turn: DEFAULT_TURN, drawing: None, press: None, hover: None, snap: DrawSnap::default(), pointer: None } } } @@ -375,11 +466,16 @@ impl QuickPenTool { return vec![]; } // The snapping leaves from the point before the piece being dragged, as the press found it. - let from = self.drawing.as_ref().and_then(|dr| { - let sp = dr.before_press.as_ref()?.path_data()?.subpaths.get(dr.si)?; - sp.anchors.get(dr.kept.last()?.checked_sub(1)?).map(|a| Leave::segment(cx, a.p, false).without_contact()) - }); + let before = self.before_piece(); + let from = before.as_ref().and_then(|sp| sp.anchors.last()).map(|a| Leave::segment(cx, a.p, false).without_contact()); let q = self.snap.drag(cx, p, from.as_ref()); + let q = match (&before, self.drawing.as_ref().and_then(|dr| dr.pieces.last())) { + (Some(sp), Some(piece)) => { + let landed = piece.stroke == Stroke::ContinuousArc && self.landed(cx, p, q, from.as_ref()); + self.on_tick(cx, sp, *piece, p, q, landed) + } + _ => q, + }; let Some(last) = self.drawing.as_mut().and_then(|dr| dr.pieces.last_mut()) else { return vec![] }; if last.to == q { return vec![]; @@ -388,6 +484,40 @@ impl QuickPenTool { vec![Action::Preview(COMMAND.into(), self.params(false)), drawn()] } + /// `q`, where the last snap put the end of `piece` drawn after `sp` (the pointer being at `p`), + /// moved onto the protractor's nearest tick ([`tick_end`]) when Smart Guides are on, the tick + /// lies within the snapping tolerance of the pointer, and nothing else snapped the point: the + /// snap left it where the pointer is, the pointer is on no Smart Guide target (shown or not, + /// `landed`), and neither the grid nor pixels snap drawn points. + fn on_tick(&self, cx: &ToolContext, sp: &SubPath, piece: Piece, p: Point, q: Point, landed: bool) -> Point { + if landed || !cx.smart_guides || q != p || cx.snap_to_grid || cx.snaps_to_pixel(PixelOp::Drawing) { + return q; + } + tick_end(sp, &Piece { to: q, ..piece }).filter(|b| b.distance(q) <= cx.tol(cx.snapping_tolerance)).unwrap_or(q) + } + + /// Whether the pointer at `p`, which the last snap left in place at `q`, lies on a Smart Guide + /// target leaving `from`, shown or not ([`DrawSnap::lands_on_target`]). A point the snap moved + /// is not asked about, since a tick applies only to a point left in place. + fn landed(&self, cx: &ToolContext, p: Point, q: Point, from: Option<&Leave>) -> bool { + q == p && self.snap.lands_on_target(cx, p, from) + } + + /// Where the next click's piece after `sp` ends while the pointer hovers: the hover's snapped + /// point, on the protractor's tick when [`Self::on_tick`] puts it there. None before the + /// pointer moves after a press. + fn hover_end(&self, cx: &ToolContext, sp: &SubPath) -> Option { + let ((p, landed), q) = (self.pointer?, self.hover?); + Some(self.on_tick(cx, sp, self.piece_to(q), p, q, landed)) + } + + /// During a press that adds a piece: the points before that piece, as the press found them + /// (the last two, see [`tail`]). + fn before_piece(&self) -> Option { + let dr = self.drawing.as_ref()?; + tail(dr.before_press.as_ref()?.path_data()?.subpaths.get(dr.si)?, *dr.kept.last()?) + } + /// Draws the path again after its last piece changed: a preview while a press draws that /// piece, else a step of its own. fn redraw(&self) -> Vec { @@ -434,6 +564,8 @@ impl QuickPenTool { } let from = self.leave(cx).map(|l| l.1); let q = self.snap.press(cx, p, &[id], from.as_ref()); + let landed = self.action == Stroke::ContinuousArc && self.landed(cx, p, q, from.as_ref()); + let q = self.on_tick(cx, sp, self.piece_to(q), p, q, landed); let (piece, kept) = (self.piece_to(q), sp.anchors.len()); if let Some(dr) = self.drawing.as_mut() { dr.push(piece, kept); @@ -459,6 +591,7 @@ impl QuickPenTool { /// Ends the path being drawn; a press that added a piece is taken back. fn end(&mut self) -> Vec { self.drawing = None; + self.pointer = None; self.snap.clear(); match self.press.take() { Some(pr) if pr.begun => vec![Action::Cancel], @@ -498,13 +631,16 @@ impl Tool for QuickPenTool { match ev.kind { PointerKind::Move => { let (on, from) = self.leave(cx).unzip(); - self.hover = Some(self.snap.hover(cx, p, on.as_slice(), from.as_ref())); + let q = self.snap.hover(cx, p, on.as_slice(), from.as_ref()); + self.hover = Some(q); + self.pointer = Some((p, on.is_some() && self.landed(cx, p, q, from.as_ref()))); vec![] } PointerKind::Down => { if self.press.is_some() { return vec![]; } + self.pointer = None; self.press_down(cx, p) } PointerKind::Drag => { @@ -670,13 +806,27 @@ impl Tool for QuickPenTool { fn hover_ended(&mut self, _cx: &ToolContext) { self.hover = None; + self.pointer = None; } fn overlays(&self, cx: &ToolContext) -> Vec { let mut o = self.snap.guides().to_vec(); let Some((id, sp)) = self.active(cx) else { return o }; + let end = if self.press.is_none() { self.hover_end(cx, sp) } else { None }; + // The arc being drawn: the piece a press drags, or the piece the next click adds while the + // rubber band shows it. + let arc = match self.press { + Some(pr) if pr.begun => { + self.before_piece().zip(self.drawing.as_ref().and_then(|dr| dr.pieces.last())).and_then(|(sp, piece)| arc_circle(&sp, piece)) + } + Some(_) => None, + None => end.filter(|_| cx.pen_rubber_band).and_then(|h| arc_circle(sp, &self.piece_to(h))), + }; + if let Some(arc) = arc { + o.push(Overlay::Path { path: protractor(cx, &arc), color: FEEDBACK, width: 1.0, dashed: false }); + } if self.press.is_none() - && let Some(h) = self.hover + && let Some(h) = end.or(self.hover) { if cx.pen_rubber_band && let Some(path) = self.rubber_band(sp, h) diff --git a/crates/tools/src/quickpen/tests.rs b/crates/tools/src/quickpen/tests.rs index f5ab9986d1..5fb23565c5 100644 --- a/crates/tools/src/quickpen/tests.rs +++ b/crates/tools/src/quickpen/tests.rs @@ -1,7 +1,7 @@ use super::*; use crate::testutil::*; use vectorcraft_doc::Selection; -use vectorcraft_geom::{ParamCurve, PathData}; +use vectorcraft_geom::{ParamCurve, PathData, PathSeg}; fn pt(x: f64, y: f64) -> Point { Point::new(x, y) @@ -196,6 +196,94 @@ fn the_first_click_starts_a_path() { assert_eq!(t.cursor(&cx, pt(400.0, 400.0), Mods::default()), Cursor::Pen); } +/// The circle `arc_circle` gives is the one `append` draws the arc on, for sharp-corner arcs of +/// less and more than a half circle, flipped, and continuous arcs; a line has none. +#[test] +fn the_arc_circle_is_the_circle_the_arc_is_drawn_on() { + let line = build(&start(pt(0.0, 0.0)), &[piece(100.0, 0.0, Stroke::Line)], false); + let cases = [ + (start(pt(0.0, 0.0)), Piece { turn: 90.0, ..piece(100.0, 0.0, Stroke::SharpArc) }), + (start(pt(0.0, 0.0)), Piece { turn: 270.0, flip: true, ..piece(100.0, 30.0, Stroke::SharpArc) }), + (line.clone(), piece(200.0, 100.0, Stroke::ContinuousArc)), + (line.clone(), piece(40.0, 60.0, Stroke::ContinuousArc)), + ]; + for (sp, pc) in cases { + let arc = arc_circle(&sp, &pc).unwrap(); + let from = sp.anchors.len() - 1; + let mut drawn = sp.clone(); + append(&mut drawn, &pc); + assert!(on_circle(&drawn, from, arc.center, arc.radius), "{pc:?} {arc:?}"); + assert_eq!(arc.start, sp.anchors.last().unwrap().p); + } + assert!(arc_circle(&line, &piece(200.0, 100.0, Stroke::Line)).is_none()); +} + +/// A continuous arc's end goes to the protractor tick nearest it: on the same circle, where the +/// sweep is a whole number of 15° steps, so an end that sweeps 61° goes to the drawn 60° tick. A +/// sharp-corner arc and a sweep that rounds to a whole circle have no tick to go to. +#[test] +fn a_continuous_arc_end_goes_to_the_nearest_tick() { + let (d, _) = doc_with_rect(); + let s = Selection::default(); + let p = paint(); + let cx = cx(&d, &s, &p); + let sp = build(&start(pt(0.0, 0.0)), &[piece(100.0, 0.0, Stroke::Line)], false); + let half = 30.5f64.to_radians(); + let to = pt(100.0 + 80.0 * half.cos(), 80.0 * half.sin()); + let pc = Piece { to, ..piece(0.0, 0.0, Stroke::ContinuousArc) }; + let arc = arc_circle(&sp, &pc).unwrap(); + assert!((arc.sweep.to_degrees() - 61.0).abs() < 1e-9, "{arc:?}"); + let b = tick_end(&sp, &pc).unwrap(); + let after = arc_circle(&sp, &Piece { to: b, ..pc }).unwrap(); + assert!((after.sweep.to_degrees() - 60.0).abs() < 1e-9, "{after:?}"); + assert!(after.center.distance(arc.center) < 1e-9 && (after.radius - arc.radius).abs() < 1e-9, "the same circle"); + let ticks = protractor(&cx, &arc); + let on_a_tick = ticks.segments().any(|seg| (seg.eval(1.0) - seg.eval(0.0)).cross(b - seg.eval(0.0)).abs() < 1e-6); + assert!(on_a_tick, "{b:?} lies across a drawn tick"); + assert!(tick_end(&sp, &Piece { stroke: Stroke::SharpArc, ..pc }).is_none()); + // Nearly straight behind: the sweep rounds to 360°. + assert!(tick_end(&sp, &Piece { to: pt(20.0, 0.5), ..pc }).is_none()); +} + +/// An end inside the document's coordinate limit whose tick lies past it has no tick to go to: a +/// 59° sweep whose 60° tick is 0.4 pt past the limit. +#[test] +fn a_tick_past_the_coordinate_limit_is_not_used() { + let x = vectorcraft_doc::MAX_COORD - 87.5; + let sp = build(&start(pt(x - 100.0, 0.0)), &[piece(x, 0.0, Stroke::Line)], false); + let half = 29.5f64.to_radians(); + let pc = Piece { to: pt(x + 100.0 * half.cos(), 100.0 * half.sin()), ..piece(0.0, 0.0, Stroke::ContinuousArc) }; + assert!(pc.to.x < vectorcraft_doc::MAX_COORD); + assert!(tick_end(&sp, &pc).is_none()); + let inside = Piece { to: pt(pc.to.x - 10.0, pc.to.y), ..pc }; + assert!(tick_end(&sp, &inside).is_some(), "a tick inside the limit is used"); +} + +/// The protractor has a tick every 15° of the sweep, each across the arc's circle, the first +/// through the arc's start; a sweep that is not a whole number of steps adds a tick at its end. +#[test] +fn the_protractor_ticks_lie_across_the_arc() { + let (d, _) = doc_with_rect(); + let s = Selection::default(); + let p = paint(); + let cx = cx(&d, &s, &p); + let sp = start(pt(0.0, 0.0)); + for (turn, ticks) in [(90.0, 7), (100.0, 8)] { + let pc = Piece { turn, ..piece(100.0, 0.0, Stroke::SharpArc) }; + let arc = arc_circle(&sp, &pc).unwrap(); + let segs: Vec<_> = protractor(&cx, &arc).segments().collect(); + assert_eq!(segs.len(), ticks, "{turn}"); + for seg in &segs { + let (a, b) = (seg.eval(0.0), seg.eval(1.0)); + assert!((a.midpoint(b).distance(arc.center) - arc.radius).abs() < 1e-9); + assert!((b - a).cross(arc.center - a).abs() < 1e-6, "points at the center"); + } + let through = |seg: &PathSeg, q: Point| (seg.eval(1.0) - seg.eval(0.0)).cross(q - seg.eval(0.0)).abs() < 1e-6; + assert!(through(segs.first().unwrap(), arc.start)); + assert!(through(segs.last().unwrap(), pc.to)); + } +} + /// The rubber band previews exactly the piece a click adds. #[test] fn the_rubber_band_is_the_next_piece() { diff --git a/docs/mcp.md b/docs/mcp.md index 5032690fc6..65383caa1b 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -7328,6 +7328,15 @@ arc size of 180°, its 15° steps, the side an arc bulges to, what C and `[` `]` path are VectorCraft's own rules. The tool keeps `action` and `turn` with the preferences (`tool.setOption {tool: "quickPen", key, value}`). +While an arc is drawn, by a drag or as the piece the next click adds, the tool shows a protractor around the arc's +center: a tick across the arc's circle every 15° from where the arc starts, a longer tick every 90°, and one where the +arc ends. The piece the next click adds shows its protractor only while Enable Rubber Band for the Pen tool shows +that piece. With Smart Guides on, the end of a continuous arc snaps onto the nearest tick of its protractor, on the same +circle, when that tick lies within the Smart Guides snapping tolerance of the pointer, no other Smart Guide snaps the +point, and neither Snap to Grid nor Snap to Pixel snaps drawn points. A sharp-corner arc sweeps the arc size, so its end +does not snap to a tick. Shift does not constrain Quick Pen points, so it does not change the tick snapping. The +protractor, its 15° step and the tick snapping are VectorCraft's own behavior. + Selecting the tool shows its toolbar on the canvas: Straight Line, Continuous Arc and Sharp Corner Arc set `action`, Flip Arc flips the last sharp-corner arc as C does (`tool.quickPen.flipArc {}`, which first finishes any pending tool edit, which can change the document, then returns false and changes nothing more when the Quick Pen tool is not active diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index f8a3dc84a0..581f72bb0f 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -642,6 +642,7 @@ since 2026-10-01. - **Recolor picker follow-up (#8031/#4028):** native Lab numeric entry, document/loaded-library swatches in the Color Picker, and Assign-row Pick from Swatches / Limit to Library menus. #4090 provided the double-click picker and #5113 the Assign sliders. Regression tests `native_lab_entry_in_color_picker` and `row_context_menu_pick_from_swatches_and_limit_to_library` exercise the fields and menu callbacks rather than writing their result state. Area score and hours unchanged. - **Quick Pen tool (#2660, in part):** a tool in the Pen tool's group (Alt+P, Option+P on macOS) draws straight lines, continuous arcs and sharp-corner arcs, one undo step per piece; Alt pressed and let go on its own switches the action, C flips the last sharp-corner arc, `[` and `]` change the arc size by 15°, a click on the first point closes the path, a click on an open end continues it, and Escape or Enter ends it (`path.quickPen`), as [Draw with the Quick Pen tool](https://helpx.adobe.com/illustrator/web/add-and-edit-artwork/draw-and-edit-paths/draw-with-quick-pen-tool.html) and [Quick Pen tool keyboard shortcuts](https://helpx.adobe.com/illustrator/web/add-and-edit-artwork/draw-and-edit-paths/quick-pen-tool-keyboard-shortcuts.html) describe. The 180° default arc, its 15° steps, the side an arc bulges to, a dragged piece ending where the press is let go, and C, `[` and `]` changing the arc being dragged are VectorCraft's own rules. Tests: tools `quickpen::tests`, engine `tests::quickpen`, ui-egui `shortcuts::alt_tap::tests`, `alt_p_chooses_the_quick_pen_and_an_alt_tap_switches_its_action` and `brackets_size_the_quick_pen_arc_being_dragged`. Score and hours unchanged. +- **Quick Pen protractor:** while an arc is drawn, by a drag or as the piece the next click adds, the Quick Pen tool shows a protractor around the arc's center: a tick every 15° from the arc's start, a longer one every 90°, and one at its end; the next click's piece shows it only with Enable Rubber Band for the Pen tool on. With Smart Guides on, the end of a continuous arc snaps onto the nearest tick within the snapping tolerance of the pointer when no other Smart Guide snaps the point and neither Snap to Grid nor Snap to Pixel snaps drawn points; Shift does not change it. The protractor, its 15° step and the tick snapping are VectorCraft's own behavior. Tests: tools `the_arc_circle_is_the_circle_the_arc_is_drawn_on`, `a_continuous_arc_end_goes_to_the_nearest_tick`, `a_tick_past_the_coordinate_limit_is_not_used`, `the_protractor_ticks_lie_across_the_arc`; engine `a_continuous_arc_end_snaps_to_the_protractor`, `a_click_puts_a_continuous_arc_end_on_a_tick`, `a_hover_snaps_to_a_tick_only_for_a_continuous_arc`, `an_arc_drag_shows_the_protractor`, `a_hovered_arc_shows_the_protractor_with_the_rubber_band`. New tests of existing Quick Pen behavior: `a_point_snaps_to_a_smart_guide`, `hovering_shows_the_distance_label`. Score and hours unchanged. - **Optional compact Tools (#7234):** Window > Toolbars > Compact Tools reduces row and column spacing and the main panel's allocated width in one or two columns, docked or floating. The setting is saved with the UI state and applies to Basic, Advanced and edited main Tools layouts; the selected tool, icon size, footer controls and tool-flyout behavior are retained. Turning it off restores the existing layout, which remains the default. Named custom toolbars and flyout spacing are unchanged. Public regressions in `crates/ui-egui/tests/toolbar_compact.rs` cover the actual toolbar layout against the default control, the command and saved-state roundtrip, tool selection, flyouts, footer controls and short-window reachability. This is an optional layout choice, without a styling-parity or score claim; hours are unchanged.