Fix #8568: a selection held by its edge lands that point on other paths

With Smart Guides on, a selection the Selection tool held by a point of
a path's edge (a press on its stroke, on its outline in Outline view, or
on the fill within 6 screen points of the edge) snapped that point only
to other anchors and centers, or lined its bounds up. It now also lands
on the other objects' paths ("path") and where paths and ruler guides
cross ("intersect"), as a selection grabbed by an anchor does since

On a straight path, the selection then slides along that path, the
point staying on it, until its bounds line up with other objects, are
spaced evenly with them or line up with a ruler guide. The slide goes
at most twice the Snapping Tolerance and not past the path's ends. On a
curved path and at a crossing the point lands as an anchor does, and
the bounds do not line up.
This commit is contained in:
dotCooCoo
2026-11-18 12:29:10 -08:00
parent e34bf8c82f
commit cb3d274550
4 changed files with 438 additions and 44 deletions
+162 -23
View File
@@ -119,6 +119,27 @@ fn parallel(a: Vec2, b: Vec2) -> bool {
scale > 1e-18 && a.dot(b) > 0.0 && a.cross(b).abs() <= 1e-6 * scale
}
/// `seg` as a line from its start to its end when it runs straight: a line, or a curve whose
/// control points lie on that line and that stays between its ends (a straight path with its
/// handles drawn out along it).
fn straight(seg: PathSeg) -> Option<Line> {
use vectorcraft_geom::kurbo::ParamCurveExtrema;
let (l, ctrl) = match seg {
PathSeg::Line(l) => return Some(l),
PathSeg::Quad(q) => (Line::new(q.p0, q.p2), [q.p1, q.p1]),
PathSeg::Cubic(c) => (Line::new(c.p0, c.p3), [c.p1, c.p2]),
};
let d = l.p1 - l.p0;
let len2 = d.hypot2();
if !len2.is_finite() || len2 <= 1e-18 || !ctrl.into_iter().all(|p| d.cross(p - l.p0).abs() <= 1e-9 * len2) {
return None;
}
// The curve's own bounds, not its control points', must stay within the ends' box.
let (b, ends) = (ParamCurveExtrema::bounding_box(&seg), Rect::from_points(l.p0, l.p1));
let eps = 1e-9 * len2.sqrt();
(b.x0 >= ends.x0 - eps && b.x1 <= ends.x1 + eps && b.y0 >= ends.y0 - eps && b.y1 <= ends.y1 + eps).then_some(l)
}
/// Does the curve `seg` run around `center` the whole way, as an arc of a circle about it drawn
/// with curves does: nearly square to the center all along, and its distance from the center
/// varying by no more than 0.03%? A circle drawn with four curves ([`vectorcraft_geom::shapes::ellipse`])
@@ -257,9 +278,10 @@ impl Targets {
Self::moving(cx, exclude, Gather::Bounds)
}
/// [`Self::for_move`]'s targets for a selection moved by one of its anchors (#7411): the path
/// segments of the art but `exclude` too, which that anchor lands on ([`Self::snap_onto_path`]),
/// as a dragged anchor does with Direct Selection.
/// [`Self::for_move`]'s targets for a selection moved by one of its anchors (#7411) or by a
/// point of a path's stroke or outline (#8568): the path segments of the art but `exclude` too,
/// which that point lands on ([`Self::snap_onto_path`]), as a dragged anchor does with Direct
/// Selection.
pub fn for_move_by_anchor(cx: &ToolContext, exclude: &[NodeId]) -> Self {
Self::moving(cx, exclude, Gather::Segments)
}
@@ -1036,15 +1058,57 @@ impl Targets {
Some((q, self.label(q, Kind::Edge.label()).into_iter().collect()))
}
/// [`Self::snap_onto_path`] for a selection held by a point `p` of a path's edge, its bounds
/// now `r` (#8568). Where paths cross, or on a curved segment, the point lands as
/// `snap_onto_path` lands it. On a straight segment, the selection then slides along that
/// segment, so the point stays on it, until its bounds line up with the other art or are spaced
/// evenly with it ([`Self::snap_rects_along`]), else until they line up with a ruler guide of
/// `rulers` ([`Self::snap_moved_along_to_rulers`]). A slide goes at most twice `tol` and not
/// past the segment's ends. Returns where the point goes and the guides.
pub(crate) fn snap_held_onto_path(&self, p: Point, r: Rect, tol: f64, rulers: Option<&Targets>) -> Option<(Point, Vec<Overlay>)> {
if self.segments.is_empty() {
return None;
}
if let Some(q) = self.crossing_with(p, tol, rulers.map_or(&self.rulers, |r| &r.rulers)) {
return Some((q, self.label(q, "intersect").into_iter().collect()));
}
let (seg, q) = self.nearest_segment(p, tol)?;
let on_path = |q: Point| self.label(q, Kind::Edge.label());
let Some(l) = straight(seg) else { return Some((q, on_path(q).into_iter().collect())) };
let len = (l.p1 - l.p0).hypot();
if !len.is_finite() || len <= 1e-9 {
return Some((q, on_path(q).into_iter().collect()));
}
let u = (l.p1 - l.p0) / len;
let moved = r + (q - p);
// How far the point may slide each way: twice `tol`, and not past the segment's ends.
let at = (q - l.p0).dot(u);
let within = ((-at).max(-2.0 * tol), (len - at).min(2.0 * tol));
let (s, mut ov) = Some(self.slide_rects_along(&[moved], u, tol, within))
.filter(|(.., hit)| *hit)
.or_else(|| rulers.map(|t| t.slide_moved_along_to_rulers(q, moved, u, tol, within)).filter(|(.., hit)| *hit))
.map_or((Vec2::ZERO, vec![]), |(s, ov, _)| (s, ov));
let q = q + s;
// The point's label is "path", the label a ruler guide's slide puts there too.
ov.retain(|o| !matches!(o, Overlay::Label { .. }));
ov.extend(on_path(q));
Some((q, ov))
}
/// The nearest point within `tol` of `p` on a target segment.
fn on_segment(&self, p: Point, tol: f64) -> Option<Point> {
self.nearest_segment(p, tol).map(|(_, q)| q)
}
/// [`Self::on_segment`], with the segment the point is on.
fn nearest_segment(&self, p: Point, tol: f64) -> Option<(PathSeg, Point)> {
self.segments
.iter()
.filter(|(b, _)| b.inflate(tol, tol).contains(p))
.map(|(_, c)| (c, c.nearest(p, 1e-6)))
.filter(|(_, n)| n.distance_sq <= tol * tol)
.min_by(|a, b| a.1.distance_sq.total_cmp(&b.1.distance_sq))
.map(|(c, n)| c.eval(n.t))
.map(|(c, n)| (*c, c.eval(n.t)))
}
/// Where two target paths, a path and a ruler guide, or two ruler guides cross, the crossing
@@ -1152,9 +1216,16 @@ impl Targets {
/// it is spaced evenly along an axis the line runs along. Returns the shift (along `dir`) and
/// the guides.
pub(crate) fn snap_rects_along(&self, rects: &[Rect], dir: Vec2, tol: f64) -> (Vec2, Vec<Overlay>) {
let (s, ov, _) = self.slide_rects_along(rects, dir, tol, (f64::NEG_INFINITY, f64::INFINITY));
(s, ov)
}
/// [`Self::snap_rects_along`] for a slide of `within` (the least and the most way along
/// `dir`), also saying whether anything lined up or was spaced evenly.
fn slide_rects_along(&self, rects: &[Rect], dir: Vec2, tol: f64, (lo, hi): (f64, f64)) -> (Vec2, Vec<Overlay>, bool) {
let len = dir.hypot();
if !len.is_finite() || len <= 1e-9 {
return (Vec2::ZERO, vec![]);
return (Vec2::ZERO, vec![], false);
}
let u = dir / len;
// The axes the line runs along: the x axis (`true`) and the y axis, and how far a step of
@@ -1170,7 +1241,7 @@ impl Targets {
for v in vs {
for (t, from, _) in lines_near(lines, v, tol).iter().filter(|(t, ..)| (t - v).abs() <= tol) {
let s = (t - v) / c;
if best.is_none_or(|b| s.abs() < b.0.abs()) {
if (lo..=hi).contains(&s) && best.is_none_or(|b| s.abs() < b.0.abs()) {
best = Some((s, *t, *from, x));
}
}
@@ -1185,17 +1256,41 @@ impl Targets {
self.line(Point::new(from.x.min(m.x0), t), Point::new(from.x.max(m.x1), t))
}
});
return (u * s, ov.into_iter().collect());
return (u * s, ov.into_iter().collect(), true);
}
let [r] = rects else { return (Vec2::ZERO, vec![]) };
let [r] = rects else { return (Vec2::ZERO, vec![], false) };
if self.boxes.is_empty() {
return (Vec2::ZERO, vec![]);
return (Vec2::ZERO, vec![], false);
}
let spaced =
axes.filter_map(|(x, c)| self.even_spacing(*r, x, tol).map(|(shift, _)| (shift / c, x))).min_by(|a, b| a.0.abs().total_cmp(&b.0.abs()));
let Some((s, x)) = spaced else { return (Vec2::ZERO, vec![]) };
// The slide that spaces it evenly along each axis, within `lo..=hi` along the line. A slide
// along a slanted line also moves it across, so the gaps must still be equal where it ends
// up.
let spaced = axes
.filter_map(|(x, c)| {
// A level or upright slide along that axis keeps its row.
let level = (if x { u.y } else { u.x }).abs() <= 1e-9;
// At most 8 slides are checked where they end up, to bound the work per pointer move.
let checked = std::cell::Cell::new(0_usize);
let fits = |shift: f64| {
let s = shift / c;
if !(lo..=hi).contains(&s) {
return false;
}
if level {
return true;
}
if checked.get() >= 8 {
return false;
}
checked.set(checked.get() + 1);
self.even_spacing(*r + u * s, x, tol).is_some_and(|(rest, _)| rest.abs() <= 1e-6)
};
self.even_spacing_by(*r, x, tol, Some(&fits)).map(|(shift, _)| (shift / c, x))
})
.min_by(|a, b| a.0.abs().total_cmp(&b.0.abs()));
let Some((s, x)) = spaced else { return (Vec2::ZERO, vec![], false) };
let gaps = self.even_spacing(*r + u * s, x, tol).map(|(_, gaps)| gaps).unwrap_or_default();
(u * s, gaps.into_iter().flat_map(|g| self.gap_marks(g, x, tol)).collect())
(u * s, gaps.into_iter().flat_map(|g| self.gap_marks(g, x, tol)).collect(), true)
}
/// Snap rectangles that move together (an artboard and its bleed): the edge or centre of any
@@ -1240,6 +1335,12 @@ impl Targets {
/// neighbour before or after it as two other objects of the row are apart, or as far from both
/// neighbours; and the equal gaps then, as (start, end, where across) along that axis.
fn even_spacing(&self, r: Rect, x: bool, tol: f64) -> Option<(f64, Vec<[f64; 3]>)> {
self.even_spacing_by(r, x, tol, None)
}
/// [`Self::even_spacing`] for the nearest shift along that axis that `accept` takes (any shift
/// when `None`).
fn even_spacing_by(&self, r: Rect, x: bool, tol: f64, accept: Option<&dyn Fn(f64) -> bool>) -> Option<(f64, Vec<[f64; 3]>)> {
let (r0, r1) = span(&r, x);
let len = r1 - r0;
let (c0, c1) = span(&r, !x);
@@ -1276,8 +1377,36 @@ impl Targets {
starts.extend(before.map(|a| (a.2 + g, Some(*g))));
starts.extend(after.map(|b| (b.1 - g - len, Some(*g))));
}
let (start, repeats) =
starts.into_iter().filter(|(t, _)| (t - r0).abs() <= tol).min_by(|a, b| (a.0 - r0).abs().total_cmp(&(b.0 - r0).abs()))?;
starts.retain(|(t, _)| (t - r0).abs() <= tol);
let nearer = |a: &(f64, Option<f64>), b: &(f64, Option<f64>)| (a.0 - r0).abs().total_cmp(&(b.0 - r0).abs());
let (start, repeats) = match accept {
// The nearest start, the first proposed among equally near ones.
None => starts.into_iter().min_by(nearer)?,
Some(accept) => {
// Nearest first; the sort is stable, so equally near starts keep the order they
// were proposed in. Starts as near as each other are at most two shifts (one each
// way), so the shifts refused at the current distance are few, and each is asked
// about once.
starts.sort_by(nearer);
let mut refused: Vec<f64> = vec![];
let mut at = f64::NAN;
starts.into_iter().find(|(t, _)| {
let shift = t - r0;
if shift.abs() != at {
at = shift.abs();
refused.clear();
}
if refused.contains(&shift) {
return false;
}
let ok = accept(shift);
if !ok {
refused.push(shift);
}
ok
})?
}
};
let at = r + if x { Vec2::new(start - r0, 0.0) } else { Vec2::new(0.0, start - r0) };
let (end, mut gaps) = (start + len, vec![]);
if let Some((a, _, a1)) = before
@@ -1385,9 +1514,16 @@ impl Targets {
/// shortest slide winning and at most twice `tol` (a line nearly parallel to a guide would
/// carry the selection far to meet it). Returns the shift along the line and the guides.
pub(crate) fn snap_moved_along_to_rulers(&self, p: Point, r: Rect, dir: Vec2, tol: f64) -> (Vec2, Vec<Overlay>) {
let (s, ov, _) = self.slide_moved_along_to_rulers(p, r, dir, tol, (f64::NEG_INFINITY, f64::INFINITY));
(s, ov)
}
/// [`Self::snap_moved_along_to_rulers`] for a slide of `within` (the least and the most way
/// along `dir`), also saying whether the bounds lined up with a guide.
fn slide_moved_along_to_rulers(&self, p: Point, r: Rect, dir: Vec2, tol: f64, (lo, hi): (f64, f64)) -> (Vec2, Vec<Overlay>, bool) {
let len = dir.hypot();
if !len.is_finite() || len <= 1e-9 {
return (Vec2::ZERO, vec![]);
return (Vec2::ZERO, vec![], false);
}
let u = dir / len;
// The way along the line, where the guide is and where it starts, and whether it is upright.
@@ -1397,18 +1533,21 @@ impl Targets {
continue;
}
let vs = if vertical { [r.x0, r.center().x, r.x1] } else { [r.y0, r.center().y, r.y1] };
let (mid, half) =
if vertical { (Point::new(0.0, r.center().y), r.height() / 2.0) } else { (Point::new(r.center().x, 0.0), r.width() / 2.0) };
for (t, from, _) in self.rulers.iter().filter(|g| g.vertical == vertical).filter_map(|g| g.line_at(mid, tol + half)) {
let half = if vertical { r.height() / 2.0 } else { r.width() / 2.0 };
for g in self.rulers.iter().filter(|g| g.vertical == vertical) {
for v in vs {
let s = (t - v) / c;
if (t - v).abs() <= tol && s.abs() <= 2.0 * tol && best.is_none_or(|b| s.abs() < b.0.abs()) {
let s = (g.pos - v) / c;
if (g.pos - v).abs() > tol || s.abs() > 2.0 * tol || !(lo..=hi).contains(&s) || best.is_some_and(|b| s.abs() >= b.0.abs()) {
continue;
}
// The guide runs past the bounds where the slide puts them.
if let Some((t, from, _)) = g.line_at(r.center() + u * s, tol + half) {
best = Some((s, t, from, vertical));
}
}
}
}
let Some((s, t, from, vertical)) = best else { return (Vec2::ZERO, vec![]) };
let Some((s, t, from, vertical)) = best else { return (Vec2::ZERO, vec![], false) };
let moved = r + u * s;
let line = if vertical {
self.line(Point::new(t, from.y.min(moved.y0)), Point::new(t, from.y.max(moved.y1)))
@@ -1417,7 +1556,7 @@ impl Targets {
};
let mut ov: Vec<Overlay> = line.into_iter().collect();
ov.extend(self.label(p + u * s, "align"));
(u * s, ov)
(u * s, ov, true)
}
/// Snap a bounding-box resize. `a` is the scale [`crate::bbox::scale_for_drag`] gave for
+67 -18
View File
@@ -81,6 +81,18 @@ fn marquee_enclosed(cx: &ToolContext, inverted: bool, directional_inside: bool)
inside != inverted
}
/// What a press took the selection by, which decides what that point snaps to.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Grip {
/// A center or the pressed point: it lands on anchors and centers, or the bounds line up.
Point,
/// One of its anchors: it also lands on paths and where they cross ([`MoveSnap::by_anchor`]).
Anchor,
/// A point of a path's stroke, outline or edge ([`hold_point`]): it also lands on paths and
/// where they cross, and along a straight path the bounds still line up ([`MoveSnap::by_edge`]).
Edge,
}
#[derive(Clone, Debug, Default)]
enum State {
#[default]
@@ -94,9 +106,9 @@ enum State {
/// The point that snaps, moving with the pointer: `start`, or where a press on a path's
/// stroke or beside its edge took hold of the path ([`hold_point`]).
hold: Point,
/// The press grabbed the selection by an anchor (`start`): it snaps as
/// [`MoveSnap::by_anchor`] says.
by_anchor: bool,
/// What the press took the selection by: an anchor (`start`), a point of a path's edge
/// (`hold`), or neither.
grip: Grip,
began: bool,
/// Shift-pressed on this selected object: released without a drag, it leaves the
/// selection.
@@ -252,6 +264,8 @@ pub(crate) struct MoveSnap {
/// onto (#1534), and lines the bounds up with (#5746), within the Snapping Tolerance as drawing
/// does; `points` holds them with Smart Guides off.
rulers: Option<Targets>,
/// Held by a point of a path's edge ([`Self::by_edge`]).
by_edge: bool,
}
impl MoveSnap {
@@ -266,6 +280,13 @@ impl MoveSnap {
Self::gather(cx, Targets::for_move_by_anchor)
}
/// [`Self::by_anchor`] for a selection held by a point of a path's stroke, outline or edge
/// (#8568): that point also lands on the other art's paths and where they cross, and on a
/// straight path the bounds still line up, sliding along it ([`Targets::snap_held_onto_path`]).
pub(crate) fn by_edge(cx: &ToolContext) -> Self {
Self { by_edge: true, ..Self::gather(cx, Targets::for_move_by_anchor) }
}
fn gather(cx: &ToolContext, for_move: fn(&ToolContext, &[NodeId]) -> Targets) -> Self {
let guides = cx.smart_guides && !cx.snap_to_grid;
let points = |exclude: &[NodeId]| if cx.snap_to_grid { None } else { Targets::snap_to_point(cx, exclude) };
@@ -276,13 +297,14 @@ impl MoveSnap {
copy_targets: guides.then(|| for_move(cx, &[])),
copy_points: points(&[]),
rulers: (guides && cx.snap_to_point).then(|| Targets::rulers(cx)),
by_edge: false,
}
}
/// Snap to Grid and Snap to Pixel alone, for a move whose box is `bounds`: the grid lands an
/// edge of the box on a gridline, and pixels put its top-left on whole pixels.
pub(crate) fn grid_only(bounds: Option<Rect>) -> Self {
Self { bounds, targets: None, points: None, copy_targets: None, copy_points: None, rulers: None }
Self { bounds, targets: None, points: None, copy_targets: None, copy_points: None, rulers: None, by_edge: false }
}
/// The move (`copy`: the copy) by `d` of the selection grabbed at `start`, snapped, and its
@@ -317,9 +339,14 @@ impl MoveSnap {
d = q - start;
guides = ov;
taken = [true; 2];
} else if let Some((q, ov)) = t.snap_onto_path(start + d, cx.snap_tol(), self.rulers.as_ref()) {
} else if let Some((q, ov)) = if self.by_edge {
t.snap_held_onto_path(start + d, b + d, cx.snap_tol(), self.rulers.as_ref())
} else {
t.snap_onto_path(start + d, cx.snap_tol(), self.rulers.as_ref())
} {
// Grabbed by an anchor ([`Self::by_anchor`]), it lands on a path near it, or where
// the path crosses another or a ruler guide, instead of lining the bounds up.
// the path crosses another or a ruler guide, instead of lining the bounds up. Held
// by its edge ([`Self::by_edge`]), along a straight path the bounds still line up.
d = q - start;
guides = ov;
taken = [true; 2];
@@ -649,8 +676,13 @@ const HOVER_REACH: f64 = 6.0;
/// hit, when the press is on its stroke or outline or within [`HOVER_REACH`] of it, else `p`
/// ([`hold_on_path`]). That point snaps, so the path itself lands on a ruler guide (#3701).
pub(crate) fn hold_point(cx: &ToolContext, h: &Hit, p: Point) -> Point {
held_on_path(cx, h, p).unwrap_or(p)
}
/// [`hold_point`]'s point of the path hit, None when the press holds no point of it.
fn held_on_path(cx: &ToolContext, h: &Hit, p: Point) -> Option<Point> {
let reach = if matches!(h.kind, HitKind::Stroke | HitKind::Outline) { f64::INFINITY } else { cx.tol(HOVER_REACH) };
cx.doc.node(h.leaf).and_then(|n| n.path_data()).and_then(|pd| hold_on_path(pd, p, reach)).unwrap_or(p)
cx.doc.node(h.leaf).and_then(|n| n.path_data()).and_then(|pd| hold_on_path(pd, p, reach))
}
/// While an opacity mask or a pattern is edited, a Shaper double-click selects a Shaper Group's
@@ -1029,7 +1061,7 @@ impl Tool for SelectionTool {
{
let several = cx.selection.objects.len() > 1 || !cx.selection.guides.is_empty();
let (deselect, key) = if m.shift { (Some(id), None) } else { (None, (several && !m.alt).then_some(id)) };
self.state = State::Moving { start: p, press: p, hold: center, by_anchor: false, began: false, deselect, key, exclude: None };
self.state = State::Moving { start: p, press: p, hold: center, grip: Grip::Point, began: false, deselect, key, exclude: None };
return vec![];
}
// 3. Objects: Cmd/Ctrl-click selects the one under the selected one (cycling).
@@ -1038,7 +1070,7 @@ impl Tool for SelectionTool {
&& let Some(behind) = object_behind(cx, p)
{
self.state =
State::Moving { start: p, press: p, hold: p, by_anchor: false, began: false, deselect: None, key: None, exclude: None };
State::Moving { start: p, press: p, hold: p, grip: Grip::Point, began: false, deselect: None, key: None, exclude: None };
return vec![Action::Exec("select.set".into(), json!({ "ids": [behind.0] }))];
}
let (hit, scope) = match selected_source_hit(cx, p) {
@@ -1060,9 +1092,13 @@ impl Tool for SelectionTool {
out.push(Action::Exec("select.set".into(), json!({ "ids": [top.0] })));
}
// Grabbed by no anchor or centre, a press on a path's stroke or beside its
// edge holds the path there, and that point of it snaps (#3701).
let hold = if grabbed.is_some() { grab } else { hold_point(cx, &h, p) };
self.state = State::Moving { start: grab, press: p, hold, by_anchor, began: false, deselect, key, exclude };
// edge holds the path there, and that point of it snaps (#3701). Like a
// grabbed anchor, that point also lands on the other art's paths (#8568).
let (hold, grip) = match grabbed {
Some(_) => (grab, if by_anchor { Grip::Anchor } else { Grip::Point }),
None => held_on_path(cx, &h, p).map_or((p, Grip::Point), |q| (q, Grip::Edge)),
};
self.state = State::Moving { start: grab, press: p, hold, grip, began: false, deselect, key, exclude };
out
}
None => {
@@ -1071,8 +1107,8 @@ impl Tool for SelectionTool {
}
}
}
(PointerKind::Drag, State::Moving { start, press, hold, by_anchor, began, exclude, .. }) => {
self.drag_moving(cx, p, m, ev.backquote, (start, press, hold, by_anchor, began), exclude)
(PointerKind::Drag, State::Moving { start, press, hold, grip, began, exclude, .. }) => {
self.drag_moving(cx, p, m, ev.backquote, (start, press, hold, grip, began), exclude)
}
(PointerKind::Drag, State::Scaling { handle, bx, areas }) => {
self.last_backquote = ev.backquote;
@@ -1841,7 +1877,16 @@ impl SelectionTool {
/// `by_anchor`: `grab` is an anchor of it.
fn press_nothing(&mut self, cx: &ToolContext, p: Point, grab: Point, by_anchor: bool, m: Mods) {
self.state = if !m.shift && selected_hidden_at(cx.doc, p, cx.selection_hit_options(), &cx.selection.objects).is_some() {
State::Moving { start: grab, press: p, hold: grab, by_anchor, began: false, deselect: None, key: None, exclude: None }
State::Moving {
start: grab,
press: p,
hold: grab,
grip: if by_anchor { Grip::Anchor } else { Grip::Point },
began: false,
deselect: None,
key: None,
exclude: None,
}
} else {
State::Marquee { start: p, cur: p, toggle: m.shift, enclosed: false, directional_inside: false }
};
@@ -1853,7 +1898,7 @@ impl SelectionTool {
p: Point,
m: Mods,
backquote: bool,
(start, press, hold, by_anchor, began): (Point, Point, Point, bool, bool),
(start, press, hold, grip, began): (Point, Point, Point, Grip, bool),
exclude: Option<(NodeId, NodeId)>,
) -> Vec<Action> {
let mut out = vec![];
@@ -1861,7 +1906,11 @@ impl SelectionTool {
if p.distance(press) < Self::drag_threshold(cx) {
return out;
}
let gather = if by_anchor { MoveSnap::by_anchor } else { MoveSnap::new };
let gather = match grip {
Grip::Point => MoveSnap::new,
Grip::Anchor => MoveSnap::by_anchor,
Grip::Edge => MoveSnap::by_edge,
};
// A Shift-drag from a highlighted object of the Global Edit selects it and moves it
// with the selection: its snap targets are gathered for the selection with it.
self.moving = Some(match exclude {
@@ -1882,7 +1931,7 @@ impl SelectionTool {
}
// Shift has already constrained `d`: any change is a snap.
self.snapped = (d - unsnapped).hypot() > 1e-9;
self.state = State::Moving { start, press, hold, by_anchor, began: true, deselect: None, key: None, exclude: None };
self.state = State::Moving { start, press, hold, grip, began: true, deselect: None, key: None, exclude: None };
self.measure = cx.measurement_labels.then(|| (p, cx.offset_label(d.x, d.y)));
let mut params = json!({ "matrix": matrix_json(Affine::translate(d)), "copy": m.alt });
if backquote {
+208 -2
View File
@@ -247,10 +247,23 @@ fn doc_with_rect_and_lines(lines: &[(Point, Point)]) -> (vectorcraft_doc::Docume
/// The rectangle of `d` grabbed at `(gx, gy)` (hovered first, so a press near an anchor grabs it)
/// and dragged to `to`, with Smart Guides on or off (`smart`): the point it was grabbed at after the
/// move, and the label shown.
fn grabbed_and_dragged(d: &vectorcraft_doc::Document, id: NodeId, smart: bool, (gx, gy): (f64, f64), to: (f64, f64)) -> (Point, Option<String>) {
fn grabbed_and_dragged(d: &vectorcraft_doc::Document, id: NodeId, smart: bool, grab: (f64, f64), to: (f64, f64)) -> (Point, Option<String>) {
grabbed_and_dragged_in(d, id, smart, false, grab, to)
}
/// [`grabbed_and_dragged`] in Preview or, with `outline`, in Outline view.
fn grabbed_and_dragged_in(
d: &vectorcraft_doc::Document,
id: NodeId,
smart: bool,
outline: bool,
(gx, gy): (f64, f64),
to: (f64, f64),
) -> (Point, Option<String>) {
let (none, mut picked, p) = (Selection::default(), Selection::default(), paint());
picked.add(id);
let (before, after) = (ToolContext { smart_guides: smart, ..cx(d, &none, &p) }, ToolContext { smart_guides: smart, ..cx(d, &picked, &p) });
let (before, after) =
(ToolContext { smart_guides: smart, outline, ..cx(d, &none, &p) }, ToolContext { smart_guides: smart, outline, ..cx(d, &picked, &p) });
let mut t = SelectionTool::default();
t.pointer(&before, &ev(PointerKind::Move, gx, gy));
t.pointer(&before, &ev(PointerKind::Down, gx, gy));
@@ -286,6 +299,199 @@ fn a_move_grabbed_by_an_anchor_lands_it_on_another_path() {
assert!(off_line(corner) > 0.4, "the corner lands at {corner:?}");
}
/// #8568: a selection held by a point of its path's edge (pressed on the edge, or on the fill just
/// beside it) lands that point on another path ("path") with Smart Guides, in Preview and in
/// Outline view.
#[test]
fn a_move_held_by_a_paths_edge_lands_it_on_another_path() {
let (a, b) = (Point::new(300.0, 400.0), Point::new(500.0, 300.0));
let (d, id) = doc_with_rect_and_lines(&[(a, b)]);
let off_line = |q: Point| ((b - a).cross(q - a) / (b - a).hypot()).abs();
for outline in [false, true] {
// Hold the rectangle by its bottom edge at (150, 200), away from its corners and center,
// and drop that point half a point beside the line.
let (edge, label) = grabbed_and_dragged_in(&d, id, true, outline, (150.0, 200.0), (430.0, 335.5));
assert!(off_line(edge) < 1e-9, "outline {outline}: the edge lands at {edge:?}, {} off the line", off_line(edge));
assert!((edge.x - 430.0).abs() < 0.5, "outline {outline}: {edge:?}");
assert_eq!(label.as_deref(), Some("path"), "outline {outline}");
// With Smart Guides off, the edge stays where it was dragged.
let (edge, _) = grabbed_and_dragged_in(&d, id, false, outline, (150.0, 200.0), (430.0, 335.5));
assert!(off_line(edge) > 0.4, "outline {outline}: the edge lands at {edge:?}");
}
// Pressed on the fill 3 points inside the bottom edge, the press holds the edge at
// (150, 200), and that point lands on the line.
let (edge, label) = pressed_and_dragged(&d, id, (150.0, 197.0), Point::new(150.0, 200.0), (430.0, 332.5), false);
assert!(off_line(edge) < 1e-9, "the edge lands at {edge:?}, {} off the line", off_line(edge));
assert_eq!(label.as_deref(), Some("path"));
}
/// The rectangle of `d` pressed at `press` (not hovered first) and dragged to `to`, Alt held for a
/// copy with `alt`: where its point `at` goes, and the label shown.
fn pressed_and_dragged(
d: &vectorcraft_doc::Document,
id: NodeId,
press: (f64, f64),
at: Point,
to: (f64, f64),
alt: bool,
) -> (Point, Option<String>) {
pressed_and_dragged_with(d, id, press, at, to, alt, true)
}
/// [`pressed_and_dragged`] with Smart Guides › Alignment Guides on or off (`lines`).
fn pressed_and_dragged_with(
d: &vectorcraft_doc::Document,
id: NodeId,
press: (f64, f64),
at: Point,
to: (f64, f64),
alt: bool,
lines: bool,
) -> (Point, Option<String>) {
let (none, mut picked, p) = (Selection::default(), Selection::default(), paint());
picked.add(id);
let (before, after) =
(ToolContext { alignment_guides: lines, ..cx(d, &none, &p) }, ToolContext { alignment_guides: lines, ..cx(d, &picked, &p) });
let mut t = SelectionTool::default();
t.pointer(&before, &ev(PointerKind::Down, press.0, press.1));
let a = t.pointer(&after, &ev(PointerKind::Drag, to.0, to.1).with_mods(Mods { alt, ..Mods::default() }));
let Some(Action::Preview(_, v)) = a.iter().find(|a| matches!(a, Action::Preview(..))) else { panic!("{a:?}") };
let label = t.overlays(&after).iter().find_map(|o| match o {
Overlay::Label { text, .. } => Some(text.clone()),
_ => None,
});
(at + Vec2::new(v["matrix"][4].as_f64().unwrap(), v["matrix"][5].as_f64().unwrap()), label)
}
/// #8568: a selection held by its edge that lands on a straight path still lines its bounds up
/// along that path: on a level path the held point keeps the path's y, and the bounds line up on
/// x with the other art, else with a ruler guide. A press on the fill farther inside than 6 points
/// holds no edge and lines the bounds up as before, and so does an edge hold with no path in reach.
#[test]
fn a_move_held_by_an_edge_on_a_straight_path_still_lines_its_bounds_up_along_it() {
let (mut d, id) = doc_with_rect_and_lines(&[(Point::new(300.0, 300.0), Point::new(500.0, 300.0))]);
// Held by the top edge at (130, 100) and dropped at (331, 300.5): the point lands on the path,
// and the left side (at 301) lines up with the path's start at x 300.
let top = Point::new(130.0, 100.0);
let (edge, label) = pressed_and_dragged(&d, id, (130.0, 100.0), top, (331.0, 300.5), false);
assert!(edge.distance(Point::new(330.0, 300.0)) < 1e-9, "the edge lands at {edge:?}");
assert_eq!(label.as_deref(), Some("path"));
// With Alignment Guides off, no line shows, and the bounds still line up.
let (edge, _) = pressed_and_dragged_with(&d, id, (130.0, 100.0), top, (331.0, 300.5), false, false);
assert!(edge.distance(Point::new(330.0, 300.0)) < 1e-9, "the edge lands at {edge:?}");
// A fill press 3 points inside the edge holds it the same way.
let (edge, _) = pressed_and_dragged(&d, id, (130.0, 103.0), top, (331.0, 303.5), false);
assert!(edge.distance(Point::new(330.0, 300.0)) < 1e-9, "the edge lands at {edge:?}");
// A fill press 10 points inside holds no edge: the bounds line up on x, and the pressed point
// does not land on the path.
let (grip, _) = pressed_and_dragged(&d, id, (130.0, 110.0), Point::new(130.0, 110.0), (331.0, 300.5), false);
assert!(grip.distance(Point::new(330.0, 300.5)) < 1e-9, "the grip lands at {grip:?}");
// Held by the edge with no path in reach, the bounds line up on x.
let (edge, _) = pressed_and_dragged(&d, id, (130.0, 100.0), top, (331.0, 280.0), false);
assert!(edge.distance(Point::new(330.0, 280.0)) < 1e-9, "the edge lands at {edge:?}");
// With a ruler guide at x 320 and nothing else in line, the left side (at 321) goes onto it
// while the point stays on the path.
d.add_ruler_guide(&vectorcraft_doc::Guide::new(true, 320.0));
let (edge, label) = pressed_and_dragged(&d, id, (130.0, 100.0), top, (351.0, 300.5), false);
assert!(edge.distance(Point::new(350.0, 300.0)) < 1e-9, "the edge lands at {edge:?}");
assert_eq!(label.as_deref(), Some("path"));
}
/// #8568: near the end of a steep straight path, the bounds of a selection held by its edge line
/// up by the shortest slide that keeps the held point on the path, not by a shorter one that
/// would take it past the path's end.
#[test]
fn a_move_held_by_an_edge_slides_only_within_the_path() {
let (a, b) = (Point::new(300.0, 300.0), Point::new(310.0, 400.0));
// Two upright paths far below: lining the left side up with the one at 269.95 slides the
// held point 6.5 back along the path, past its start, and with the one at 271.343 slides it
// 7.5 on.
let (d, id) = doc_with_rect_and_lines(&[
(a, b),
(Point::new(269.95, 440.0), Point::new(269.95, 490.0)),
(Point::new(271.343, 440.0), Point::new(271.343, 490.0)),
]);
let u = (b - a) / (b - a).hypot();
// Dropped on the path 6 points from its start, the top edge's point at (130, 100) leaves the
// left side at 30 points before it.
let q = a + u * 6.0;
let (edge, label) = pressed_and_dragged(&d, id, (130.0, 100.0), Point::new(130.0, 100.0), (q.x, q.y), false);
let off_line = (b - a).cross(edge - a) / (b - a).hypot();
assert!(off_line.abs() < 1e-9, "the edge lands at {edge:?}, {off_line} off the path");
assert!((edge.x - 30.0 - 271.343).abs() < 1e-9, "the left side lands at {}", edge.x - 30.0);
assert_eq!(label.as_deref(), Some("path"));
}
/// #8568: a straight path drawn with its handles pulled out along it counts as straight, also
/// with a handle reaching past the far end while the curve stays between its ends: a selection
/// held by its edge slides along it to line its bounds up, as along a plain line.
#[test]
fn a_move_held_by_an_edge_slides_along_a_straight_path_with_handles() {
use vectorcraft_geom::{Anchor, AnchorKind, PathData, SubPath};
let (a, b) = (Point::new(300.0, 300.0), Point::new(500.0, 300.0));
for (out, into) in [(350.0, 450.0), (520.0, 480.0)] {
let (mut d, id) = doc_with_rect();
let l = d.layers[0].id;
let n = d.alloc_id();
let anchors = vec![
Anchor { p: a, h_in: a, h_out: Point::new(out, 300.0), kind: AnchorKind::Corner },
Anchor { p: b, h_in: Point::new(into, 300.0), h_out: b, kind: AnchorKind::Corner },
];
let path = PathData::single(SubPath::new(anchors, false));
d.insert(Some(l), 1, vectorcraft_doc::Node::path(n, path, vectorcraft_doc::Appearance::default_art())).unwrap();
let (edge, label) = pressed_and_dragged(&d, id, (130.0, 100.0), Point::new(130.0, 100.0), (331.0, 300.5), false);
assert!(edge.distance(Point::new(330.0, 300.0)) < 1e-9, "handles at {out} and {into}: the edge lands at {edge:?}");
assert_eq!(label.as_deref(), Some("path"));
}
}
/// #8568: an artboard's ruler guide ends at the artboard's edge. A selection held by its edge
/// slides along a shallow path onto such a guide when the slide brings its bounds within reach of
/// the guide's end, even though they start out beyond it.
#[test]
fn a_move_held_by_an_edge_slides_onto_an_artboard_guide_it_reaches() {
let (a, b) = (Point::new(640.0, 300.0), Point::new(440.0, 310.0));
let (mut d, id) = doc_with_rect_and_lines(&[(a, b)]);
let u = (b - a) / (b - a).hypot();
// Held by the left edge at (100, 130) and dropped on the path where x is 507: the top is 30
// above the point, and the middle at x 557 is beyond the guide's end at 500 by more than half
// the width and the Snapping Tolerance. A slide of 6 along the path puts the top on the guide.
let q = a + u * ((a.x - 507.0) / -u.x);
let guide = q.y - 30.0 + u.y * 6.0;
let board = d.artboards[0].id;
d.add_ruler_guide(&vectorcraft_doc::Guide { artboard: Some(board), ..vectorcraft_doc::Guide::new(false, guide) });
let (edge, label) = pressed_and_dragged(&d, id, (100.0, 130.0), Point::new(100.0, 130.0), (q.x, q.y), false);
assert!(edge.distance(q + u * 6.0) < 1e-9, "the edge lands at {edge:?}, not {:?}", q + u * 6.0);
assert_eq!(label.as_deref(), Some("path"));
}
/// #8568: a selection held by its edge lands that point where two other paths cross, and where a
/// path crosses a ruler guide ("intersect"), as an anchor does.
#[test]
fn a_move_held_by_an_edge_lands_it_where_paths_cross() {
let bottom = Point::new(150.0, 200.0);
let (mut d, id) =
doc_with_rect_and_lines(&[(Point::new(300.0, 400.0), Point::new(500.0, 300.0)), (Point::new(460.0, 250.0), Point::new(460.0, 420.0))]);
let (edge, label) = pressed_and_dragged(&d, id, (150.0, 200.0), bottom, (460.4, 320.5), false);
assert!(edge.distance(Point::new(460.0, 320.0)) < 1e-9, "the edge lands at {edge:?}");
assert_eq!(label.as_deref(), Some("intersect"));
d.add_ruler_guide(&vectorcraft_doc::Guide::new(true, 440.0));
let (edge, label) = pressed_and_dragged(&d, id, (150.0, 200.0), bottom, (440.5, 330.5), false);
assert!(edge.distance(Point::new(440.0, 330.0)) < 1e-9, "the edge lands at {edge:?}");
assert_eq!(label.as_deref(), Some("intersect"));
}
/// #8568: an Alt copy held by its edge snaps to the original too: dragged along the original's
/// top edge, the held point stays on that edge and the copy's right side lines up with another
/// path.
#[test]
fn a_copy_held_by_an_edge_slides_along_the_originals_edge() {
let (d, id) = doc_with_rect_and_lines(&[(Point::new(230.0, 300.0), Point::new(230.0, 400.0))]);
let (edge, label) = pressed_and_dragged(&d, id, (130.0, 100.0), Point::new(130.0, 100.0), (161.0, 100.5), true);
assert!(edge.distance(Point::new(160.0, 100.0)) < 1e-9, "the edge lands at {edge:?}");
assert_eq!(label.as_deref(), Some("path"));
}
/// #7411: a selection grabbed by an anchor lands it where two other paths cross ("intersect"), and
/// on another object's anchor near the path rather than on the path.
#[test]
File diff suppressed because one or more lines are too long