Smart Guides: a scale lines up geometric edges with Use Preview Bounds on

With Use Preview Bounds on, dragging a bounding-box handle with the
Selection tool, a shape tool or Free Transform lined up the outside of
the selection's stroke with the other art's geometric bounds, which
Smart Guides use for the targets. A stroked object then stopped half a
stroke short of the edge it showed a guide for, the same mismatch moves
had before.

- The handle still drags the visual box, and the edges of the
  selection's geometric bounds line up with the targets and with even
  spacing. The margins between the two boxes keep their size unless
  Scale Strokes & Effects is on, when they scale with the box. Snap to
  Grid and Snap to Pixel still use the bounds the box shows, and the
  Slice Selection tool is unchanged.
- Tool contexts carry the Scale Strokes & Effects preference.
- New tests drag the right-middle handle of a rectangle with a 20 pt
  stroke toward another rectangle with the Selection tool and with Free
  Transform.

Part of #6436
This commit is contained in:
dotCooCoo committed 2026-11-28 17:32:11 -08:00
1 parent 664571cbef
commit 4ceaee694a
9 files changed
+172 -20

No files matched your search

+1
View File
@@ -630,6 +630,7 @@ impl Session {
freeform_point: self.selected_freeform_point(),
raster_sample: self.prefs.eyedropper.sample_size,
preview_bounds: self.prefs.use_preview_bounds,
scale_strokes: self.prefs.scale_strokes,
glyph_bounds: self.prefs.type_glyph_bounds,
preview_memo: Some(&self.preview_memo),
unit,
+2
View File
@@ -253,6 +253,8 @@ pub struct ToolContext<'a> {
pub raster_sample: u32,
/// General → Use Preview Bounds: the bounding box measures visual bounds (strokes included).
pub preview_bounds: bool,
/// General → Scale Strokes & Effects: a scale scales the strokes and effects with the art.
pub scale_strokes: bool,
/// Type › Measure Type by Glyph Bounds: the bounding box measures each point type object
/// selected as an object (not inside a selected group) by the ink of its glyphs
/// ([`vectorcraft_effects::preview::Measure`]).
+26 -6
View File
@@ -116,6 +116,10 @@ pub struct PointSnap {
/// The kind of edit the point serves: whether Snap to Pixel rounds it
/// ([`ToolContext::snaps_to_pixel`]).
op: PixelOp,
/// For a scale with Smart Guides and Use Preview Bounds on: the selection's geometric bounds,
/// whose edges line up with the other art's geometric bounds while the handle drags the visual
/// box ([`Self::snap_scale`]).
edges: Option<OrientedBox>,
}
impl PointSnap {
@@ -134,6 +138,17 @@ impl PointSnap {
Self::for_op(cx, PixelOp::Scaling, targets)
}
/// [`Self::scaling`] for the selection's bounding box: with Smart Guides and Use Preview
/// Bounds on, the selection's geometric bounds are the edges that line up.
pub fn scaling_selection(cx: &ToolContext) -> Self {
let mut snap = Self::scaling(cx, || Targets::for_scale(cx));
if snap.targets.is_some() && cx.smart_guides && cx.preview_bounds {
let geometric = vectorcraft_effects::preview::Measure { preview: false, ..cx.bounds_measure() };
snap.edges = vectorcraft_effects::preview::oriented_bounds_with(cx.doc, &cx.selection.objects, geometric);
}
snap
}
fn for_op(cx: &ToolContext, op: PixelOp, targets: impl FnOnce() -> Targets) -> Self {
let targets = if cx.snaps_to_pixel(op) || cx.snap_to_grid {
None
@@ -147,7 +162,7 @@ impl PointSnap {
} else {
None
};
Self { targets, op }
Self { targets, op, edges: None }
}
/// Snapping for a point placed anywhere, as a drawing tool's ([`DrawSnap`]) is: the art in the
@@ -182,7 +197,10 @@ impl PointSnap {
/// Snap to Pixel on for scaling, the corner or side the handle moves lines up with whole
/// pixels, and with Snap to Grid on it lines up with the nearest gridline, however far that
/// is; neither shows guides. Otherwise the handle snaps to the targets [`Self::scaling`]
/// gathered.
/// gathered. With Smart Guides and Use Preview Bounds on, the edges of the selection's
/// geometric bounds line up with the targets, which are the other art's geometric bounds, while
/// the handle stays on the visual box (#6436). The margins between the two boxes keep their
/// size unless Scale Strokes & Effects is on.
pub fn snap_scale(
&self,
cx: &ToolContext,
@@ -205,8 +223,10 @@ impl PointSnap {
// one step always finds one.
return (Targets::grid_lines(moved, step).snap_scale(bx, handle, a, proportional, from_center, step).0, vec![]);
}
// The geometric box lines up when it turns with the box the handle drags.
let edges = self.edges.filter(|g| (g.angle - bx.angle).abs() <= 1e-9).map(|g| (g.rect, !cx.scale_strokes));
match &self.targets {
Some((t, tol)) => t.snap_scale(bx, handle, a, proportional, from_center, cx.tol(*tol)),
Some((t, tol)) => t.snap_scale_edges(bx, edges, handle, a, proportional, from_center, cx.tol(*tol)),
None => (a, vec![]),
}
}
@@ -448,7 +468,7 @@ impl DrawSnap {
/// Guides snapping tolerance (the Knife's straight cut). The targets serve this press only.
pub fn press_on_paths(&mut self, cx: &ToolContext, p: Point) -> Point {
let targets = Targets::for_drawing(cx.doc, &[], visible(cx), None).styled(cx).anchors_and_paths();
self.targets = Some((None, PointSnap { targets: Some((targets, cx.snapping_tolerance)), op: PixelOp::Drawing }));
self.targets = Some((None, PointSnap { targets: Some((targets, cx.snapping_tolerance)), op: PixelOp::Drawing, edges: None }));
self.snap(cx, p, None)
}
@@ -467,7 +487,7 @@ impl DrawSnap {
/// again on every move, as [`PointSnap::snap_from`] reads pixels and the grid), nothing in
/// reach, or an anchor, center or crossing in reach of `p` or at `corner`.
pub fn circle_radius(&mut self, cx: &ToolContext, center: Point, p: Point, corner: Point, r: f64) -> Option<f64> {
let Some((_, PointSnap { targets: Some((t, tol)), op })) = &self.targets else { return None };
let Some((_, PointSnap { targets: Some((t, tol)), op, .. })) = &self.targets else { return None };
if !cx.smart_guides || !cx.snap_tangent || cx.snaps_to_pixel(*op) || cx.snap_to_grid {
return None;
}
@@ -517,7 +537,7 @@ impl DrawSnap {
/// gathered ([`Targets::snap_hit`]), whether or not its guides show. False with Smart Guides
/// off, with no targets, and while pixels or the grid snap instead.
pub(crate) fn lands_on_target(&self, cx: &ToolContext, p: Point, from: Option<&Leave>) -> bool {
let Some((_, PointSnap { targets: Some((t, tol)), op })) = &self.targets else { return false };
let Some((_, PointSnap { targets: Some((t, tol)), op, .. })) = &self.targets else { return false };
cx.smart_guides && !cx.snaps_to_pixel(*op) && !cx.snap_to_grid && t.snap_hit(p, from, cx.tol(*tol)).2
}
+63 -9
View File
@@ -1583,12 +1583,55 @@ impl Targets {
/// the nearest target or ruler guide ("align"), whatever the box's angle. A handle with one way
/// to go (a side, or a proportional corner) slides along it until one of them is on a target.
pub fn snap_scale(&self, bx: &OrientedBox, handle: Handle, a: Affine, proportional: bool, from_center: bool, tol: f64) -> (Affine, Vec<Overlay>) {
self.snap_scale_edges(bx, None, handle, a, proportional, from_center, tol)
}
/// [`Self::snap_scale`], with the edges of `edges` landing on the targets in place of the
/// edges of `bx`. `edges` is a box in `bx`'s frame, such as the selection's geometric bounds
/// inside the visual bounds that Use Preview Bounds shows. With its `true`, the margins between
/// the two boxes keep their size as `bx` scales, as `object.setBounds` keeps them; with `false`
/// they scale with it, as `object.transform` scales them. The scale stays one of `bx`.
#[allow(clippy::too_many_arguments)]
pub fn snap_scale_edges(
&self,
bx: &OrientedBox,
edges: Option<(Rect, bool)>,
handle: Handle,
a: Affine,
proportional: bool,
from_center: bool,
tol: f64,
) -> (Affine, Vec<Overlay>) {
type Hit = Option<(f64, Point)>;
// Where a snap lands: in line with a target's x and/or y, or on an anchor or centre.
type Snap = (Hit, Hit, Option<(Point, Kind)>);
let r = bx.rect;
let origin = if from_center { r.center() } else { handle.opposite().pos(r) };
let (d0, [sx, _, _, sy, _, _]) = (handle.pos(r) - origin, a.as_coeffs());
// Margins that keep their size are only measured on a box that does not flip.
let edges = edges.filter(|(g, keep)| g.is_finite() && (!keep || (sx > 0.0 && sy > 0.0)));
// A point `h` of the box that may land on a target goes to `origin + scale·v + off` for
// its `(v, off)`.
let lands = |h: Handle| -> (Vec2, Vec2) {
match edges {
Some((g, true)) => (h.pos(r) - origin, h.pos(g) - h.pos(r)),
Some((g, false)) => (h.pos(g) - origin, Vec2::ZERO),
None => (h.pos(r) - origin, Vec2::ZERO),
}
};
let at = |nx: f64, ny: f64, h: Handle| {
let (v, off) = lands(h);
origin + Vec2::new(nx * v.x, ny * v.y) + off
};
// The box whose edges line up, on the page, after the scale `out`.
let landed = |out: Affine| match edges {
Some((g, true)) => {
let n = out.transform_rect_bbox(r);
bx.to_doc().transform_rect_bbox(Rect::new(n.x0 + g.x0 - r.x0, n.y0 + g.y0 - r.y0, n.x1 - (r.x1 - g.x1), n.y1 - (r.y1 - g.y1)))
}
Some((g, false)) => (bx.to_doc() * out).transform_rect_bbox(g),
None => (bx.to_doc() * out).transform_rect_bbox(r),
};
let (to_doc, to_local) = (bx.to_doc(), bx.to_doc().inverse());
// A scale that collapses or flips the box is no snap.
let valid = |n: f64, s: f64| n.is_finite() && n * s > 0.0;
@@ -1610,7 +1653,8 @@ impl Targets {
if handle.is_corner() && !proportional {
// The corner goes anywhere: onto an anchor or centre, else it takes the target's x, its
// y, or both.
let p = to_doc * (a * handle.pos(r));
let (v, off) = lands(handle);
let p = to_doc * at(sx, sy, handle);
let (hx, hy) = (nearest(p, true), nearest(p, false));
let on = self.nearest_point(p, tol).map(|(q, k)| (Some((q.x, q)), Some((q.y, q)), Some((q, k))));
for (tx, ty, at) in on.into_iter().chain([(hx, hy, None), (hx, None, None), (None, hy, None)]) {
@@ -1618,7 +1662,7 @@ impl Targets {
continue;
}
let q = to_local * Point::new(tx.map_or(p.x, |h| h.0), ty.map_or(p.y, |h| h.0));
let (mut cx, mut cy) = ((q.x - origin.x) / d0.x, (q.y - origin.y) / d0.y);
let (mut cx, mut cy) = ((q.x - off.x - origin.x) / v.x, (q.y - off.y - origin.y) / v.y);
// Square to the page, the axis without a target stays exactly where it was.
if bx.angle == 0.0 {
(cx, cy) = (if tx.is_some() { cx } else { sx }, if ty.is_some() { cy } else { sy });
@@ -1654,8 +1698,8 @@ impl Targets {
}
};
for h in std::iter::once(handle).chain(ends.into_iter().flatten().copied()) {
let v = h.pos(r) - origin;
let base = to_doc * (origin + Vec2::new(c.0 * v.x, c.1 * v.y));
let (v, off) = lands(h);
let base = to_doc * (origin + Vec2::new(c.0 * v.x, c.1 * v.y) + off);
let dir = (to_doc * Point::new(e.0 * v.x, e.1 * v.y)).to_vec2();
let p = base + dir * s0;
// An anchor or centre beside its way: it stops at the nearest point of the way.
@@ -1683,7 +1727,7 @@ impl Targets {
return (out, self.label(q, k.label()).into_iter().collect());
}
// The lines run from the target's own point across the resized box, on the page.
let mut nr = (to_doc * out).transform_rect_bbox(r);
let mut nr = landed(out);
let mut ov = vec![];
if let Some((x, from)) = hit_x {
ov.extend(self.line(Point::new(x, from.y.min(nr.y0)), Point::new(x, from.y.max(nr.y1))));
@@ -1692,7 +1736,7 @@ impl Targets {
ov.extend(self.line(Point::new(from.x.min(nr.x0), y), Point::new(from.x.max(nr.x1), y)));
}
if hit_x.is_some() || hit_y.is_some() {
ov.extend(self.label(to_doc * (out * handle.pos(r)), "align"));
ov.extend(self.label(to_doc * at(nx, ny, handle), "align"));
}
if !self.boxes.is_empty() && !from_center {
let aligned = [hit_x.is_some(), hit_y.is_some()];
@@ -1705,8 +1749,18 @@ impl Targets {
let (lo, hi) = span(&nr, is_x);
let len = hi - lo;
let new_len = if moves_min { hi - (lo + shift) } else { hi + shift - lo };
if len > 1e-9 && new_len > 1e-9 {
let f = new_len / len;
// The length the scale multiplies: the box's own, when the margins between it
// and the edges keep their size.
let scaled = match edges {
Some((_, true)) => {
let (lo, hi) = span(&(to_doc * out).transform_rect_bbox(r), is_x);
hi - lo
}
_ => len,
};
let grown = scaled + new_len - len;
if len > 1e-9 && new_len > 1e-9 && scaled > 1e-9 && grown > 1e-9 {
let f = grown / scaled;
let (ax, ay) = handle.axes();
if is_x {
nx *= f;
@@ -1720,7 +1774,7 @@ impl Targets {
}
}
out = Affine::translate(origin.to_vec2()) * Affine::scale_non_uniform(nx, ny) * Affine::translate(-origin.to_vec2());
nr = (to_doc * out).transform_rect_bbox(r);
nr = landed(out);
ov.extend(gaps.into_iter().flat_map(|g| self.gap_marks(g, is_x, tol)));
}
}
+1
View File
@@ -652,6 +652,7 @@ pub(crate) mod testutil {
freeform_point: None,
raster_sample: 1,
preview_bounds: false,
scale_strokes: false,
glyph_bounds: false,
preview_memo: None,
unit: Unit::Points,
+1 -1
View File
@@ -1985,7 +1985,7 @@ impl SelectionTool {
// What the handle moves snaps as a dragged point does: to pixels or the
// grid, else with Smart Guides to the other objects, else with Snap to
// Point to their anchors; the ruler guides with Snap to Point.
self.targets = Some(PointSnap::scaling(cx, || Targets::for_scale(cx)));
self.targets = Some(PointSnap::scaling_selection(cx));
self.last_backquote = false;
self.last_box_pos = None;
self.state = State::Scaling { handle, bx, areas };
+42
View File
@@ -1291,6 +1291,48 @@ fn a_move_lines_up_geometric_edges_with_use_preview_bounds_on() {
}
}
/// With Use Preview Bounds on, a scale handle drags the visual box, and Smart Guides line up the
/// selection's geometric edge with the other art's geometric edge, as a move does.
#[test]
fn a_scale_lines_up_geometric_edges_with_use_preview_bounds_on() {
use vectorcraft_color::{Color, Paint};
use vectorcraft_doc::{Appearance, Node};
// An artboard whose edges and center are out of reach, and two rectangles stroked 20 pt.
let mut d = Document::new(1000.0, 1000.0);
let l = d.layers[0].id;
let mut add = |r: Rect| {
let id = d.alloc_id();
let wide = Appearance::basic(Paint::solid(Color::WHITE), Paint::solid(Color::BLACK), 20.0);
d.insert(Some(l), 0, Node::path(id, vectorcraft_geom::shapes::rectangle(r), wide)).unwrap();
id
};
let a = add(Rect::new(100.0, 100.0, 200.0, 200.0));
add(Rect::new(300.0, 100.0, 400.0, 200.0));
let s = Selection { objects: vec![a], ..Default::default() };
let p = paint();
// The right edge of the box the right-middle handle leaves: the geometric edge with the option
// off, the visual edge 10 pt outside it with the option on.
let right = |preview: bool, from: f64, to: f64| {
let c = ToolContext { preview_bounds: preview, ..cx(&d, &s, &p) };
let mut t = SelectionTool::default();
t.pointer(&c, &ev(PointerKind::Down, from, 150.0));
let a = t.pointer(&c, &ev(PointerKind::Drag, to, 150.0));
match a.last() {
Some(Action::Preview(cmd, v)) if cmd == "object.setBounds" => 90.0 + v["width"].as_f64().unwrap(),
Some(Action::Preview(_, v)) => v["matrix"][0].as_f64().unwrap() * 200.0 + v["matrix"][4].as_f64().unwrap(),
_ => panic!("{a:?}"),
}
};
let near = |got: f64, want: f64| (got - want).abs() < 1e-9;
// Option off: the edge 1 pt short of the other rectangle's left edge (x = 300) lands on it.
assert!(near(right(false, 200.0, 299.0), 300.0), "{}", right(false, 200.0, 299.0));
assert!(near(right(false, 200.0, 291.0), 291.0), "{}", right(false, 200.0, 291.0));
// Option on: the geometric edge 1 pt short lands on it, which leaves the visual edge at 310.
assert!(near(right(true, 210.0, 309.0), 310.0), "{}", right(true, 210.0, 309.0));
// The visual edge 1 pt past it does not pull the box there: the geometric edge is 9 pt short.
assert!(near(right(true, 210.0, 301.0), 301.0), "{}", right(true, 210.0, 301.0));
}
/// Smart Guides › Snap to Last Location: a move that comes within Snapping Tolerance of where it
/// began goes back there, labeled "last location", a Shift move too; farther out, with the option
/// or Smart Guides off, it stays where it is dragged, and an Alt copy snaps as it does with the
+2 -2
View File
@@ -41,7 +41,7 @@ use vectorcraft_geom::{Affine, Point, Rect, Vec2};
use crate::bbox::{Handle, move_delta, rotate_for_drag, scale_for_drag};
use crate::corners::{self, CornerDrag};
use crate::guides::{DrawSnap, Leave, PointSnap, TangentLine, Targets, square};
use crate::guides::{DrawSnap, Leave, PointSnap, TangentLine, square};
use crate::pie::{self, PieDrag};
use crate::select::{MoveSnap, handle_cursor, hit_center, is_area_type, matrix_json, rotate_zone, shown_box};
use crate::sidewidget::{self, SideDrag};
@@ -363,7 +363,7 @@ impl ShapeTool {
self.selection = if let Some((handle, bx)) = self.over_handle(cx, ev.pos) {
let is_area = |id: &vectorcraft_doc::NodeId| cx.doc.node(*id).is_some_and(is_area_type);
let areas = cx.selection.objects.iter().any(is_area);
Some(SelectionDrag::Scale { handle, bx, areas, snap: Box::new(PointSnap::scaling(cx, || Targets::for_scale(cx))), last: None })
Some(SelectionDrag::Scale { handle, bx, areas, snap: Box::new(PointSnap::scaling_selection(cx)), last: None })
} else {
match hit_center(cx, ev.pos, cx.point_tol()) {
Some((_, hold)) => Some(SelectionDrag::Move { start: ev.pos, hold, began: false, snap: Box::new(MoveSnap::new(cx)) }),
+34 -2
View File
@@ -14,7 +14,7 @@ use vectorcraft_geom::{Affine, Point, Rect, Vec2};
use super::{BLUE, polygon, rect_corners};
use crate::bbox::{Handle, hit_handle, in_rotate_zone, move_delta, rotate_for_drag, scale_for_drag};
use crate::guides::{PointSnap, Targets};
use crate::guides::PointSnap;
use crate::select::{handle_cursor, matrix_json, screen_handle, selection_box};
use crate::{Action, Cursor, Mods, Overlay, PointerEvent, PointerKind, Tool, ToolContext, ToolKey};
@@ -273,7 +273,7 @@ impl Tool for FreeTransformTool {
self.drag = None;
let Some(bx) = selection_box(cx) else { return vec![] };
if let Some(op) = self.classify(cx, &bx, p, ev.mods) {
self.targets = op.handle().is_some().then(|| PointSnap::scaling(cx, || Targets::for_scale(cx)));
self.targets = op.handle().is_some().then(|| PointSnap::scaling_selection(cx));
self.drag = Some(Drag { op, bx, start: p, began: false });
}
vec![]
@@ -454,6 +454,38 @@ mod tests {
assert_eq!(t.pointer(&cx, &ev(PointerKind::Up, 213.0, 150.0)), vec![Action::Commit]);
}
/// With Use Preview Bounds on, a handle drags the visual box, and Smart Guides line up the
/// selection's geometric edge with the other art's geometric edge.
#[test]
fn handle_drag_lines_up_geometric_edges_with_use_preview_bounds_on() {
use vectorcraft_color::{Color, Paint};
use vectorcraft_doc::{Appearance, Document, Node};
let mut d = Document::new(1000.0, 1000.0);
let l = d.layers[0].id;
let mut add = |r: Rect| {
let id = d.alloc_id();
let wide = Appearance::basic(Paint::solid(Color::WHITE), Paint::solid(Color::BLACK), 20.0);
d.insert(Some(l), 0, Node::path(id, vectorcraft_geom::shapes::rectangle(r), wide)).unwrap();
id
};
let a = add(Rect::new(100.0, 100.0, 200.0, 200.0));
add(Rect::new(300.0, 100.0, 400.0, 200.0));
let s = Selection { objects: vec![a], ..Default::default() };
let p = paint();
let c = ToolContext { preview_bounds: true, ..cx(&d, &s, &p) };
// The right edge of the visual box (90 to 210) after a drag of its right-middle handle.
let right = |to: f64| {
let mut t = FreeTransformTool::default();
t.pointer(&c, &ev(PointerKind::Down, 210.0, 150.0));
let a = t.pointer(&c, &ev(PointerKind::Drag, to, 150.0));
let Some(Action::Preview(_, v)) = a.last() else { panic!("{a:?}") };
v["matrix"][0].as_f64().unwrap() * 210.0 + v["matrix"][4].as_f64().unwrap()
};
// The geometric edge 1 pt short of x = 300 lands on it; the visual edge 1 pt past does not.
assert!((right(309.0) - 310.0).abs() < 1e-9, "{}", right(309.0));
assert!((right(301.0) - 301.0).abs() < 1e-9, "{}", right(301.0));
}
/// In a view turned 90° the handles' cursors turn with the view.
#[test]
fn handle_cursors_turn_with_the_view() {