TransformBox snapping follows PhotoCraft: inside drags snap the box's bounds, the reference point snaps to the box's nine points only, Distort corners snap to guides only and Ctrl keeps their snapping, and a folded-short corner reports no line

This commit is contained in:
aiongg
2026-11-16 21:15:37 +00:00
parent fd73622066
commit c53698127e
4 changed files with 179 additions and 26 deletions
+7 -2
View File
@@ -59,6 +59,11 @@ impl SnapKinds {
}
}
/// The set of `kind` alone.
pub const fn only(kind: SnapKind) -> Self {
SnapKinds(Self::bit(kind))
}
/// This set without `kind`.
pub fn without(self, kind: SnapKind) -> Self {
SnapKinds(self.0 & !Self::bit(kind))
@@ -313,8 +318,8 @@ impl SnapTargets {
self.snap_point_of(point, tolerance, SnapKinds::ALL)
}
/// [`snap_point`](Self::snap_point) to the targets of a kind in `kinds` only (a Distort corner skips layer edges
/// and centres).
/// [`snap_point`](Self::snap_point) to the targets of a kind in `kinds` only (a Distort corner snaps to guides
/// only).
///
/// Public: craft-ui-canvas's `Snap::point` filters through it.
pub fn snap_point_of(&self, point: Point, tolerance: f64, kinds: SnapKinds) -> (Point, Vec<SnapLine>) {
+61 -22
View File
@@ -5,7 +5,7 @@
#[cfg(feature = "screen-testing")]
mod stories;
use craft_behavior::geometry::SnapLine;
use craft_behavior::geometry::{SNAP_PX, SnapKind, SnapKinds, SnapLine};
use craft_behavior::geometry::quad::{self, BoxAllow, BoxDrag, BoxPart, BoxRules, BoxState, ScaleRule, TransformMode};
use craft_behavior::kurbo::{Point, Rect as DocRect, Vec2 as DocVec};
use craft_behavior::{
@@ -252,9 +252,11 @@ fn slop_sense(part: BoxPart) -> Sense {
/// corner winning where both reach), the inside or the outside. Parts the [rules](Self::rules) refuse take no
/// press, except the outside in [`RotateZone::Outside`], where a click applies. An Alt press away from the handles
/// moves the reference point there and drags it, whether it shows or not.
/// - Snapping is the canvas's ([`canvas_snap`]): a dragged point snaps through [`Snap::point`], and the lines it
/// snapped to are [`TransformBoxOutput::snapped`] for the host's one drawing site. Without a canvas snap nothing
/// snaps. A pass reports the lines of its own drag events only.
/// - Snapping is the canvas's ([`canvas_snap`]): a dragged handle snaps through [`Snap::point`] and a box moved from
/// inside snaps its bounds through [`Snap::rect_of`]; the lines the result reaches are
/// [`TransformBoxOutput::snapped`] for the host's one drawing site. Without a canvas snap nothing snaps but the
/// reference point, which snaps to the box's nine points only. In Distort only the corners snap, to guides. A pass
/// reports the lines of its own drag events only.
/// - The box is one Tab stop with one part group, whose arrival is the picked part. Page Down and Page Up pick the
/// next and previous part (the whole box, the corners and edges clockwise from the top left, the reference
/// point), Home and End the first and last. The arrows move the picked part as a plain drag of it would, one
@@ -403,31 +405,55 @@ impl<'a> TransformBox<'a> {
quad::drag(state, state, part, at, at + by, Mods::NONE, &self.rules)
}
/// The box the pointer at screen position `pos` gives a drag, snapped through the canvas's `snap` and rounded, with
/// the lines it snapped to. A corner, an edge or the reference point snaps the grabbed point, not the pointer: a
/// press a few pixels off the handle still lands the handle on the line. The Control key suspends the snapping
/// unless it changes what the drag does (off macOS Ctrl is ⌘: a corner distorts, an edge skews).
/// The box the pointer at screen position `pos` gives a drag, snapped and rounded, with the lines it snapped to.
///
/// - A corner or an edge snaps the grabbed handle through the canvas's `snap`, not the pointer: a press a few
/// pixels off the handle still lands the handle on the line. A distorting corner reports only the lines it
/// reaches once the box's folding rule has placed it: a corner stopped short of a line claims no alignment.
/// - A drag from inside snaps the bounds of the moved box (its edges and centre).
/// - The reference point snaps to the nine points of the box at the press (corners, edge midpoints, centre) and
/// to nothing else, with or without the canvas's snap, the Control key held or not.
/// - In [`TransformMode::Distort`] only the corners snap, and to guides only. The outside (rotating) never snaps.
/// - The Control key suspends the snapping unless the drag reads it (off macOS Ctrl is ⌘): where it changes what
/// the drag does (a corner distorts, an edge skews) or on a corner that distorts.
fn proposal(&self, space: &CanvasSpace, snap: Option<&Snap>, grip: &Grip, pos: Pos2, mods: Mods) -> (BoxState, Vec<SnapLine>) {
let to = space.view.to_doc(pos);
let reads_control = self.rules.drag_kind(grip.part, mods) != self.rules.drag_kind(grip.part, Mods { cmd: false, ..mods });
let quad = &grip.start.quad;
let grabbed = match grip.part {
BoxPart::Corner(i) => Some(quad[usize::from(i % 4)]),
BoxPart::Edge(i) => Some(quad[usize::from(i % 4)].midpoint(quad[usize::from(i + 1) % 4])),
BoxPart::Pivot => Some(grip.start.pivot),
_ => None,
};
let (to, lines) = match (snap, grabbed) {
(Some(snap), Some(grabbed)) => {
let kind = self.rules.drag_kind(grip.part, mods);
let reads_control = mods.cmd && (kind != self.rules.drag_kind(grip.part, Mods { cmd: false, ..mods }) || kind == Some(BoxDrag::Distort));
let distort_mode = self.rules.effective_mode() == TransformMode::Distort;
let kinds = if distort_mode { SnapKinds::only(SnapKind::Guide) } else { SnapKinds::ALL };
let gesture = GestureSnap::default().reads_control(reads_control).kinds(kinds);
let grabbed = handle_point(&grip.start, grip.part);
let (to, mut lines) = match (grip.part, snap, grabbed) {
(BoxPart::Pivot, _, Some(grabbed)) if !distort_mode => {
let off = grip.from - grabbed;
let (at, lines) = snap.point(to - off, mods, GestureSnap::default().reads_control(reads_control));
(box_point_pull(&grip.start, to - off, space.view.doc_len(SNAP_PX as f32)) + off, Vec::new())
}
(BoxPart::Corner(_), Some(snap), Some(grabbed)) | (BoxPart::Edge(_), Some(snap), Some(grabbed))
if !distort_mode || matches!(grip.part, BoxPart::Corner(_)) =>
{
let off = grip.from - grabbed;
let (at, lines) = snap.point(to - off, mods, gesture);
(at + off, lines)
}
(Some(snap), None) => snap.point(to, mods, GestureSnap::default().reads_control(reads_control)),
(None, _) => (to, Vec::new()),
(BoxPart::Inside, Some(snap), _) if !distort_mode => {
let moved = bounds_of(&grip.start.quad) + (to - grip.from);
let (by, lines) = snap.rect_of(moved, mods, kinds);
(to + by, lines)
}
_ => (to, Vec::new()),
};
let dragged = quad::drag(&grip.start, &grip.last, grip.part, grip.from, to, mods, &self.rules);
(if self.pixel_grid { on_pixel_grid(dragged) } else { dragged }, lines)
let dragged = if self.pixel_grid { on_pixel_grid(dragged) } else { dragged };
if kind == Some(BoxDrag::Distort)
&& let Some(at) = handle_point(&dragged, grip.part)
{
lines.retain(|line| {
let across = if matches!(line.along, Axis::Y) { at.x } else { at.y };
(across - line.position).abs() < 1e-6
});
}
(dragged, lines)
}
/// The pointer for `part` at `pointer`, `dragging` during its drag.
@@ -968,6 +994,19 @@ fn handle_point(state: &BoxState, part: BoxPart) -> Option<Point> {
}
}
/// The bounds of `quad`.
fn bounds_of(quad: &[Point; 4]) -> DocRect {
quad[1..].iter().fold(DocRect::from_points(quad[0], quad[0]), |r, p| r.union_pt(*p))
}
/// `p` pulled onto the nearest of the nine points of `state`'s box (its corners, edge midpoints and centre) within
/// `reach` document units, else `p`.
fn box_point_pull(state: &BoxState, p: Point, reach: f64) -> Point {
let q = &state.quad;
let points = [q[0], q[1], q[2], q[3], q[0].midpoint(q[1]), q[1].midpoint(q[2]), q[2].midpoint(q[3]), q[3].midpoint(q[0]), q[0].midpoint(q[2]).midpoint(q[1].midpoint(q[3]))];
points.into_iter().map(|a| (a.distance(p), a)).filter(|(d, _)| *d <= reach).min_by(|a, b| a.0.total_cmp(&b.0)).map_or(p, |(_, a)| a)
}
/// The corner of `screen` nearest `p` and its distance.
fn nearest_corner(screen: &BoxState, p: Pos2) -> (usize, f32) {
let p = Point::new(f64::from(p.x), f64::from(p.y));
+110 -1
View File
@@ -1,7 +1,7 @@
//! `TransformBox`, `TransformOverlay` and `TransformTool`: the parts the pointer takes, what each drag does, the
//! keys, the readout and the overlay's edits.
use craft_behavior::geometry::quad::{BoxPart, BoxRules, BoxState, ScaleRule};
use craft_behavior::geometry::quad::{BoxPart, BoxRules, BoxState, ScaleRule, TransformMode};
use craft_behavior::geometry::{SnapKind, SnapOptions, SnapTarget, SnapTargets};
use craft_behavior::kurbo::{Point, Rect};
use craft_behavior::{CanvasView, EditEvent, RulerUnits, Ticks};
@@ -51,6 +51,8 @@ struct Config {
f32_host: bool,
centre_mark: bool,
line: Option<LineLook>,
/// Snap targets beside the guides at [`SNAP_XS`].
targets: Vec<SnapTarget>,
}
/// What the host keeps of the box and what the passes reported.
@@ -65,6 +67,8 @@ struct Host {
id: egui::Id,
view: CanvasView,
guide_events: usize,
/// The snap lines the last pass reported.
snapped: usize,
}
struct Harness {
@@ -92,6 +96,7 @@ fn defaults() -> Config {
f32_host: false,
centre_mark: false,
line: None,
targets: Vec::new(),
}
}
@@ -117,6 +122,7 @@ fn harness(state: BoxState, setup: impl FnOnce(&mut Config)) -> Harness {
id: egui::Id::NULL,
view: CanvasView::new(egui::Rect::NOTHING, Point::ZERO, 1.0),
guide_events: 0,
snapped: 0,
}));
let shown_host = Rc::clone(&host);
let mut guides = vec![Guide::new(GuideKey::new(1), craft_behavior::Axis::Y, 300.0)];
@@ -124,6 +130,9 @@ fn harness(state: BoxState, setup: impl FnOnce(&mut Config)) -> Harness {
for x in SNAP_XS {
targets.add(SnapTarget::new(craft_behavior::Axis::Y, x, SnapKind::Guide));
}
for target in &shown_config.borrow().targets {
targets.add(*target);
}
let snap = Snap::new(Arc::new(targets), SnapOptions::default());
let mut fixture = Fixture::new(move |ui| {
let room = ui.available_rect_before_wrap();
@@ -172,6 +181,7 @@ fn harness(state: BoxState, setup: impl FnOnce(&mut Config)) -> Harness {
if let Some((output, guide_edits)) = canvas.inner {
let mut host = shown_host.borrow_mut();
host.guide_events += guide_edits;
host.snapped = output.snapped.len();
host.id = output.edit.response.id;
host.applied += usize::from(output.apply.is_some());
host.discarded += usize::from(output.discard);
@@ -790,3 +800,102 @@ fn a_secondary_click_on_the_box_opens_the_mode_menu() {
right_click(&mut fixture, screen(Point::new(200.0, 150.0)));
assert!(fixture.by_label("Distort").is_some(), "a secondary click on the box opens the mode menu");
}
/// A drag from inside snaps the moved box's edges, not the pointer: the right edge lands on the guide at 310 while the
/// pointer stays far from both guides.
#[trial]
fn a_box_moved_from_inside_snaps_its_edges() {
let mut h = harness(BoxState::from_rect(RECT), |config| config.snap = true);
let from = h.screen(Point::new(130.0, 120.0));
frame(&mut h, vec![pointer::moved(from)]);
frame(&mut h, vec![pointer::press(from)]);
frame(&mut h, vec![pointer::moved(from + by(4.0, 0.0))]);
frame(&mut h, vec![pointer::moved(from + by(7.0, 0.0))]);
assert_eq!(h.host.borrow().snapped, 1, "the right edge's line");
frame(&mut h, vec![pointer::release(from + by(7.0, 0.0))]);
let moved = h.state().quad[0].x - RECT.x0;
assert!((moved - 10.0).abs() < 1e-6, "the box moved {moved}, its right edge onto 310");
}
/// Free Transform's corner snaps to a layer edge and a guide alike; an explicit Distort corner snaps to guides only,
/// and a corner the folding rule stops short of a guide crossing claims no line.
#[trial]
fn a_distort_corner_snaps_to_guides_only_and_claims_no_line_it_stops_short_of() {
let layer_edge = SnapTarget::new(craft_behavior::Axis::X, 230.0, SnapKind::LayerEdge);
for (mode, expected, lines) in [(TransformMode::Free, Point::new(310.0, 230.0), 2), (TransformMode::Distort, Point::new(310.0, 227.0), 1)] {
let mut h = harness(BoxState::from_rect(RECT), |config| {
config.snap = true;
config.rules = BoxRules::in_mode(mode).with_aspect_linked(false);
config.targets = vec![layer_edge];
});
let from = h.screen(Point::new(300.0, 220.0));
frame(&mut h, vec![pointer::moved(from)]);
frame(&mut h, vec![pointer::press(from)]);
frame(&mut h, vec![pointer::moved(from + by(4.0, 4.0))]);
frame(&mut h, vec![pointer::moved(from + by(7.0, 7.0))]);
let corner = h.state().quad[2];
assert!(corner.distance(expected) < 1e-6, "{mode:?}: {corner:?}, expected {expected:?}");
assert_eq!(h.host.borrow().snapped, lines, "{mode:?}");
}
// The guides cross at (250, 180), past the diagonal from corner 1 to corner 3: corner 0 there would fold the box.
let mut h = harness(BoxState::from_rect(RECT), |config| {
config.snap = true;
config.rules = BoxRules::in_mode(TransformMode::Distort);
config.targets = vec![
SnapTarget::new(craft_behavior::Axis::Y, 250.0, SnapKind::Guide),
SnapTarget::new(craft_behavior::Axis::X, 180.0, SnapKind::Guide),
];
});
let from = h.screen(Point::new(100.0, 80.0));
frame(&mut h, vec![pointer::moved(from)]);
frame(&mut h, vec![pointer::press(from)]);
frame(&mut h, vec![pointer::moved(from + by(4.0, 4.0))]);
frame(&mut h, vec![pointer::moved(from + by(147.0, 97.0))]);
let q = h.state().quad;
assert!(q[0].distance(Point::new(250.0, 180.0)) > 1.0, "the crossing would fold the box: {q:?}");
for i in 0..4 {
let (a, b, c) = (q[i], q[(i + 1) % 4], q[(i + 2) % 4]);
assert!((b - a).cross(c - b) > 0.0, "still convex: {q:?}");
}
assert_eq!(h.host.borrow().snapped, 0, "a stopped corner reports no guide line");
}
/// Off macOS Control is ⌘: on an explicit Distort corner it keeps the snapping, in Skew and Perspective it suspends it.
#[trial]
fn control_keeps_snapping_on_an_explicit_distort_corner_only() {
for (mode, snaps) in [(TransformMode::Distort, true), (TransformMode::Skew, false), (TransformMode::Perspective, false)] {
let mut h = harness(BoxState::from_rect(RECT), |config| {
config.snap = true;
config.mods = Some(Mods::CMD);
config.rules = BoxRules::in_mode(mode);
});
h.fixture.os(Platform::Windows);
let from = h.screen(Point::new(300.0, 220.0));
frame(&mut h, vec![pointer::moved(from)]);
frame(&mut h, vec![pointer::press(from)]);
frame(&mut h, vec![pointer::moved(from + by(4.0, 0.0))]);
frame(&mut h, vec![pointer::moved(from + by(7.0, 0.0))]);
let x = h.state().quad[2].x;
assert_eq!((x - 310.0).abs() < 1e-6, snaps, "{mode:?}: corner at x {x}");
}
}
/// The reference point snaps to the turned box's nine points and to nothing else, with the canvas's snapping on or
/// off: 2 units off the guide at 160 it stays put.
#[trial]
fn the_reference_point_snaps_to_the_turned_boxs_points_only() {
let turned = BoxState::from_rect(RECT).turned_about_pivot(30f64.to_radians());
for snap in [true, false] {
let mut h = harness(turned, |config| config.snap = snap);
let centre = turned.pivot;
drag(&mut h, centre, Point::new(158.0, 150.0));
let pivot = h.state().pivot;
assert!(pivot.distance(Point::new(158.0, 150.0)) < 1e-6, "snap {snap}: no pull to the guide: {pivot:?}");
let corner = turned.quad[1];
drag(&mut h, pivot, corner + kurbo_vec(-2.0, 1.0));
let pivot = h.state().pivot;
assert!(pivot.distance(corner) < 1e-6, "snap {snap}: onto the corner: {pivot:?} vs {corner:?}");
assert_eq!(h.state().quad, turned.quad, "the box never moved");
}
}
+1 -1
View File
@@ -28,7 +28,7 @@ pub struct Snap {
pub struct GestureSnap {
/// Whether the gesture reads the Control key itself, so Control does not suspend snapping.
pub reads_control: bool,
/// The kinds of target the gesture snaps to (Distort corners skip layer edges and centres).
/// The kinds of target the gesture snaps to (an explicit Distort snaps its corners to guides only).
pub kinds: craft_behavior::geometry::SnapKinds,
}