From f428b58d6575d3ed4e8bb3a0065fdaf71502e6da Mon Sep 17 00:00:00 2001 From: ncic <1848265+ncic@users.noreply.github.com> Date: Mon, 26 Oct 2026 04:27:34 +0100 Subject: [PATCH] Pencil: Edit Selected Paths follows a stroke lifted away from the path, carves, loops and closes (#3793) A Pencil or Paintbrush stroke that starts on a selected path and is lifted away from it drew a new path, and a stroke back onto the path joined it with a straight piece at each end. - A stroke that starts on the path and is lifted farther than Edit selected paths within from it takes the path with it: a closed path opens where the stroke starts and ends where the stroke does; an open path is cut there and drops the part the stroke heads along (one the stroke leaves nearly square to it, more than 70 degrees from its direction, drops its shorter part). From one of its ends it drops nothing. - A stroke that ends back on the path (within Edit selected paths within) replaces the section between. On a closed path that is the way round that lies nearer the stroke, so carving across a shape cuts off the part the stroke crosses and drawing round outside it replaces the part it follows. On an open path, a stroke over its open ends closes it along the stroke. - A stroke that returns to where it started adds a loop there. - The stroke's ends bend smoothly onto the path over Edit selected paths within, instead of meeting it with a straight piece. - A shape's holes keep their winding, so they stay holes. Tests: tests_draw2 covers each case (opening a closed shape, cutting an open path, the loop, the side a closed redraw takes, carving, closing over open ends, the smooth join, a shape with a hole); bend_tests checks the end bending. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/draw2.rs | 316 +++++++++++++++++++++++++++---- crates/engine/src/tests_draw2.rs | 254 ++++++++++++++++++++++++- 2 files changed, 533 insertions(+), 37 deletions(-) diff --git a/crates/engine/src/cmd/draw2.rs b/crates/engine/src/cmd/draw2.rs index 8a8e7b8b17..d7db9facb0 100644 --- a/crates/engine/src/cmd/draw2.rs +++ b/crates/engine/src/cmd/draw2.rs @@ -27,7 +27,7 @@ pub fn specs() -> Vec { "Pencil", [], None, - "{points: [[x,y]…] or [[x,y,pressure]…] (pen pressure 0..1: the stroke keeps it, for Calligraphic brushes with Pressure variation; a point without one presses fully), fidelity?: pt (1.5), fit?: bool (true; false: the points are joined by straight segments, as the Pencil previews a stroke with Live curve fitting off), closed?, style?: \"pencil\"|\"brush\", fill?: bool, keepSelected?: bool (true: the drawn or continued path is selected; false: it is not, and the rest of the selection stays), extend?: {id, end: \"start\"|\"end\"}, connect?: {id, end: \"start\"|\"end\"}, redraw?: {id, within?: pt (12)}} fit a freehand stroke → {id}. extend continues the path from that end; with connect, the stroke ends on that end of another path's last open subpath and joins it on, in one path with the extended path's appearance (the other path is removed when nothing of it is left); redraw (Edit Selected Paths) replaces the section of the path between where the stroke starts and ends, each within `within` of one subpath (the shorter way round a closed one), and draws a new path when the stroke doesn't end on it", + "{points: [[x,y]…] or [[x,y,pressure]…] (pen pressure 0..1: the stroke keeps it, for Calligraphic brushes with Pressure variation; a point without one presses fully), fidelity?: pt (1.5), fit?: bool (true; false: the points are joined by straight segments, as the Pencil previews a stroke with Live curve fitting off), closed?, style?: \"pencil\"|\"brush\", fill?: bool, keepSelected?: bool (true: the drawn or continued path is selected; false: it is not, and the rest of the selection stays), extend?: {id, end: \"start\"|\"end\"}, connect?: {id, end: \"start\"|\"end\"}, redraw?: {id, within?: pt (12)}} fit a freehand stroke → {id}. extend continues the path from that end; with connect, the stroke ends on that end of another path's last open subpath and joins it on, in one path with the extended path's appearance (the other path is removed when nothing of it is left); redraw (Edit Selected Paths) replaces the section of the path between where the stroke starts and ends, each within `within` of one subpath (the way round a closed one, or the part of an open one, that lies nearer the stroke; an open one's ends beyond them when the stroke lies along those, which closes it), the stroke's ends bent smoothly onto the path; a stroke that starts on it and returns to the same point adds a loop there, and one lifted farther than `within` from it takes the path with it: a closed subpath opens where the stroke starts, an open one is cut there and drops the part the stroke heads along, and the path ends where the stroke does", has_doc, freehand ), @@ -594,13 +594,245 @@ fn stroke_subpath(pts: &[Point], tol: Option, closed: bool) -> SubPath { } } -/// Pencil's Edit Selected Paths in the middle of a path: a stroke from one point of a subpath of -/// `pd` to another, each within `within` of it, replaces the section between them (the shorter -/// way round a closed subpath) with the stroke fitted at `tol` (with no `tol`, unfitted). The -/// subpath's index and its new shape; None when the stroke doesn't start and end on the same -/// subpath, or meets it once. +/// The anchor of `sp` at the point of it nearest to `q`: the one there, else a new one, and +/// whether it was added. +fn anchor_at(sp: &mut SubPath, q: Point) -> Option<(usize, bool)> { + let (_, seg, t, _, _) = PathData::single(sp.clone()).nearest(q)?; + let n = sp.anchors.len(); + if n == 0 { + return None; + } + Some(if t <= 1e-6 { + (seg % n, false) + } else if t >= 1.0 - 1e-6 { + ((seg + 1) % n, false) + } else { + (sp.insert_anchor(seg, t), true) + }) +} + +/// The direction `sp` leaves anchor `k` going forward (towards the next anchor). +fn forward_at(sp: &SubPath, k: usize) -> Option { + let a = sp.anchors.get(k)?; + let n = sp.anchors.len(); + let next = if sp.closed || k + 1 < n { sp.anchors.get((k + 1) % n) } else { None }; + let toward = if a.h_out != a.p { + a.h_out + } else if let Some(b) = next { + if b.h_in != b.p { b.h_in } else { b.p } + } else { + // The last anchor of an open subpath: forward goes on the way it arrived. + let prev = sp.anchors.get(k.checked_sub(1)?)?; + return Some(a.p - if a.h_in != a.p { a.h_in } else { prev.p }); + }; + let v = toward - a.p; + (v.hypot() > 1e-9).then_some(v) +} + +/// The direction stroke `pts` leaves its first point: towards its first point farther than +/// `reach` from it, or its last point. +fn heading(pts: &[Point], reach: f64) -> Option { + let (&p0, rest) = pts.split_first()?; + let to = rest.iter().find(|q| q.distance(p0) > reach).or(rest.last())?; + let v = *to - p0; + (v.hypot() > 1e-9).then_some(v) +} + +/// `stroke` (its first point moved onto anchor `a` of the path it leaves) fitted at `tol`: its +/// anchors, the first of which is at `a`. +fn fit_from(a: Point, pts: &[Point], tol: Option, reach: f64) -> Vec { + let mut stroke = pts.to_vec(); + bend_ends(&mut stroke, Some(a), None, reach); + stroke_subpath(&stroke, tol, false).anchors +} + +/// Bend the ends of `stroke` onto `a` (its start) and `b` (its end): each end moves all the way +/// and the stroke behind it less and less, to not at all `reach` along it (Edit selected paths +/// within), so a stroke that starts or ends near the path joins it smoothly instead of with a +/// straight piece. +fn bend_ends(stroke: &mut [Point], a: Option, b: Option, reach: f64) { + let bend = |pts: &mut dyn Iterator, to: Point| { + let mut pts = pts.peekable(); + let Some(first) = pts.peek().map(|p| **p) else { return }; + let shift = to - first; + let (mut along, mut prev) = (0.0, first); + for p in pts { + along += prev.distance(*p); + prev = *p; + let w = if reach > 0.0 { + 1.0 - along / reach + } else if along == 0.0 { + 1.0 + } else { + 0.0 + }; + if w <= 0.0 { + break; + } + *p += shift * w; + } + }; + if let Some(a) = a { + bend(&mut stroke.iter_mut(), a); + } + if let Some(b) = b { + bend(&mut stroke.iter_mut().rev(), b); + } +} + +/// Pencil's Edit Selected Paths for a stroke that starts on a subpath of `pd` (within `within` of +/// it) and ends away from it (#2850 follow-up): the path follows the stroke and ends where the +/// stroke does. A closed subpath opens where the stroke starts and keeps its whole outline, run +/// so that it arrives there heading the stroke's way. An open subpath is cut there and keeps the +/// part behind the stroke: the part the stroke heads along is dropped. The subpath's index and its +/// new shape; None when the stroke doesn't start on `pd`. +fn redraw_extend(pd: &PathData, pts: &[Point], tol: Option, within: f64) -> Option<(usize, SubPath)> { + let first = *pts.first()?; + let (si, _, _, _, d) = pd.nearest(first)?; + if d > within || pts.len() < 2 { + return None; + } + let mut sp = pd.subpaths.get(si)?.clone(); + if sp.anchors.len() < 2 { + return None; + } + let (mut k, _) = anchor_at(&mut sp, first)?; + let last = sp.anchors.len() - 1; + // Run the subpath so the stroke goes on from `k` forward; the result runs the subpath's own way + // again below, so a shape's holes stay holes under the non-zero fill rule. A closed subpath + // arrives at `k` heading the stroke's way. An open one drops the part the stroke heads along; + // one it leaves nearly square to it (more than 70° from its direction) drops its shorter + // part, never most of the path. From one of its ends it drops nothing. + let dir = heading(pts, within.max(tol.unwrap_or(0.0) * 2.0))?; + let cos = forward_at(&sp, k).map_or(0.0, |f| f.dot(dir) / (f.hypot() * dir.hypot()).max(1e-12)); + let flipped = if sp.closed { + cos < 0.0 + } else if k == 0 || k == last { + k == 0 + } else if cos.abs() >= 0.34 { + cos < 0.0 + } else { + let len = |i: usize, j: usize| (i..j).map(|s| kurbo::ParamCurveArclen::arclen(&sp.segment(s), 0.01)).sum::(); + len(0, k) < len(k, last) + }; + if flipped { + sp.reverse(); + k = sp.anchors.len().checked_sub(1 + k)?; + } + let at = *sp.anchors.get(k)?; + let mut anchors: Vec = if sp.closed { + // From `k` all the way round back to `k`: the shape opens there. + let mut v: Vec = sp.anchors.get(k..)?.iter().chain(sp.anchors.get(..k)?).copied().collect(); + if let Some(a0) = v.first_mut() { + *a0 = Anchor::with_handles(a0.p, a0.p, a0.h_out); + } + v.push(at); + v + } else { + sp.anchors.get(..=k)?.to_vec() + }; + let fit = fit_from(at.p, pts, tol, within); + let (f0, rest) = fit.split_first()?; + if let Some(a) = anchors.last_mut() { + *a = Anchor::with_handles(a.p, a.h_in, f0.h_out); + } + anchors.extend_from_slice(rest); + let mut out = SubPath::new(anchors, false); + if flipped { + out.reverse(); + } + Some((si, out)) +} + +/// A stroke that leaves anchor `k` of `sp` and comes back to it: the stroke is inserted there as a +/// loop out of the path (#2850 follow-up). +fn redraw_loop(mut sp: SubPath, k: usize, pts: &[Point], tol: Option, within: f64) -> Option { + let at = *sp.anchors.get(k)?; + let mut stroke = pts.to_vec(); + bend_ends(&mut stroke, Some(at.p), Some(at.p), within); + let fit = stroke_subpath(&stroke, tol, false).anchors; + let (Some(f0), Some(fl)) = (fit.first().copied(), fit.last().copied()) else { return None }; + if fit.len() < 3 { + return None; + } + let inner = fit.get(1..fit.len() - 1)?; + let mut anchors = sp.anchors.get(..k)?.to_vec(); + anchors.push(Anchor::with_handles(at.p, at.h_in, f0.h_out)); + anchors.extend_from_slice(inner); + anchors.push(Anchor::with_handles(at.p, fl.h_in, at.h_out)); + anchors.extend_from_slice(sp.anchors.get(k + 1..)?); + sp.anchors = anchors; + Some(sp) +} + +/// How far, on average, the run of `sp`'s segments from anchor `i` forward to anchor `j` lies from +/// stroke `pts` (sampled along both; the stroke thinned to at most 200 points). +fn run_distance(sp: &SubPath, i: usize, j: usize, pts: &[Point]) -> f64 { + let (sum, count) = run_distance_sum(sp, i, j, pts); + if count == 0 { f64::INFINITY } else { sum / count as f64 } +} + +/// [`run_distance`]'s sum of the samples' distances and their count. +fn run_distance_sum(sp: &SubPath, i: usize, j: usize, pts: &[Point]) -> (f64, usize) { + use kurbo::ParamCurve; + let n = sp.anchors.len(); + if n == 0 || pts.is_empty() { + return (0.0, 0); + } + let step = pts.len().div_ceil(200).max(1); + let line: Vec = pts.iter().step_by(step).chain(pts.last()).copied().collect(); + let to_line = |q: Point| { + line.windows(2) + .map(|w| { + let (a, b) = (w[0], w[1]); + let ab = b - a; + let t = if ab.hypot2() > 1e-18 { ((q - a).dot(ab) / ab.hypot2()).clamp(0.0, 1.0) } else { 0.0 }; + q.distance(a + ab * t) + }) + .fold(line.first().map_or(f64::INFINITY, |a| q.distance(*a)), f64::min) + }; + let segs = (j + n - i) % n; + let (mut sum, mut count) = (0.0, 0usize); + for k in 0..segs { + let c = sp.segment((i + k) % n); + for m in 1..=8 { + sum += to_line(c.eval(f64::from(m) / 8.0)); + count += 1; + } + } + (sum, count) +} + +/// An open subpath `sp` redrawn by a stroke from anchor `from` to anchor `to` across its open +/// ends: the part between them stays, the ends beyond them go, and the stroke closes the path. +fn redraw_across_gap(sp: &SubPath, from: usize, to: usize, pts: &[Point], tol: Option, within: f64) -> Option { + let (lo, hi) = (from.min(to), from.max(to)); + let (a_lo, a_hi) = (*sp.anchors.get(lo)?, *sp.anchors.get(hi)?); + // The path runs lo → hi, then the stroke from hi back to lo. + let mut stroke = pts.to_vec(); + if from == lo { + stroke.reverse(); + } + bend_ends(&mut stroke, Some(a_hi.p), Some(a_lo.p), within); + let fit = stroke_subpath(&stroke, tol, false).anchors; + let (Some(f0), Some(fl)) = (fit.first().copied(), fit.last().copied()) else { return None }; + let mut anchors = sp.anchors.get(lo..=hi)?.to_vec(); + if let Some(a) = anchors.first_mut() { + *a = Anchor::with_handles(a.p, fl.h_in, a.h_out); + } + if let Some(a) = anchors.last_mut() { + *a = Anchor::with_handles(a.p, a.h_in, f0.h_out); + } + anchors.extend_from_slice(fit.get(1..fit.len().saturating_sub(1)).unwrap_or_default()); + Some(SubPath::new(anchors, true)) +} + +/// Pencil's Edit Selected Paths in the middle of a path: a stroke that starts and ends within +/// `within` of a subpath of `pd` replaces the section between with the stroke fitted at `tol` (with +/// no `tol`, unfitted), its ends bent onto the path ([`bend_ends`]). On a closed subpath that is the +/// way round that lies nearer the stroke, so the stroke takes the side it was drawn along. The subpath's index and its new shape; None +/// when the stroke doesn't start and end on the same subpath. fn redraw_section(pd: &PathData, pts: &[Point], tol: Option, within: f64) -> Option<(usize, SubPath)> { - use kurbo::ParamCurveArclen; let (first, last) = (*pts.first()?, *pts.last()?); let (si, _, _, _, d_a) = pd.nearest(first)?; let (sj, _, _, _, d_b) = pd.nearest(last)?; @@ -611,35 +843,37 @@ fn redraw_section(pd: &PathData, pts: &[Point], tol: Option, within: f64) - if sp.anchors.len() < 2 { return None; } - // The anchor nearest to `q`: the one there, else a new one, and whether it was added. Each - // point is looked up on the subpath as it is by then: splitting a straight segment makes two - // new ones, which a `t` along the old one doesn't measure. - let place = |sp: &mut SubPath, q: Point| { - let (_, seg, t, _, _) = PathData::single(sp.clone()).nearest(q)?; - let n = sp.anchors.len(); - Some(if t <= 1e-6 { - (seg % n, false) - } else if t >= 1.0 - 1e-6 { - ((seg + 1) % n, false) - } else { - (sp.insert_anchor(seg, t), true) - }) - }; - let (mut from, _) = place(&mut sp, first)?; - let (to, added) = place(&mut sp, last)?; + // Each point is looked up on the subpath as it is by then: splitting a straight segment makes + // two new ones, which a `t` along the old one doesn't measure. + let (mut from, _) = anchor_at(&mut sp, first)?; + let (to, added) = anchor_at(&mut sp, last)?; if added && to <= from { from += 1; } if from == to { - return None; + // The stroke starts and ends on the same point: it is a loop out of the path there. + return redraw_loop(sp, from, pts, tol, within).map(|sp| (si, sp)); } let n = sp.anchors.len(); - // The length of the run of segments from anchor i forward to anchor j. - let run = |i: usize, j: usize| (0..(j + n - i) % n).map(|k| sp.segment((i + k) % n).arclen(0.01)).sum::(); + // On an open subpath the stroke replaces the part it lies along: the run between where it + // starts and ends, or the ends beyond them and the gap between, which closes the path. + if !sp.closed { + let (lo, hi) = (from.min(to), from.max(to)); + let inner = run_distance(&sp, lo, hi, pts); + let (s1, c1) = run_distance_sum(&sp, 0, lo, pts); + let (s2, c2) = run_distance_sum(&sp, hi, n - 1, pts); + // Both ends taken: the stroke only spans the gap. + let outer = if c1 + c2 == 0 { 0.0 } else { (s1 + s2) / (c1 + c2) as f64 }; + if outer < inner { + return redraw_across_gap(&sp, from, to, pts, tol, within).map(|sp| (si, sp)); + } + } // The stroke goes from `start` to `end` and replaces the run between them; `kept` runs from // `end` round to `start`, then the stroke's inner anchors follow. let (start, end, reversed) = if sp.closed { - if run(from, to) <= run(to, from) { (from, to, false) } else { (to, from, true) } + // The way round that lies along the stroke: carving across a shape replaces the part the + // stroke cuts off, drawing round outside it replaces the part it follows. + if run_distance(&sp, from, to, pts) <= run_distance(&sp, to, from, pts) { (from, to, false) } else { (to, from, true) } } else if from < to { (from, to, false) } else { @@ -649,10 +883,8 @@ fn redraw_section(pd: &PathData, pts: &[Point], tol: Option, within: f64) - if reversed { stroke.reverse(); } - let (Some(s0), Some(s1)) = (stroke.first_mut(), sp.anchors.get(start)) else { return None }; - *s0 = s1.p; - let (Some(e0), Some(e1)) = (stroke.last_mut(), sp.anchors.get(end)) else { return None }; - *e0 = e1.p; + let (Some(s1), Some(e1)) = (sp.anchors.get(start), sp.anchors.get(end)) else { return None }; + bend_ends(&mut stroke, Some(s1.p), Some(e1.p), within); let fit = stroke_subpath(&stroke, tol, false).anchors; let (Some(f0), Some(f1)) = (fit.first().copied(), fit.last().copied()) else { return None }; let inner = fit.get(1..fit.len().saturating_sub(1)).unwrap_or_default(); @@ -840,7 +1072,9 @@ fn freehand(s: &mut Session, p: &Value) -> Result { let (pd, _) = path_of(&s.doc()?.doc, id)?; // shortcut: a stroke pressure profile is left as it was, measured along the old path; fit // it to the new length if Calligraphic pressure strokes get redrawn. - if let Some((si, sp)) = redraw_section(&pd, &pts, fit_tol, within) { + // A stroke that ends back on the path redraws the section between; one that ends away from + // it takes the path with it (it is where the pen is lifted that decides). + if let Some((si, sp)) = redraw_section(&pd, &pts, fit_tol, within).or_else(|| redraw_extend(&pd, &pts, fit_tol, within)) { s.edit(if brush { "Paintbrush" } else { "Pencil" }, |d, sel| { *path_mut(d, id)?.subpaths.get_mut(si).ok_or_else(|| bad(C, "no such subpath"))? = sp; // A member path of a compound path is redrawn in it: the compound path is what is @@ -1636,3 +1870,21 @@ fn blob(s: &mut Session, p: &Value) -> Result { })?; Ok(json!({ "id": keep.0 })) } + +#[cfg(test)] +mod bend_tests { + use super::*; + + /// The ends move onto their targets, the stroke behind them less and less, and nothing farther + /// along than `reach`. + #[test] + fn bend_ends_moves_the_ends_and_fades_out_along_the_reach() { + let mut pts: Vec = (0..=10).map(|i| Point::new(f64::from(i) * 10.0, 0.0)).collect(); + bend_ends(&mut pts, Some(Point::new(0.0, 8.0)), Some(Point::new(100.0, -8.0)), 40.0); + assert_eq!(pts[0], Point::new(0.0, 8.0)); + assert_eq!(pts[10], Point::new(100.0, -8.0)); + assert!((pts[2].y - 8.0 * 0.5).abs() < 1e-9, "halfway along the reach, half the shift: {:?}", pts[2]); + assert!((pts[8].y + 8.0 * 0.5).abs() < 1e-9, "{:?}", pts[8]); + assert_eq!(pts[5], Point::new(50.0, 0.0), "the middle doesn't move"); + } +} diff --git a/crates/engine/src/tests_draw2.rs b/crates/engine/src/tests_draw2.rs index f712891d55..2c63d7b4bf 100644 --- a/crates/engine/src/tests_draw2.rs +++ b/crates/engine/src/tests_draw2.rs @@ -81,6 +81,12 @@ fn near(a: Point, b: Point) -> bool { a.distance(b) < 1e-6 } +/// Whether open subpath `sp`'s two ends are at `a` and `b`, in either order (within `tol`). +fn ends_at(sp: &vectorcraft_geom::SubPath, a: Point, b: Point, tol: f64) -> bool { + let (Some(f), Some(l)) = (sp.anchors.first(), sp.anchors.last()) else { return false }; + (f.p.distance(a) < tol && l.p.distance(b) < tol) || (f.p.distance(b) < tol && l.p.distance(a) < tol) +} + fn area(pd: &PathData) -> f64 { vectorcraft_pathops::area(pd, FillRule::NonZero) } @@ -293,7 +299,8 @@ fn pencil_redraws_the_section_of_a_selected_path_between_its_ends() { } /// On a closed path the stroke replaces the shorter way between where it starts and ends, and the -/// path stays closed; a stroke that doesn't end on the path draws a new one. +/// path stays closed; a stroke that doesn't end on the path opens it where the stroke starts and +/// ends where the stroke does (no new path). #[test] fn pencil_redraws_the_shorter_way_round_a_closed_path() { let mut s = session(); @@ -310,11 +317,12 @@ fn pencil_redraws_the_shorter_way_round_a_closed_path() { } let top = kurbo::Shape::bounding_box(&path(&s, id).to_bezpath()).y0; assert!(top < -20.0, "the dip: top {top}"); - // Not ending on the path: a new path, the rectangle as it was. - let before = path(&s, id); + // Not ending on the path: the rectangle opens at (50, 100) and follows the stroke out. s.execute("path.freehand", &json!({"points": [[50, 100], [80, 150], [120, 160]], "redraw": {"id": id.0, "within": 4}})).unwrap(); - assert_eq!(paths(&s).len(), 2); - assert_eq!(path(&s, id), before); + assert_eq!(paths(&s).len(), 1, "no new path"); + let sp = &path(&s, id).subpaths[0]; + assert!(!sp.closed, "the rectangle opened"); + assert!(ends_at(sp, Point::new(50.0, 100.0), Point::new(120.0, 160.0), 1e-6), "from the opening to the stroke's end: {sp:?}"); assert!(s.execute("path.freehand", &json!({"points": [[0, 0], [1, 1]], "redraw": {"id": id.0, "within": -1}})).is_err()); } @@ -2771,3 +2779,239 @@ fn pencil_redraws_a_selected_compound_path() { assert_eq!(s.doc().unwrap().selection.objects, compound); assert!(members(&s)[1] != before[1], "the hole is redrawn"); } + +/// A Pencil stroke that starts on a selected closed shape and is lifted away from it takes the +/// shape with it: the shape opens where the stroke started, keeps its whole outline, fill and +/// selection, and ends where the pen was lifted. Going out past Edit Selected Paths' distance on +/// the way changes nothing: no new path appears at any point of the stroke. +#[test] +fn a_stroke_lifted_away_from_a_closed_shape_opens_it_and_follows_the_stroke() { + let mut s = session(); + s.execute("select.none", &json!({})).unwrap(); + s.execute("paint.setFill", &json!({"color": "#000000"})).unwrap(); + let id = rect(&mut s, 100.0, 100.0, 200.0, 100.0); + let fill = s.doc().unwrap().doc.node(id).unwrap().appearance.fill_paint().clone(); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + s.set_tool_option_cmd(&json!({"tool": "pencil", "values": {"editWithin": 12}})).unwrap(); + let v = view(); + s.select_tool("pencil", v).unwrap(); + let count = |s: &Session| s.doc().unwrap().doc.layers[0].children().map_or(0, |c| c.len()); + // From the right edge, a little hook up and out to the right. + s.pointer(&PointerEvent::new(PointerKind::Down, 300.0, 150.0), v).unwrap(); + for (x, y) in [(303.0, 140.0), (308.0, 128.0), (316.0, 118.0), (326.0, 112.0), (338.0, 110.0)] { + s.pointer(&PointerEvent::new(PointerKind::Drag, x, y), v).unwrap(); + assert_eq!(count(&s), 1, "no new path while drawing"); + } + s.pointer(&PointerEvent::new(PointerKind::Up, 338.0, 110.0), v).unwrap(); + assert_eq!(count(&s), 1, "no new path"); + assert_eq!(s.doc().unwrap().selection.objects, vec![id], "the shape stays selected"); + let n = s.doc().unwrap().doc.node(id).unwrap(); + assert_eq!(n.appearance.fill_paint(), fill, "the fill stays"); + let sp = &n.path_data().unwrap().subpaths[0]; + assert!(!sp.closed, "the shape opened"); + let ps: Vec = sp.anchors.iter().map(|a| a.p).collect(); + for corner in [(100.0, 100.0), (300.0, 100.0), (300.0, 200.0), (100.0, 200.0)] { + assert!(ps.iter().any(|p| near(*p, Point::new(corner.0, corner.1))), "{corner:?} kept: {ps:?}"); + } + assert!(ends_at(sp, Point::new(300.0, 150.0), Point::new(338.0, 110.0), 0.5), "from the opening to where the pen was lifted: {ps:?}"); + // The outline joins the stroke heading up, the stroke's way: next to the anchor where the + // stroke leaves the opening is the bottom right corner. + let last = ps.len() - 1; + let k = (1..last).find(|&i| ps[i].distance(Point::new(300.0, 150.0)) < 0.5).unwrap(); + assert!(near(ps[k - 1], Point::new(300.0, 200.0)) || near(ps[k + 1], Point::new(300.0, 200.0)), "joins from below: {ps:?}"); +} + +/// On an open path, a stroke from its middle lifted away from it cuts the path there and drops the +/// part the stroke heads along; the part behind stays and ends where the pen was lifted. +#[test] +fn a_stroke_lifted_away_from_an_open_path_drops_the_part_it_heads_along() { + for (towards_end, kept) in [(true, Point::new(100.0, 100.0)), (false, Point::new(300.0, 100.0))] { + let mut s = session(); + let id = line(&mut s, 100.0, 100.0, 300.0, 100.0); + let dx = if towards_end { 1.0 } else { -1.0 }; + let pts: Vec<_> = (0..8).map(|i| json!([200.0 + dx * 4.0 * f64::from(i), 100.0 - 5.0 * f64::from(i)])).collect(); + s.execute("path.freehand", &json!({"points": pts, "redraw": {"id": id.0, "within": 4}})).unwrap(); + assert_eq!(paths(&s).len(), 1, "no new path"); + let sp = &path(&s, id).subpaths[0]; + let ps: Vec = sp.anchors.iter().map(|a| a.p).collect(); + assert!( + ends_at(sp, kept, Point::new(200.0 + dx * 28.0, 65.0), 0.5), + "towards the end {towards_end}: the part behind stays and ends where the pen was lifted: {ps:?}" + ); + let dropped = Point::new(if towards_end { 300.0 } else { 100.0 }, 100.0); + assert!(!ps.iter().any(|p| p.distance(dropped) < 1.0), "the part ahead is dropped: {ps:?}"); + } +} + +/// A stroke that leaves a selected path and comes back to the same point adds a loop there; the +/// path stays closed and keeps its corners. +#[test] +fn a_stroke_back_to_where_it_started_adds_a_loop() { + let mut s = session(); + let id = rect(&mut s, 0.0, 0.0, 200.0, 100.0); + let before = path(&s, id).subpaths[0].anchors.len(); + let loop_pts = json!([[100, 0], [90, -15], [95, -35], [110, -38], [120, -20], [108, -8], [100, 0]]); + s.execute("path.freehand", &json!({"points": loop_pts, "redraw": {"id": id.0, "within": 4}})).unwrap(); + assert_eq!(paths(&s).len(), 1, "no new path"); + let sp = &path(&s, id).subpaths[0]; + assert!(sp.closed && sp.anchors.len() > before, "{sp:?}"); + let top = kurbo::Shape::bounding_box(&path(&s, id).to_bezpath()).y0; + assert!(top < -30.0, "the loop: top {top}"); + for corner in [(0.0, 0.0), (200.0, 0.0), (200.0, 100.0), (0.0, 100.0)] { + assert!(sp.anchors.iter().any(|a| near(a.p, Point::new(corner.0, corner.1))), "{corner:?} kept"); + } +} + +/// On a closed path the stroke replaces the way round it heads from its start, even when that is +/// the longer way: the shape doesn't flip to the other side as the stroke goes on. +#[test] +fn a_redraw_of_a_closed_path_goes_the_way_the_stroke_heads() { + let mut s = session(); + let id = rect(&mut s, 0.0, 0.0, 200.0, 100.0); + // From (20, 0) out to the left, round below the rectangle and up its right side to (180, 0). + let pts = json!([[20, 0], [10, -15], [-20, -10], [-25, 50], [-20, 120], [100, 125], [220, 120], [225, 50], [210, -10], [190, -12], [180, 0]]); + s.execute("path.freehand", &json!({"points": pts, "redraw": {"id": id.0, "within": 4}})).unwrap(); + assert_eq!(paths(&s).len(), 1); + let sp = &path(&s, id).subpaths[0]; + assert!(sp.closed); + let ps: Vec = sp.anchors.iter().map(|a| a.p).collect(); + // The rectangle's left, bottom and right sides went with the stroke; its top between 20 and + // 180 stays. + for corner in [(0.0, 0.0), (0.0, 100.0), (200.0, 100.0), (200.0, 0.0)] { + assert!(!ps.iter().any(|p| p.distance(Point::new(corner.0, corner.1)) < 1.0), "{corner:?} replaced: {ps:?}"); + } + let b = kurbo::Shape::bounding_box(&path(&s, id).to_bezpath()); + assert!(b.y1 > 115.0 && b.x0 < -15.0, "the stroke's way round: {b:?}"); +} + +/// A stroke lifted farther from the path than Edit selected paths within takes the path with it; +/// one lifted within that distance joins it again, its end bent smoothly onto it. +#[test] +fn a_stroke_lifted_beyond_the_edit_distance_takes_the_path_along() { + let mut s = session(); + let id = rect(&mut s, 0.0, 0.0, 200.0, 100.0); + // A hook out of the right side that ends 8 pt from it. + let hook = json!([[200, 50], [210, 40], [222, 38], [226, 46], [222, 56], [208, 58]]); + s.execute("path.freehand", &json!({"points": hook, "redraw": {"id": id.0, "within": 4}})).unwrap(); + let sp = &path(&s, id).subpaths[0]; + assert!(!sp.closed, "8 pt away with 4 pt to edit within: the shape opened"); + let ends = [sp.anchors.first().unwrap().p, sp.anchors.last().unwrap().p]; + assert!(ends.iter().any(|p| p.distance(Point::new(208.0, 58.0)) < 0.5), "it ends where the pen was lifted: {ends:?}"); +} + +/// A shape with a hole that opens keeps its outline running its own way, so the hole stays a hole. +#[test] +fn opening_a_shape_with_a_hole_keeps_the_hole() { + for heads_back in [false, true] { + let mut s = session(); + let outer = rect(&mut s, 0.0, 0.0, 200.0, 200.0); + let hole = rect(&mut s, 50.0, 50.0, 100.0, 100.0); + s.execute("select.set", &json!({"ids": [outer.0, hole.0]})).unwrap(); + s.execute("object.compoundPath.make", &json!({})).unwrap(); + let compound = s.doc().unwrap().selection.objects[0]; + let member = |s: &Session, i: usize| s.doc().unwrap().doc.node(compound).unwrap().children().unwrap()[i].clone(); + let (outer_id, sign) = { + let m = member(&s, 0); + (m.id, m.path_data().unwrap().subpaths[0].signed_area().signum()) + }; + // A hook out of the top edge, heading one way or the other along it. + let dx = if heads_back { -1.0 } else { 1.0 }; + let hook: Vec<_> = (0..6).map(|i| json!([100.0 + dx * 6.0 * f64::from(i), -5.0 * f64::from(i)])).collect(); + s.execute("path.freehand", &json!({"points": hook, "redraw": {"id": outer_id.0, "within": 4}})).unwrap(); + let sp = member(&s, 0).path_data().unwrap().subpaths[0].clone(); + assert!(!sp.closed, "heads back {heads_back}: opened"); + assert_eq!(sp.signed_area().signum(), sign, "heads back {heads_back}: the outline runs its own way, the hole stays a hole"); + } +} + +/// A stroke across a shape from one point of its outline to another carves off the part it cuts +/// across, the lobe on that side, and keeps the rest, whichever way it is drawn. +#[test] +fn a_stroke_across_a_shape_carves_off_the_part_it_cuts() { + for reversed in [false, true] { + let mut s = session(); + // A wide shape with a lobe on top between x = 80 and x = 120. + let shape = json!([[0, 0], [80, 0], [80, -60], [120, -60], [120, 0], [300, 0], [300, 100], [0, 100]]); + let id = NodeId(s.execute("path.freehand", &json!({"points": shape, "closed": true, "fidelity": 0.01})).unwrap()["id"].as_u64().unwrap()); + // Across the lobe's base, a little inside the shape. + let mut cut = vec![json!([70, 0]), json!([85, 8]), json!([100, 10]), json!([115, 8]), json!([130, 0])]; + if reversed { + cut.reverse(); + } + s.execute("path.freehand", &json!({"points": cut, "redraw": {"id": id.0, "within": 4}})).unwrap(); + let sp = &path(&s, id).subpaths[0]; + assert!(sp.closed, "reversed {reversed}"); + let b = kurbo::Shape::bounding_box(&path(&s, id).to_bezpath()); + assert!(b.y0 > -20.0, "reversed {reversed}: the lobe (up to y = -60) is carved off: {b:?}"); + assert!(b.x1 > 295.0 && b.y1 > 95.0, "reversed {reversed}: the rest stays: {b:?}"); + } +} + +/// A stroke leaving an open path across it (no direction along it) drops the nearer, short side, +/// not most of the path. +#[test] +fn a_stroke_leaving_an_open_path_across_it_drops_the_side_it_is_near() { + let mut s = session(); + let id = line(&mut s, 100.0, 100.0, 300.0, 100.0); + // Straight up from x = 280, then bending towards the near end. + let up = json!([[280, 100], [280, 90], [281, 75], [284, 60], [290, 50]]); + s.execute("path.freehand", &json!({"points": up, "redraw": {"id": id.0, "within": 4}})).unwrap(); + let sp = &path(&s, id).subpaths[0]; + assert!(ends_at(sp, Point::new(100.0, 100.0), Point::new(290.0, 50.0), 0.5), "the long side stays: {sp:?}"); +} + +/// A stroke drawn over an open shape's open ends, from near one end to near the other, redraws +/// those ends along the stroke and closes the shape, whichever way it is drawn; the shape's body +/// between stays. +#[test] +fn a_stroke_over_an_open_shapes_ends_closes_it_along_the_stroke() { + for reversed in [false, true] { + let mut s = session(); + // A C open on the right: from the top right round the left to the bottom right. + let c: Vec<_> = (0..=30) + .map(|i| { + let a = (40.0 + 280.0 * f64::from(i) / 30.0).to_radians(); + json!([200.0 + 100.0 * a.cos(), 200.0 - 100.0 * a.sin()]) + }) + .collect(); + let id = NodeId(s.execute("path.freehand", &json!({"points": c, "fidelity": 0.5})).unwrap()["id"].as_u64().unwrap()); + let on = |deg: f64| { + let a = deg.to_radians(); + (200.0 + 100.0 * a.cos(), 200.0 - 100.0 * a.sin()) + }; + // From the C near its top end, out round the open side, back onto it near the bottom end. + let (a, b) = (on(60.0), on(300.0)); + let mut stroke = vec![json!([a.0, a.1]), json!([290.0, 150.0]), json!([315.0, 200.0]), json!([290.0, 250.0]), json!([b.0, b.1])]; + if reversed { + stroke.reverse(); + } + s.execute("path.freehand", &json!({"points": stroke, "redraw": {"id": id.0, "within": 4}})).unwrap(); + assert_eq!(paths(&s).len(), 1, "reversed {reversed}: no new path"); + let sp = &path(&s, id).subpaths[0]; + assert!(sp.closed, "reversed {reversed}: the shape closed"); + let bb = kurbo::Shape::bounding_box(&path(&s, id).to_bezpath()); + assert!(bb.x1 > 310.0 && bb.x0 < 105.0, "reversed {reversed}: closed along the stroke, the body kept: {bb:?}"); + // The old ends (at 40° and 320°) are gone. + for deg in [40.0, 320.0] { + let e = on(deg); + assert!(!sp.anchors.iter().any(|q| q.p.distance(Point::new(e.0, e.1)) < 1.0), "reversed {reversed}: the end at {deg}° is redrawn"); + } + } +} + +/// A stroke that comes back near the path, within Edit selected paths within but not on it, joins +/// it again: the shape stays one closed path, and the stroke's end bends onto it, so no anchor +/// lies off the stroke's way back. +#[test] +fn a_stroke_back_near_the_path_joins_it_smoothly() { + let mut s = session(); + let id = rect(&mut s, 0.0, 0.0, 200.0, 100.0); + // A bump out of the top edge that comes back down to 10 pt above it. + let bump = json!([[40, 0], [45, -20], [60, -40], [80, -45], [100, -40], [115, -25], [120, -10]]); + s.execute("path.freehand", &json!({"points": bump, "redraw": {"id": id.0, "within": 20}})).unwrap(); + assert_eq!(paths(&s).len(), 1); + let sp = &path(&s, id).subpaths[0]; + assert!(sp.closed, "joined again: still closed"); + let top = kurbo::Shape::bounding_box(&path(&s, id).to_bezpath()).y0; + assert!(top < -35.0, "the bump: top {top}"); +}