Merge pull request #4221 from ncic/pencil-redraw-extend

Pencil: Edit Selected Paths follows a stroke lifted away from the path, carves, loops and closes
This commit is contained in:
BFlat
2026-11-25 17:44:43 +07:00
committed by GitHub
8 changed files with 842 additions and 47 deletions
+1 -1
View File
@@ -12,7 +12,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Pencil",
[],
None,
"{points: [[x,y]…] or [[x,y,pressure]…] or [[x,y,pressure,tiltX,tiltY,rotation,wheel]…] (pen pressure 0..1: the stroke keeps it, for Calligraphic and Scatter brushes with Pressure variation; a point without one presses fully. Pen tilt in degrees, each −90..90, x positive leaning right and y leaning down the page, and barrel rotation in degrees clockwise, 0..360: the stroke keeps how far the pen leaned, which way and how far its barrel turned, for brushes with Tilt, Bearing and Rotation variation. An airbrush pen's finger wheel 0..1: the stroke keeps it for brushes with Stylus Wheel variation, a point without one half way; null for what a point lacks. A pressure, tilt, rotation or wheel outside its range, or a point array of more than seven numbers, is an error), fidelity?: pt (1.5; from 0.000015625 (0.01 / 640) to 100 / 0.0313 (about 3194.89), the Pencil's and the Paintbrush's 0.01 to 100 px Fidelity at the highest and the lowest zoom; a value outside that range is an error. The tools send their Fidelity in pixels divided by the zoom, kept within the range), 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\" (default) | \"brush\", fill?: bool, keepSelected?: bool (true: the drawn or continued path is selected; false: a new path leaves nothing selected, and a continued or redrawn one is deselected while the rest of the selection stays), extend?: {id, end?: \"end\" (default) | \"start\"}, connect?: {id, end: \"start\"|\"end\"} (only with extend), redraw?: {id, within?: pt (12)}} fit a freehand stroke → {id}. extend continues the path from that end, and closes it when `closed` is true (left out, when the stroke ends within four Fidelities of the path's other end, 6 to 400 pt); 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. Any other style, extend end or connect end, connect without extend, and a connect that names no other path with an open end are errors, a stroke of one point included, and nothing changes",
"{points: [[x,y]…] or [[x,y,pressure]…] or [[x,y,pressure,tiltX,tiltY,rotation,wheel]…] (pen pressure 0..1: the stroke keeps it, for Calligraphic and Scatter brushes with Pressure variation; a point without one presses fully. Pen tilt in degrees, each −90..90, x positive leaning right and y leaning down the page, and barrel rotation in degrees clockwise, 0..360: the stroke keeps how far the pen leaned, which way and how far its barrel turned, for brushes with Tilt, Bearing and Rotation variation. An airbrush pen's finger wheel 0..1: the stroke keeps it for brushes with Stylus Wheel variation, a point without one half way; null for what a point lacks. A pressure, tilt, rotation or wheel outside its range, or a point array of more than seven numbers, is an error), fidelity?: pt (1.5; from 0.000015625 (0.01 / 640) to 100 / 0.0313 (about 3194.89), the Pencil's and the Paintbrush's 0.01 to 100 px Fidelity at the highest and the lowest zoom; a value outside that range is an error. The tools send their Fidelity in pixels divided by the zoom, kept within the range), 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\" (default) | \"brush\", fill?: bool, keepSelected?: bool (true: the drawn or continued path is selected; false: a new path leaves nothing selected, and a continued or redrawn one is deselected while the rest of the selection stays), leaveSelection?: bool (false; true with keepSelected false: a new path leaves the selection as it is, as the Pencil previews a stroke that redraws a path), extend?: {id, end?: \"end\" (default) | \"start\"}, connect?: {id, end: \"start\"|\"end\"} (only with extend), redraw?: {id, within?: pt (12)}} fit a freehand stroke → {id}. extend continues the path from that end, and closes it when `closed` is true (left out, when the stroke ends within four Fidelities of the path's other end, 6 to 400 pt); 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 that leaves the bigger shape; on an open one the way the stroke runs along it at each end decides: it replaces the part it runs along where it starts and joins the part it runs into where it lands, so it replaces the part between, keeps it and closes the path along the stroke, or, when its ends disagree, ends where it is lifted; an end that leaves or meets the path squarely follows the other end, and when both do it closes only if it goes round both pieces beyond), 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. Any other style, extend end or connect end, connect without extend, and a connect that names no other path with an open end are errors, a stroke of one point included, and nothing changes",
has_doc,
freehand
),
+380 -32
View File
@@ -74,13 +74,329 @@ fn stroke_subpath(pts: &[Point], tol: Option<f64>, 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<kurbo::Vec2> {
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<kurbo::Vec2> {
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<f64>, reach: f64) -> Vec<Anchor> {
let mut stroke = pts.to_vec();
bend_ends(&mut stroke, Some(a), None, reach);
stroke_subpath(&stroke, tol, false).anchors.into_vec()
}
/// 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. A stroke shorter than `reach` bends over its own length, so each end still
/// lands on its target and the other end's bend doesn't move it off.
fn bend_ends(stroke: &mut [Point], a: Option<Point>, b: Option<Point>, reach: f64) {
let (Some(&first), Some(&last)) = (stroke.first(), stroke.last()) else { return };
// How far along the stroke each point lies, measured before anything moves.
let mut along = Vec::with_capacity(stroke.len());
let mut total = 0.0;
let mut prev = first;
for p in stroke.iter() {
total += prev.distance(*p);
prev = *p;
along.push(total);
}
let reach = reach.min(total);
if !reach.is_finite() || reach <= 0.0 {
// No length to bend over: only the ends move.
if let (Some(a), Some(p)) = (a, stroke.first_mut()) {
*p = a;
}
if let (Some(b), Some(p)) = (b, stroke.last_mut()) {
*p = b;
}
return;
}
let weight = |d: f64| (1.0 - d / reach).max(0.0);
let (shift_a, shift_b) = (a.map(|a| a - first), b.map(|b| b - last));
for (p, &d) in stroke.iter_mut().zip(&along) {
if let Some(s) = shift_a {
*p += s * weight(d);
}
if let Some(s) = shift_b {
*p += s * weight(total - d);
}
}
}
/// 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`. `runs_up`, when given, says which part of
/// an open subpath the stroke heads along: the part towards its last anchor when true.
fn redraw_extend(pd: &PathData, pts: &[Point], tol: Option<f64>, within: f64, runs_up: Option<bool>) -> 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 let Some(up) = runs_up {
!up
} 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::<f64>();
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<Anchor> = if sp.closed {
// From `k` all the way round back to `k`: the shape opens there.
let mut v: Vec<Anchor> = sp.anchors.get_range(k..)?.into_iter().chain(sp.anchors.get_range(..k)?).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_range(..=k)?
};
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<f64>, within: f64) -> Option<SubPath> {
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.into_vec();
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_range(..k)?;
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_range(k + 1..)?);
sp.anchors = anchors.into();
Some(sp)
}
/// The area closed subpath `sp` would have with `stroke` (running from anchor `start` to anchor
/// `end`) in place of its run from `start` forward to `end`.
fn redrawn_area(sp: &SubPath, start: usize, end: usize, stroke: impl Iterator<Item = Point>) -> f64 {
use kurbo::ParamCurveArea;
let n = sp.anchors.len();
let (Some(from), Some(to)) = (sp.anchors.get(start), sp.anchors.get(end)) else { return 0.0 };
let mut area: f64 = (0..(start + n - end) % n).map(|k| sp.segment((end + k) % n).signed_area()).sum();
let mut at = from.p;
for q in stroke.chain([to.p]) {
area += kurbo::Line::new(at, q).signed_area();
at = q;
}
area.abs()
}
/// Which way a stroke runs along open subpath `sp` where it meets it: `stroke` starts at that end
/// of the stroke. It runs along when its first `within` of length stays within `within` of the
/// path and moves along the path more than away from it: Some(true) towards the subpath's last
/// anchor. None when it goes straight off (or onto) the path.
fn run_along(sp: &SubPath, mut stroke: impl Iterator<Item = Point>, within: f64) -> Option<bool> {
let one = PathData::single(sp.clone());
let p0 = stroke.next()?;
// The point `within` along the stroke, or its other end when it is shorter.
let (mut prev, mut len, mut q) = (p0, 0.0, p0);
for p in stroke {
let step = prev.distance(p);
if len + step >= within && step > 0.0 {
q = prev.lerp(p, (within - len) / step);
break;
}
len += step;
prev = p;
q = p;
}
let (_, s0, t0, on0, _) = one.nearest(p0)?;
let (_, s1, t1, on1, away) = one.nearest(q)?;
if away > within || on0.distance(on1) <= away {
return None;
}
Some(s1 as f64 + t1 > s0 as f64 + t0)
}
/// What a stroke from anchor `from` to anchor `to` of open subpath `sp` does to it.
enum OpenRedraw {
/// Replaces the part between and leaves the path open.
Replace,
/// Keeps the part between, drops the pieces beyond and closes the path with the stroke.
Close,
/// Drops the part it starts along (towards the last anchor when true) and ends where it does.
Extend(bool),
}
/// Pencil's Edit Selected Paths on an open subpath: what a stroke from anchor `from` to anchor `to`
/// of `sp` does, from the way it runs along the path at each end ([`run_along`]; `before` is the
/// subpath before the anchors at `from` and `to` were added). Where it starts, it replaces the part
/// it runs along; where it lands, it joins the part it runs into and the part behind goes. An end
/// that goes straight off or onto the path follows the other end. When both do, it closes only if
/// the shape it makes with the part between goes round both pieces beyond ([`goes_round`]). When
/// the two ends disagree, the start decides and the stroke's end stays where it is lifted.
fn open_redraw(before: &SubPath, sp: &SubPath, from: usize, to: usize, pts: &[Point], within: f64) -> OpenRedraw {
let up = to > from;
// Each end runs towards the last anchor (true) or the first. Running towards the other end
// of the stroke at the start, or on away from it where it lands, replaces the part between;
// the other way keeps the part between and closes the path.
let at_start = run_along(before, pts.iter().copied(), within);
let at_end = run_along(before, pts.iter().rev().copied(), within).map(|back| !back);
match (at_start, at_end) {
(Some(s), Some(e)) if s != e => OpenRedraw::Extend(s),
(Some(r), _) | (None, Some(r)) => {
if r == up {
OpenRedraw::Replace
} else {
OpenRedraw::Close
}
}
(None, None) => {
if goes_round(sp, from, to, pts) {
OpenRedraw::Close
} else {
OpenRedraw::Replace
}
}
}
}
/// Does the shape that stroke `pts` (from anchor `from` to anchor `to` of open subpath `sp`) makes
/// with the part of `sp` between them go round both pieces of `sp` beyond them? A piece counts as
/// inside when more of it lies inside than outside; a piece of no length counts as inside.
fn goes_round(sp: &SubPath, from: usize, to: usize, pts: &[Point]) -> bool {
use kurbo::{ParamCurve, Shape};
let (lo, hi) = (from.min(to), from.max(to));
let Some(middle) = sp.anchors.get_range(lo..=hi) else { return false };
let mut shape = PathData::single(SubPath::new(middle, false)).to_bezpath();
// The stroke runs from `hi` back to `lo` to close the shape.
let back: Vec<Point> = if from == lo { pts.iter().rev().copied().collect() } else { pts.to_vec() };
for p in back {
shape.line_to(p);
}
shape.close_path();
let inside = |segs: std::ops::Range<usize>| {
let (mut yes, mut no) = (0, 0);
for k in segs {
let seg = sp.segment(k);
for t in [0.25, 0.5, 0.75] {
if shape.winding(seg.eval(t)) != 0 { yes += 1 } else { no += 1 }
}
}
yes >= no
};
inside(0..lo) && inside(hi..sp.anchors.len().saturating_sub(1))
}
/// Closes open subpath `sp` with stroke `pts`, which runs from anchor `from` to anchor `to`: the
/// anchors between them stay, the pieces beyond go, and the stroke, its ends bent onto those
/// anchors ([`bend_ends`] over `within`), runs from one back to the other.
fn redraw_across_gap(sp: &SubPath, from: usize, to: usize, pts: &[Point], tol: Option<f64>, within: f64) -> Option<SubPath> {
let (lo, hi) = (from.min(to), from.max(to));
let (a_lo, a_hi) = (*sp.anchors.get(lo)?, *sp.anchors.get(hi)?);
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.into_vec();
let (Some(f0), Some(fl)) = (fit.first().copied(), fit.last().copied()) else { return None };
let mut anchors = sp.anchors.get_range(lo..=hi)?;
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 leaves the bigger shape. On an open one the way the stroke runs along the path
/// at its ends decides ([`open_redraw`]): it replaces the part between, keeps the part between and
/// closes the path, or ends where it is lifted. 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<f64>, 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)?;
@@ -91,35 +407,35 @@ fn redraw_section(pd: &PathData, pts: &[Point], tol: Option<f64>, 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)?;
let before = sp.clone();
// 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));
}
if !sp.closed {
match open_redraw(&before, &sp, from, to, pts, within) {
OpenRedraw::Replace => {}
OpenRedraw::Close => return redraw_across_gap(&sp, from, to, pts, tol, within).map(|sp| (si, sp)),
OpenRedraw::Extend(up) => return redraw_extend(pd, pts, tol, within, Some(up)),
}
}
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::<f64>();
// 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 bigger of the two shapes the stroke could make stays: carving across a shape replaces
// the part it cuts off, drawing round outside it the part it goes round. Picking the side
// nearer the stroke instead threw away a thin shape under a tall arch over its long side.
let forward = redrawn_area(&sp, from, to, pts.iter().copied());
let backward = redrawn_area(&sp, to, from, pts.iter().rev().copied());
if forward >= backward { (from, to, false) } else { (to, from, true) }
} else if from < to {
(from, to, false)
} else {
@@ -129,10 +445,8 @@ fn redraw_section(pd: &PathData, pts: &[Point], tol: Option<f64>, 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.into_vec();
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();
@@ -212,6 +526,9 @@ pub(crate) fn freehand_brushed(s: &mut Session, p: &Value, brush_name: Option<&s
// The undo step's name: a stroke painted with a brush is a Paintbrush stroke, whatever its style.
let label = if brush || brush_name.is_some() { "Paintbrush" } else { "Pencil" };
let keep_selected = switch_or(p, "keepSelected", true, C)?;
// The Pencil's preview of a stroke that redraws a path draws it as a new path but leaves the
// selection as it is: the path being redrawn stays selected until the release redraws it.
let leave_selection = switch_or(p, "leaveSelection", false, C)?;
let filled = switch_or(p, "fill", false, C)?;
let extend = p.get("extend").filter(|v| !v.is_null());
if extend.is_none() && p.get("connect").is_some_and(|v| !v.is_null()) {
@@ -416,7 +733,9 @@ pub(crate) fn freehand_brushed(s: &mut Session, p: &Value, brush_name: Option<&s
// shortcut: a stroke's pressure, tilt, bearing and rotation profiles are left as they
// were, measured along the old path; fit them to the new length if strokes drawn with a
// pen 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, None)) {
// A member path of a compound path is redrawn in it: the compound path is what is
// selected, and what a brush paints.
let whole = brush_target(&s.doc()?.doc, id);
@@ -461,7 +780,7 @@ pub(crate) fn freehand_brushed(s: &mut Session, p: &Value, brush_name: Option<&s
}
}
let out = insert_look(s, label, path_kind(PathData::single(sp)), look, None, keep_selected)?;
if !keep_selected {
if !keep_selected && !leave_selection {
// A new stroke with Keep selected off leaves nothing selected: Illustrator starts the stroke
// by dropping the earlier selection, it does not keep it (#5752).
s.select(|_, sel| sel.clear())?;
@@ -628,3 +947,32 @@ pub(super) fn blob(s: &mut Session, p: &Value) -> Result<Value> {
})?;
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<Point> = (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");
}
/// A stroke shorter than `reach` still has both ends on their targets: bending one end onto
/// its target doesn't pull the other end off its own.
#[test]
fn bend_ends_keeps_both_ends_on_target_for_a_short_stroke() {
let mut pts = vec![Point::new(40.0, -12.0), Point::new(44.0, -12.0), Point::new(48.0, -12.0)];
bend_ends(&mut pts, Some(Point::new(40.0, 0.0)), Some(Point::new(48.0, 0.0)), 16.0);
assert_eq!(pts[0], Point::new(40.0, 0.0), "{pts:?}");
assert_eq!(pts[2], Point::new(48.0, 0.0), "{pts:?}");
assert_eq!(pts[1], Point::new(44.0, 0.0), "halfway, half of each end's shift: {pts:?}");
}
}
+4 -1
View File
@@ -1357,7 +1357,10 @@ fn brush_freehand_refuses_unknown_keys() {
let spec = crate::cmd::find_command("brush.freehand").unwrap();
let mut keys = crate::cmd::params::accepted_keys(spec.params).expect("the description names every key");
keys.sort_unstable();
assert_eq!(keys, ["brush", "closed", "connect", "extend", "fidelity", "fill", "fit", "keepSelected", "points", "redraw", "style"]);
assert_eq!(
keys,
["brush", "closed", "connect", "extend", "fidelity", "fill", "fit", "keepSelected", "leaveSelection", "points", "redraw", "style"]
);
let mut s = session();
let a = rect(&mut s, 0.0, 0.0, 10.0, 10.0);
select(&mut s, &[a]);
+389 -5
View File
@@ -198,6 +198,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)
}
@@ -519,7 +525,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();
@@ -536,11 +543,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());
}
@@ -7037,6 +7045,382 @@ fn pencil_redraws_a_selected_compound_path() {
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. While the stroke is drawn the shape stays as it
/// was and the selection with it (the preview shows the stroke on its own); the release leaves no
/// new path.
#[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());
let shape = |s: &Session| s.doc().unwrap().doc.node(id).unwrap().path_data().unwrap().clone();
let before = shape(&s);
// 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!(shape(&s) == before, "the shape stays as it was while the stroke is drawn");
assert_eq!(s.doc().unwrap().selection.objects, vec![id], "and stays selected");
}
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<Point> = 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<Point> = 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<Point> = 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 starts and ends on an open path decides by the way it runs along the path at its
/// ends: where it starts it replaces the part it runs along, where it lands it joins the part it runs
/// into, an end that goes straight off or onto the path follows the other end, and when both do it
/// closes only round both pieces beyond. A stroke lifted away from the path ends there. The path is
/// an L whose bottom arm turns up and back over to a hook near the upright arm.
#[test]
fn a_redraw_on_an_open_path_follows_the_way_its_ends_run() {
// From the upright arm's top (100, 0) down, along the bottom, up the right side, back along the
// top to the hook, which ends at (160, 60).
let shape = [[100.0, 0.0], [100.0, 300.0], [400.0, 300.0], [400.0, 100.0], [160.0, 100.0], [160.0, 60.0]];
// A stroke through `pts`, a point every 2 pt, as a hand draws it.
let dense = |pts: &[[f64; 2]]| {
let mut out = vec![json!(pts[0])];
for w in pts.windows(2) {
let (a, b) = (Point::new(w[0][0], w[0][1]), Point::new(w[1][0], w[1][1]));
let n = (a.distance(b) / 2.0).ceil().max(1.0) as usize;
out.extend((1..=n).map(|i| {
let q = a.lerp(b, i as f64 / n as f64);
json!([q.x, q.y])
}));
}
out
};
let has = |sp: &vectorcraft_geom::SubPath, x: f64, y: f64| sp.anchors.iter().any(|a| a.p.distance(Point::new(x, y)) < 1.0);
// Over the loop above the path, from the top edge round to the left of the upright arm.
let over = [[250.0, 40.0], [200.0, -30.0], [100.0, -40.0], [40.0, 0.0]];
// Each: its name, the stroke, and whether the path is closed and keeps the bottom right corner,
// the upright arm's top and the hook's end.
let cases = [
// Runs along the top towards the hook, then up the upright arm: the hook goes, the end is
// left where the pen is lifted, on the arm, and the rest of the path stays.
(
"towards the hook, landing up the arm",
vec![[250.0, 100.0], [165.0, 100.0], [130.0, 95.0], [100.0, 90.0], [100.0, 40.0]],
[false, true, true, false],
),
// Runs along the top away from the hook, then lands running up the arm: the part between
// is replaced, both ends stay.
(
"away from the hook, landing up the arm",
vec![[250.0, 100.0], [300.0, 100.0], [320.0, 60.0], [250.0, 30.0], [140.0, 40.0], [100.0, 90.0], [100.0, 60.0]],
[false, false, true, true],
),
// Straight up off the top, over the arm's top, landing running down the arm: the arm's top and
// the hook go and the path closes round the rest.
(
"straight off, landing down the arm",
[&[[250.0, 100.0]][..], &over, &[[40.0, 120.0], [85.0, 140.0], [100.0, 150.0], [100.0, 180.0]]].concat(),
[true, true, false, false],
),
// Straight off and straight onto the arm, round both the arm's top and the hook: it closes.
("straight off and on, round both", [&[[250.0, 100.0]][..], &over, &[[40.0, 150.0], [100.0, 150.0]]].concat(), [true, true, false, false]),
// The same loop carried on across the arm and lifted inside: the path ends there; the hook,
// the shorter side, goes.
(
"across the arm, lifted away",
[&[[250.0, 100.0]][..], &over, &[[40.0, 150.0], [100.0, 150.0], [200.0, 160.0]]].concat(),
[false, true, true, false],
),
];
for (name, stroke, [closed, body, top, hook]) in cases {
let mut s = session();
let id = NodeId(s.execute("path.freehand", &json!({"points": shape, "fit": false})).unwrap()["id"].as_u64().unwrap());
s.execute("path.freehand", &json!({"points": dense(&stroke), "redraw": {"id": id.0, "within": 12}})).unwrap();
assert_eq!(paths(&s).len(), 1, "{name}: no new path");
let sp = &path(&s, id).subpaths[0];
assert_eq!(sp.closed, closed, "{name}: closed: {sp:?}");
assert_eq!(has(sp, 400.0, 300.0), body, "{name}: the bottom right corner: {sp:?}");
assert_eq!(has(sp, 100.0, 0.0), top, "{name}: the upright arm's top: {sp:?}");
assert_eq!(has(sp, 160.0, 60.0), hook, "{name}: the hook's end: {sp:?}");
}
}
/// A stroke that starts on an open C's upper arm running towards its end, goes round the opening
/// and lands on the lower arm running back into the C closes it into a ring.
#[test]
fn a_stroke_run_over_both_arms_of_a_c_closes_it() {
let mut s = session();
let on = |deg: f64| {
let a = deg.to_radians();
json!([200.0 + 100.0 * a.cos(), 200.0 - 100.0 * a.sin()])
};
let c: Vec<_> = (0..=28).map(|i| on(40.0 + 10.0 * f64::from(i))).collect();
let id = NodeId(s.execute("path.freehand", &json!({"points": c, "fidelity": 0.5})).unwrap()["id"].as_u64().unwrap());
let mut stroke: Vec<_> = (0..=8).map(|i| on(56.0 - 2.0 * f64::from(i))).collect();
stroke.extend([json!([300.0, 160.0]), json!([310.0, 200.0]), json!([300.0, 240.0])]);
stroke.extend((0..=8).map(|i| on(324.0 - 2.0 * f64::from(i))));
s.execute("path.freehand", &json!({"points": stroke, "redraw": {"id": id.0, "within": 4}})).unwrap();
let sp = &path(&s, id).subpaths[0];
assert!(sp.closed, "a ring: {sp:?}");
let bb = kurbo::Shape::bounding_box(&path(&s, id).to_bezpath());
assert!(bb.x0 < 105.0 && bb.x1 > 300.0, "the C's body and the stroke: {bb:?}");
}
/// A tall bump redrawn over most of an open line replaces that part: the ends beyond it stay and
/// the line stays open.
#[test]
fn a_tall_redraw_over_most_of_an_open_line_keeps_its_ends() {
for reversed in [false, true] {
let mut s = session();
let id = line(&mut s, 100.0, 300.0, 700.0, 300.0);
let mut bump =
vec![json!([200, 300]), json!([250, 226]), json!([325, 148]), json!([400, 120]), json!([475, 148]), json!([550, 226]), json!([600, 300])];
if reversed {
bump.reverse();
}
s.execute("path.freehand", &json!({"points": bump, "redraw": {"id": id.0, "within": 12}})).unwrap();
let sp = &path(&s, id).subpaths[0];
assert!(!sp.closed, "reversed {reversed}: still open");
assert!(ends_at(sp, Point::new(100.0, 300.0), Point::new(700.0, 300.0), 1e-6), "reversed {reversed}: both ends stay: {sp:?}");
assert!(kurbo::Shape::bounding_box(&path(&s, id).to_bezpath()).y0 < 135.0, "reversed {reversed}: the bump");
}
}
/// A tall arch over one long side of a thin closed shape replaces that side: the result is the
/// bigger of the two shapes the stroke could make, not the arch alone.
#[test]
fn a_tall_arch_over_a_thin_shapes_side_keeps_the_shape() {
for reversed in [false, true] {
let mut s = session();
let id = rect(&mut s, 100.0, 300.0, 600.0, 60.0);
let mut arch =
vec![json!([130, 300]), json!([197, 216]), json!([265, 144]), json!([400, 80]), json!([535, 144]), json!([603, 216]), json!([670, 300])];
if reversed {
arch.reverse();
}
s.execute("path.freehand", &json!({"points": arch, "redraw": {"id": id.0, "within": 12}})).unwrap();
let sp = &path(&s, id).subpaths[0];
assert!(sp.closed, "reversed {reversed}");
for corner in [(100.0, 300.0), (700.0, 300.0), (700.0, 360.0), (100.0, 360.0)] {
assert!(sp.anchors.iter().any(|a| near(a.p, Point::new(corner.0, corner.1))), "reversed {reversed}: {corner:?} kept: {sp:?}");
}
assert!(kurbo::Shape::bounding_box(&path(&s, id).to_bezpath()).y0 < 95.0, "reversed {reversed}: the arch");
}
}
/// 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}");
}
/// With the Pencil's Live preview off, nothing is added to the document while a filled stroke is
/// drawn; the release draws the path with its fill, as one undo step.
#[test]
+26 -5
View File
@@ -1561,6 +1561,26 @@ impl GestureTool {
v
}
/// The preview of a stroke being drawn: [`Self::freehand_params`], except that a stroke that
/// redraws a selected path is shown as it is drawn, joined at its start to the point of the
/// path nearest to it, with no fill, and leaves the path and the selection as they are: where
/// the stroke ends is only known at the release, which redraws the path (`finish`).
fn drawing_params(&self, cx: &ToolContext) -> Value {
let mut v = self.freehand_params(cx, false);
let Some((id, _)) = self.redraw else { return v };
if let Some(o) = v.as_object_mut() {
o.remove("redraw");
}
v["fill"] = json!(false);
v["keepSelected"] = json!(false);
v["leaveSelection"] = json!(true);
let on = self.points.first().and_then(|&p| cx.doc.node(id)?.path_data()?.nearest(p)).map(|n| n.3);
if let (Some(on), Some(pts)) = (on, v["points"].as_array_mut()) {
pts.insert(0, json!([on.x, on.y]));
}
v
}
fn finish(&mut self, cx: &ToolContext, m: Mods) -> Vec<Action> {
let pts = &self.points;
let has_sel = !cx.selection.is_empty();
@@ -1764,7 +1784,7 @@ impl Tool for GestureTool {
}
// With the Pencil's Live preview off a thin line shows instead (`overlays`).
if self.previews() && crate::previews_at(self.points.len()) {
let mut v = self.freehand_params(cx, false);
let mut v = self.drawing_params(cx);
let fidelity = self.fidelity.max(PREVIEW_FIDELITY_PX);
v["fidelity"] = json!(fit_tolerance(cx, fidelity));
// A preview fitted coarser than the stroke kept is stale (`deactivate`).
@@ -1883,10 +1903,11 @@ impl Tool for GestureTool {
fn deactivate(&mut self, cx: &ToolContext) -> Vec<Action> {
let began = self.began;
self.tip_at = None;
// Drags past the last preview are in the stroke kept, too, and with Live curve fitting
// off the stroke kept is fitted.
let stale = (began && (self.previewed != self.points.len() || !self.live_fit) && self.draws_path() && !self.smoothing)
.then(|| Action::Preview("path.freehand".into(), self.freehand_params(cx, false)));
// Drags past the last preview are in the stroke kept, too, with Live curve fitting off the
// stroke kept is fitted, and a stroke that redraws a path redraws it (`drawing_params`).
let stale =
(began && (self.previewed != self.points.len() || !self.live_fit || self.redraw.is_some()) && self.draws_path() && !self.smoothing)
.then(|| Action::Preview("path.freehand".into(), self.freehand_params(cx, false)));
self.snap.clear();
self.active = false;
self.near_start = false;
+38
View File
@@ -856,6 +856,44 @@ fn pencil_shows_the_straight_line_cursor_when_a_press_draws_a_line() {
assert_eq!(Cursor::PencilStraight.precise(), Cursor::Crosshair, "Use Precise Cursors");
}
/// While a stroke that redraws a selected path is drawn, its previews show the stroke as drawn,
/// joined at its start to the path, unfilled, and leave the path and the selection as they are;
/// the release (or a switch of tool mid-stroke) redraws the path.
#[test]
fn pencil_previews_a_redraw_as_the_stroke_drawn_and_redraws_at_the_release() {
let (mut d, _) = doc_with_rect();
let l = d.layers[0].id;
let id = d.alloc_id();
let line = vectorcraft_geom::PathData::from_bezpath(&vectorcraft_geom::BezPath::from_vec(vec![
vectorcraft_geom::PathEl::MoveTo(Point::new(300.0, 300.0)),
vectorcraft_geom::PathEl::LineTo(Point::new(400.0, 300.0)),
]));
d.insert(Some(l), 1, vectorcraft_doc::Node::path(id, line, vectorcraft_doc::Appearance::default_art())).unwrap();
let mut s = Selection::default();
s.set([id]);
let p = paint();
let mut cx = cx(&d, &s, &p);
cx.smart_guides = false;
let mut t = GestureTool::new("pencil");
t.set_option("fill", &json!(true));
// Out from the path and back onto it: within Edit selected paths within all the way.
let acts = drag(&mut t, &cx, &[(350.0, 304.0), (352.0, 308.0), (356.0, 309.0), (360.0, 303.0)], Mods::default());
let (release, drawing) = acts.split_last().unwrap();
let previews: Vec<&Value> = drawing.iter().flatten().filter_map(|a| if let Action::Preview(_, v) = a { Some(v) } else { None }).collect();
assert!(!previews.is_empty(), "{acts:?}");
for v in previews {
assert!(v.get("redraw").is_none() && v["fill"] == false && v["keepSelected"] == false && v["leaveSelection"] == true, "{v}");
assert_eq!(v["points"][0], json!([350.0, 300.0]), "joined to the path where it starts: {v}");
assert_eq!(v["points"][1], json!([350.0, 304.0]), "{v}");
}
assert!(matches!(release.as_slice(), [Action::Preview(_, v), Action::Commit] if v["redraw"]["id"] == id.0 && v["fill"] == true), "{release:?}");
// A switch of tool mid-stroke keeps the redraw too.
t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 350.0, 304.0));
t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 352.0, 320.0));
let acts = t.deactivate(&cx);
assert!(matches!(acts.as_slice(), [Action::Preview(_, v), Action::Commit] if v["redraw"]["id"] == id.0), "{acts:?}");
}
/// Before a press, the Pencil shows its new-path cursor (the star) exactly when the press draws
/// a new path: over an end of a selected open path, which the stroke continues, and over a
/// selected path, which it redraws, it does not. With nothing selected, with Edit Selected Paths
File diff suppressed because one or more lines are too long
+2 -2
View File
File diff suppressed because one or more lines are too long