From 5b9bf4c985231f44f7a6d42e5c62f8f30a56f2df Mon Sep 17 00:00:00 2001 From: Martin Ball Date: Wed, 18 Nov 2026 14:03:47 +0000 Subject: [PATCH] canvas-w4: net change of 5 commits - canvas-w4: repair 1 - canvas-w4: finished by an agent - canvas-w4: finished by an agent - canvas-w4: finished by an agent - canvas-w4: review fixes (review-1) --- crates/behavior/src/geometry/quad.rs | 20 +- crates/behavior/src/geometry/snap.rs | 43 ++- crates/behavior/tests/geometry/quad.rs | 23 ++ crates/behavior/tests/geometry/snap.rs | 27 +- crates/draw/src/ui/transform/transform_box.rs | 277 +++++++++++++++--- .../src/ui/transform/transform_box/stories.rs | 51 +++- crates/draw/tests/it/transform_box.rs | 189 +++++++++++- crates/ui-canvas/src/canvas/snap.rs | 12 +- crates/ui-canvas/tests/it/canvas/snap.rs | 30 +- 9 files changed, 596 insertions(+), 76 deletions(-) diff --git a/crates/behavior/src/geometry/quad.rs b/crates/behavior/src/geometry/quad.rs index d0265f358..6b44078e0 100644 --- a/crates/behavior/src/geometry/quad.rs +++ b/crates/behavior/src/geometry/quad.rs @@ -100,8 +100,8 @@ pub enum ScaleRule { /// A shape or path bounds box: a corner scales by the projection of the drag on the anchor-corner diagonal, /// keeping the proportions; an edge stretches its one axis. Shape, - /// A corner keeps the proportions (⇧ frees them) and an edge stretches its one axis; distinct from - /// [`ScaleRule::Shape`] and [`ScaleRule::Proportional`]. + /// A corner keeps the proportions and ⇧ frees them, as [`ScaleRule::Proportional`]; an edge stretches its one + /// axis, as [`ScaleRule::Shape`]. The aspect link plays no part. Corners, } @@ -274,8 +274,9 @@ impl BoxRules { /// The modifiers a drag of `part` acts on, from the keys held: ⌘ is dropped on a corner or /// edge the content refuses to distort or skew, the legacy scale rule ([`ScaleRule::Free`]) - /// or an unlinked aspect ratio turns ⇧ over on corners and edges, and the shape rule - /// ([`ScaleRule::Shape`]) sets ⇧ by the part alone. Mode keys ([`TransformMode::Distort`], + /// or an unlinked aspect ratio turns ⇧ over on corners and edges, the shape rule + /// ([`ScaleRule::Shape`]) sets ⇧ by the part alone, and the corners rule ([`ScaleRule::Corners`]) sets ⇧ on + /// edges only. Mode keys ([`TransformMode::Distort`], /// [`TransformMode::Perspective`]) are not added here: they are part of /// [`drag_kind`](Self::drag_kind). [`drag`] acts on these modifiers. fn drag_modifiers(&self, part: BoxPart, mods: Mods) -> Mods { @@ -317,10 +318,13 @@ pub fn drag(start: &BoxState, last: &BoxState, part: BoxPart, from: Point, to: P apply_mode_drag(&g, to, rules, mods) } -/// The [`ScaleRule::Corners`] rule: a corner keeps the proportions unless ⇧ frees it, an edge stretches its one axis. -fn corners_mods(part: BoxPart, mods: Mods) -> Mods { - let _ = (part, mods); - todo!("cv.K34") +/// The [`ScaleRule::Corners`] rule: a corner keeps the keys as given, so it keeps the proportions and ⇧ frees them; +/// an edge stretches its one axis whatever ⇧ and the aspect link say. ⌘ gestures are left alone. +fn corners_mods(part: BoxPart, mut mods: Mods) -> Mods { + if !mods.cmd && matches!(part, BoxPart::Edge(_)) { + mods.shift = true; + } + mods } /// The shape bounds box's rule: a corner keeps the proportions along the diagonal and an edge diff --git a/crates/behavior/src/geometry/snap.rs b/crates/behavior/src/geometry/snap.rs index 2dcbc1543..b01e503a7 100644 --- a/crates/behavior/src/geometry/snap.rs +++ b/crates/behavior/src/geometry/snap.rs @@ -7,11 +7,13 @@ //! caller converts [`SNAP_PX`] screen points with the zoom. Results carry [`SnapLine`]s the //! caller draws. //! -//! Snapping is on when View › Snap is; holding Ctrl while dragging turns it off, except when Ctrl -//! is the tool's own modifier (the caller reads the keys). Smart guides follow View › Show › +//! Snapping is on when View › Snap is; holding the suspend key ([`SnapSuspend`], Ctrl by default) +//! while dragging turns it off, except when that key is the tool's own modifier (the caller reads +//! the keys). Smart guides follow View › Show › //! Smart Guides and also snap the Move tool to other layers' edges and centres. use crate::flow::Axis; +use craft_keymap::{Mods, Platform}; use kurbo::{Point, Rect, Vec2}; /// Screen points within which a position snaps (Photoshop). @@ -189,6 +191,23 @@ pub enum SnapSuspend { Alt, } +impl SnapSuspend { + /// Whether this key is held in `mods` on `os`: Control is the Control key without ⌘ on macOS and Ctrl + /// elsewhere (where it is `Mods::cmd`); Alt is Alt (⌥). + pub fn is_held(self, mods: Mods, os: Platform) -> bool { + match self { + SnapSuspend::Control => { + if os.is_mac() { + mods.ctrl && !mods.cmd + } else { + mods.cmd + } + } + SnapSuspend::Alt => mods.alt, + } + } +} + /// How the host snaps a tool's pointer. #[derive(Clone, Copy, Debug, PartialEq)] #[non_exhaustive] @@ -219,6 +238,15 @@ pub struct SnapTargets { /// Distances closer than this are equal. const TIE: f64 = 1e-9; +/// Whether `target` reaches a point or box spanning `across` on the other axis: a target with a span (a layer's +/// edge on its page) only where the two overlap; a target without a span, or a query without an extent, always. +fn reaches(target: &SnapTarget, across: Option<(f64, f64)>) -> bool { + match (target.span, across) { + (Some((a, b)), Some((lo, hi))) => lo <= b && a <= hi, + _ => true, + } +} + /// The line through `target` reaching the snapped object at `a..b` along the line; a target /// without a span stays full height. fn line(target: &SnapTarget, a: f64, b: f64) -> SnapLine { @@ -320,9 +348,8 @@ impl SnapTargets { /// span catches only a point or box overlapping that span there; without `across`, or for a target without a /// span, it is `nearest_of`. pub fn nearest_within(&self, along: Axis, value: f64, across: Option<(f64, f64)>, tolerance: f64, kinds: SnapKinds) -> Option { - let _ = across; // P3(canvas-w4): cv.K36 let mut best: Option<(f64, SnapTarget)> = None; - for target in self.targets.iter().filter(|t| t.along == along && kinds.contains(t.kind)) { + for target in self.targets.iter().filter(|t| t.along == along && kinds.contains(t.kind) && reaches(t, across)) { let distance = (target.position - value).abs(); if distance > tolerance { continue; @@ -355,11 +382,11 @@ impl SnapTargets { pub fn snap_point_of(&self, point: Point, tolerance: f64, kinds: SnapKinds) -> (Point, Vec) { let mut out = point; let mut lines = Vec::new(); - if let Some(t) = self.nearest_of(Axis::Y, point.x, tolerance, kinds) { + if let Some(t) = self.nearest_within(Axis::Y, point.x, Some((point.y, point.y)), tolerance, kinds) { out.x = t.position; lines.push(line(&t, point.y, point.y)); } - if let Some(t) = self.nearest_of(Axis::X, point.y, tolerance, kinds) { + if let Some(t) = self.nearest_within(Axis::X, point.y, Some((out.x, out.x)), tolerance, kinds) { out.y = t.position; lines.push(line(&t, out.x, out.x)); } @@ -389,7 +416,7 @@ impl SnapTargets { let anchors = [lo, hi, (lo + hi) / 2.0]; let mut best: Option = None; for anchor in anchors { - if let Some(t) = self.nearest_of(along, anchor, tolerance, kinds) { + if let Some(t) = self.nearest_within(along, anchor, Some(other), tolerance, kinds) { let d = t.position - anchor; if best.is_none_or(|b| d.abs() < b.abs() - TIE) { best = Some(d); @@ -406,7 +433,7 @@ impl SnapTargets { let hit = self .targets .iter() - .filter(|t| t.along == along && kinds.contains(t.kind) && (t.position - moved).abs() < 1e-6) + .filter(|t| t.along == along && kinds.contains(t.kind) && reaches(t, Some(other)) && (t.position - moved).abs() < 1e-6) .min_by_key(|t| u8::from(t.kind != SnapKind::Guide)); if let Some(t) = hit { lines.push(line(t, other.0, other.1)); diff --git a/crates/behavior/tests/geometry/quad.rs b/crates/behavior/tests/geometry/quad.rs index 2d8f74416..e716f2511 100644 --- a/crates/behavior/tests/geometry/quad.rs +++ b/crates/behavior/tests/geometry/quad.rs @@ -92,6 +92,29 @@ fn a_distort_corner_stops_before_the_box_folds() { assert_eq!(q, [p(5.0, 5.0), p(1.0, 0.0), p(2.0, 0.0), p(3.0, 0.0)]); } +#[test] +fn a_corners_box_keeps_a_corner_proportional_until_shift_and_stretches_an_edge_on_one_axis() { + let linked = BoxRules::default().with_scale(ScaleRule::Corners); + let unlinked = linked.with_aspect_linked(false); + for rules in [&linked, &unlinked] { + // A plain corner keeps the proportions along the diagonal, whatever the aspect link says. + let kept = dragged(p(100.0, 50.0), p(200.0, 60.0), Mods::NONE, rules); + assert!(corners_are(&kept, 0.0, 0.0, 184.0, 92.0), "{:?}", kept.quad); + // ⇧ frees them. + let freed = dragged(p(100.0, 50.0), p(200.0, 60.0), Mods::SHIFT, rules); + assert!(corners_are(&freed, 0.0, 0.0, 200.0, 60.0), "{:?}", freed.quad); + // The right edge's middle stretches only x, with ⇧ or without. + for mods in [Mods::NONE, Mods::SHIFT] { + let edge = dragged(p(100.0, 25.0), p(150.0, 40.0), mods, rules); + assert!(corners_are(&edge, 0.0, 0.0, 150.0, 50.0), "{mods:?}: {:?}", edge.quad); + } + } + // A ⌘ corner distorts as it does under the default rule: the gesture is left alone. + let distorted = dragged(p(100.0, 50.0), p(200.0, 60.0), Mods::CMD, &linked); + assert_eq!(distorted, dragged(p(100.0, 50.0), p(200.0, 60.0), Mods::CMD, &BoxRules::default())); + assert!(near(distorted.quad[2], p(200.0, 60.0)) && near(distorted.quad[0], p(0.0, 0.0)), "{:?}", distorted.quad); +} + #[test] fn a_shape_box_scales_corners_by_the_diagonal_and_edges_on_one_axis() { // The reference measurement: the bounds 100,98–723,451, the bottom-right handle dragged by diff --git a/crates/behavior/tests/geometry/snap.rs b/crates/behavior/tests/geometry/snap.rs index 3df1bcb57..0a8c44c09 100644 --- a/crates/behavior/tests/geometry/snap.rs +++ b/crates/behavior/tests/geometry/snap.rs @@ -2,7 +2,7 @@ use craft_behavior::Axis; use craft_behavior::geometry::{SnapKind, SnapKinds, SnapTarget, SnapTargets}; -use kurbo::{Rect, Vec2}; +use kurbo::{Point, Rect, Vec2}; fn guide(along: Axis, position: f64) -> SnapTarget { SnapTarget::new(along, position, SnapKind::Guide) @@ -31,3 +31,28 @@ fn a_moving_rect_skips_the_kinds_left_out() { let (offset, lines) = targets.snap_rect_of(rect, 4.0, SnapKinds::ALL.without(SnapKind::Selection)); assert_eq!((offset, lines.len()), (Vec2::ZERO, 0), "a moved selection ignores the selection's edges"); } + +#[test] +fn a_spanned_target_catches_only_a_box_that_overlaps_its_span_on_the_other_axis() { + let mut targets = SnapTargets::new(); + // A layer on page 2: its left edge at x 100 spans y 1200 to 1300. + targets.add_rect(Rect::new(100.0, 1200.0, 300.0, 1300.0), SnapKind::LayerEdge, SnapKind::LayerCenter); + targets.add(guide(Axis::Y, 400.0)); + + // Over page 1, 2 units right of the edge's line but far from its span: no snap. + let (offset, lines) = targets.snap_rect(Rect::new(102.0, 50.0, 150.0, 90.0), 4.0); + assert_eq!((offset, lines.len()), (Vec2::ZERO, 0), "a box over page 1 is not caught by page 2's layer"); + // Beside the layer on page 2: caught. + let (offset, _) = targets.snap_rect(Rect::new(102.0, 1210.0, 150.0, 1240.0), 4.0); + assert_eq!(offset.x, -2.0, "a box overlapping the span snaps to the edge"); + + // A point the same way. + let (at, lines) = targets.snap_point(Point::new(102.0, 60.0), 4.0); + assert_eq!((at, lines.len()), (Point::new(102.0, 60.0), 0)); + let (at, _) = targets.snap_point(Point::new(102.0, 1250.0), 4.0); + assert_eq!(at.x, 100.0); + + // A full-height guide catches a box anywhere along it. + let (offset, _) = targets.snap_rect(Rect::new(402.0, 50.0, 450.0, 90.0), 4.0); + assert_eq!(offset.x, -2.0, "an unspanned target is unchanged"); +} diff --git a/crates/draw/src/ui/transform/transform_box.rs b/crates/draw/src/ui/transform/transform_box.rs index 44d9ae8c8..7ba508dab 100644 --- a/crates/draw/src/ui/transform/transform_box.rs +++ b/crates/draw/src/ui/transform/transform_box.rs @@ -6,7 +6,7 @@ mod stories; use craft_behavior::geometry::quad::{self, BoxAllow, BoxDrag, BoxPart, BoxRules, BoxState, ScaleRule, TransformMode}; -use craft_behavior::geometry::{SNAP_PX, SnapKind, SnapKinds, SnapLine}; +use craft_behavior::geometry::{SNAP_PX, SnapKind, SnapKinds, SnapLine, SnapSuspend}; use craft_behavior::kurbo::{Point, Rect as DocRect, Vec2 as DocVec}; use craft_behavior::{ Axis, CancelReason, CanvasView, Cursor, CursorIcon, CursorPriority, GesturePhase, HitLevel, HitPriority, HitShape, Intent, Metrics, NavShape, @@ -72,6 +72,18 @@ const OVERFLOW_IN_HANDLES: f32 = 1.5; /// The keyboard path of a rotation by the outside parts: the options bar's angle field, which the host shows beside the box. const ROTATE_BY_KEY: &str = "the angle field in the options bar"; +/// The rotate handle of [`RotateZone::Handle`]: the zone's one rotating part, a knob on a stem off the middle of side 0. +const ROTATE_HANDLE: PartKey = PartKey::new("rotateHandle"); + +/// The length of the rotate handle's stem, from the side to the knob's centre, in standard handle sides. +const STEM_IN_HANDLES: f32 = 3.0; + +/// The ends of a line in [`LineEnds::Free`]: `LINE_END.at(0)` its start, `LINE_END.at(1)` its end. +const LINE_END: PartKey = PartKey::new("lineEnd"); + +/// The keyboard path of a free line end: the host commits the ends, through its own fields for them. +const LINE_END_BY_KEY: &str = "the line's end fields in the options bar"; + /// The part the keyboard picked, as the box remembers it between passes. #[derive(Clone, Copy, Default)] struct KeyPicked(Option); @@ -127,7 +139,8 @@ impl RotateZone { match self { RotateZone::Border { points } => border_distance(quad, pointer) <= points, RotateZone::Outside | RotateZone::Band => true, - RotateZone::Handle => todo!("cv.K37"), + // The handle is the zone's only outside part, so a press that reaches the outside is on it. + RotateZone::Handle => true, } } } @@ -195,12 +208,24 @@ pub struct LineLook { pub to: Point, /// The box aligned with the segment, corner by corner around it. pub outline: Option<[Point; 4]>, + /// What the two ends are: box handles, or free points the host commits. + pub ends: LineEnds, +} + +impl LineEnd { + /// The repeat of [`LINE_END`] the end is declared under. + const fn index(self) -> u64 { + match self { + LineEnd::From => 0, + LineEnd::To => 1, + } + } } impl LineLook { - /// The controls of the line from `from` to `to`, with no outline. + /// The controls of the line from `from` to `to`, with no outline, each end a box handle. pub fn new(from: Point, to: Point) -> Self { - LineLook { from, to, outline: None } + LineLook { from, to, outline: None, ends: LineEnds::Box } } /// These controls with the segment-aligned box `outline`. @@ -212,15 +237,25 @@ impl LineLook { /// These controls with `ends`: whether the ends are box handles or free points reported for the host to commit. #[must_use] - pub fn ends(self, ends: LineEnds) -> Self { - let _ = ends; - todo!("cv.K38") + pub fn ends(mut self, ends: LineEnds) -> Self { + self.ends = ends; + self } /// Each end that stands for a box handle, with the handle: the corner the end points to, away from the other end - /// (on a level or upright line, the side). A line of no length has none. + /// (on a level or upright line, the side). A line of no length, or one with free ends, has none. fn end_parts(&self) -> impl Iterator { - [(self.from, self.to), (self.to, self.from)].into_iter().filter_map(|(end, other)| Some((end_part(end, other)?, end))) + let boxed = self.ends == LineEnds::Box; + [(self.from, self.to), (self.to, self.from)] + .into_iter() + .filter(move |_| boxed) + .filter_map(|(end, other)| Some((end_part(end, other)?, end))) + } + + /// Each free end with its point, in [`LineEnds::Free`]; none when the ends are box handles. + fn free_ends(&self) -> impl Iterator { + let free = self.ends == LineEnds::Free; + [(LineEnd::From, self.from), (LineEnd::To, self.to)].into_iter().filter(move |_| free) } } @@ -285,6 +320,10 @@ pub struct TransformBoxStyle { band_outer: f32, pivot_radius: f32, pivot_arm: f32, + /// The rotate handle's stem, from the side to the knob's centre. + rotate_stem: f32, + /// The radius of the rotate handle's knob. + rotate_knob: f32, /// The round widget at a live line's middle: the corner widgets' look. widget: CornerStyle, } @@ -314,6 +353,7 @@ struct Report { picked: Option, held: Option, snapped: Vec, + line_end: Option, } /// The press the box is dragging a part with, kept from the press to its release. @@ -342,6 +382,21 @@ impl Default for Grip { } } +/// The press dragging a free line end, kept from the press to its release. +#[derive(Clone, Copy, Debug)] +struct EndGrip { + end: LineEnd, + /// From the press to the end, in document units: the end keeps it, so a press off the end's point does not jump. + offset: DocVec, + began: bool, +} + +impl Default for EndGrip { + fn default() -> Self { + EndGrip { end: LineEnd::From, offset: DocVec::ZERO, began: false } + } +} + /// Whether a press on `part` moves the box from the first pointer move inside the slop, so the box does not jump when /// the drag is recognised: every part but the outside, where a click applies the box. The parts' declared sense /// ([`slop_sense`]) and the grip both read it. @@ -381,7 +436,10 @@ fn slop_sense(part: BoxPart) -> Sense { /// [`session_arrows`](Self::session_arrows) off the arrows stay the tool's (the Move tool nudges the layer). /// - A [centre mark](Self::centre_mark) draws the reference point's glyph at the middle of the box and takes no press. /// A [live line's look](Self::line) declares only the line's two ends, each standing for the box handle it points -/// to, and draws the line's controls in place of the frame. +/// to, and draws the line's controls in place of the frame. With [free ends](LineEnds::Free) each end is a point of +/// its own: its drag reports [`TransformBoxOutput::line_end`] for the host to commit and leaves the box alone. +/// - In [`RotateZone::Handle`] only the rotate handle, a knob on a stem off the middle of the top side, rotates, and +/// the rest of the outside is the tool's. While Alt is the canvas's snap suspend key, the drag never reads Alt. /// - Nothing mirrors in a right-to-left interface: the box is the document's. #[derive(craft_ui::contract::Component, craft_ui::contract::Props)] #[component(canvas_control)] @@ -536,17 +594,17 @@ impl<'a> TransformBox<'a> { /// - 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. + /// - The canvas's suspend key (Control by default) suspends the snapping unless the drag reads it + /// ([`reads_suspend_key`](Self::reads_suspend_key)). The snap reads the keys as held; the drag acts on them as + /// [`drag_mods`] leaves them, so with Alt as the suspend key Alt only suspends. fn proposal(&self, space: &CanvasSpace, snap: Option<&Snap>, grip: &Grip, pos: Pos2, mods: Mods) -> (BoxState, Vec) { let to = space.view.to_doc(pos); - 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 suspend = suspend_key(snap); + let acting = drag_mods(mods, suspend); + let kind = self.rules.drag_kind(grip.part, acting); 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_suspend_key(reads_control) // P3(canvas-w4): cv.K9 - .kinds(kinds); + let gesture = GestureSnap::default().reads_suspend_key(self.reads_suspend_key(grip.part, acting, suspend)).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 => { @@ -567,7 +625,7 @@ impl<'a> TransformBox<'a> { } _ => (to, Vec::new()), }; - let dragged = quad::drag(&grip.start, &grip.last, grip.part, grip.from, to, mods, &self.rules); + let dragged = quad::drag(&grip.start, &grip.last, grip.part, grip.from, to, acting, &self.rules); // The canvas's pixel grid rounds an upright box and its corners to whole document units; keys are not rounded. let dragged = if snap.is_some_and(Snap::rounds_to_pixels) { on_pixel_grid(dragged) } else { dragged }; if kind == Some(BoxDrag::Distort) @@ -581,6 +639,20 @@ impl<'a> TransformBox<'a> { (dragged, lines) } + /// Whether a drag of `part` with `mods` (as the drag acts on them, [`drag_mods`]) reads the snap's `suspend` key + /// itself, so the key does not suspend the snapping. Control: where ⌘ (Ctrl off macOS) changes what the drag + /// does (a corner distorts, an edge skews) or on a corner that distorts. Alt: never, since the drag does not + /// see Alt while Alt is the suspend key. + fn reads_suspend_key(&self, part: BoxPart, mods: Mods, suspend: SnapSuspend) -> bool { + match suspend { + SnapSuspend::Alt => false, + _ => { + let kind = self.rules.drag_kind(part, mods); + mods.cmd && (kind != self.rules.drag_kind(part, Mods { cmd: false, ..mods }) || kind == Some(BoxDrag::Distort)) + } + } + } + /// The pointer for `part` at `pointer`, `dragging` during its drag. fn cursor(&self, look: &CursorLook<'_>, part: BoxPart, pointer: Pos2, mods: Mods, dragging: bool) -> Cursor { let Some(kind) = self.rules.drag_kind(part, mods) else { return CursorIcon::Default.into() }; @@ -589,6 +661,10 @@ impl<'a> TransformBox<'a> { let turn = || Cursor::from(PaintedCursor::turn(quad::bisector(screen, corner))); let along = |from: usize| vec2_of(screen.quad[(from + 1) % 4] - screen.quad[from % 4]); match (kind, part) { + // The rotate handle turns the cursor with the box: it points in across the side the handle stands on. + (BoxDrag::Rotate, BoxPart::Outside) if self.rotate_zone == RotateZone::Handle => { + Cursor::from(PaintedCursor::turn(-outward_normals(&screen.quad.map(pos))[0])) + } (BoxDrag::Rotate, BoxPart::Outside) if !dragging && !self.rotate_zone.rotates_at(&screen.quad, pointer) => CursorIcon::Default.into(), (BoxDrag::Rotate, BoxPart::Outside) => { if dragging || matches!(self.rotate_zone, RotateZone::Band | RotateZone::Border { .. }) || away <= style.rotate_reach { @@ -657,8 +733,8 @@ impl<'a> TransformBox<'a> { } /// The parts that take a press, with the box part each stands for. Mirrors what [`parts`](Component::parts) - /// declares: the keyboard parts, a segment per allowed edge, the centre where declared, and the outside; or only the - /// move strips. + /// declares: the keyboard parts, a segment per allowed edge, the centre where declared, and the outside or the + /// rotate handle; or only the move strips. fn pointer_parts(&self) -> Vec<(PartRef, BoxPart)> { if self.move_only().is_some() { let parts = if self.ring_reach().is_some() { 0..8 } else { 0..0 }; @@ -678,6 +754,7 @@ impl<'a> TransformBox<'a> { parts.push((CENTRE.at(0), BoxPart::Inside)); } parts.extend((0..4).map(|corner| (OUTSIDE.at(corner), BoxPart::Outside))); + parts.push((ROTATE_HANDLE.at(0), BoxPart::Outside)); parts } @@ -687,15 +764,17 @@ impl<'a> TransformBox<'a> { let style = cx.style; let mut held: Option = *cx.press_slot::(); let snap = canvas_snap(&cx.env); + let suspend = suspend_key(snap.as_ref()); for (reference, part) in self.pointer_parts() { let Some(result) = cx.part_if_declared(reference) else { continue }; let (press, hover) = (result.press, result.hover_pos.filter(|_| result.hovered)); let mods = self.mods.unwrap_or(press.mods); + let acting = drag_mods(mods, suspend); if let Some(pos) = hover && held.is_none() { self.report.hovered = Some(part); - let cursor = self.cursor(&CursorLook { space, screen: &screen, style }, part, pos, mods, false); + let cursor = self.cursor(&CursorLook { space, screen: &screen, style }, part, pos, acting, false); cx.cursor(cursor, CursorPriority::Part); } match press.phase { @@ -703,8 +782,10 @@ impl<'a> TransformBox<'a> { PressPhase::Down { start, .. } if part == BoxPart::Outside && !self.rotate_zone.rotates_at(&screen.quad, start.origin) => {} PressPhase::Down { start, .. } if start.button == PointerButton::Primary => { let from = space.view.to_doc(start.origin); - // The move reach only moves: an Alt press there is a move too. - let moves_pivot = mods.alt && self.move_only().is_none() && matches!(part, BoxPart::Inside | BoxPart::Outside); + // The move reach only moves: an Alt press there is a move too. The rotate handle is a handle, so + // an Alt press on it rotates. + let away_from_handles = part == BoxPart::Inside || (part == BoxPart::Outside && self.rotate_zone != RotateZone::Handle); + let moves_pivot = acting.alt && self.move_only().is_none() && away_from_handles; let follows = follows_in_slop(part); let (part, begin) = if moves_pivot { (BoxPart::Pivot, BoxState::new(shown.quad, from)) } else { (part, *shown) }; held = Some(Grip { part, start: begin, from, began: false, follows, moves_pivot, pressed: *shown, last: *shown }); @@ -749,7 +830,7 @@ impl<'a> TransformBox<'a> { cx.cancel(CancelReason::Unchanged); } else if grip.began { cx.commit(); - } else if grip.part == BoxPart::Outside && click && start.clicks <= 1 { + } else if grip.part == BoxPart::Outside && reference.key == OUTSIDE && click && start.clicks <= 1 { self.report.apply = Some(ApplyBy::ClickOutside { at: space.view.to_doc(start.origin) }); } else if grip.moves_pivot && click { cx.set(grip.start); @@ -772,10 +853,62 @@ impl<'a> TransformBox<'a> { cx.propose(next); let rows = self.readout_rows(cx, space, grip.part, &next, &grip.start); readout(&*cx, pos, &rows); - let cursor = self.cursor(&CursorLook { space, screen: &on_screen(&space.view, &next), style }, grip.part, pos, mods, true); + let acting = drag_mods(mods, suspend_key(snap)); + let cursor = self.cursor(&CursorLook { space, screen: &on_screen(&space.view, &next), style }, grip.part, pos, acting, true); cx.cursor(cursor, CursorPriority::Drag); } + /// The pointer on a line's free ends: a drag of an end reports [`LineEndDrag`] (`Begin` with its first position + /// once the press passes the slop, `Update`, `Commit` on the release, `Cancel` when the press is cancelled) with + /// the end snapped through the canvas's snap, and leaves the box's value alone: the host moves the end. A click + /// moves nothing. + fn run_line_ends(&mut self, cx: &mut Cx<'_, Self>, space: &CanvasSpace, line: &LineLook) { + let snap = canvas_snap(&cx.env); + let mut held: Option = *cx.press_slot::(); + for (end, at) in line.free_ends() { + let Some(result) = cx.part_if_declared(LINE_END.at(end.index())) else { continue }; + let (press, hovered) = (result.press, result.hovered); + let mods = self.mods.unwrap_or(press.mods); + if hovered && held.is_none() { + cx.cursor(Cursor::System(CursorIcon::Move), CursorPriority::Part); + } + let ours = held.filter(|grip| grip.end == end); + let (phase, pos, grip) = match (press.phase, ours) { + (PressPhase::Down { start, .. }, _) if start.button == PointerButton::Primary => { + held = Some(EndGrip { end, offset: at - space.view.to_doc(start.origin), began: false }); + continue; + } + (PressPhase::DragStart { pos, .. }, Some(grip)) => (GesturePhase::Begin, pos, grip), + (PressPhase::Drag { pos, .. }, Some(grip)) if grip.began => (GesturePhase::Update, pos, grip), + (PressPhase::Release { pos, .. }, Some(grip)) => { + held = None; + if !grip.began { + continue; + } + (GesturePhase::Commit, pos, grip) + } + (PressPhase::Cancel { .. }, Some(grip)) => { + held = None; + if grip.began { + self.report.line_end = Some(LineEndDrag { phase: GesturePhase::Cancel, end, at, mods }); + } + continue; + } + _ => continue, + }; + let to = space.view.to_doc(pos) + grip.offset; + let (to, lines) = match &snap { + Some(snap) => snap.point(to, mods, GestureSnap::default()), + None => (to, Vec::new()), + }; + self.report.snapped = lines; + self.report.line_end = Some(LineEndDrag { phase, end, at: to, mods }); + held = (phase != GesturePhase::Commit).then_some(EndGrip { began: true, ..grip }); + cx.cursor(Cursor::System(CursorIcon::Move), CursorPriority::Drag); + } + *cx.press_slot::() = held; + } + /// The session keys: the arrows nudge the picked part (the whole box when no part has focus), Enter applies and /// Escape closes the box. Untaken, a session's arrows go back to the canvas's tool. fn run_keys(&mut self, cx: &mut Cx<'_, Self>, space: &CanvasSpace, shown: &BoxState, pressing: bool) { @@ -822,10 +955,7 @@ impl TransformBox<'_> { fn paint_handle(&self, draw: &Draw<'_>, cx: &Cx<'_, Self>, part: BoxPart, at: Pos2, enlarged: bool) { let look = &cx.style.handle; let side = if enlarged { look.side * OVERFLOW_IN_HANDLES } else { look.side }; - let square = PaintShape::Rect(Rect::from_center_size(at, Vec2::splat(side)), CornerRadius::ZERO); - let fill = if self.rules.allows(part) { cx.resolve_part(BOX.at(part.index()), &look.fill) } else { cx.resolve(&look.fill) }; - draw.fill(&square, fill); - draw.stroke(&square, StrokeWidth::Thin, look.stroke); + paint_square(draw, cx, at, side, self.rules.allows(part).then(|| BOX.at(part.index()))); if enlarged { Handle::plus(draw, look, at, side); } @@ -838,21 +968,53 @@ impl TransformBox<'_> { if let Some(outline) = line.outline { let corners = outline.map(|corner| view.to_screen(corner)); paint_frame(draw, style, corners); - let look = &style.handle; for k in 0..4 { - let middle = corners[k].lerp(corners[(k + 1) % 4], 0.5); - let square = PaintShape::Rect(Rect::from_center_size(middle, Vec2::splat(look.side)), CornerRadius::ZERO); - draw.fill(&square, cx.resolve(&look.fill)); - draw.stroke(&square, StrokeWidth::Thin, look.stroke); + paint_square(draw, cx, corners[k].lerp(corners[(k + 1) % 4], 0.5), style.handle.side, None); } } for (part, end) in line.end_parts() { self.paint_handle(draw, cx, part, view.to_screen(end), false); } + for (end, at) in line.free_ends() { + paint_square(draw, cx, view.to_screen(at), style.handle.side, Some(LINE_END.at(end.index()))); + } paint_widget(draw, view.to_screen(line.from.midpoint(line.to)), &style.widget); } } +/// A handle square of `side` centred on `at`, filled as the state of `part` shows, or at rest without one. +fn paint_square(draw: &Draw<'_>, cx: &Cx<'_, TransformBox<'_>>, at: Pos2, side: f32, part: Option) { + let look = &cx.style.handle; + let square = PaintShape::Rect(Rect::from_center_size(at, Vec2::splat(side)), CornerRadius::ZERO); + let fill = match part { + Some(part) => cx.resolve_part(part, &look.fill), + None => cx.resolve(&look.fill), + }; + draw.fill(&square, fill); + draw.stroke(&square, StrokeWidth::Thin, look.stroke); +} + +/// The rotate handle of [`RotateZone::Handle`] on the box whose corners are `quad` on the screen: its stem from the +/// middle of side 0 over its halo, and the round knob at its end, filled as the handle's state shows. +fn paint_rotate_handle(draw: &Draw<'_>, cx: &Cx<'_, TransformBox<'_>>, quad: &[Pos2; 4]) { + let style = cx.style; + let (base, knob) = rotate_handle(quad, style.rotate_stem); + let stem = PaintShape::Path(vec![base, knob]); + draw.stroke(&stem, StrokeWidth::Thick, style.halo); + draw.stroke(&stem, StrokeWidth::Medium, style.line); + let look = &style.handle; + let circle = PaintShape::Circle(knob, style.rotate_knob); + draw.fill(&circle, cx.resolve_part(ROTATE_HANDLE.at(0), &look.fill)); + draw.stroke(&circle, StrokeWidth::Thin, look.stroke); +} + +/// The rotate handle of the box whose corners are `quad` on the screen: the middle of side 0 (corners 0 to 1) and the +/// knob's centre, `stem` out from it across the side, so the handle turns with the box. +fn rotate_handle(quad: &[Pos2; 4], stem: f32) -> (Pos2, Pos2) { + let base = quad[0].lerp(quad[1], 0.5); + (base, base + outward_normals(quad)[0] * stem) +} + /// The outline of a box whose corners are `corners` on the screen: the line over its halo. fn paint_frame(draw: &Draw<'_>, style: &TransformBoxStyle, corners: [Pos2; 4]) { let outline = PaintShape::Polygon(corners.to_vec()); @@ -960,6 +1122,8 @@ impl Component for TransformBox<'_> { band_outer: handle.md * BAND_OUTER_IN_HANDLES, pivot_radius: cx.tokens.size.handle.sm / 2.0, pivot_arm: hit.target, + rotate_stem: handle.md * STEM_IN_HANDLES, + rotate_knob: handle.sm / 2.0, widget: CornerStyle::from_cx(cx), } } @@ -990,7 +1154,8 @@ impl Component for TransformBox<'_> { /// alike, so the nearest wins where they overlap on a small box; /// they rank above a side, which ranks above the inside, which ranks above the outside. Every part takes a press's /// click with its drag, so a press on the box is the box's alone, not split with what lies under it (8.3). A live - /// line's controls declare its two ends only. + /// line's controls declare its two ends only; free ends as points of their own. In [`RotateZone::Handle`] the + /// rotate handle ranks with the handles and is the only outside part. fn parts(&mut self, rect: Rect, cx: &mut PartsCx<'_, Self>) { let (Some(space), Some(state)) = (canvas_space(&cx.env), cx.value().copied()) else { return }; let style = cx.style; @@ -1028,7 +1193,13 @@ impl Component for TransformBox<'_> { cx.part(BOX.at(part.index()), shape).sense(sense | slop_sense(part)).priority(priority).focus_shape(focus).focusable(); any = true; } - if self.line.is_some() { + if let Some(line) = self.line { + for (end, at) in line.free_ends() { + cx.part(LINE_END.at(end.index()), HitShape::circle(space.view.to_screen(at), style.handle_reach)) + .sense(Sense::DRAG | Sense::CLICK) + .priority(HitPriority::new(HitLevel::Handle, HANDLE_SUB)) + .pointer_only(LINE_END_BY_KEY); + } if any { cx.roving(Roving::new(NavShape::Flat).page(Some(1))); } @@ -1080,18 +1251,28 @@ impl Component for TransformBox<'_> { } } RotateZone::Band => {} - RotateZone::Handle => todo!("cv.K37"), + RotateZone::Handle if self.rules.allows(BoxPart::Outside) => { + let (_, knob) = rotate_handle(&quad, style.rotate_stem); + cx.part(ROTATE_HANDLE.at(0), HitShape::circle(knob, style.handle_reach)) + .sense(Sense::DRAG | Sense::CLICK | slop_sense(BoxPart::Outside)) + .priority(HitPriority::new(HitLevel::Handle, HANDLE_SUB)) + .pointer_only(ROTATE_BY_KEY); + } + RotateZone::Handle => {} } } fn update(&mut self, cx: &mut Cx<'_, Self>) { let (Some(space), Some(shown)) = (canvas_space(&cx.env), cx.value().copied()) else { return }; - let held = cx.press_slot::().is_some(); + let held = cx.press_slot::().is_some() || cx.press_slot::().is_some(); self.run_pointer(cx, &space, &shown); + if let Some(line) = self.line.filter(|line| line.ends == LineEnds::Free) { + self.run_line_ends(cx, &space, &line); + } self.pivot_held = cx.press_slot::().is_some_and(|grip| grip.part == BoxPart::Pivot); self.dragging = cx.press_slot::().is_some_and(|grip| grip.began); self.report.held = cx.press_slot::().map(|grip| grip.part); - let pressing = held || cx.press_slot::().is_some(); + let pressing = held || cx.press_slot::().is_some() || cx.press_slot::().is_some(); if self.move_only().is_none() { self.run_keys(cx, &space, &shown, pressing); } @@ -1112,6 +1293,9 @@ impl Component for TransformBox<'_> { Some(line) => self.paint_line(&draw, cx, &space.view, &line), None => { paint_frame(&draw, style, screen.quad.map(pos)); + if self.rotate_zone == RotateZone::Handle && self.rules.allows(BoxPart::Outside) { + paint_rotate_handle(&draw, cx, &screen.quad.map(pos)); + } if self.centre_mark { let centre = screen.quad.iter().fold(Vec2::ZERO, |sum, corner| sum + pos(*corner).to_vec2()) / 4.0; paint_centre_glyph(&draw, centre.to_pos2(), style); @@ -1148,8 +1332,8 @@ impl Component for TransformBox<'_> { } fn finish(self, cx: Cx<'_, Self>) -> TransformBoxOutput { - let Report { apply, discard, hovered, picked, held, snapped } = self.report; - TransformBoxOutput { edit: cx.edit_response(), apply, discard, picked, hovered, held, snapped, line_end: None } + let Report { apply, discard, hovered, picked, held, snapped, line_end } = self.report; + TransformBoxOutput { edit: cx.edit_response(), apply, discard, picked, hovered, held, snapped, line_end } } } @@ -1198,6 +1382,17 @@ fn vec2_of(v: DocVec) -> Vec2 { Vec2::new(v.x as f32, v.y as f32) } +/// The suspend key of the canvas's snap, Control without one. +fn suspend_key(snap: Option<&Snap>) -> SnapSuspend { + snap.map_or_else(SnapSuspend::default, |snap| snap.options().suspend) +} + +/// The keys a drag acts on, from the keys held: while Alt suspends the canvas's snapping, Alt is the snap's alone, so +/// it neither scales about the reference point nor moves it. +fn drag_mods(mods: Mods, suspend: SnapSuspend) -> Mods { + if suspend == SnapSuspend::Alt { Mods { alt: false, ..mods } } else { mods } +} + /// The position of a corner, an edge's midpoint or the reference point; `None` for the inside and the outside. fn handle_point(state: &BoxState, part: BoxPart) -> Option { let q = &state.quad; diff --git a/crates/draw/src/ui/transform/transform_box/stories.rs b/crates/draw/src/ui/transform/transform_box/stories.rs index 9dc87eb10..6ccdedd56 100644 --- a/crates/draw/src/ui/transform/transform_box/stories.rs +++ b/crates/draw/src/ui/transform/transform_box/stories.rs @@ -1,7 +1,8 @@ //! Stories of the transform box: Free Transform with its reference point, the Move tool's controls, Distort, the -//! Ellipse tool's centre mark and the Line tool's live-line controls. +//! Ellipse tool's centre mark, the rotate handle and the Line tool's live-line controls, with box or free ends. -use super::{BOX, LineLook, RotateZone, TransformBox}; +use super::{BOX, LINE_END, LineEnd, LineEnds, LineLook, ROTATE_HANDLE, RotateZone, TransformBox, TransformBoxOutput}; +use craft_behavior::GesturePhase; use craft_behavior::geometry::quad::{BoxPart, BoxRules, BoxState, TransformMode}; use craft_behavior::kurbo::{Point, Rect as DocRect}; use craft_ui::canvas::Canvas; @@ -27,6 +28,15 @@ fn free_box(state: Bind<'_, BoxState>) -> TransformBox<'_> { /// Shows the box `make` builds over the story's box as the only canvas control of a canvas. fn on_canvas(ui: &mut Ui, data: &mut StoryData, make: impl for<'a> Fn(Bind<'a, BoxState>) -> TransformBox<'a>) -> StoryOutput { + shown_on_canvas(ui, data, make).map(|output| StoryOutput::from(output.edit)).unwrap_or_default() +} + +/// [`on_canvas`] with the box's whole output. +fn shown_on_canvas( + ui: &mut Ui, + data: &mut StoryData, + make: impl for<'a> Fn(Bind<'a, BoxState>) -> TransformBox<'a>, +) -> Option { let state = data.value("box", BoxState::from_rect(PICTURE)); let room = craft_ui::testing::stage(ui); let view = craft_ui::testing::canvas_story::story_view(room, ui.pixels_per_point(), PICTURE.center(), 100.0); @@ -36,7 +46,7 @@ fn on_canvas(ui: &mut Ui, data: &mut StoryData, make: impl for<'a> Fn(Bind<'a, B show_quad(ui, body.rect, "Layer", state.quad, &layer); make(Bind::bound(&mut *state)).show_at(ui, body.rect) }); - shown.inner.map(|output| StoryOutput::from(output.edit)).unwrap_or_default() + shown.inner } #[story(TransformBox<'static>, covers = [Default], drive = Drive::Drag(Grip::part(BOX.at(BoxPart::Corner(2).index())).toward(vec2(1.0, 1.0))))] @@ -80,3 +90,38 @@ fn live_line(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { let line = LineLook::new(quad[3], quad[1]); on_canvas(ui, data, move |state| free_box(state).rotate_zone(RotateZone::Band).inside_moves(false).reference_point(false).line(line)) } + +/// Free Transform turned only by the rotate handle on its stem above the top side; the rest of the outside is the +/// tool's. +#[story(TransformBox<'static>, covers = [Default], drive = Drive::Drag(Grip::part(ROTATE_HANDLE.at(0)).toward(vec2(1.0, 0.0))))] +fn rotate_handle(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { + on_canvas(ui, data, |state| free_box(state).reference_point(true).rotate_zone(RotateZone::Handle)) +} + +/// A live line whose ends are free points: dragging an end moves only that end, at any angle, and the story commits +/// it as a host does; the box stays. +#[story(TransformBox<'static>, covers = [Default], drive = Drive::Drag(Grip::part(LINE_END.at(1)).toward(vec2(1.0, -1.0))))] +fn line_free_ends(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { + let quad = BoxState::from_rect(PICTURE).quad; + let ends = *data.value("ends", [quad[3], quad[1]]); + let line = LineLook::new(ends[0], ends[1]).ends(LineEnds::Free); + let shown = + shown_on_canvas(ui, data, move |state| free_box(state).rotate_zone(RotateZone::Band).inside_moves(false).reference_point(false).line(line)); + let Some(output) = shown else { return StoryOutput::default() }; + if let Some(drag) = output.line_end { + let index = usize::from(drag.end == LineEnd::To); + match drag.phase { + GesturePhase::Cancel => { + let before = *data.value("before", ends); + *data.value("ends", ends) = before; + } + phase => { + if phase == GesturePhase::Begin { + *data.value("before", ends) = ends; + } + data.value("ends", ends)[index] = drag.at; + } + } + } + StoryOutput::from(output.edit) +} diff --git a/crates/draw/tests/it/transform_box.rs b/crates/draw/tests/it/transform_box.rs index 4f4b10608..53d981754 100644 --- a/crates/draw/tests/it/transform_box.rs +++ b/crates/draw/tests/it/transform_box.rs @@ -1,12 +1,13 @@ //! `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, TransformMode}; -use craft_behavior::geometry::{SnapKind, SnapOptions, SnapTarget, SnapTargets}; -use craft_behavior::kurbo::{Point, Rect}; -use craft_behavior::{CanvasView, EditEvent, RulerUnits, Ticks}; +use craft_behavior::geometry::quad::{BoxAllow, BoxPart, BoxRules, BoxState, ScaleRule, TransformMode}; +use craft_behavior::geometry::{SnapKind, SnapOptions, SnapSuspend, SnapTarget, SnapTargets}; +use craft_behavior::kurbo::{Affine, Point, Rect}; +use craft_behavior::{CanvasView, EditEvent, GesturePhase, RulerUnits, Ticks}; use craft_draw::ui::transform::{ - LineLook, RotateZone, TransformBox, TransformEdit, TransformOverlay, TransformReach, TransformSession, TransformSettings, + LineEnd, LineEndDrag, LineEnds, LineLook, RotateZone, TransformBox, TransformEdit, TransformOverlay, TransformReach, TransformSession, + TransformSettings, }; use craft_keymap::{Mods, Platform}; use craft_ui::canvas::{Canvas, RulerText, Snap}; @@ -55,6 +56,8 @@ struct Config { line: Option, /// Snap targets beside the guides at [`SNAP_XS`]. targets: Vec, + /// The key that suspends the canvas's snapping. + suspend: SnapSuspend, } /// What the host keeps of the box and what the passes reported. @@ -71,6 +74,8 @@ struct Host { guide_events: usize, /// The snap lines the last pass reported. snapped: usize, + /// Every free line end drag the passes reported. + line_ends: Vec, } struct Harness { @@ -99,6 +104,7 @@ fn defaults() -> Config { centre_mark: false, line: None, targets: Vec::new(), + suspend: SnapSuspend::Control, } } @@ -125,6 +131,7 @@ fn harness(state: BoxState, setup: impl FnOnce(&mut Config)) -> Harness { view: CanvasView::new(egui::Rect::NOTHING, Point::ZERO, 1.0), guide_events: 0, snapped: 0, + line_ends: Vec::new(), })); let shown_host = Rc::clone(&host); let mut guides = vec![Guide::new(GuideKey::new(1), craft_behavior::Axis::Y, 300.0)]; @@ -142,6 +149,7 @@ fn harness(state: BoxState, setup: impl FnOnce(&mut Config)) -> Harness { // A box on the pixel grid alone has the grid through a snap that snaps to nothing. let mut options = SnapOptions::default(); options.on = config.snap; + options.suspend = config.suspend; let snap = Snap::new(Arc::clone(&targets), options).whole_pixels(config.pixel_grid); let view = CanvasView::new(room, Point::new(f64::from(room.width()) / 2.0, f64::from(room.height()) / 2.0), 1.0) .rotation(config.rotation) @@ -187,6 +195,9 @@ fn harness(state: BoxState, setup: impl FnOnce(&mut Config)) -> Harness { let mut host = shown_host.borrow_mut(); host.guide_events += guide_edits; host.snapped = output.snapped.len(); + if let Some(drag) = output.line_end { + host.line_ends.push(drag); + } host.id = output.edit.response.id; host.applied += usize::from(output.apply.is_some()); host.discarded += usize::from(output.discard); @@ -985,6 +996,174 @@ fn control_keeps_snapping_on_an_explicit_distort_corner_only() { } } +/// The rotate handle stands on its stem above the middle of the top side: a drag from it turns the box about its +/// reference point (Shift in rotate steps); the rest of the outside is the tool's, and a click there or on the handle +/// applies nothing. Where the rules refuse rotating there is no handle. +#[trial] +fn the_rotate_handle_turns_the_box_about_its_reference_point_and_the_rest_of_the_outside_is_the_tools() { + let handle = |config: &mut Config| config.zone = RotateZone::Handle; + // The points straight above the top side's middle that the handle takes. + let handle_reach = |h: &mut Harness| -> Vec { + (1..80) + .map(|up| Point::new(200.0, RECT.y0 - f64::from(up))) + .filter(|&at| { + hover(h, at); + h.host.borrow().hovered == Some(BoxPart::Outside) + }) + .collect() + }; + let mut h = harness(BoxState::from_rect(RECT), handle); + let reach = handle_reach(&mut h); + assert!(!reach.is_empty(), "the handle stands above the top side"); + assert!(reach[0].y < RECT.y0 - 8.0, "on a stem, clear of the top edge's handle: {reach:?}"); + let knob = reach[reach.len() / 2]; + + let centre = RECT.center(); + for (mods, angle, within) in [(None, 20.0, 0.01), (Some(Mods::SHIFT), 15.0, 1e-6)] { + let mut h = harness(BoxState::from_rect(RECT), |config| { + handle(config); + config.mods = mods; + }); + drag(&mut h, knob, Affine::rotate_about(20f64.to_radians(), centre) * knob); + let state = h.state(); + assert!((state.angle() - angle).abs() < within, "{mods:?}: turned {}, expected {angle}", state.angle()); + assert!(state.pivot.distance(centre) < 1e-9, "about the reference point: {:?}", state.pivot); + assert_eq!(h.host.borrow().events.last(), Some(&Seen::Commit)); + } + + // Elsewhere outside: nothing of the box. + let mut h = harness(BoxState::from_rect(RECT), handle); + let away = Point::new(340.0, 260.0); + hover(&mut h, away); + assert_eq!(h.host.borrow().hovered, None, "the rest of the outside is the tool's"); + drag(&mut h, away, Point::new(360.0, 200.0)); + assert!(h.host.borrow().events.is_empty(), "a drag there turns nothing: {:?}", h.host.borrow().events); + assert_eq!(h.state(), BoxState::from_rect(RECT)); + for at in [away, knob] { + let at = h.screen(at); + frame(&mut h, vec![pointer::moved(at)]); + frame(&mut h, vec![pointer::press(at)]); + frame(&mut h, vec![pointer::release(at)]); + frame(&mut h, Vec::new()); + } + assert_eq!(h.host.borrow().applied, 0, "a click outside or on the handle applies nothing"); + + let mut h = harness(BoxState::from_rect(RECT), |config| { + handle(config); + config.rules = BoxRules::default().with_allow(BoxAllow::new(false, true, true)); + }); + assert!(handle_reach(&mut h).is_empty(), "no handle where rotating is refused"); +} + +/// With Alt as the snap suspend key, Alt suspends the snapping and is never the drag's: a corner does not scale about +/// the reference point and an Alt press inside moves the box, not the reference point. Control no longer suspends. +#[trial] +fn with_alt_as_the_snap_key_alt_suspends_snapping_and_no_alt_press_moves_the_reference_point() { + // (os, the keys held, whether the corner snaps onto 310) + let cases = [(Platform::Mac, None, true), (Platform::Mac, Some(Mods::ALT), false), (Platform::Mac, Some(Mods::CTRL), true), (Platform::Windows, Some(Mods::ALT), false)]; + for (os, held, snaps) in cases { + let mut h = harness(BoxState::from_rect(RECT), |config| { + config.snap = true; + config.suspend = SnapSuspend::Alt; + config.mods = held; + config.rules = BoxRules::default().with_aspect_linked(false); + }); + h.fixture.os(os); + 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))]); + frame(&mut h, vec![pointer::release(from + by(7.0, 0.0))]); + let quad = h.state().quad; + let moved = quad[2].x - RECT.x1; + let expected = if snaps { 10.0 } else { 7.0 }; + assert!((moved - expected).abs() < 1e-3, "{os:?} {held:?}: moved {moved}, expected {expected}"); + assert!(quad[0].distance(Point::new(RECT.x0, RECT.y0)) < 1e-6, "{os:?} {held:?}: no scaling about the reference point: {quad:?}"); + } + + let mut h = harness(BoxState::from_rect(RECT), |config| { + config.snap = true; + config.suspend = SnapSuspend::Alt; + config.mods = Some(Mods::ALT); + }); + // 7 right brings the right edge within reach of the guide at 310; the Alt drag stays unsnapped. + drag(&mut h, Point::new(150.0, 120.0), Point::new(157.0, 120.0)); + let state = h.state(); + assert!(state.quad[0].distance(Point::new(107.0, RECT.y0)) < 1e-3, "the Alt drag moves the box, unsnapped: {:?}", state.quad); + assert!(state.pivot.distance(Point::new(207.0, 150.0)) < 1e-3, "the reference point rides along: {:?}", state.pivot); +} + +/// The resize arrows follow the box's own axes: corner 2's along its bisector, the right edge's along the box's x +/// axis, so a box turned by 30° shows other arrows than a level one. +#[trial] +fn a_turned_box_shows_resize_arrows_along_its_own_axes() { + use craft_behavior::{Cursor, CursorIcon}; + let cursor_over = |h: &mut Harness, at: Point| { + hover(h, at); + craft_ui::runtime::cursor::current(h.fixture.ctx()) + }; + let level = BoxState::from_rect(RECT); + let turned = level.turned_about_pivot(30f64.to_radians()); + // Level: the corner's arrow at 45°, the edge's at 0°. Turned by 30°: 75° and 30°. + for (state, corner, edge) in [(level, CursorIcon::ResizeNwSe, CursorIcon::ResizeHorizontal), (turned, CursorIcon::ResizeVertical, CursorIcon::ResizeNwSe)] { + let mut h = harness(state, |_| {}); + let at_corner = state.quad[2]; + let at_edge = state.quad[1].midpoint(state.quad[2]); + assert_eq!(cursor_over(&mut h, at_corner), Some(Cursor::from(corner)), "corner 2 of {:?}", state.quad); + assert_eq!(cursor_over(&mut h, at_edge), Some(Cursor::from(edge)), "the right edge of {:?}", state.quad); + } +} + +/// Free line ends: a drag of an end reports Begin, Update and Commit for that end only, at any angle, snapped through +/// the canvas's snap unless Control suspends it, and leaves the box value alone; Escape cancels the drag. +#[trial] +fn free_line_ends_move_one_end_and_report_the_drag_for_the_host_to_commit() { + let (from, to) = (Point::new(RECT.x0, RECT.y1), Point::new(RECT.x1, RECT.y0)); + let line = LineLook::new(from, to).ends(LineEnds::Free); + let free = |held: Option| { + let mut h = harness(BoxState::from_rect(RECT), |config| { + config.snap = true; + config.mods = held; + config.reference_point = false; + config.zone = RotateZone::Band; + config.line = Some(line); + }); + h.fixture.os(Platform::Mac); + h + }; + // 7 right and 30 up, at a slant: the end lands on the guide at 310. + let dragged_to = to + kurbo_vec(7.0, -30.0); + for (held, x) in [(None, 310.0), (Some(Mods::CTRL), 307.0)] { + let mut h = free(held); + drag(&mut h, to, dragged_to); + let drags = h.host.borrow().line_ends.clone(); + let phases: Vec = drags.iter().map(|drag| drag.phase).collect(); + assert_eq!(phases.first(), Some(&GesturePhase::Begin), "{held:?}: {phases:?}"); + assert_eq!(phases.last(), Some(&GesturePhase::Commit), "{held:?}: {phases:?}"); + assert!(phases[1..phases.len() - 1].iter().all(|phase| *phase == GesturePhase::Update), "{held:?}: {phases:?}"); + assert!(drags.iter().all(|drag| drag.end == LineEnd::To), "only the dragged end moves: {drags:?}"); + let Some(last) = drags.last() else { panic!("no drag reported") }; + assert!(last.at.distance(Point::new(x, dragged_to.y)) < 1e-3, "{held:?}: the end at {:?}, expected x {x}", last.at); + assert_eq!(h.state(), BoxState::from_rect(RECT), "the box value is unchanged"); + assert!(h.host.borrow().events.is_empty(), "no edit of the box: {:?}", h.host.borrow().events); + } + + let mut h = free(None); + let (start, end) = (h.screen(to), h.screen(dragged_to)); + frame(&mut h, vec![pointer::moved(start)]); + frame(&mut h, vec![pointer::press(start)]); + frame(&mut h, vec![pointer::moved(start + (end - start) * 0.5)]); + frame(&mut h, vec![pointer::moved(end)]); + h.fixture.key(egui::Key::Escape, egui::Modifiers::NONE); + frame(&mut h, vec![pointer::release(end)]); + frame(&mut h, Vec::new()); + let phases: Vec = h.host.borrow().line_ends.iter().map(|drag| drag.phase).collect(); + assert_eq!(phases.last(), Some(&GesturePhase::Cancel), "Escape cancels the end drag: {phases:?}"); + assert!(!phases.contains(&GesturePhase::Commit), "nothing is committed: {phases:?}"); + assert_eq!(h.host.borrow().discarded, 0, "Escape cancels the drag and does not close the box"); +} + /// 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] diff --git a/crates/ui-canvas/src/canvas/snap.rs b/crates/ui-canvas/src/canvas/snap.rs index de55ed932..c280527a5 100644 --- a/crates/ui-canvas/src/canvas/snap.rs +++ b/crates/ui-canvas/src/canvas/snap.rs @@ -23,7 +23,7 @@ pub struct Snap { whole_pixels: bool, } -/// The gesture's snap options in one argument: whether the gesture reads Control itself, and a kind filter. +/// The gesture's snap options in one argument: whether the gesture reads the suspend key itself, and a kind filter. #[derive(Clone, Copy, Debug, Default)] #[non_exhaustive] pub struct GestureSnap { @@ -55,7 +55,7 @@ impl Snap { /// This snap rounding every point it gives to whole document units when `on`: the pixel grid for drawn points and /// transform boxes (Preferences > Tools > Snap Vector Tools and Transforms to Pixel Grid, as the app decides it - /// applies). The rounding follows the target snap and holds with snapping off or suspended by Control. + /// applies). The rounding follows the target snap and holds with snapping off or suspended by its key. #[must_use] pub fn whole_pixels(mut self, on: bool) -> Self { self.whole_pixels = on; @@ -145,13 +145,11 @@ impl std::fmt::Debug for Snap { } } -/// Whether the modifiers held now turn snapping off: the Control key (Control without ⌘ on macOS, Ctrl elsewhere) -/// suspends it while held, Photoshop's rule, unless the gesture reads that key itself (`tool_reads_control`: off macOS +/// Whether the modifiers held now turn snapping off: the `suspend` key ([`SnapSuspend::is_held`]; Control by default, +/// Photoshop's rule) suspends it while held, unless the gesture reads that key itself (`gesture_reads_key`: off macOS /// Ctrl on a transform box corner distorts). Every snapped drag applies it, whatever its targets are. pub fn snap_suspended(mods: Mods, os: Platform, suspend: SnapSuspend, gesture_reads_key: bool) -> bool { - let _ = suspend; // P3(canvas-w4): cv.K9 - let control = if os.is_mac() { mods.ctrl && !mods.cmd } else { mods.cmd }; - control && !gesture_reads_key + suspend.is_held(mods, os) && !gesture_reads_key } /// How far, in document units under `view`, a dragged point still snaps to a target: [`SNAP_PX`] screen points, or diff --git a/crates/ui-canvas/tests/it/canvas/snap.rs b/crates/ui-canvas/tests/it/canvas/snap.rs index 7c69c636c..2691042cb 100644 --- a/crates/ui-canvas/tests/it/canvas/snap.rs +++ b/crates/ui-canvas/tests/it/canvas/snap.rs @@ -1,7 +1,7 @@ //! `Snap` (cw.C16): the canvas's one snapping, over its targets, at the tolerance of the view it shows, gated by View > -//! Snap and the Control key of the OS. +//! Snap and the suspend key of its options (Control of the OS by default, or Alt). -use craft_behavior::geometry::{SnapKind, SnapOptions, SnapTarget, SnapTargets}; +use craft_behavior::geometry::{SnapKind, SnapOptions, SnapSuspend, SnapTarget, SnapTargets}; use craft_behavior::kurbo::{Point, Rect as DocRect, Vec2}; use craft_behavior::{Axis, CancelReason, CanvasView}; use craft_keymap::{Mods, Platform}; @@ -72,7 +72,7 @@ fn snapped_with(fixture: &mut ToolFixture, mods: Modifiers) -> Point { // The body's snap and the tool's both snap within 8 screen points, 4 document units at zoom 2: a coordinate 3 units off // a guide moves onto it and one 5 units off stays. A point snaps on both axes and a box by its edge, each with the // lines to draw. View > Snap off returns the input. Control suspends snapping on macOS and Ctrl elsewhere, unless the -// gesture reads that key itself. +// gesture reads that key itself. With Alt as the options' suspend key, Alt suspends instead and Control does not. #[trial] fn snap_targets_snap_points_and_boxes_unless_control_suspends() { let options = SnapOptions::default(); @@ -109,6 +109,30 @@ fn snap_targets_snap_points_and_boxes_unless_control_suspends() { assert_eq!(snap.apply(Axis::Y, 103.0, Mods::NONE), 100.0); assert_eq!(snapped_with(&mut fixture, Modifiers::CTRL), NEAR, "Ctrl held suspends the tool's snap"); + // With Alt as the suspend key, Alt suspends and Control no longer does, on either OS. + let mut alt = options; + alt.suspend = SnapSuspend::Alt; + for os in [Platform::Mac, Platform::Windows] { + let (mut fixture, seen) = rig(Snap::new(targets(), alt)); + fixture.fixture().os(os).frame(Vec::new()); + let snap = seen.borrow().clone().expect("the canvas publishes its snap to its body"); + assert_eq!(snap.options().suspend, SnapSuspend::Alt); + assert_eq!(snap.apply(Axis::Y, 103.0, Mods::ALT), 103.0, "Alt suspends on {os:?}"); + assert_eq!(snap.apply(Axis::Y, 103.0, Mods::CTRL), 100.0, "Control keeps snapping on {os:?}"); + assert_eq!(snap.point(NEAR, Mods::ALT, GestureSnap::default()), (NEAR, Vec::new()), "on {os:?}"); + assert_eq!(snap.point(NEAR, Mods::CTRL, GestureSnap::default()).0, Point::new(100.0, 200.0), "on {os:?}"); + assert_eq!( + snap.point(NEAR, Mods::ALT, GestureSnap::default().reads_suspend_key(true)).0, + Point::new(100.0, 200.0), + "a gesture that reads Alt keeps snapping on {os:?}" + ); + assert_eq!(snap.rect(DocRect::new(60.0, 10.0, 97.0, 40.0), Mods::ALT), (Vec2::ZERO, Vec::new()), "on {os:?}"); + assert_eq!(snap.rect(DocRect::new(60.0, 10.0, 97.0, 40.0), Mods::CTRL).0, Vec2::new(3.0, 0.0), "on {os:?}"); + assert!(!snap.rect(DocRect::new(60.0, 10.0, 97.0, 40.0), Mods::CTRL).1.is_empty(), "Control snaps and reports its line on {os:?}"); + assert_eq!(snapped_with(&mut fixture, Modifiers::ALT), NEAR, "Alt held suspends the tool's snap on {os:?}"); + assert_eq!(snapped_with(&mut fixture, Modifiers::CTRL), Point::new(100.0, 200.0), "Control held snaps the tool on {os:?}"); + } + let mut off = options; off.on = false; let (mut fixture, seen) = rig(Snap::new(targets(), off));