diff --git a/crates/draw/src/ui/transform/transform_box.rs b/crates/draw/src/ui/transform/transform_box.rs index 37bdae51e..5b51b8c7b 100644 --- a/crates/draw/src/ui/transform/transform_box.rs +++ b/crates/draw/src/ui/transform/transform_box.rs @@ -7,14 +7,13 @@ mod stories; use craft_behavior::geometry::SnapTargets; use craft_behavior::geometry::quad::{self, BoxDrag, BoxPart, BoxRules, BoxState, TransformMode}; -use craft_behavior::geometry::snap::SNAP_PX; use craft_behavior::kurbo::{Point, Rect as DocRect, Vec2 as DocVec}; use craft_behavior::{ Axis, CanvasView, Cursor, CursorIcon, CursorPriority, HitLevel, HitPriority, HitShape, Intent, Metrics, NavShape, PaintedCursor, PartKey, PartRef, PointerButton, PressPhase, Roving, Sense, resize_cursor, }; -use craft_keymap::Mods; -use craft_ui::canvas::{CanvasSpace, canvas_space, readout}; +use craft_keymap::{Mods, Platform}; +use craft_ui::canvas::{CanvasSpace, canvas_space, readout, snap_tolerance}; use craft_ui::contract::{ Access, Bind, BindMut, Common, Component, Cx, Edit as _, EditResponse, Focus as _, MeasureCx, Name, Outcome, PaintUi, PartsCx, Pointer as _, Props as _, Remember as _, Role, Styled as _, WordSetCx as _, @@ -230,10 +229,15 @@ 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 and rounded. - fn proposal(&self, space: &CanvasSpace, grip: &Grip, pos: Pos2, mods: Mods) -> BoxState { + /// The box the pointer at screen position `pos` gives a drag, snapped and rounded. The Control key suspends the + /// snapping unless it changes what the drag does (off macOS Ctrl is ⌘: a corner distorts, an edge skews). + fn proposal(&self, space: &CanvasSpace, grip: &Grip, pos: Pos2, mods: Mods, os: Platform) -> BoxState { let to = space.view.to_doc(pos); - let to = self.snap.map_or(to, |targets| targets.snap_point(to, space.view.doc_len(SNAP_PX as f32)).0); + let reads_control = self.rules.drag_kind(grip.part, mods) != self.rules.drag_kind(grip.part, Mods { cmd: false, ..mods }); + let to = match (self.snap, snap_tolerance(&space.view, mods, os, reads_control)) { + (Some(targets), Some(tolerance)) => targets.snap_point(to, tolerance).0, + _ => to, + }; 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 } } @@ -340,7 +344,7 @@ impl<'a> TransformBox<'a> { if !grip.began { continue; } - let next = self.proposal(space, &grip, pos, mods); + let next = self.proposal(space, &grip, pos, mods, cx.env.shell().os); grip.last = next; held = Some(grip); cx.propose(next); diff --git a/crates/draw/tests/it/transform_box.rs b/crates/draw/tests/it/transform_box.rs index d52e9abea..e962157c3 100644 --- a/crates/draw/tests/it/transform_box.rs +++ b/crates/draw/tests/it/transform_box.rs @@ -2,10 +2,11 @@ //! keys, the readout and the overlay's edits. use craft_behavior::geometry::quad::{BoxPart, BoxRules, BoxState}; +use craft_behavior::geometry::{SnapKind, SnapTarget, SnapTargets}; use craft_behavior::kurbo::{Point, Rect}; use craft_behavior::{CanvasView, EditEvent}; use craft_draw::ui::transform::{RotateZone, TransformBox}; -use craft_keymap::Mods; +use craft_keymap::{Mods, Platform}; use craft_ui::canvas::Canvas; use craft_ui::canvas::{Guide, GuideKey}; use craft_ui::canvas_controls::Guides; @@ -38,6 +39,7 @@ struct Config { rotation: f64, flip: bool, guides: bool, + snap: bool, } /// What the host keeps of the box and what the passes reported. @@ -70,6 +72,7 @@ fn defaults() -> Config { rotation: 0.0, flip: false, guides: false, + snap: false, } } @@ -91,6 +94,10 @@ fn harness(state: BoxState, setup: impl FnOnce(&mut Config)) -> Harness { })); let shown_host = Rc::clone(&host); let mut guides = vec![Guide::new(GuideKey::new(1), craft_behavior::Axis::Y, 300.0)]; + let mut targets = SnapTargets::new(); + for x in SNAP_XS { + targets.add(SnapTarget::new(craft_behavior::Axis::Y, x, SnapKind::Guide)); + } let mut fixture = Fixture::new(move |ui| { let room = ui.available_rect_before_wrap(); let config = shown_config.borrow().clone(); @@ -117,6 +124,9 @@ fn harness(state: BoxState, setup: impl FnOnce(&mut Config)) -> Harness { if let Some(mods) = config.mods { control = control.mods(mods); } + if config.snap { + control = control.snap(&targets); + } (control.show_at(ui, body.rect), guide_edits) }); if let Some((output, guide_edits)) = canvas.inner { @@ -175,6 +185,10 @@ impl Harness { } } +/// The x of the vertical snap targets of a box with `Config::snap`: 10 units right of an inside point away from the +/// reference point and of the right edge. +const SNAP_XS: [f64; 2] = [160.0, 310.0]; + /// A screen displacement. fn by(x: f32, y: f32) -> Vec2 { Vec2::new(x, y) @@ -209,3 +223,32 @@ fn a_release_with_the_pointer_gone_is_not_a_click_outside() { frame(&mut h, Vec::new()); assert_eq!(h.host.borrow().applied, 0); } + +#[trial] +fn the_control_key_turns_snapping_off_unless_it_distorts_the_dragged_corner() { + // (os, the Control key there, the press point, whether Control changes that drag) + let cases = [ + (Platform::Mac, Mods::CTRL, Point::new(150.0, 120.0), false), + (Platform::Windows, Mods::CMD, Point::new(150.0, 120.0), false), + (Platform::Windows, Mods::CMD, Point::new(300.0, 220.0), true), + ]; + for (os, control, at, distorts) in cases { + for held in [None, Some(control)] { + let mut h = harness(BoxState::from_rect(RECT), |config| { + config.snap = true; + config.mods = held; + }); + h.fixture.os(os); + let from = h.screen(at); + 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 moved = h.state().quad[2].x - RECT.x1; + let snaps = held.is_none() || distorts; + let expected = if snaps { 10.0 } else { 7.0 }; + assert!((moved - expected).abs() < 1e-6, "{os:?} {held:?} at {at:?}: moved {moved}, expected {expected}"); + } + } +} diff --git a/crates/ui-canvas/src/canvas/crop/gesture.rs b/crates/ui-canvas/src/canvas/crop/gesture.rs index 80585b82c..1abd66a5d 100644 --- a/crates/ui-canvas/src/canvas/crop/gesture.rs +++ b/crates/ui-canvas/src/canvas/crop/gesture.rs @@ -3,11 +3,13 @@ use craft_behavior::CanvasView; use craft_behavior::geometry::crop::{direction, drawn, image_turn, normalized_angle}; -use craft_behavior::geometry::{BoxPart, CropBox, SNAP_PX, SnapLine, SnapTargets, crop_view_about, screen_step}; +use craft_behavior::geometry::{BoxPart, CropBox, SnapLine, SnapTargets, crop_view_about, screen_step}; use craft_behavior::kurbo::{Point, Rect, Vec2}; -use craft_keymap::Mods; +use craft_keymap::{Mods, Platform}; use egui::Pos2; +use crate::canvas::snap_tolerance; + /// What a drag does to the frame. #[derive(Clone, Copy, Debug, PartialEq)] pub(super) enum Kind { @@ -48,6 +50,7 @@ pub(super) struct Rules<'a> { pub image: bool, pub auto_center: bool, pub snap: Option<&'a SnapTargets>, + pub os: Platform, } impl Rules<'_> { @@ -101,9 +104,9 @@ impl Rules<'_> { } /// The screen point of `pos` after the snap targets: an end of the Straighten line. - pub fn snap_screen(&self, view: &CanvasView, pos: Pos2) -> Pos2 { - let Some(targets) = self.snap else { return pos }; - let (point, _) = targets.snap_point(view.to_doc(pos), view.doc_len(SNAP_PX as f32)); + pub fn snap_screen(&self, view: &CanvasView, pos: Pos2, mods: Mods) -> Pos2 { + let (Some(targets), Some(tolerance)) = (self.snap, snap_tolerance(view, mods, self.os, false)) else { return pos }; + let (point, _) = targets.snap_point(view.to_doc(pos), tolerance); view.to_screen(point) } @@ -111,8 +114,8 @@ impl Rules<'_> { /// image mode the point is in the view of the press, which the moving view never feeds back into: the correction /// is turned back into pointer travel. pub fn snapped(&self, drag: &Drag, view: &CanvasView, to: Point, mods: Mods, space: bool) -> (Point, Vec) { - let Some(targets) = self.snap else { return (to, Vec::new()) }; - let tolerance = drag.press_view.as_ref().unwrap_or(view).doc_len(SNAP_PX as f32); + let tolerance = snap_tolerance(drag.press_view.as_ref().unwrap_or(view), mods, self.os, false); + let (Some(targets), Some(tolerance)) = (self.snap, tolerance) else { return (to, Vec::new()) }; let mut probe = drag.clone(); let Some(candidate) = self.proposal(&mut probe, to, mods, space) else { return (to, Vec::new()) }; let (by, lines, travel_per_unit) = match probe.kind { diff --git a/crates/ui-canvas/src/canvas/crop/mod.rs b/crates/ui-canvas/src/canvas/crop/mod.rs index 7c80e626a..561dcd6da 100644 --- a/crates/ui-canvas/src/canvas/crop/mod.rs +++ b/crates/ui-canvas/src/canvas/crop/mod.rs @@ -23,7 +23,7 @@ use craft_behavior::{ Axis, CancelReason, CanvasView, CursorIcon, CursorPriority, HitLevel, HitPriority, HitShape, Intent, Metrics, NavShape, PaintedCursor, PartKey, PointerButton, PressPhase, Roving, Sense, resize_cursor, }; -use craft_keymap::{Chord, Key, Mods}; +use craft_keymap::{Chord, Key, Mods, Platform}; use egui::{Pos2, Rect, Response, Vec2}; use gesture::{Drag, Kind, Rules}; @@ -180,7 +180,7 @@ impl<'a> CropOverlay<'a> { .label(label) } - fn rules(&self) -> Rules<'a> { + fn rules(&self, os: Platform) -> Rules<'a> { Rules { ratio: self.ratio.filter(|k| k.is_finite() && *k > 0.0), bounds: self.bounds, @@ -188,6 +188,7 @@ impl<'a> CropOverlay<'a> { image: self.image_mode, auto_center: self.auto_center, snap: self.snap, + os, } } @@ -258,12 +259,12 @@ fn angle_row(cx: &Cx<'_, CropOverlay<'_>>, degrees: f64) -> Vec<(Label, String)> impl CropOverlay<'_> { /// Starts the drag of `grab` pressed at screen point `origin`. - fn begin(&mut self, cx: &mut Cx<'_, Self>, space: &CanvasSpace, frame: &CropBox, grab: Grab, origin: Pos2) -> Drag { + fn begin(&mut self, cx: &mut Cx<'_, Self>, space: &CanvasSpace, frame: &CropBox, grab: Grab, origin: Pos2, mods: Mods) -> Drag { let view = space.view; let from = view.to_doc(origin); let kind = match grab { Grab::Line => { - let from = self.rules().snap_screen(&view, origin); + let from = self.rules(cx.env.shell().os).snap_screen(&view, origin, mods); Kind::Line { from, to: from } } Grab::Turn => Kind::Turn { grab: gesture::grab(frame, from) }, @@ -280,9 +281,9 @@ impl CropOverlay<'_> { /// One step of the drag with the pointer at screen point `pos`. fn step(&mut self, cx: &mut Cx<'_, Self>, space: &CanvasSpace, drag: &mut Drag, pos: Pos2, mods: Mods) { let view = space.view; - let rules = self.rules(); + let rules = self.rules(cx.env.shell().os); if let Kind::Line { from, to } = &mut drag.kind { - *to = rules.snap_screen(&view, pos); + *to = rules.snap_screen(&view, pos, mods); self.report.dragging = true; if let Some(degrees) = gesture::line_degrees(*from, *to) { readout(cx, pos, &angle_row(cx, degrees)); @@ -355,7 +356,7 @@ impl CropOverlay<'_> { if cx.intents().take(Intent::Cancel) { self.report.discard = true; } - let rules = self.rules(); + let rules = self.rules(cx.env.shell().os); let mut next = None; if let Some((direction, mods)) = cx.intents().take_nudge() { let step = if mods.shift { NUDGE_FAR } else { NUDGE }; @@ -548,7 +549,7 @@ impl Component for CropOverlay<'_> { } } PressPhase::DragStart { start, pos, .. } if start.button == PointerButton::Primary => { - let mut drag = self.begin(cx, &space, &frame, grab, start.origin); + let mut drag = self.begin(cx, &space, &frame, grab, start.origin, mods); self.step(cx, &space, &mut drag, pos, mods); live.drag = Some(drag); } diff --git a/crates/ui-canvas/src/canvas/mod.rs b/crates/ui-canvas/src/canvas/mod.rs index 8698f84d2..186664355 100644 --- a/crates/ui-canvas/src/canvas/mod.rs +++ b/crates/ui-canvas/src/canvas/mod.rs @@ -55,7 +55,7 @@ pub use raster::{DetailPlan, RasterDisplay, RasterDisplayOutput, RasterStyle, sn mod snap; pub(crate) use rulers::LABEL_STEP_MIN; pub use rulers::{NUDGE, NUDGE_FAR}; -pub use snap::{Snap, canvas_snap}; +pub use snap::{Snap, canvas_snap, snap_suspended, snap_tolerance}; pub(crate) use space::context_menu; pub use space::{BackgroundPress, BodyKeys, CanvasRulers, context_click}; // End of l4d-space. diff --git a/crates/ui-canvas/src/canvas/snap.rs b/crates/ui-canvas/src/canvas/snap.rs index 91fc10d9b..58b8cacba 100644 --- a/crates/ui-canvas/src/canvas/snap.rs +++ b/crates/ui-canvas/src/canvas/snap.rs @@ -1,8 +1,9 @@ //! `Snap`: a canvas's snapping of a coordinate the pointer sets. use crate::runtime::env::{AppValues, EnvValue, EnvView}; -use craft_behavior::Axis; -use craft_keymap::Mods; +use craft_behavior::geometry::SNAP_PX; +use craft_behavior::{Axis, CanvasView}; +use craft_keymap::{Mods, Platform}; use std::sync::Arc; /// A canvas's snapping of a coordinate the pointer sets (View > Snap To): the axis a guide at the coordinate would @@ -39,6 +40,20 @@ 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 +/// Ctrl on a transform box corner distorts). Every snapped drag applies it, whatever its targets are. +pub fn snap_suspended(mods: Mods, os: Platform, tool_reads_control: bool) -> bool { + let control = if os.is_mac() { mods.ctrl && !mods.cmd } else { mods.cmd }; + control && !tool_reads_control +} + +/// How far, in document units under `view`, a dragged point still snaps to a target: [`SNAP_PX`] screen points, or +/// `None` while [`snap_suspended`] holds. +pub fn snap_tolerance(view: &CanvasView, mods: Mods, os: Platform, tool_reads_control: bool) -> Option { + (!snap_suspended(mods, os, tool_reads_control)).then(|| view.doc_len(SNAP_PX as f32)) +} + #[derive(Clone, PartialEq)] struct InCanvasSnap(Option); diff --git a/crates/ui-canvas/src/canvas/tool.rs b/crates/ui-canvas/src/canvas/tool.rs index a19a53797..f7b0997ae 100644 --- a/crates/ui-canvas/src/canvas/tool.rs +++ b/crates/ui-canvas/src/canvas/tool.rs @@ -13,7 +13,7 @@ use crate::style::StyleCx; use craft_behavior::kurbo::Point; use craft_behavior::{Axis, CancelReason, CanvasView, Cursor, CursorIcon, GestureId, PointerButton, PointerSample}; use craft_i18n::{Digits, Format, Region}; -use craft_keymap::{Chord, Key, Mods}; +use craft_keymap::{Chord, Key, Mods, Platform}; use egui::{Pos2, Rect, Vec2}; use std::sync::{Arc, OnceLock}; @@ -388,8 +388,8 @@ impl<'a> ToolContext<'a> { } /// `point`, a document point under the pointer, moved to what the canvas snaps it to (View > Snap To) with the - /// modifiers held now; the point itself when the canvas has no snapping. The tool builds no snapping of its - /// own. + /// modifiers held now; the point itself when the canvas has no snapping or the Control key suspends it + /// ([`snap_suspended`](super::snap_suspended)). The tool builds no snapping of its own. pub fn snap(&self, point: Point) -> Point { Point::new(self.snap_along(Axis::Y, point.x), self.snap_along(Axis::X, point.y)) } @@ -397,7 +397,15 @@ impl<'a> ToolContext<'a> { /// The coordinate `position` across a guide that would run along `along`, snapped as [`snap`](Self::snap) does: /// an x coordinate is across `Axis::Y`. pub fn snap_along(&self, along: Axis, position: f64) -> f64 { - self.snap.map_or(position, |snap| snap.apply(along, position, self.mods)) + match self.snap { + Some(snap) if !super::snap_suspended(self.mods, self.os(), false) => snap.apply(along, position, self.mods), + _ => position, + } + } + + /// The OS the pass runs on: the env's; the build's for a context built without an env. + fn os(&self) -> Platform { + self.env.map_or_else(Platform::current, |env| env.os) } /// The scope's number format and unit words, to write the values of a readout in the document's units and the diff --git a/crates/ui-canvas/tests/it/canvas/crop.rs b/crates/ui-canvas/tests/it/canvas/crop.rs index ac3ba8498..d6e790d61 100644 --- a/crates/ui-canvas/tests/it/canvas/crop.rs +++ b/crates/ui-canvas/tests/it/canvas/crop.rs @@ -252,6 +252,19 @@ fn a_quick_drag_in_one_frame_starts_at_the_press() { assert_eq!((events.first(), events.last()), (Some(&"begin"), Some(&"commit")), "{events:?}"); } +#[trial] +fn the_control_key_held_during_a_resize_turns_snapping_off() { + for (held, right) in [(Modifiers::NONE, 310.0), (Modifiers::CTRL, 307.0)] { + let mut rig = Rig::new(CropBox::upright(RECT), { + let mut s = Setup::new(); + s.snap_x = Some(310.0); + s + }); + rig.drag(rig.at(300.0, 220.0), rig.at(307.0, 220.0), held); + assert!((rig.rect().x1 - right).abs() < 1e-6, "{held:?}: {:?}", rig.rect()); + } +} + // Straighten. // Image mode.