diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index ae67281995..e2bc50cdc5 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -235,11 +235,7 @@ pub fn has_multi(s: &Session) -> std::result::Result<(), String> { /// editing and symbol editing mode isolate their own layer, which does not count here; an object /// isolated inside them counts. pub(crate) fn ordinary_isolation(st: &crate::DocState) -> Option { - st.isolation.filter(|l| { - !st.doc.pattern_edit.as_ref().is_some_and(|e| e.layer == *l) - && !st.doc.mask_edit.as_ref().is_some_and(|e| e.layer == *l) - && !st.doc.symbol_edit.as_ref().is_some_and(|e| e.layer == *l) - }) + vectorcraft_tools::ordinary_isolation(&st.doc, st.isolation) } /// Objects are selected ([`has_selection`]), and in isolation mode ([`ordinary_isolation`]) at /// least one of them is inside the isolated object: Object › Lock's and Object › Hide's items. diff --git a/crates/engine/src/cmd/addons/pathtools/trim.rs b/crates/engine/src/cmd/addons/pathtools/trim.rs index 134edc6607..f1ffab9ba0 100644 --- a/crates/engine/src/cmd/addons/pathtools/trim.rs +++ b/crates/engine/src/cmd/addons/pathtools/trim.rs @@ -1,15 +1,13 @@ //! Trim at Crossings: remove the stretch of a path between the places where other paths, or the //! path itself, cross it. The command takes the stretch at a point, every stretch a rectangle //! touches, or every stretch a line through some points crosses. It works on every path that can -//! be edited, selected or not. - -use std::collections::HashSet; +//! be edited, selected or not. What it removes is worked out by +//! [`vectorcraft_tools::addons::trim::plan`], which the tool also uses to show it beforehand. use serde_json::{Value, json}; -use vectorcraft_doc::{Document, NodeId, NodeKind}; -use vectorcraft_geom::kurbo::{Line, PathSeg}; -use vectorcraft_geom::{PathData, Point, Rect, SubPath, hit}; -use vectorcraft_pathops::addons::pathtools as pt; +use vectorcraft_doc::{NodeId, NodeKind}; +use vectorcraft_geom::{Point, Rect}; +use vectorcraft_tools::addons::trim::plan::{self, Limits, Pick, Stretches}; use super::super::super::draw2::replace_with_pieces; use super::super::super::pathops::Beside; @@ -41,16 +39,6 @@ pub(super) fn specs() -> Vec { )] } -/// What picks the stretches to remove. -enum Pick { - /// The stretch of the nearest path within the tolerance of the point. - At(Point, f64), - /// Every stretch the rectangle touches. - Rect(Rect), - /// Every stretch the line through the points crosses. - Line(Vec, Rect), -} - fn pick(p: &Value) -> Result { const C: &str = "addon.pathtools.trim"; let given = |key: &str| p.get(key).filter(|v| !v.is_null()); @@ -89,194 +77,15 @@ fn pick(p: &Value) -> Result { } } -/// A path that takes part: its id, geometry and control-point box. -type Part<'a> = (NodeId, &'a PathData, Rect); - -/// The paths that take part, bottom to top: the ones that can be edited, without guides and -/// clipping paths. The clipping path of a clip group or a clipped layer is left out whole, the -/// members of a compound clipping path included. -fn parts(d: &Document) -> Vec> { - let editable = d.editable(); - let mut masks = HashSet::new(); - d.walk(|n| { - if n.clips() - && let Some(first) = n.children().and_then(|c| c.first()) - { - first.walk(&mut |m| { - masks.insert(m.id); - }); - } - }); - let mut out = vec![]; - d.walk(|n| { - if let NodeKind::Path { path, guide: false, clipping: false, .. } = &n.kind - && !masks.contains(&n.id) - && let Some(b) = path.control_bounds() - && editable(n.id) - { - out.push((n.id, path, b)); - } - }); - out -} - -/// Most box tests one command makes between a line's pieces and the paths' segments. -const MAX_LINE_TESTS: usize = 60_000_000; -/// Most tests one command makes between the boxes of the paths to trim and of the other paths. -const MAX_BOX_TESTS: usize = 50_000_000; - -/// Does the line through `pts` cross `sp`? Each piece of the line compared costs one of `budget`; -/// `None` once it is spent. -fn crossed_by_line(sp: &SubPath, pts: &[Point], budget: &mut usize) -> Option { - let segs: Vec<_> = (0..sp.segment_count()) - .map(|i| { - let c = sp.segment(i); - (c, Rect::from_points(c.p0, c.p1).union_pt(c.p2).union_pt(c.p3).inflate(1e-9, 1e-9)) - }) - .collect(); - let Some(reach) = segs.iter().map(|s| s.1).reduce(|a, b| a.union(b)) else { return Some(false) }; - for w in pts.windows(2) { - let [a, b] = w else { continue }; - let piece = Rect::from_points(*a, *b); - *budget = budget.checked_sub(1)?; - if !reach.overlaps(piece) { - continue; - } - for (c, r) in &segs { - *budget = budget.checked_sub(1)?; - if r.overlaps(piece) && !PathSeg::Cubic(*c).intersect_line(Line::new(*a, *b)).is_empty() { - return Some(true); - } - } - } - Some(false) -} - -/// Does the rectangle or line of `pick` touch the outline of `piece`? Never for `Pick::At`. -fn touches(piece: &SubPath, pick: &Pick, budget: &mut usize) -> Result { - match pick { - Pick::At(..) => Ok(false), - Pick::Rect(r) => Ok(hit::intersects_rect(&PathData::single(piece.clone()), *r)), - Pick::Line(pts, _) => crossed_by_line(piece, pts, budget) - .ok_or_else(|| bad("addon.pathtools.trim", "the line is too long, or the paths it passes too many, to check")), - } -} - -/// `path` without the stretches `pick` takes (`on`: the place of `Pick::At` on it): its subpaths -/// then, and how many stretches went. `None` when none does. A rectangle or a line that touches no -/// part of `path` leaves it out before its crossings are looked for. -fn trimmed( - path: &PathData, - others: &[&PathData], - pick: &Pick, - on: Option, - budget: &mut usize, - work: &mut pt::Work, -) -> Result, usize)>> { - const C: &str = "addon.pathtools.trim"; - let reached = match pick { - Pick::At(..) => true, - Pick::Rect(r) => hit::intersects_rect(path, *r), - Pick::Line(..) => { - let mut any = false; - for sp in &path.subpaths { - if touches(sp, pick, budget)? { - any = true; - break; - } - } - any - } - }; - if !reached { - return Ok(None); - } - let places = - pt::crossings_on_within(path, others, work).ok_or_else(|| bad(C, "the paths are too many or too tangled to find where they cross"))?; - let mut subs = vec![]; - let mut removed = 0; - for (si, sp) in path.subpaths.iter().enumerate() { - // The places come in subpath order: this subpath's are one run of them. - let run = places.partition_point(|p| p.0 < si)..places.partition_point(|p| p.0 <= si); - let here: Vec<(usize, f64)> = places.get(run).unwrap_or_default().iter().map(|&(_, seg, t)| (seg, t)).collect(); - let spans = pt::spans(sp, &here); - let marks: Vec = match pick { - Pick::At(..) => { - let at = on.filter(|(s, ..)| *s == si).and_then(|(_, seg, t)| pt::span_at(sp, &spans, seg, t)); - (0..spans.len()).map(|i| Some(i) == at).collect() - } - _ => spans.iter().map(|s| touches(&pt::slice(sp, *s), pick, budget)).collect::>()?, - }; - match pt::without_spans(sp, &spans, &marks) { - Some(pieces) => { - removed += marks.iter().filter(|m| **m).count(); - subs.extend(pieces); - } - None => subs.push(sp.clone()), - } - } - Ok((removed > 0).then_some((subs, removed))) -} - fn trim(s: &mut Session, p: &Value) -> Result { const C: &str = "addon.pathtools.trim"; let pick = pick(p)?; let st = s.doc()?; - let d = &st.doc; - let parts = parts(d); // In isolation mode only the isolated object's paths are trimmed; paths outside it still cross them. let root = crate::cmd::ordinary_isolation(st); - let in_scope = |id: NodeId| root.is_none_or(|r| id == r || crate::cmd::inside_isolation(d, r, id)); - // The paths to trim, each with the place `at` falls on. - let targets: Vec<(usize, Option)> = match &pick { - Pick::At(at, tolerance) => { - let mut best: Option<(usize, pt::Place, f64)> = None; - for (i, (id, path, b)) in parts.iter().enumerate() { - if !in_scope(*id) { - continue; - } - let b = b.inflate(*tolerance, *tolerance); - if !(b.x0 <= at.x && at.x <= b.x1 && b.y0 <= at.y && at.y <= b.y1) { - continue; - } - // Of paths equally near, the one on top. - if let Some((si, seg, t, _, dist)) = path.nearest(*at) - && dist <= *tolerance - && best.is_none_or(|b| dist <= b.2) - { - best = Some((i, (si, seg, t), dist)); - } - } - best.map(|(i, on, _)| (i, Some(on))).into_iter().collect() - } - Pick::Rect(r) | Pick::Line(_, r) => { - parts.iter().enumerate().filter(|(_, (id, _, b))| in_scope(*id) && b.overlaps(*r)).map(|(i, _)| (i, None)).collect() - } - }; - // Each path to trim has its box tested against every other path's. - if targets.len().saturating_mul(parts.len()) > MAX_BOX_TESTS { - return Err(bad(C, "the rectangle or line reaches too many paths to check")); - } - let mut plan: Vec<(NodeId, Vec)> = vec![]; - let mut removed = 0; - let mut budget = MAX_LINE_TESTS; - // One budget of crossing work for every path the command trims. - let mut work = pt::Work::default(); - for (i, on) in targets { - let Some((id, path, b)) = parts.get(i) else { continue }; - let reach = b.inflate(1e-3, 1e-3); - let others: Vec<&PathData> = - parts.iter().enumerate().filter(|(j, (_, _, ob))| *j != i && reach.overlaps(*ob)).map(|(_, (_, o, _))| *o).collect(); - let Some((subs, n)) = trimmed(path, &others, &pick, on, &mut budget, &mut work)? else { continue }; - removed += n; - // A path of one subpath becomes a path per piece; the pieces of one with more stay its subpaths. - let pieces = match (path.subpaths.len(), subs.is_empty()) { - (_, true) => vec![], - (1, false) => subs.into_iter().map(PathData::single).collect(), - _ => vec![PathData::new(subs)], - }; - plan.push((*id, pieces)); - } + let trimmed = plan::plan(&st.doc, root, &pick, Limits::COMMAND, &mut Stretches::default()).map_err(|e| bad(C, e.message()))?; + let removed: usize = trimmed.iter().map(|t| t.count).sum(); + let plan: Vec<(NodeId, Vec<_>)> = trimmed.into_iter().map(|t| (t.id, t.pieces)).collect(); if plan.is_empty() { return Ok(json!({ "ids": [], "removed": 0 })); } diff --git a/crates/engine/src/cmd/addons/pathtools/trim/tests.rs b/crates/engine/src/cmd/addons/pathtools/trim/tests.rs index 42adb70ab9..a36c705e4f 100644 --- a/crates/engine/src/cmd/addons/pathtools/trim/tests.rs +++ b/crates/engine/src/cmd/addons/pathtools/trim/tests.rs @@ -480,6 +480,129 @@ fn the_tool_trims_on_release_as_one_step_and_escape_drops_a_drag() { assert_eq!(steps(&s), n + 2); } +/// The ends of each red path the tool shows. +fn highlighted(s: &mut Session, view: crate::ViewInfo) -> Vec<(Point, Point)> { + use vectorcraft_geom::kurbo::ParamCurve; + s.overlays(view) + .into_iter() + .filter_map(|o| match o { + vectorcraft_tools::Overlay::Path { path, color, .. } if color == vectorcraft_tools::builder::HIGHLIGHT_RED => { + let segs: Vec<_> = path.segments().collect(); + Some((segs.first()?.start(), segs.last()?.end())) + } + _ => None, + }) + .collect() +} + +#[test] +fn hovering_with_the_tool_shows_the_stretch_its_click_removes() { + use vectorcraft_tools::{PointerEvent, PointerKind}; + let mut s = session(); + let (h, _, _) = across_and_uprights(&mut s); + let hidden = line(&mut s, &[(0.0, 200.0), (300.0, 200.0)], false); + set_flags(&mut s, hidden, false, false); + let view = crate::ViewInfo { smart_guides: false, ..crate::ViewInfo::default() }; + s.select_tool("trimAtCrossings", view).unwrap(); + let n = steps(&s); + // Over the middle of the line across: the stretch between the uprights, and nothing changes. + s.pointer(&PointerEvent::new(PointerKind::Move, 150.0, 101.0), view).unwrap(); + let shown = highlighted(&mut s, view); + assert!(matches!(shown.as_slice(), [(a, b)] if near(*a, 100.0, 100.0) && near(*b, 200.0, 100.0)), "{shown:?}"); + assert_eq!(steps(&s), n); + // Over the hidden path and over empty canvas: nothing. + s.pointer(&PointerEvent::new(PointerKind::Move, 150.0, 200.0), view).unwrap(); + assert!(highlighted(&mut s, view).is_empty()); + s.pointer(&PointerEvent::new(PointerKind::Move, 150.0, 250.0), view).unwrap(); + assert!(highlighted(&mut s, view).is_empty()); + // A click where the stretch was shown removes exactly it: the line keeps 0 to 100 and 200 to 300. + s.pointer(&PointerEvent::new(PointerKind::Move, 150.0, 101.0), view).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Down, 150.0, 101.0), view).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Up, 150.0, 101.0), view).unwrap(); + assert_eq!(steps(&s), n + 1); + assert!(near(ends(&s, h).0, 0.0, 100.0) && near(ends(&s, h).1, 100.0, 100.0)); + let rest = stack(&s).into_iter().find(|id| *id != h && path(&s, *id).subpaths.len() == 1 && near(ends(&s, *id).0, 200.0, 100.0)); + assert!(rest.is_some_and(|id| near(ends(&s, id).1, 300.0, 100.0))); + assert!(highlighted(&mut s, view).is_empty(), "the edit drops the highlight"); +} + +/// The red paths the tool shows. +fn red(s: &mut Session, view: crate::ViewInfo) -> Vec { + s.overlays(view) + .into_iter() + .filter_map(|o| match o { + vectorcraft_tools::Overlay::Path { path, color, .. } if color == vectorcraft_tools::builder::HIGHLIGHT_RED => Some(path), + _ => None, + }) + .collect() +} + +/// The length of every path in the first layer. +fn total_length(s: &Session) -> f64 { + use vectorcraft_geom::kurbo::ParamCurveArclen; + stack(s).into_iter().flat_map(|id| path(s, id).to_bezpath().segments().collect::>()).map(|seg| seg.arclen(1e-9)).sum() +} + +/// `act` removes exactly the red paths shown before it: the paths lose their length, and nothing +/// is left on the middle of any of them. +fn removes_what_was_shown(s: &mut Session, view: crate::ViewInfo, act: &dyn Fn(&mut Session)) { + use vectorcraft_geom::kurbo::{ParamCurve, ParamCurveArclen}; + let shown = red(s, view); + assert!(!shown.is_empty()); + let shown_length: f64 = shown.iter().flat_map(|p| p.segments().collect::>()).map(|seg| seg.arclen(1e-9)).sum(); + let before = total_length(s); + act(s); + assert!((before - total_length(s) - shown_length).abs() < 1e-3, "{before} - {} != {shown_length}", total_length(s)); + for p in &shown { + let segs: Vec<_> = p.segments().collect(); + let mid = segs[segs.len() / 2].eval(if segs.len() % 2 == 1 { 0.5 } else { 0.0 }); + let left = stack(s).into_iter().filter_map(|id| path(s, id).nearest(mid)).map(|n| n.4).fold(f64::INFINITY, f64::min); + assert!(left > 0.5, "a path is left at {mid:?}"); + } +} + +#[test] +fn what_the_tool_shows_before_a_click_or_a_release_is_what_the_command_removes() { + use vectorcraft_tools::{Mods, PointerEvent, PointerKind}; + let view = crate::ViewInfo { smart_guides: false, ..crate::ViewInfo::default() }; + let ev = |kind, x, y| PointerEvent::new(kind, x, y); + let alt = Mods { alt: true, ..Mods::default() }; + let setup = || { + let mut s = session(); + s.execute("shape.ellipse", &json!({"x": 100, "y": 50, "width": 200, "height": 100})).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + line(&mut s, &[(50.0, 100.0), (350.0, 100.0)], false); + // A Z whose first and last sides cross. + line(&mut s, &[(0.0, 160.0), (100.0, 260.0), (100.0, 160.0), (0.0, 260.0)], false); + s.select_tool("trimAtCrossings", view).unwrap(); + s + }; + // A click on the ellipse's top, on the line inside it and on the Z's loop. + for (x, y) in [(200.0, 51.0), (200.0, 101.0), (101.0, 210.0)] { + let mut s = setup(); + s.pointer(&ev(PointerKind::Move, x, y), view).unwrap(); + removes_what_was_shown(&mut s, view, &|s| { + s.pointer(&ev(PointerKind::Down, x, y), view).unwrap(); + s.pointer(&ev(PointerKind::Up, x, y), view).unwrap(); + }); + } + // A rectangle over the ellipse's left side and the line. + let mut s = setup(); + s.pointer(&ev(PointerKind::Down, 90.0, 90.0), view).unwrap(); + s.pointer(&ev(PointerKind::Drag, 120.0, 110.0), view).unwrap(); + removes_what_was_shown(&mut s, view, &|s| { + s.pointer(&ev(PointerKind::Up, 120.0, 110.0), view).unwrap(); + }); + // An Alt line through the ellipse's bottom and the Z's tail. + let mut s = setup(); + s.pointer(&ev(PointerKind::Down, 200.0, 140.0).with_mods(alt), view).unwrap(); + s.pointer(&ev(PointerKind::Drag, 200.0, 170.0).with_mods(alt), view).unwrap(); + s.pointer(&ev(PointerKind::Drag, 10.0, 250.0).with_mods(alt), view).unwrap(); + removes_what_was_shown(&mut s, view, &|s| { + s.pointer(&ev(PointerKind::Up, 10.0, 250.0).with_mods(alt), view).unwrap(); + }); +} + #[test] fn a_line_too_long_to_check_against_the_paths_is_refused() { let mut s = session(); diff --git a/crates/pathops/src/addons/pathtools/crossings.rs b/crates/pathops/src/addons/pathtools/crossings.rs index c20e559d96..bcc254aa82 100644 --- a/crates/pathops/src/addons/pathtools/crossings.rs +++ b/crates/pathops/src/addons/pathtools/crossings.rs @@ -226,6 +226,27 @@ impl Default for Work { } } +impl Work { + /// One `n`th of the work of [`Work::default`] (all of it for `n` of 0 or 1). + pub const fn share(n: usize) -> Work { + let n = if n == 0 { 1 } else { n }; + Work { pairs: MAX_PAIRS / n, steps: MAX_STEPS / n } + } + + /// The work done since the budget was `before`. + pub fn spent_since(self, before: Work) -> Work { + Work { pairs: before.pairs.saturating_sub(self.pairs), steps: before.steps.saturating_sub(self.steps) } + } + + /// Take `cost` (from [`Work::spent_since`]) out of what is left, as if that work were done + /// again. `None`, leaving the budget as it was, when less than `cost` is left. + pub fn draw(&mut self, cost: Work) -> Option<()> { + let (pairs, steps) = (self.pairs.checked_sub(cost.pairs)?, self.steps.checked_sub(cost.steps)?); + *self = Work { pairs, steps }; + Some(()) + } +} + /// Where `others` cross `path`, and where `path` crosses itself (a segment that loops over itself /// included): the places on `path`, in order, within the work of [`Work::default`]. pub fn crossings_on(path: &PathData, others: &[&PathData]) -> Option> { diff --git a/crates/pathops/src/addons/pathtools/tests.rs b/crates/pathops/src/addons/pathtools/tests.rs index 301da1a57c..3c6c592d71 100644 --- a/crates/pathops/src/addons/pathtools/tests.rs +++ b/crates/pathops/src/addons/pathtools/tests.rs @@ -515,6 +515,29 @@ fn one_work_budget_bounds_several_calls_together() { assert!(crossings_on(&path, &[]).is_some(), "a call of its own has its own budget"); } +#[test] +fn work_done_once_can_be_drawn_again_from_another_budget() { + let row: Vec<(f64, f64)> = (0..=1000).map(|i| (i as f64, 0.0)).collect(); + let path = PathData::single(line(&row, false)); + let start = Work::default(); + let mut work = start; + crossings_on_within(&path, &[], &mut work).unwrap(); + let cost = work.spent_since(start); + // Drawing a call's cost leaves what the call itself leaves, 120 times and no more. + let mut again = Work::default(); + assert_eq!(again.draw(cost), Some(())); + assert_eq!(again, work); + let draws = (1..200).take_while(|_| again.draw(cost).is_some()).count(); + assert_eq!(draws, 119); + let left = again; + assert_eq!(again.draw(cost), None); + assert_eq!(again, left, "a draw that fails takes nothing"); + // A twentieth of the budget pays for the call 6 times. + assert_eq!((Work::share(0), Work::share(1)), (Work::default(), Work::default())); + let mut part = Work::share(20); + assert_eq!((0..200).take_while(|_| part.draw(cost).is_some()).count(), 6); +} + #[test] fn a_segment_that_loops_over_itself_crosses_itself() { // One cubic that meets itself at t = 0.25 and t = 0.75. diff --git a/crates/tools/src/addons/trim.rs b/crates/tools/src/addons/trim.rs index 9eee5c436f..9c0681f4b4 100644 --- a/crates/tools/src/addons/trim.rs +++ b/crates/tools/src/addons/trim.rs @@ -3,10 +3,20 @@ //! rectangle and removes every stretch it touches; an Alt-drag draws a freehand line and removes //! every stretch it crosses. Each runs `addon.pathtools.trim` on release, as one undo step, on //! every path that can be edited, selected or not. Escape during a drag removes nothing. +//! +//! Hovering shows in red the stretch a click would remove while finding its crossings takes at +//! most a twentieth of the work a click may do ([`HOVER`]), and a drag shows what it would remove while +//! it reaches few paths ([`PREVIEW`]). + +pub mod plan; use serde_json::json; -use vectorcraft_geom::{Point, Rect}; +use vectorcraft_doc::NodeId; +use vectorcraft_geom::{BezPath, PathData, Point, Rect}; +use vectorcraft_pathops::addons::pathtools as pt; +use self::plan::{Limits, Pick, Stretches}; +use crate::builder::HIGHLIGHT_RED; use crate::draw2::FEEDBACK; use crate::xform::polygon; use crate::{Action, Cursor, Mods, Overlay, PointerEvent, PointerKind, Tool, ToolContext, ToolKey}; @@ -21,6 +31,18 @@ const MIN_DRAG_PX: f64 = 3.0; pub(crate) const MAX_POINTS: usize = 65_536; /// The command the tool runs. const COMMAND: &str = "addon.pathtools.trim"; +/// How much finding the crossings for a preview may take: a twentieth of what the command may. +const PREVIEW_CROSSINGS: pt::Work = pt::Work::share(20); +/// How much hovering may work out on each move: past it the hover shows no highlight, and a +/// click still removes the stretch. +pub const HOVER: Limits = Limits { crossings: PREVIEW_CROSSINGS, ..Limits::COMMAND }; +/// How much a drag's preview may work out on each move: past it the drag shows no preview, and +/// the release still removes everything it reaches. +pub const PREVIEW: Limits = Limits { paths: 32, box_tests: 10_000_000, line_tests: 1_000_000, crossings: PREVIEW_CROSSINGS }; +/// The most points a freehand line has for the drag to show a preview. +const PREVIEW_POINTS: usize = 4_096; +/// The preview's line width (screen pixels). +const PREVIEW_PX: f32 = 3.0; #[derive(Default)] pub struct TrimTool { @@ -32,6 +54,27 @@ pub struct TrimTool { freehand: bool, /// The pointer went `MIN_DRAG_PX` or more from the press: the gesture is a drag from then on. moved: bool, + /// The stretches the gesture would remove, and the document state they were found in. + preview: Vec, + preview_state: Option, + /// Finding the drag's crossings took more work than a preview may: it shows none until the + /// next press. + gave_up: bool, + /// The stretches of the paths looked at so far, for the document state `seen`. + stretches: Stretches, + seen: Option, +} + +/// The document's revision and its isolated object: what a pick is worked out for. +type State = ((u64, u64), Option); + +fn state(cx: &ToolContext) -> State { + (cx.revision, cx.isolation) +} + +/// How near the pointer a click finds a path (pt). +fn reach(cx: &ToolContext) -> f64 { + cx.tol(REACH).min(100.0) } impl TrimTool { @@ -40,6 +83,64 @@ impl TrimTool { self.line.clear(); self.freehand = false; self.moved = false; + self.gave_up = false; + self.preview.clear(); + } + + /// Work out what `pick` would remove, within `limits`, as the preview: nothing when it + /// removes nothing or needs more work than that (then why). + fn look(&mut self, cx: &ToolContext, pick: &Pick, limits: Limits) -> Option { + if self.seen != Some(state(cx)) { + self.stretches.clear(); + self.seen = Some(state(cx)); + } + let root = crate::ordinary_isolation(cx.doc, cx.isolation); + self.preview_state = Some(state(cx)); + match plan::plan(cx.doc, root, pick, limits, &mut self.stretches) { + Ok(all) => { + self.preview = all.into_iter().flat_map(|t| t.removed).map(|sp| PathData::single(sp).to_bezpath()).collect(); + None + } + Err(e) => { + self.preview.clear(); + Some(e) + } + } + } + + /// The preview of the drag as it is: its rectangle, or its freehand line to `to`. + fn look_at_drag(&mut self, cx: &ToolContext, to: Point) { + let Some(start) = self.start else { return }; + if self.gave_up { + self.preview.clear(); + return; + } + if !self.freehand { + self.look_or_give_up(cx, &Pick::Rect(Rect::from_points(start, to))); + return; + } + if self.line.len() > PREVIEW_POINTS { + self.preview.clear(); + return; + } + let mut pts = self.line.clone(); + if pts.last().is_some_and(|p| *p != to) { + pts.push(to); + } + if pts.len() < 2 { + self.preview.clear(); + return; + } + let bounds = pts.iter().fold(Rect::from_points(to, to), |r, q| r.union_pt(*q)); + self.look_or_give_up(cx, &Pick::Line(pts, bounds)); + } + + /// [`Self::look`] for a drag. A drag that reaches too many paths may come back to fewer; one + /// whose crossings or line take too much work shows nothing more. + fn look_or_give_up(&mut self, cx: &ToolContext, pick: &Pick) { + if let Some(plan::TooMuch::Crossings | plan::TooMuch::Line) = self.look(cx, pick, PREVIEW) { + self.gave_up = true; + } } } @@ -57,15 +158,22 @@ impl Tool for TrimTool { if ev.kind == PointerKind::Up { self.reset(); } + self.preview.clear(); return vec![]; } match ev.kind { + PointerKind::Move => { + self.look(cx, &Pick::At(ev.pos, reach(cx)), HOVER); + vec![] + } PointerKind::Down => { self.start = Some(ev.pos); self.end = ev.pos; self.freehand = ev.mods.alt; self.moved = false; self.line = if self.freehand { vec![ev.pos] } else { vec![] }; + // Until the pointer moves away, the press is a click at this point. + self.look(cx, &Pick::At(ev.pos, reach(cx)), HOVER); vec![] } PointerKind::Drag if self.start.is_some() => { @@ -79,6 +187,9 @@ impl Tool for TrimTool { } self.line.push(ev.pos); } + if self.moved { + self.look_at_drag(cx, ev.pos); + } vec![] } PointerKind::Up => { @@ -89,7 +200,7 @@ impl Tool for TrimTool { // A press that stayed near where it started is a click, even when a freehand line // took a few points on the way. One that went farther stays a drag when it comes back. if !moved && start.distance(ev.pos) < cx.tol(MIN_DRAG_PX) { - return vec![Action::Exec(COMMAND.into(), json!({"at": [start.x, start.y], "tolerance": cx.tol(REACH).min(100.0)}))]; + return vec![Action::Exec(COMMAND.into(), json!({"at": [start.x, start.y], "tolerance": reach(cx)}))]; } if !freehand { let r = Rect::from_points(start, ev.pos); @@ -116,16 +227,34 @@ impl Tool for TrimTool { self.start.is_some() && key == ToolKey::Escape } - fn overlays(&self, _cx: &ToolContext) -> Vec { - let Some(start) = self.start else { return vec![] }; - if self.freehand { - return if self.line.len() < 2 { - vec![] - } else { - vec![Overlay::Path { path: polygon(&self.line, false), color: FEEDBACK, width: 1.0, dashed: false }] - }; + fn hover_ended(&mut self, _cx: &ToolContext) { + if self.start.is_none() { + self.preview.clear(); } - if self.moved { vec![Overlay::Marquee(Rect::from_points(start, self.end))] } else { vec![] } + } + + /// The highlight shows what lies under the pointer, which panning or an edit changes. + fn wants_rehover(&self) -> bool { + true + } + + fn overlays(&self, cx: &ToolContext) -> Vec { + // A preview found in another revision of the document, or for another isolated object, is + // out of date. + let mut out: Vec = if self.preview_state == Some(state(cx)) { + self.preview.iter().map(|p| Overlay::Path { path: p.clone(), color: HIGHLIGHT_RED, width: PREVIEW_PX, dashed: false }).collect() + } else { + vec![] + }; + let Some(start) = self.start else { return out }; + if self.freehand { + if self.line.len() >= 2 { + out.push(Overlay::Path { path: polygon(&self.line, false), color: FEEDBACK, width: 1.0, dashed: false }); + } + } else if self.moved { + out.push(Overlay::Marquee(Rect::from_points(start, self.end))); + } + out } fn cursor(&self, _cx: &ToolContext, _p: Point, _mods: Mods) -> Cursor { @@ -137,7 +266,9 @@ impl Tool for TrimTool { mod tests { use super::*; use crate::testutil::*; - use vectorcraft_doc::Selection; + use vectorcraft_doc::{Appearance, Document, Node, Selection}; + use vectorcraft_geom::kurbo::{ParamCurve, PathSeg}; + use vectorcraft_geom::shapes; fn ev(kind: PointerKind, x: f64, y: f64) -> PointerEvent { PointerEvent::new(kind, x, y) @@ -151,7 +282,8 @@ mod tests { cx.zoom = 2.0; let mut t = TrimTool::default(); assert!(t.pointer(&cx, &ev(PointerKind::Down, 100.0, 100.0)).is_empty()); - assert!(t.busy() && t.overlays(&cx).is_empty()); + // No marquee for a press; the rectangle, which nothing crosses, would go whole. + assert!(t.busy() && matches!(t.overlays(&cx).as_slice(), [Overlay::Path { color: HIGHLIGHT_RED, .. }])); let up = t.pointer(&cx, &ev(PointerKind::Up, 100.5, 100.0)); assert_eq!(up, vec![Action::Exec(COMMAND.into(), json!({"at": [100.0, 100.0], "tolerance": 2.0}))], "4 px at 200%"); assert!(!t.busy()); @@ -166,7 +298,10 @@ mod tests { let mut t = TrimTool::default(); t.pointer(&cx, &ev(PointerKind::Down, 160.0, 130.0)); assert!(t.pointer(&cx, &ev(PointerKind::Drag, 140.0, 90.0)).is_empty(), "nothing runs while dragging"); - assert!(matches!(t.overlays(&cx).as_slice(), [Overlay::Marquee(r)] if *r == Rect::new(140.0, 90.0, 160.0, 130.0))); + assert!(matches!( + t.overlays(&cx).as_slice(), + [Overlay::Path { color: HIGHLIGHT_RED, .. }, Overlay::Marquee(r)] if *r == Rect::new(140.0, 90.0, 160.0, 130.0) + )); let up = t.pointer(&cx, &ev(PointerKind::Up, 140.0, 90.0)); assert_eq!(up, vec![Action::Exec(COMMAND.into(), json!({"rect": [140.0, 90.0, 20.0, 40.0]}))]); // Escape during a drag: nothing runs on release, and the key is the tool's only then. @@ -233,4 +368,247 @@ mod tests { assert!(!t.busy()); assert!(t.pointer(&cx, &ev(PointerKind::Up, 0.0, 0.0)).is_empty()); } + + /// A document holding `paths`, bottom to top. + fn doc_of(paths: Vec) -> (Document, Vec) { + let mut d = Document::new(500.0, 500.0); + let l = d.layers[0].id; + let mut ids = vec![]; + for (i, p) in paths.into_iter().enumerate() { + let id = d.alloc_id(); + d.insert(Some(l), i, Node::path(id, p, Appearance::default_art())).unwrap(); + ids.push(id); + } + (d, ids) + } + + fn open(pts: &[(f64, f64)]) -> PathData { + let mut b = BezPath::new(); + for (i, (x, y)) in pts.iter().enumerate() { + if i == 0 { b.move_to((*x, *y)) } else { b.line_to((*x, *y)) } + } + PathData::from_bezpath(&b) + } + + /// The red stretches shown, each as its two ends. + fn shown(t: &TrimTool, cx: &ToolContext) -> Vec<(Point, Point)> { + t.overlays(cx) + .iter() + .filter_map(|o| match o { + Overlay::Path { path, color, .. } if *color == HIGHLIGHT_RED => { + let segs: Vec = path.segments().collect(); + Some((segs.first()?.start(), segs.last()?.end())) + } + _ => None, + }) + .collect() + } + + fn hover(t: &mut TrimTool, cx: &ToolContext, x: f64, y: f64) -> Vec<(Point, Point)> { + assert!(t.pointer(cx, &ev(PointerKind::Move, x, y)).is_empty(), "hovering runs nothing"); + shown(t, cx) + } + + /// The two ends, either way round, are near (ax, ay) and (bx, by). + fn ends_are(e: (Point, Point), (ax, ay): (f64, f64), (bx, by): (f64, f64)) -> bool { + let near = |p: Point, x: f64, y: f64| p.distance(Point::new(x, y)) < 1e-3; + (near(e.0, ax, ay) && near(e.1, bx, by)) || (near(e.0, bx, by) && near(e.1, ax, ay)) + } + + /// What a click at (x, y) with the tool's reach removes, worked out as the command does. + fn click_removes(d: &Document, cx: &ToolContext, x: f64, y: f64) -> Vec { + let all = plan::plan(d, None, &Pick::At(Point::new(x, y), reach(cx)), Limits::COMMAND, &mut Stretches::default()).unwrap(); + all.into_iter().flat_map(|t| t.removed).map(|sp| PathData::single(sp).to_bezpath()).collect() + } + + fn red_paths(t: &TrimTool, cx: &ToolContext) -> Vec { + t.overlays(cx) + .into_iter() + .filter_map(|o| match o { + Overlay::Path { path, color, .. } if color == HIGHLIGHT_RED => Some(path), + _ => None, + }) + .collect() + } + + #[test] + fn hovering_shows_the_stretch_a_click_removes_on_a_line_across_an_ellipse() { + let ellipse = shapes::ellipse(Rect::new(100.0, 100.0, 300.0, 200.0)); + let (d, _) = doc_of(vec![ellipse, open(&[(50.0, 150.0), (350.0, 150.0)])]); + let (sel, p) = (Selection::default(), paint()); + let cx = cx(&d, &sel, &p); + let mut t = TrimTool::default(); + // The ellipse's upper half, between the two places the line crosses it. + let top = hover(&mut t, &cx, 200.0, 101.0); + assert!(matches!(top.as_slice(), [e] if ends_are(*e, (100.0, 150.0), (300.0, 150.0))), "{top:?}"); + assert_eq!(red_paths(&t, &cx), click_removes(&d, &cx, 200.0, 101.0)); + // The line's end outside the ellipse, and its middle inside it. + let end = hover(&mut t, &cx, 70.0, 150.0); + assert!(matches!(end.as_slice(), [e] if ends_are(*e, (50.0, 150.0), (100.0, 150.0))), "{end:?}"); + let middle = hover(&mut t, &cx, 200.0, 151.0); + assert!(matches!(middle.as_slice(), [e] if ends_are(*e, (100.0, 150.0), (300.0, 150.0))), "{middle:?}"); + assert_eq!(red_paths(&t, &cx), click_removes(&d, &cx, 200.0, 151.0)); + // Off every path: no highlight. + assert!(hover(&mut t, &cx, 400.0, 400.0).is_empty()); + assert!(t.overlays(&cx).is_empty()); + } + + #[test] + fn hovering_an_open_square_and_a_path_that_crosses_itself() { + // Three sides of a square, crossed by an upright through the top and bottom sides. + let square = open(&[(100.0, 100.0), (200.0, 100.0), (200.0, 200.0), (100.0, 200.0)]); + let (d, _) = doc_of(vec![square, open(&[(150.0, 50.0), (150.0, 250.0)])]); + let (sel, p) = (Selection::default(), paint()); + let cx = cx(&d, &sel, &p); + let mut t = TrimTool::default(); + let side = hover(&mut t, &cx, 201.0, 150.0); + assert!(matches!(side.as_slice(), [e] if ends_are(*e, (150.0, 100.0), (150.0, 200.0))), "{side:?}"); + assert_eq!(red_paths(&t, &cx), click_removes(&d, &cx, 201.0, 150.0)); + let corner = hover(&mut t, &cx, 110.0, 99.0); + assert!(matches!(corner.as_slice(), [e] if ends_are(*e, (100.0, 100.0), (150.0, 100.0))), "{corner:?}"); + + // A Z drawn back over itself: its first and last sides cross at (50, 50). + let (d, _) = doc_of(vec![open(&[(0.0, 0.0), (100.0, 100.0), (100.0, 0.0), (0.0, 100.0)])]); + let cx = crate::testutil::cx(&d, &sel, &p); + let mut t = TrimTool::default(); + let lobe = hover(&mut t, &cx, 101.0, 50.0); + assert!(matches!(lobe.as_slice(), [e] if ends_are(*e, (50.0, 50.0), (50.0, 50.0))), "{lobe:?}"); + assert_eq!(red_paths(&t, &cx), click_removes(&d, &cx, 101.0, 50.0)); + let tail = hover(&mut t, &cx, 10.0, 11.0); + assert!(matches!(tail.as_slice(), [e] if ends_are(*e, (0.0, 0.0), (50.0, 50.0))), "{tail:?}"); + } + + #[test] + fn hidden_and_locked_paths_show_nothing_and_a_changed_document_drops_the_highlight() { + let (mut d, ids) = doc_of(vec![open(&[(0.0, 100.0), (300.0, 100.0)]), open(&[(0.0, 200.0), (300.0, 200.0)])]); + d.node_mut(ids[0]).unwrap().visible = false; + d.node_mut(ids[1]).unwrap().locked = true; + let (sel, p) = (Selection::default(), paint()); + let mut cx = cx(&d, &sel, &p); + let mut t = TrimTool::default(); + assert!(hover(&mut t, &cx, 150.0, 100.0).is_empty(), "hidden"); + assert!(hover(&mut t, &cx, 150.0, 200.0).is_empty(), "locked"); + + let (d, _) = doc_of(vec![open(&[(0.0, 100.0), (300.0, 100.0)])]); + cx.doc = &d; + assert_eq!(hover(&mut t, &cx, 150.0, 100.0).len(), 1); + // Once the document changes, the highlight found before is not shown. + cx.revision = (0, 1); + assert!(shown(&t, &cx).is_empty()); + // Leaving the canvas clears it. + cx.revision = (0, 0); + t.hover_ended(&cx); + assert!(shown(&t, &cx).is_empty()); + } + + #[test] + fn in_isolation_mode_only_paths_inside_the_isolated_group_are_highlighted() { + // A group holding a line across, and an upright outside it that crosses the line. + let mut d = Document::new(500.0, 500.0); + let l = d.layers[0].id; + let across = Node::path(d.alloc_id(), open(&[(0.0, 100.0), (300.0, 100.0)]), Appearance::default_art()); + let group = Node::group(d.alloc_id(), vec![std::sync::Arc::new(across)]); + let g = group.id; + d.insert(Some(l), 0, group).unwrap(); + let upright = d.alloc_id(); + d.insert(Some(l), 1, Node::path(upright, open(&[(150.0, 0.0), (150.0, 300.0)]), Appearance::default_art())).unwrap(); + let (sel, p) = (Selection::default(), paint()); + let mut cx = cx(&d, &sel, &p); + let mut t = TrimTool::default(); + // Outside isolation mode the upright is highlighted; entering it drops that highlight. + assert_eq!(hover(&mut t, &cx, 151.0, 50.0).len(), 1); + cx.isolation = Some(g); + assert!(shown(&t, &cx).is_empty(), "found before the group was isolated"); + // The upright is not trimmed, and still crosses the line inside the group. + assert!(hover(&mut t, &cx, 151.0, 50.0).is_empty()); + let left = hover(&mut t, &cx, 50.0, 101.0); + assert!(matches!(left.as_slice(), [e] if ends_are(*e, (0.0, 100.0), (150.0, 100.0))), "{left:?}"); + } + + #[test] + fn a_path_whose_crossings_take_more_than_a_hover_may_shows_nothing_and_a_click_still_trims_it() { + // 2,500 segments crossing each other's boxes: about 3,125,000 pairs, more than a twentieth + // of the 60,000,000 a click may look at. + let row = open(&(0..=2500).map(|i| (i as f64 * 0.1, 100.0)).collect::>()); + let (d, _) = doc_of(vec![row]); + let (sel, p) = (Selection::default(), paint()); + let cx = cx(&d, &sel, &p); + let mut t = TrimTool::default(); + assert!(hover(&mut t, &cx, 125.0, 100.0).is_empty()); + assert_eq!(click_removes(&d, &cx, 125.0, 100.0).len(), 1); + let up = { + t.pointer(&cx, &ev(PointerKind::Down, 125.0, 100.0)); + t.pointer(&cx, &ev(PointerKind::Up, 125.0, 100.0)) + }; + assert_eq!(up, vec![Action::Exec(COMMAND.into(), json!({"at": [125.0, 100.0], "tolerance": 4.0}))]); + } + + #[test] + fn a_small_drag_shows_what_it_would_remove_and_a_large_one_shows_nothing() { + let ellipse = shapes::ellipse(Rect::new(100.0, 100.0, 300.0, 200.0)); + let (d, _) = doc_of(vec![ellipse, open(&[(50.0, 150.0), (350.0, 150.0)])]); + let (sel, p) = (Selection::default(), paint()); + let cx = cx(&d, &sel, &p); + let mut t = TrimTool::default(); + // A rectangle across the ellipse's top: its upper half. + t.pointer(&cx, &ev(PointerKind::Down, 190.0, 90.0)); + t.pointer(&cx, &ev(PointerKind::Drag, 210.0, 110.0)); + assert!(matches!(shown(&t, &cx).as_slice(), [e] if ends_are(*e, (100.0, 150.0), (300.0, 150.0)))); + t.pointer(&cx, &ev(PointerKind::Up, 210.0, 110.0)); + assert!(shown(&t, &cx).is_empty(), "the release drops the preview"); + // An Alt line through the ellipse's left side and the line's left end. + let alt = Mods { alt: true, ..Mods::default() }; + t.pointer(&cx, &ev(PointerKind::Down, 60.0, 140.0).with_mods(alt)); + t.pointer(&cx, &ev(PointerKind::Drag, 110.0, 160.0)); + assert_eq!(shown(&t, &cx).len(), 2, "the line's end and the ellipse's lower half"); + t.key(&cx, ToolKey::Escape, Mods::default()); + assert!(shown(&t, &cx).is_empty()); + + // A rectangle over more paths than the preview's limit shows nothing. + let many: Vec = (0..=PREVIEW.paths).map(|i| open(&[(0.0, i as f64 * 2.0), (100.0, i as f64 * 2.0)])).collect(); + let (d, _) = doc_of(many); + let cx = crate::testutil::cx(&d, &sel, &p); + t.pointer(&cx, &ev(PointerKind::Down, 50.0, -10.0)); + t.pointer(&cx, &ev(PointerKind::Drag, 60.0, 500.0)); + assert!(shown(&t, &cx).is_empty()); + assert!(matches!(t.overlays(&cx).as_slice(), [Overlay::Marquee(_)])); + // What lies under a still pointer changes when the view pans: the canvas hovers again. + assert!(t.wants_rehover()); + } + + #[test] + fn crossings_kept_from_earlier_picks_still_count_against_the_budget() { + // Three rows of 7,000 segments, apart: each costs 24,500,000 pairs of the 60,000,000 a + // pick may look at, so a rectangle over all three is refused. + let row = |y: f64| open(&(0..=7000).map(|i| (i as f64 * 0.01, y)).collect::>()); + let (d, _) = doc_of(vec![row(0.0), row(10.0), row(20.0)]); + let rect = Pick::Rect(Rect::new(-1.0, -1.0, 80.0, 21.0)); + assert_eq!(plan::plan(&d, None, &rect, Limits::COMMAND, &mut Stretches::default()), Err(plan::TooMuch::Crossings)); + // Hovering two of them keeps their crossings; the rectangle is refused all the same. + let mut kept = Stretches::default(); + for y in [0.0, 10.0] { + assert_eq!(plan::plan(&d, None, &Pick::At(Point::new(35.0, y), 1.0), Limits::COMMAND, &mut kept).map(|t| t.len()), Ok(1)); + } + assert_eq!(plan::plan(&d, None, &rect, Limits::COMMAND, &mut kept), Err(plan::TooMuch::Crossings)); + // A rectangle over two is not. + let two = Pick::Rect(Rect::new(-1.0, -1.0, 80.0, 11.0)); + assert_eq!(plan::plan(&d, None, &two, Limits::COMMAND, &mut kept).map(|t| t.len()), Ok(2)); + + // A drag whose crossings take too much shows nothing until the next press, even over less. + // Rows of 1,500 segments cost 1,125,000 pairs each, so a preview has room for two. + let row = |y: f64| open(&(0..=1500).map(|i| (i as f64 * 0.05, y)).collect::>()); + let (d, _) = doc_of(vec![row(0.0), row(10.0), row(20.0)]); + let (sel, p) = (Selection::default(), paint()); + let cx = cx(&d, &sel, &p); + let mut t = TrimTool::default(); + t.pointer(&cx, &ev(PointerKind::Down, -1.0, -1.0)); + t.pointer(&cx, &ev(PointerKind::Drag, 80.0, 21.0)); + assert!(shown(&t, &cx).is_empty()); + t.pointer(&cx, &ev(PointerKind::Drag, 80.0, 5.0)); + assert!(shown(&t, &cx).is_empty()); + t.pointer(&cx, &ev(PointerKind::Up, 80.0, 5.0)); + t.pointer(&cx, &ev(PointerKind::Down, -1.0, -1.0)); + t.pointer(&cx, &ev(PointerKind::Drag, 80.0, 5.0)); + assert_eq!(shown(&t, &cx).len(), 1); + } } diff --git a/crates/tools/src/addons/trim/plan.rs b/crates/tools/src/addons/trim/plan.rs new file mode 100644 index 0000000000..d88dbec7b8 --- /dev/null +++ b/crates/tools/src/addons/trim/plan.rs @@ -0,0 +1,351 @@ +//! What Trim at Crossings removes: the stretch at a point, every stretch a rectangle touches, or +//! every stretch a line through some points crosses, on every path that can be edited. The command +//! `addon.pathtools.trim` applies it, and the tool shows it before a click or while a drag stays +//! small, so the two always agree. + +use std::collections::{HashMap, HashSet}; + +use vectorcraft_doc::{Document, NodeId, NodeKind}; +use vectorcraft_geom::kurbo::{Line, PathSeg}; +use vectorcraft_geom::{PathData, Point, Rect, SubPath, hit}; +use vectorcraft_pathops::addons::pathtools as pt; + +/// What picks the stretches to remove. +#[derive(Clone, Debug, PartialEq)] +pub enum Pick { + /// The stretch of the nearest path within the tolerance (pt) of the point. + At(Point, f64), + /// Every stretch the rectangle touches. + Rect(Rect), + /// Every stretch the line through the points crosses, with the points' bounds. + Line(Vec, Rect), +} + +/// Why a pick could not be worked out. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum TooMuch { + /// Finding where the paths cross took more than its budget. + Crossings, + /// The line has too many pieces, or passes too many segments, to check. + Line, + /// The rectangle or line reaches more paths than the limit. + Paths, +} + +impl TooMuch { + /// The error message the command reports. + pub fn message(self) -> &'static str { + match self { + TooMuch::Crossings => "the paths are too many or too tangled to find where they cross", + TooMuch::Line => "the line is too long, or the paths it passes too many, to check", + TooMuch::Paths => "the rectangle or line reaches too many paths to check", + } + } +} + +/// How much work one pick may take. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Limits { + /// Most paths a rectangle or a line may reach. + pub paths: usize, + /// Most box tests between the paths to trim and the other paths. + pub box_tests: usize, + /// Most box tests between a line's pieces and the paths' segments. + pub line_tests: usize, + /// The crossing work of every path the pick trims together. + pub crossings: pt::Work, +} + +impl Limits { + /// The command's limits. + pub const COMMAND: Limits = Limits { paths: usize::MAX, box_tests: 50_000_000, line_tests: 60_000_000, crossings: pt::Work::share(1) }; +} + +/// One path the pick trims. +#[derive(Clone, Debug, PartialEq)] +pub struct Trimmed { + pub id: NodeId, + /// What takes its place: a path per piece for a path of one subpath, one path holding the + /// pieces for a path of more, nothing when no piece is left. + pub pieces: Vec, + /// The stretches removed, each an open subpath. + pub removed: Vec, + /// How many stretches were removed. + pub count: usize, +} + +/// The stretches of each subpath of a path between the places it is crossed, for the document as +/// it was when they were found, with the crossing work finding them took. A pick fills it with the +/// paths it looks at; one kept between picks on an unchanged document saves finding the same +/// crossings again, and a pick still draws their work from its budget, so it fails where a pick +/// without them would. It also keeps the paths whose crossings could not be found within the whole +/// crossing work of the picks' limits (`whole`), which no pick with those limits can find either. +#[derive(Default)] +pub struct Stretches { + by_path: HashMap>, pt::Work)>, + too_much: HashSet, + whole: Option, +} + +impl Stretches { + pub fn clear(&mut self) { + self.by_path.clear(); + self.too_much.clear(); + self.whole = None; + } +} + +/// A path that takes part: its id, geometry and control-point box. +type Part<'a> = (NodeId, &'a PathData, Rect); + +/// The paths that take part, bottom to top: the ones that can be edited, without guides and +/// clipping paths. The clipping path of a clip group or a clipped layer is left out whole, the +/// members of a compound clipping path included. +fn parts(d: &Document) -> Vec> { + let editable = d.editable(); + let mut masks = HashSet::new(); + d.walk(|n| { + if n.clips() + && let Some(first) = n.children().and_then(|c| c.first()) + { + first.walk(&mut |m| { + masks.insert(m.id); + }); + } + }); + let mut out = vec![]; + d.walk(|n| { + if let NodeKind::Path { path, guide: false, clipping: false, .. } = &n.kind + && !masks.contains(&n.id) + && let Some(b) = path.control_bounds() + && editable(n.id) + { + out.push((n.id, path, b)); + } + }); + out +} + +/// Does the line through `pts` cross `sp`? Each piece of the line compared costs one of `budget`; +/// `None` once it is spent. +fn crossed_by_line(sp: &SubPath, pts: &[Point], budget: &mut usize) -> Option { + let segs: Vec<_> = (0..sp.segment_count()) + .map(|i| { + let c = sp.segment(i); + (c, Rect::from_points(c.p0, c.p1).union_pt(c.p2).union_pt(c.p3).inflate(1e-9, 1e-9)) + }) + .collect(); + let Some(reach) = segs.iter().map(|s| s.1).reduce(|a, b| a.union(b)) else { return Some(false) }; + for w in pts.windows(2) { + let [a, b] = w else { continue }; + let piece = Rect::from_points(*a, *b); + *budget = budget.checked_sub(1)?; + if !reach.overlaps(piece) { + continue; + } + for (c, r) in &segs { + *budget = budget.checked_sub(1)?; + if r.overlaps(piece) && !PathSeg::Cubic(*c).intersect_line(Line::new(*a, *b)).is_empty() { + return Some(true); + } + } + } + Some(false) +} + +/// Does the rectangle or line of `pick` touch the outline of `piece`? Never for `Pick::At`. +fn touches(piece: &SubPath, pick: &Pick, budget: &mut usize) -> Result { + match pick { + Pick::At(..) => Ok(false), + Pick::Rect(r) => Ok(hit::intersects_rect(&PathData::single(piece.clone()), *r)), + Pick::Line(pts, _) => crossed_by_line(piece, pts, budget).ok_or(TooMuch::Line), + } +} + +/// What a trim leaves of a path: its subpaths, the stretches removed and how many. +type Cut = (Vec, Vec, usize); + +/// What trimming `path` by `pick` leaves (`on`: the place of `Pick::At` on it): its subpaths then, +/// the stretches removed and how many. `None` when none goes. A rectangle or a line that touches +/// no part of `path` leaves it out before its crossings are looked for. +#[allow(clippy::too_many_arguments)] +fn trimmed<'a>( + id: NodeId, + path: &PathData, + others: &dyn Fn() -> Vec<&'a PathData>, + pick: &Pick, + on: Option, + budget: &mut usize, + work: &mut pt::Work, + stretches: &mut Stretches, +) -> Result, TooMuch> { + let reached = match pick { + Pick::At(..) => true, + Pick::Rect(r) => hit::intersects_rect(path, *r), + Pick::Line(..) => { + let mut any = false; + for sp in &path.subpaths { + if touches(sp, pick, budget)? { + any = true; + break; + } + } + any + } + }; + if !reached { + return Ok(None); + } + let all = match stretches.by_path.get(&id) { + Some((all, cost)) => { + work.draw(*cost).ok_or(TooMuch::Crossings)?; + all.clone() + } + None if stretches.too_much.contains(&id) => return Err(TooMuch::Crossings), + None => { + let before = *work; + let Some(places) = pt::crossings_on_within(path, &others(), work) else { + if Some(before) == stretches.whole { + stretches.too_much.insert(id); + } + return Err(TooMuch::Crossings); + }; + let all: Vec> = path + .subpaths + .iter() + .enumerate() + .map(|(si, sp)| { + // The places come in subpath order: this subpath's are one run of them. + let run = places.partition_point(|p| p.0 < si)..places.partition_point(|p| p.0 <= si); + let here: Vec<(usize, f64)> = places.get(run).unwrap_or_default().iter().map(|&(_, seg, t)| (seg, t)).collect(); + pt::spans(sp, &here) + }) + .collect(); + stretches.by_path.insert(id, (all.clone(), work.spent_since(before))); + all + } + }; + let mut subs = vec![]; + let mut removed = vec![]; + let mut count = 0; + for ((si, sp), spans) in path.subpaths.iter().enumerate().zip(&all) { + let marks: Vec = match pick { + Pick::At(..) => { + let at = on.filter(|(s, ..)| *s == si).and_then(|(_, seg, t)| pt::span_at(sp, spans, seg, t)); + (0..spans.len()).map(|i| Some(i) == at).collect() + } + _ => spans.iter().map(|s| touches(&pt::slice(sp, *s), pick, budget)).collect::>()?, + }; + match pt::without_spans(sp, spans, &marks) { + Some(pieces) => { + count += marks.iter().filter(|m| **m).count(); + removed.extend(spans.iter().zip(&marks).filter(|(_, m)| **m).map(|(s, _)| pt::slice(sp, *s)).filter(|p| p.anchors.len() >= 2)); + subs.extend(pieces); + } + None => subs.push(sp.clone()), + } + } + Ok((count > 0).then_some((subs, removed, count))) +} + +/// What `pick` removes from the document's paths, bottom to top. With `isolation` (the isolated +/// object in isolation mode, see [`crate::ordinary_isolation`]) only paths inside it are trimmed; +/// paths outside it still cross them. `stretches` must hold only what it learned from this +/// document as it is. +pub fn plan(d: &Document, isolation: Option, pick: &Pick, limits: Limits, stretches: &mut Stretches) -> Result, TooMuch> { + let parts = parts(d); + let in_scope = |id: NodeId| isolation.is_none_or(|r| id == r || d.ancestry(id).is_some_and(|a| a.contains(&r))); + // The paths to trim, each with the place `at` falls on. + let targets: Vec<(usize, Option)> = match pick { + Pick::At(at, tolerance) => { + let mut best: Option<(usize, pt::Place, f64)> = None; + for (i, (id, path, b)) in parts.iter().enumerate() { + if !in_scope(*id) { + continue; + } + let b = b.inflate(*tolerance, *tolerance); + if !(b.x0 <= at.x && at.x <= b.x1 && b.y0 <= at.y && at.y <= b.y1) { + continue; + } + // Of paths equally near, the one on top. + if let Some((si, seg, t, _, dist)) = path.nearest(*at) + && dist <= *tolerance + && best.is_none_or(|b| dist <= b.2) + { + best = Some((i, (si, seg, t), dist)); + } + } + best.map(|(i, on, _)| (i, Some(on))).into_iter().collect() + } + Pick::Rect(r) | Pick::Line(_, r) => { + parts.iter().enumerate().filter(|(_, (id, _, b))| in_scope(*id) && b.overlaps(*r)).map(|(i, _)| (i, None)).collect() + } + }; + // Each path to trim has its box tested against every other path's. + if targets.len() > limits.paths || targets.len().saturating_mul(parts.len()) > limits.box_tests { + return Err(TooMuch::Paths); + } + let mut out = vec![]; + let mut budget = limits.line_tests; + // A path that failed within a whole budget of another size may fit in this one. + if stretches.whole != Some(limits.crossings) { + stretches.too_much.clear(); + stretches.whole = Some(limits.crossings); + } + // One budget of crossing work for every path the pick trims. + let mut work = limits.crossings; + for (i, on) in targets { + let Some((id, path, b)) = parts.get(i) else { continue }; + let reach = b.inflate(1e-3, 1e-3); + let others = || parts.iter().enumerate().filter(|(j, (_, _, ob))| *j != i && reach.overlaps(*ob)).map(|(_, (_, o, _))| *o).collect(); + let Some((subs, removed, count)) = trimmed(*id, path, &others, pick, on, &mut budget, &mut work, stretches)? else { continue }; + // A path of one subpath becomes a path per piece; the pieces of one with more stay its subpaths. + let pieces = match (path.subpaths.len(), subs.is_empty()) { + (_, true) => vec![], + (1, false) => subs.into_iter().map(PathData::single).collect(), + _ => vec![PathData::new(subs)], + }; + out.push(Trimmed { id: *id, pieces, removed, count }); + } + Ok(out) +} + +#[cfg(test)] +mod tests { + use super::*; + use vectorcraft_doc::{Appearance, Node}; + + fn row(y: f64, segments: usize) -> PathData { + PathData::single(SubPath::polyline(&(0..=segments).map(|i| Point::new(i as f64 * 0.01, y)).collect::>(), false)) + } + + #[test] + fn a_path_too_large_for_a_whole_budget_is_not_searched_again_and_one_cut_short_by_a_shared_budget_is() { + let mut d = Document::new(500.0, 500.0); + let l = d.layers[0].id; + let mut ids = vec![]; + for (i, p) in [row(0.0, 7000), row(10.0, 7000), row(20.0, 7000), row(30.0, 10_001)].into_iter().enumerate() { + let id = d.alloc_id(); + d.insert(Some(l), i, Node::path(id, p, Appearance::default_art())).unwrap(); + ids.push(id); + } + let mut kept = Stretches::default(); + // More segments than a crossing search takes: no budget finds its crossings. + assert_eq!(plan(&d, None, &Pick::At(Point::new(50.0, 30.0), 1.0), Limits::COMMAND, &mut kept), Err(TooMuch::Crossings)); + assert!(kept.too_much.contains(&ids[3])); + // The third of three rows runs out of the budget the rectangle shares; alone it has enough. + let rect = Pick::Rect(Rect::new(-1.0, -1.0, 80.0, 21.0)); + assert_eq!(plan(&d, None, &rect, Limits::COMMAND, &mut kept), Err(TooMuch::Crossings)); + assert!(!kept.too_much.contains(&ids[2])); + assert_eq!(plan(&d, None, &Pick::At(Point::new(35.0, 20.0), 1.0), Limits::COMMAND, &mut kept).map(|t| t.len()), Ok(1)); + // A row is too much for a twentieth of the budget, and is remembered only for picks with it. + let small = Limits { crossings: pt::Work::share(20), ..Limits::COMMAND }; + let mut kept = Stretches::default(); + assert_eq!(plan(&d, None, &Pick::At(Point::new(35.0, 10.0), 1.0), small, &mut kept), Err(TooMuch::Crossings)); + assert!(kept.too_much.contains(&ids[1])); + assert_eq!(plan(&d, None, &Pick::At(Point::new(35.0, 10.0), 1.0), Limits::COMMAND, &mut kept).map(|t| t.len()), Ok(1)); + assert!(!kept.too_much.contains(&ids[1])); + kept.clear(); + assert!(kept.too_much.is_empty() && kept.by_path.is_empty()); + } +} diff --git a/crates/tools/src/context.rs b/crates/tools/src/context.rs index 1e8f57ffc9..0e7280ae9a 100644 --- a/crates/tools/src/context.rs +++ b/crates/tools/src/context.rs @@ -164,6 +164,17 @@ pub enum PixelOp { Scaling, } +/// The isolated group, layer or object in isolation mode, of `isolation` (the document's isolated +/// node). Pattern editing mode, opacity mask editing and symbol editing mode isolate their own +/// layer, which does not count here; an object isolated inside them counts. +pub fn ordinary_isolation(doc: &Document, isolation: Option) -> Option { + isolation.filter(|l| { + !doc.pattern_edit.as_ref().is_some_and(|e| e.layer == *l) + && !doc.mask_edit.as_ref().is_some_and(|e| e.layer == *l) + && !doc.symbol_edit.as_ref().is_some_and(|e| e.layer == *l) + }) +} + /// Read-only context a tool sees. pub struct ToolContext<'a> { pub doc: &'a Document, diff --git a/crates/tools/src/lib.rs b/crates/tools/src/lib.rs index 70f6422055..9b26d1381d 100644 --- a/crates/tools/src/lib.rs +++ b/crates/tools/src/lib.rs @@ -59,7 +59,7 @@ mod cursor; mod input; mod readout; -pub use context::{GlyphSnap, MarqueeMode, PaintDefaults, PixelOp, PixelSnap, ScreenFrame, ToolContext}; +pub use context::{GlyphSnap, MarqueeMode, PaintDefaults, PixelOp, PixelSnap, ScreenFrame, ToolContext, ordinary_isolation}; pub use cursor::Cursor; pub use input::{Action, Mods, PenPose, PointerEvent, PointerKind, ToolKey}; pub use readout::Readout; diff --git a/docs/mcp.md b/docs/mcp.md index 9d7f7d6d17..77c6af7afc 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -12149,7 +12149,14 @@ Tools: screen pixels of the pointer. A drag draws a rectangle and runs it with `rect` on release; once the pointer has gone 3 screen pixels from the press, the gesture stays a drag even when it ends near the press. An Alt-drag draws a freehand line and runs it with `points` on release; a line of more than 65,536 points is dropped. Nothing changes - while dragging, and Escape during a drag removes nothing. The tool has no options. + while dragging, and Escape during a drag removes nothing. Hovering draws in red the stretch a click there would + remove. It draws nothing when a click would remove nothing, or when finding the path's crossings takes more than a + twentieth of the work a click may do. A drag draws in red every stretch its release would remove while it reaches at + most 32 paths, the paths it reaches times the paths that can be edited come to at most 10,000,000, and a freehand + line has at most 4,096 points; past those limits it draws none. Once finding the crossings takes more than a + twentieth of the work a release may do, or checking the line against the paths' segments takes more than 1,000,000 + box tests, the drag draws none until the next press. A click or a release still removes what it reaches. The tool + has no options. Commands: diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 6b9b0c438a..6ab8b6104b 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -2503,7 +2503,7 @@ A VectorCraft addition, not a feature of the reference app, so no area score mov ## 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 (kept out of the shipped toolbars, listed in the All Tools drawer, 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}`. Not yet: a highlight of the stretch under the pointer before the click, and 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. +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 (kept out of the shipped toolbars, listed in the All Tools drawer, 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. ## Document Tools add-on: Save a Timestamped Copy (2026-11-01) diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 35d29727f5..6f2b7ab8c0 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -485,7 +485,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 selects its eight tools (Anchor Eraser Brush, Extend Path, Measure & Inspect, Parametric Shape, Corner Tool, Slide Anchor Along Path, Shared Edge Merge Tool, Trim at Crossings Tool), which the All Tools drawer lists under their own heading but neither toolbar shows as shipped, opens the Anchor Inspector panel (the selected anchor's X/Y and handle lengths and angles as fields; Make Smooth, Make Corner, Equalize Handles, Remove Points Keep Shape, Add Points, the three ways to close) and the Parametric Shape panel (kind, count, W/H, rotation, the kind's own values and corner radius of the selected parametric shape, or of the tool's next one), and runs Add Points at / Split at Crossings and Convert to Parametric Shape; the Parametric Shape Tool draws ten re-editable kinds from the centre (↑/↓ and ←/→ change their numbers while dragging) and edits a selected one with handles; the Corner Tool cuts editable corners on any path (hover shows the anchor, a click uses its radius and kind, a drag sizes the corner, Shift whole values; a corner's marker selects it and loads its values, drags to resize, to 0 or double-clicked removes it; never past what fits; Alt-marquee cuts every anchor inside) with a Corners section in the Anchor Inspector (radius, kind, selected count, Apply to Selected Anchors); Slide Anchor Along Path drags an anchor along its curve with the segments beside it refitted, Shift snapping where the tangent is a multiple of 45°; the Shared Edge Merge Tool shows, over two paths touching at two coincident anchors, the two stretches and the edge merging them, a click merges them (half way; Shift the upper path, Alt the lower), and near anchors meet or an anchor one path lacks is added to match (Shift+Alt asks for this inside a stretch), with a Shared Edges section in the Anchor Inspector (brush diameter, coincidence 0 to 3 pt, Keep Shared Points Together, which takes coincident anchors along with the add-on's own anchor moves); a double-click on the brush or Extend Path tool opens its options | done | `addon.pathtools.*`, `crates/tools/src/addons/`, `crates/ui-egui/src/addons/pathtools.rs`, `crates/ui-egui/src/addons/pathtools/` 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 › 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 (in the All Tools drawer under the add-on's heading, in neither toolbar as shipped, no shortcut) 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 every stretch its rectangle touches, an Alt-drag every stretch its freehand line crosses; one undo step each; Escape during a drag removes nothing | 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 › Trim at Crossings Tool (in the All Tools drawer under the add-on's heading, in neither toolbar as shipped, no shortcut) 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 every stretch its rectangle touches, an Alt-drag 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 › 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): Effect › Path Effects lists its live effects (Dashes to Geometry, Add Anchors, Extend Path, Close Path, Smooth Anchors, Retract Handles, Reverse Direction, Simplify Anchors, Split at Anchors), each with the effect dialog's live Preview except Reverse Direction, which has no options, and listed in the Appearance panel like any effect | done | `addon.path.*`, `crates/effects/src/addons/path.rs`, `crates/ui-egui/src/addons/pathtools.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 selects its four tools (Anchor Eraser Brush, Extend Path, Measure & Inspect, Parametric Shape), which the All Tools drawer lists under their own heading but neither toolbar shows as shipped, opens the Anchor Inspector panel (the selected anchor's X/Y and handle lengths and angles as fields; Make Smooth, Make Corner, Equalize Handles, Remove Points Keep Shape, Add Points, the three ways to close) and the Parametric Shape panel (kind, count, W/H, rotation, the kind's own values and corner radius of the selected parametric shape, or of the tool's next one), and runs Add Points at / Split at Crossings and Convert to Parametric Shape; the Parametric Shape Tool draws ten re-editable kinds from the centre (↑/↓ and ←/→ change their numbers while dragging) and edits a selected one with handles; a double-click on the brush or Extend Path tool opens its options | done | `addon.pathtools.*`, `crates/tools/src/addons/`, `crates/ui-egui/src/addons/pathtools.rs`, `crates/ui-egui/src/addons/pathtools/shape.rs` and their tests; not a feature of the reference app, so it is not scored |