diff --git a/crates/behavior/src/geometry/draft.rs b/crates/behavior/src/geometry/draft.rs index 5e6912df1..3a551cbc6 100644 --- a/crates/behavior/src/geometry/draft.rs +++ b/crates/behavior/src/geometry/draft.rs @@ -8,7 +8,10 @@ use craft_keymap::Mods; use kurbo::Point; -use super::lock::turn_to_45; +use super::lock::polygon_step; + +/// The most points [`OutlineDraft`]'s close reach measures the outline's box from. +const BOX_SAMPLES: usize = 64; /// Which tool's rules an [`OutlineDraft`] follows. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] @@ -21,11 +24,12 @@ pub enum DraftKind { /// switches to straight segments, where each click adds a vertex and a drag draws freehand /// again; releasing ⌥ with the button up closes. ⌥ held at the press means subtract (the /// tool's operation), not straight segments, until it is released and pressed again; with - /// nothing selected it starts straight segments at once. + /// nothing selected it starts straight segments at once. ⇧ puts each new point on the + /// horizontal, vertical or 45° line through the previous one. #[default] Mixed, - /// The Polygonal Lasso: each click adds a vertex, ⇧ (without ⌥) turns the new segment to a - /// multiple of 45° from the last vertex, and a drag with ⌥ held draws freehand. + /// The Polygonal Lasso: each click adds a vertex, ⇧ (without ⌥) puts it in the nearest of + /// eight directions from the last vertex, and a drag with ⌥ held draws freehand. Polygonal, } @@ -191,14 +195,16 @@ impl OutlineDraft { /// with a selection stays in the intent (subtract) and the outline is freehand. /// [`DraftKind::Polygonal`]: the press is the first vertex, and ⌥ with `has_selection` /// false is dropped from the intent too. - /// - An open outline of 3 or more points: a press within `reach.close / zoom` of the first - /// point, or within `reach.same_point / zoom` of the last, closes it - /// ([`DraftEvent::Closed`]). + /// - An open outline of 3 or more points: a press near the first point, or within + /// `reach.same_point / zoom` of the last, closes it ([`DraftEvent::Closed`]). Near the first + /// point is within a quarter of the narrower side of the outline's box on screen, at least 1 + /// and at most `reach.close` screen points, so a small outline's corners stay vertices. /// - Otherwise, in straight-segment mode (Mixed with ⌥ latched, Polygonal): the press adds a /// vertex and its index goes into [`straight`](Self::straight) ([`DraftEvent::Changed`]). - /// Polygonal with ⇧ and not ⌥: the vertex is turned to the nearest multiple of 45° about the - /// last vertex, keeping its distance (in document space, so view rotation and mirroring do - /// not skew it); the first vertex is never turned. + /// With ⇧ (Polygonal: without ⌥) the vertex goes to the nearest of eight directions from the + /// last vertex ([`polygon_step`]; in document space, so view rotation and mirroring do not + /// skew it); the first vertex is never moved. A Mixed draft's freehand points follow the same + /// ⇧ rule ([`drag`](Self::drag)). /// /// A point that isn't finite is ignored (`None`). pub fn press(&mut self, at: DraftPoint, has_selection: bool) -> Option { @@ -230,14 +236,7 @@ impl OutlineDraft { if !self.polygonal { return None; } - let mut vertex = at.at; - if self.kind == DraftKind::Polygonal - && at.mods.shift - && !at.mods.alt - && let Some(&last) = self.points.last() - { - vertex = turn_to_45(last, vertex); - } + let vertex = self.shift_step(at); self.cursor = Some(vertex); self.down = true; if self.append(vertex) { @@ -247,7 +246,8 @@ impl OutlineDraft { } /// The pointer moved to `at` with the button down. Freehand and Mixed: the point is added - /// (a freehand point, not in [`straight`](Self::straight)). Polygonal: added only while ⌥ + /// (a freehand point, not in [`straight`](Self::straight)); Mixed with ⇧ places it on the + /// horizontal, vertical or 45° line through the previous point. Polygonal: added only while ⌥ /// is held (an ⌥-drag draws freehand); otherwise only the rubber band follows. Returns /// [`DraftEvent::Changed`] when the outline or the rubber band moved. pub fn drag(&mut self, at: DraftPoint) -> Option { @@ -257,20 +257,40 @@ impl OutlineDraft { if !self.is_open() || !at.at.x.is_finite() || !at.at.y.is_finite() { return None; } - if self.kind != DraftKind::Polygonal || at.mods.alt { - self.append(at.at); - } - self.cursor = Some(at.at); + let point = if self.kind != DraftKind::Polygonal || at.mods.alt { + let point = self.shift_step(at); + self.append(point); + point + } else { + at.at + }; + self.cursor = Some(point); Some(DraftEvent::Changed) } - /// The pointer moved to `at` with the button up: only the rubber band follows (hover moves - /// never become vertices). [`DraftEvent::Changed`] while an outline is open. + /// Where a new point of `at` goes: with ⇧, on the horizontal, vertical or 45° line through the previous point + /// ([`polygon_step`]), for a Mixed draft's every point and a Polygonal vertex placed without ⌥; `at` itself + /// otherwise, and for the first point. + fn shift_step(&self, at: DraftPoint) -> Point { + let shifted = at.mods.shift + && match self.kind { + DraftKind::Freehand => false, + DraftKind::Mixed => true, + DraftKind::Polygonal => !at.mods.alt, + }; + match self.points.last() { + Some(&last) if shifted => polygon_step(last, at.at), + _ => at.at, + } + } + + /// The pointer moved to `at` with the button up: only the rubber band follows, to where a click would place the + /// point ([`shift_step`](Self::shift_step)); hover moves never become vertices. [`DraftEvent::Changed`] while an outline is open. pub fn hover(&mut self, at: DraftPoint) -> Option { if !self.is_open() || !at.at.x.is_finite() || !at.at.y.is_finite() { return None; } - self.cursor = Some(at.at); + self.cursor = Some(self.shift_step(at)); Some(DraftEvent::Changed) } @@ -383,7 +403,19 @@ impl OutlineDraft { } let zoom = at.zoom.max(0.01); let near = |q: Point, reach: f64| (q - at.at).hypot() < reach / zoom; - near(self.points[0], self.reach.close) || self.points.last().is_some_and(|&last| near(last, self.reach.same_point)) + near(self.points[0], self.close_reach(zoom)) || self.points.last().is_some_and(|&last| near(last, self.reach.same_point)) + } + + /// The reach of a press on the first point, in screen points: a quarter of the narrower side of the outline's + /// box on screen, at least 1 and at most `reach.close`, so the corners of a small outline stay vertices. The box + /// is measured from at most [`BOX_SAMPLES`] of the points. + fn close_reach(&self, zoom: f64) -> f64 { + let step = self.points.len().div_ceil(BOX_SAMPLES).max(1); + let Some(&first) = self.points.first() else { return self.reach.close }; + let bounds = self.points.iter().step_by(step).fold(kurbo::Rect::from_points(first, first), |rect, &p| rect.union_pt(p)); + let narrow = bounds.width().min(bounds.height()) * zoom; + // `max` then `min`, not `clamp`: a reach under 1 point would make `clamp` panic. + (narrow / 4.0).max(1.0).min(self.reach.close) } /// Whether an outline is open. diff --git a/crates/behavior/src/geometry/lock.rs b/crates/behavior/src/geometry/lock.rs index f785602b2..dab4fbb43 100644 --- a/crates/behavior/src/geometry/lock.rs +++ b/crates/behavior/src/geometry/lock.rs @@ -1,4 +1,5 @@ -//! Direction locking for ⇧ drags: [`Directions`], [`lock_direction`], [`round_to_direction`] and [`turn_to_45`]. +//! Direction locking for ⇧ drags: [`Directions`], [`lock_direction`], [`round_to_direction`], [`turn_to_45`] and +//! [`polygon_step`]. use kurbo::{Point, Vec2}; @@ -40,12 +41,24 @@ pub fn round_to_direction(angle: f64, directions: Directions) -> f64 { /// segment's length, a diagonal keeps the shorter offset on both axes. `point` itself for a zero-length or /// non-finite offset. pub fn polygon_step(from: Point, point: Point) -> Point { - let _ = (from, point); - todo!("cw.C23") + let delta = point - from; + let length = delta.hypot(); + if !length.is_finite() || length == 0.0 { + return point; + } + let direction = Vec2::from_angle(round_to_direction(delta.atan2(), Directions::Eight)); + let (x, y) = (direction.x.round(), direction.y.round()); + if x == 0.0 || y == 0.0 { + return from + Vec2::new(x, y) * length; + } + // Inside a diagonal's sector both offsets have the diagonal's signs. + let shorter = delta.x.abs().min(delta.y.abs()); + from + Vec2::new(shorter.copysign(delta.x), shorter.copysign(delta.y)) } -/// `point` turned about `from` to the nearest multiple of 45°, keeping its distance: the one ⇧ rule for a line, a -/// handle or a segment drawn from a fixed point. `point` itself when it is on `from` or not finite. +/// `point` turned about `from` to the nearest multiple of 45°, keeping its distance: the ⇧ rule for a line, a handle +/// or a segment drawn from a fixed point. A polygon's vertex takes [`polygon_step`] instead. `point` itself when it +/// is on `from` or not finite. pub fn turn_to_45(from: Point, point: Point) -> Point { let delta = point - from; let length = delta.hypot(); diff --git a/crates/behavior/src/geometry/snap.rs b/crates/behavior/src/geometry/snap.rs index 0bf65da02..9daf8ad43 100644 --- a/crates/behavior/src/geometry/snap.rs +++ b/crates/behavior/src/geometry/snap.rs @@ -39,7 +39,6 @@ pub enum SnapKind { } /// A set of [`SnapKind`]s, a bit per kind: the kind filter a gesture passes to its snapping. -// P3(canvas-widgets-w3): cw.C16 `SnapKinds` #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct SnapKinds(u8); @@ -47,16 +46,27 @@ impl SnapKinds { /// Every kind. pub const ALL: SnapKinds = SnapKinds(0x7f); + /// The bit of `kind`; [`SnapKinds::ALL`] holds the seven. + const fn bit(kind: SnapKind) -> u8 { + 1 << match kind { + SnapKind::Guide => 0, + SnapKind::Grid => 1, + SnapKind::Bounds => 2, + SnapKind::Center => 3, + SnapKind::LayerEdge => 4, + SnapKind::LayerCenter => 5, + SnapKind::Selection => 6, + } + } + /// This set without `kind`. pub fn without(self, kind: SnapKind) -> Self { - let _ = kind; - todo!("cw.C16") + SnapKinds(self.0 & !Self::bit(kind)) } /// Whether `kind` is in this set. pub fn contains(self, kind: SnapKind) -> bool { - let _ = kind; - todo!("cw.C16") + self.0 & Self::bit(kind) != 0 } } @@ -201,8 +211,9 @@ impl SnapTargets { } /// Add a rectangle's four edges as `edge` targets and its two centre lines as `center` - /// targets, each spanning the rectangle. - fn add_rect(&mut self, rect: Rect, edge: SnapKind, center: SnapKind) { + /// targets, each spanning the rectangle: how the app adds each layer (`LayerEdge`, `LayerCenter`) and the + /// selection (`Selection` for both) to the targets [`with_document`](Self::with_document) built. + pub fn add_rect(&mut self, rect: Rect, edge: SnapKind, center: SnapKind) { let r = rect.abs(); let (xs, ys) = ((r.y0, r.y1), (r.x0, r.x1)); for (along, position, kind, span) in [ @@ -219,7 +230,7 @@ impl SnapTargets { /// Guides as full-height targets, grid lines of `spacing` from `origin` over `bounds`, the /// document bounds and centre: what every app has. Layers and the selection are added by - /// the app with `add_rect`. + /// the app with [`add_rect`](Self::add_rect). pub fn with_document( self, options: &SnapOptions, @@ -274,16 +285,9 @@ impl SnapTargets { /// The nearest target of a kind in `kinds` among the lines that run `along` an axis, within `tolerance` of /// `value` across them; [`SnapTargets::nearest`] is this with [`SnapKinds::ALL`]. - // P3(canvas-widgets-w3): cw.C16 `nearest_of` pub fn nearest_of(&self, along: Axis, value: f64, tolerance: f64, kinds: SnapKinds) -> Option { - let _ = (along, value, tolerance, kinds); - todo!("cw.C16") - } - - /// The nearest target among the lines that run `along` an axis, within `tolerance` of `value` across them. - pub fn nearest(&self, along: Axis, value: f64, tolerance: f64) -> Option { let mut best: Option<(f64, SnapTarget)> = None; - for target in self.targets.iter().filter(|t| t.along == along) { + for target in self.targets.iter().filter(|t| t.along == along && kinds.contains(t.kind)) { let distance = (target.position - value).abs(); if distance > tolerance { continue; @@ -299,15 +303,28 @@ impl SnapTargets { best.map(|(_, target)| target) } + /// The nearest target among the lines that run `along` an axis, within `tolerance` of `value` across them. + pub fn nearest(&self, along: Axis, value: f64, tolerance: f64) -> Option { + self.nearest_of(along, value, tolerance, SnapKinds::ALL) + } + /// `point` snapped on each axis independently, with the lines to draw. pub fn snap_point(&self, point: Point, tolerance: f64) -> (Point, Vec) { + 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). + /// + /// Public: craft-ui-canvas's `Snap::point` filters through it. + 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(Axis::Y, point.x, tolerance) { + if let Some(t) = self.nearest_of(Axis::Y, point.x, tolerance, kinds) { out.x = t.position; lines.push(line(&t, point.y, point.y)); } - if let Some(t) = self.nearest(Axis::X, point.y, tolerance) { + if let Some(t) = self.nearest_of(Axis::X, point.y, tolerance, kinds) { out.y = t.position; lines.push(line(&t, out.x, out.x)); } diff --git a/crates/behavior/tests/geometry/draft.rs b/crates/behavior/tests/geometry/draft.rs index 918fce1dd..d4765636c 100644 --- a/crates/behavior/tests/geometry/draft.rs +++ b/crates/behavior/tests/geometry/draft.rs @@ -26,3 +26,43 @@ fn a_polygon_closes_by_clicking_near_its_start_at_any_zoom() { assert_eq!(build().press(at(9.0 * unit, 0.0, zoom), true), Some(DraftEvent::Changed)); } } + +#[test] +fn a_small_polygon_does_not_close_at_its_last_corner() { + // A square 4 points wide on screen at either zoom: its corners are nearer the start than the 8-point reach. + for zoom in [1.0, 2.0] { + let unit = 1.0 / zoom; + let mut draft = OutlineDraft::new(DraftKind::Polygonal, REACH); + for (x, y) in [(0.0, 0.0), (4.0, 0.0), (4.0, 4.0)] { + draft.press(at(x * unit, y * unit, zoom), true); + draft.release(at(x * unit, y * unit, zoom)); + } + assert_eq!(draft.press(at(0.0, 4.0 * unit, zoom), true), Some(DraftEvent::Changed), "the last corner is a vertex"); + draft.release(at(0.0, 4.0 * unit, zoom)); + assert_eq!(draft.points().len(), 4); + // A quarter of the narrow side is 1 point. + assert_eq!(draft.clone().press(at(1.5 * unit, 0.0, zoom), true), Some(DraftEvent::Changed)); + assert!(matches!(draft.press(at(0.5 * unit, 0.0, zoom), true), Some(DraftEvent::Closed { points, .. }) if points.len() == 4)); + } +} + +#[test] +fn shift_steps_keep_the_shorter_diagonal_offset() { + let shift = |x: f64, y: f64| DraftPoint::new(Point::new(x, y), Mods::SHIFT, 1.0); + let mut draft = OutlineDraft::new(DraftKind::Polygonal, REACH); + draft.press(at(0.0, 0.0, 1.0), true); + draft.release(at(0.0, 0.0, 1.0)); + let mut click = |point: DraftPoint| { + assert_eq!(draft.press(point, true), Some(DraftEvent::Changed)); + draft.release(point); + *draft.points().last().expect("a vertex") + }; + // Near the diagonal: both offsets become the shorter one (7), not the 45° turn of the whole length. + assert_eq!(click(shift(10.0, 7.0)), Point::new(7.0, 7.0)); + // Near an axis: the segment keeps its length. + let along = click(shift(27.0, 9.0)); + assert!((along.x - (7.0 + 404f64.sqrt())).abs() < 1e-9 && along.y == 7.0, "{along:?}"); + // The signs of the offset are kept. + let back = click(shift(along.x - 9.0, 1.0)); + assert!((back.x - (along.x - 6.0)).abs() < 1e-9 && back.y == 1.0, "{back:?}"); +} diff --git a/crates/imaging/src/ui/fill/tool.rs b/crates/imaging/src/ui/fill/tool.rs index 42a442913..fd9b61e0a 100644 --- a/crates/imaging/src/ui/fill/tool.rs +++ b/crates/imaging/src/ui/fill/tool.rs @@ -211,7 +211,7 @@ impl FillCanvasTool<'_> { let Some(dimensions) = self.canvas.resize.dimensions() else { return }; let words = cx.words::(); let pixels = cx.units().pixels(dimensions.diameter.round().max(0.0)); - cx.readout(vec![(words.diameter.clone(), pixels)]); + cx.hud(vec![(words.diameter.clone(), pixels)]); } fn begin_resize(&mut self, pointer: &ToolPointer, cx: &mut ToolContext<'_>) -> ToolAction { diff --git a/crates/imaging/src/ui/liquify/canvas.rs b/crates/imaging/src/ui/liquify/canvas.rs index 1b84fb0aa..a51bef5db 100644 --- a/crates/imaging/src/ui/liquify/canvas.rs +++ b/crates/imaging/src/ui/liquify/canvas.rs @@ -199,7 +199,7 @@ impl LiquifyCanvasTool<'_> { fn show_readout(&self, cx: &mut ToolContext<'_>) { let rows = self.canvas.resize.readout_rows(&cx.units(), &cx.words::()); if !rows.is_empty() { - cx.readout(rows); + cx.hud(rows); } } diff --git a/crates/imaging/src/ui/live_preview/damage.rs b/crates/imaging/src/ui/live_preview/damage.rs index f7cb37d2d..97f6d9ead 100644 --- a/crates/imaging/src/ui/live_preview/damage.rs +++ b/crates/imaging/src/ui/live_preview/damage.rs @@ -11,9 +11,10 @@ impl LivePreview { /// `visible` the document pixels the view shows (`PixelRect::visible`). /// /// - Both keys [`owns`](Self::owns) and not both [`PreviewKey::NONE`]: to a preview, the - /// region's visible part (remembered as covered for `to`, so [`uncovered`](Self::uncovered) - /// catches up as the view moves); back to `NONE`, the whole region (and nothing stays - /// covered). + /// changed area's visible part (remembered as covered for `to`, so + /// [`uncovered`](Self::uncovered) catches up as the view moves); back to `NONE`, the whole + /// changed area (and nothing stays covered). The changed area is [`changed`](Self::changed) + /// when both keys were keyed with an area, else the region. /// - Either key foreign, both `NONE`, or no session: `None`, and the host recomposites /// everything. /// @@ -26,11 +27,12 @@ impl LivePreview { if !(self.owns(from) && self.owns(to) && (!from.is_none() || !to.is_none())) { return None; } + let area = self.changed(from, to).unwrap_or(self.region); if to.is_none() { self.covered = None; - return Some(self.region); + return Some(area); } - let shown = self.region.intersect(&visible); + let shown = area.intersect(&visible); self.covered = Some((to, shown)); Some(shown) } diff --git a/crates/imaging/src/ui/live_preview/key.rs b/crates/imaging/src/ui/live_preview/key.rs index 31e48f582..e2b594e1a 100644 --- a/crates/imaging/src/ui/live_preview/key.rs +++ b/crates/imaging/src/ui/live_preview/key.rs @@ -27,7 +27,8 @@ pub enum PreviewLane { } impl PreviewLane { - /// The lane's tag bit (59 or 58) and the session's width in bits (19 or 18). + /// The lane's tag bit (59, 58 or 57) and the session's width in bits (19, 18 or 17). A key sets only its own + /// lane's tag bit and its session ends below it, so the keys of two lanes never meet. pub(crate) fn bits(self) -> (u32, u32) { // pc: crates/ui-egui/src/dialogs/adjust_preview.rs:52 `TAG` (1 << 59), :55 `SESSION_SHIFT` // (40), :272 (`session & 0x7_ffff`); :476 `LIVE_TAG` (1 << 58), :479, :481 @@ -51,8 +52,10 @@ impl PreviewLane { pub struct PreviewKey(u64); impl PreviewKey { - /// The display key of progressive stage `n` (1..=7) of a result of the same settings: bit 0 cleared and `n` in bits - /// 1..=3, so it never equals a settings key. + /// The display key of progressive stage `n` (1..=7) of a result of the same settings (Content-Aware Move shows a + /// scaled-down solve as stage 1, then the exact one under the key itself): bit 0 cleared and `n` in bits 1..=3. + /// Every [`settings_hash`] sets bit 0, so a stage key never equals a settings key; it keeps the lane and session + /// bits, so [`LivePreview::owns`](super::LivePreview::owns) accepts it. #[must_use] pub fn stage(self, n: u8) -> PreviewKey { PreviewKey((self.0 & !0xF) | (u64::from(n & 7) << 1)) diff --git a/crates/imaging/src/ui/live_preview/session.rs b/crates/imaging/src/ui/live_preview/session.rs index 2b6edb1d8..edb27921b 100644 --- a/crates/imaging/src/ui/live_preview/session.rs +++ b/crates/imaging/src/ui/live_preview/session.rs @@ -4,6 +4,9 @@ use craft_ui::canvas::PixelRect; use super::key::{PreviewKey, PreviewLane, PreviewSession}; +/// How many keys keep the area they change: as far back as a display's shown key can lag behind the last key given. +const AREA_KEYS: usize = 8; + /// The live preview of one flow (an adjustment dialog, or a Properties-panel drag): the keys of /// its current session, the area a preview can change, what the canvas has composited of it, and /// when the settings last changed. @@ -12,8 +15,10 @@ use super::key::{PreviewKey, PreviewLane, PreviewSession}; /// - Keys: [`key`](Self::key) gives equal keys for equal settings hashes within one session; /// [`PreviewKey::NONE`] is the committed document. [`begin`](Self::begin) with another session /// starts empty, so keys of the old one become foreign. -/// - Damage: [`switch`](Self::switch) is the area to recomposite when the shown key changes; -/// [`uncovered`](Self::uncovered) catches up as the view moves (`damage.rs`). +/// - Damage: [`switch`](Self::switch) is the area to recomposite when the shown key changes: the +/// region, or the areas the two keys change when both were keyed with one +/// ([`key_in`](Self::key_in)); [`uncovered`](Self::uncovered) catches up as the view moves +/// (`damage.rs`). /// - Settle: [`settling`](Self::settling) is true for `within` seconds after the last key change /// while a preview shows; secondary views (the Navigator) wait for it. /// @@ -28,6 +33,8 @@ pub struct LivePreview { pub(super) last: Option<(PreviewKey, f64)>, /// The canvas shows this key only within this rect; elsewhere in the region it is older. pub(super) covered: Option<(PreviewKey, PixelRect)>, + /// The area each of the last [`AREA_KEYS`] keys given by [`key_in`](Self::key_in) changes, oldest first. + pub(super) areas: Vec<(PreviewKey, PixelRect)>, } impl LivePreview { @@ -50,7 +57,7 @@ impl LivePreview { if self.session == Some(session) { return; } - *self = Self { lane: self.lane, session: Some(session), region, last: None, covered: None }; + *self = Self { lane: self.lane, session: Some(session), region, last: None, covered: None, areas: Vec::new() }; } /// Forgets the session (the document closed or the dialog's flow ended for good): every key @@ -89,6 +96,43 @@ impl LivePreview { key } + /// [`key`](Self::key), recording `area` (document pixels) as what the preview of this key changes, so + /// [`switch`](Self::switch) recomposites only that: a tool's preview that changes a small part of the region + /// (Patch heals around one offset). The last [`AREA_KEYS`] keys keep their area; an older key falls back to the + /// region, which damages more, never less. + pub fn key_in(&mut self, settings: u64, now: f64, area: PixelRect) -> PreviewKey { + let key = self.key(settings, now); + if key.is_none() { + return key; + } + self.areas.retain(|(known, _)| *known != key); + if self.areas.len() >= AREA_KEYS { + self.areas.remove(0); + } + self.areas.push((key, area)); + key + } + + /// The area [`key_in`](Self::key_in) recorded for `key`; [`PreviewKey::NONE`] changes nothing (an empty rect). + /// `None` for a key keyed without an area or evicted since. + fn area(&self, key: PreviewKey) -> Option { + if key.is_none() { + return Some(PixelRect::default()); + } + self.areas.iter().find(|(known, _)| *known == key).map(|(_, area)| *area) + } + + /// The pixels that differ between showing `from` and showing `to`: the union of the areas the two keys were + /// keyed with ([`key_in`](Self::key_in); `NONE` adds nothing). `None` unless both keys are owned and not both + /// `NONE`, or when a key other than `NONE` has no recorded area. Read-only, for a host that computes its damage + /// from shared state. + pub fn changed(&self, from: PreviewKey, to: PreviewKey) -> Option { + if !(self.owns(from) && self.owns(to) && (!from.is_none() || !to.is_none())) { + return None; + } + Some(self.area(from)?.union(&self.area(to)?)) + } + /// Whether `key` is [`PreviewKey::NONE`] or one of the current session's keys. pub fn owns(&self, key: PreviewKey) -> bool { // pc: crates/ui-egui/src/dialogs/adjust_preview.rs:297-298 (`ours`: key 0 or the session's diff --git a/crates/imaging/src/ui/select/drag.rs b/crates/imaging/src/ui/select/drag.rs index 42d0dcd44..f000b8e1a 100644 --- a/crates/imaging/src/ui/select/drag.rs +++ b/crates/imaging/src/ui/select/drag.rs @@ -1,8 +1,8 @@ //! A press inside the selection: which drag it starts, the cursor over the selection, and the drag itself (the lasso -//! tools use it unchanged). Public for the app's own click tools: the Magic Wand takes the same rule as the Polygonal -//! Lasso ([`PressRule::Clicks`]). +//! tools use it unchanged). Public for the app's own tools: the Magic Wand in New mode drags the outline like a +//! marquee, so it takes [`PressRule::Drags`]. -use craft_behavior::geometry::{ConstrainStyle, Directions, MoveGesture, SelectionOperation}; +use craft_behavior::geometry::{ConstrainStyle, Directions, MoveGesture, MoveValue, SelectionOperation}; use craft_behavior::{CancelReason, Cursor, CursorBadge, CursorIcon, EditEvent, GestureId, Mixed, PaintedCursor}; use craft_keymap::Mods; use kurbo::{Point, Vec2}; @@ -14,10 +14,10 @@ use super::{DragKind, SelectEvent, SelectionDrag, SelectionProbe}; #[derive(Clone, Copy, Debug, PartialEq, Eq)] #[non_exhaustive] pub enum PressRule { - /// A drag tool (the marquees, the Lasso): a plain press with the operation New drags the outline, Cmd the pixels. + /// A drag tool (the marquees, the Lasso, the app's Magic Wand): a plain press with the operation New drags the + /// outline, Cmd the pixels. Drags, - /// A click-driven tool (the Polygonal Lasso, the app's Magic Wand): only Cmd drags, and never while - /// `outline_open`. + /// A click-driven tool (the Polygonal Lasso): only Cmd drags, and never while `outline_open`. #[non_exhaustive] Clicks { /// The tool has an outline open (the Polygonal Lasso between clicks). @@ -34,11 +34,12 @@ impl PressRule { /// What a press at `at` with `mods` drags, or `None` when it draws (or is not the tool's). /// -/// With a floating piece: a press on it (`probe.on_floating`) drags it as `Pixels` unless Shift is held, or Alt -/// without Cmd; a click-driven tool needs Cmd; elsewhere the press draws a new selection. Without one, a press outside -/// the selection draws; inside, Cmd without Shift is `Pixels { copy: Alt }` (Cmd+Alt copies), and a drag tool with no -/// Cmd whose resolved operation (`SelectionOperation::resolve(bar, mods, has_selection)`) is New drags the `Outline`. -/// A click-driven tool returns `None` for everything while its outline is open. +/// With a floating piece: on it (`probe.on_floating`), Cmd without Shift drags the piece as `Pixels { copy: Alt }`, +/// and a plain press (no Cmd, Shift or Alt) of a drag tool whose resolved operation is New drags the `Outline` (the +/// app drops the piece before the outline moves); elsewhere the press draws a new selection. Without one, a press +/// outside the selection draws; inside, Cmd without Shift is `Pixels { copy: Alt }` (Cmd+Alt copies), and a drag tool +/// with no Cmd whose resolved operation (`SelectionOperation::resolve(bar, mods, has_selection)`) is New drags the +/// `Outline`. A click-driven tool needs Cmd, and returns `None` for everything while its outline is open. pub fn drag_kind(probe: &dyn SelectionProbe, at: Point, mods: Mods, bar: SelectionOperation, rule: PressRule) -> Option { let clicky = match rule { PressRule::Drags => false, @@ -48,8 +49,18 @@ pub fn drag_kind(probe: &dyn SelectionProbe, at: Point, mods: Mods, bar: Selecti let cut = mods.cmd && !mods.shift; let copy = mods.alt && mods.cmd; if probe.floating() { - let on = probe.on_floating(at) && !mods.shift && (!mods.alt || mods.cmd) && (cut || !clicky); - return on.then_some(DragKind::Pixels { copy }); + if !probe.on_floating(at) { + return None; + } + if cut { + return Some(DragKind::Pixels { copy }); + } + let plain = !clicky + && !mods.cmd + && !mods.shift + && !mods.alt + && SelectionOperation::resolve(bar, mods, true) == SelectionOperation::New; + return plain.then_some(DragKind::Outline); } if !probe.inside_selection(at) { return None; @@ -62,8 +73,9 @@ pub fn drag_kind(probe: &dyn SelectionProbe, at: Point, mods: Mods, bar: Selecti } /// The cursor over the selection for a press with `mods`, or `None` for the tool's own: `Outline` shows the move -/// cursor, `Pixels` the arrow (with the copy badge for Cmd+Alt), a floating piece the plain arrow. While `dragging`, -/// `Outline` keeps the move cursor and `Pixels` shows the plain arrow. +/// cursor, `Pixels` the arrow with the scissors badge (the copy badge for Cmd+Alt), a floating piece the plain arrow +/// (the copy badge for Cmd+Alt). While `dragging`, `Outline` keeps the move cursor and `Pixels` shows the hollow +/// arrowhead. pub fn cursor_over( probe: &dyn SelectionProbe, at: Point, @@ -74,13 +86,16 @@ pub fn cursor_over( ) -> Option { match dragging { Some(DragKind::Outline) => return Some(CursorIcon::Move.into()), - Some(DragKind::Pixels { .. }) => return Some(CursorIcon::Default.into()), + Some(DragKind::Pixels { .. }) => return Some(PaintedCursor::arrow(true).into()), None => {} } + // `drag_kind` answers over a floating piece only on the piece. + let on_piece = probe.floating(); Some(match drag_kind(probe, at, mods, bar, rule)? { - DragKind::Outline => CursorIcon::Move.into(), DragKind::Pixels { copy: true } => PaintedCursor::badged(CursorIcon::Default, CursorBadge::Copy).into(), - DragKind::Pixels { copy: false } => CursorIcon::Default.into(), + _ if on_piece => CursorIcon::Default.into(), + DragKind::Outline => CursorIcon::Move.into(), + DragKind::Pixels { copy: false } => PaintedCursor::badged(CursorIcon::Default, CursorBadge::Scissors).into(), }) } @@ -92,13 +107,15 @@ pub struct InsideDrag { kind: DragKind, id: GestureId, gesture: MoveGesture, + /// The selection's bounds at the press, which snap as they move; `None` leaves the drag unsnapped. + bounds: Option, /// The whole-pixel delta of the last event. last: [i32; 2], } impl InsideDrag { - /// Starts a `kind` drag named `id` at `at` (document units): the gesture and the `Begin` event, which names the - /// undo step `label`. + /// Starts a `kind` drag named `id` at `at` (document units, unsnapped): the gesture and the `Begin` event, which + /// names the undo step `label`. `bounds` are the selection's at the press ([`SelectionProbe::bounds`]). pub fn begin( style: &ConstrainStyle, kind: DragKind, @@ -108,10 +125,9 @@ impl InsideDrag { label: Arc, bounds: Option, ) -> (InsideDrag, SelectEvent) { - let _ = bounds; // P3(canvas-widgets-w3): cw.C20 let gesture = MoveGesture::press(style, at, mods, Directions::Eight); let event = SelectEvent::DragSelection(EditEvent::begin(id, Mixed::Same(SelectionDrag { kind, delta: [0, 0] }), label, None)); - (InsideDrag { kind, id, gesture, last: [0, 0] }, event) + (InsideDrag { kind, id, gesture, bounds, last: [0, 0] }, event) } /// The kind of drag. @@ -119,12 +135,18 @@ impl InsideDrag { self.kind } - /// The pointer moved to `at` at `zoom` screen points per document unit: an `Update` when the whole-pixel delta - /// changed. The delta is the gesture's offset rounded per axis and clamped to 10^7; the gesture's own Alt copy is - /// ignored (the copy is latched in `kind`). + /// What moves and the whole-pixel offset of the last event, for [`SelectPhase::Dragging`](super::SelectPhase). + pub fn selection_drag(&self) -> SelectionDrag { + SelectionDrag { kind: self.kind, delta: self.last } + } + + /// The pointer moved to `at` (document units, unsnapped) at `zoom` screen points per document unit: an `Update` + /// when the whole-pixel delta changed. The gesture's offset moves the press bounds, which `snap` (the tool's + /// `ToolContext::snap_rect`) moves onto a snap target; the sum is rounded per axis and clamped to 10^7. The + /// gesture's own Alt copy is ignored (the copy is latched in `kind`). pub fn drag(&mut self, at: Point, mods: Mods, zoom: f64, snap: &mut dyn FnMut(kurbo::Rect) -> Vec2) -> Option { - let _ = snap; // P3(canvas-widgets-w3): cw.C20 - let delta = whole_pixels(self.gesture.follow(at, mods, zoom)?.delta); + let value = self.gesture.follow(at, mods, zoom)?; + let delta = whole_pixels(snapped(self.bounds, &value, snap)); if delta == self.last { return None; } @@ -132,10 +154,11 @@ impl InsideDrag { Some(SelectEvent::DragSelection(EditEvent::update(self.id, SelectionDrag { kind: self.kind, delta }))) } - /// The release: the `Commit`. A delta of 0 means nothing moved. + /// The release at `at` (document units, unsnapped), snapped as [`drag`](Self::drag) is: the `Commit`. A delta of + /// 0 means nothing moved. pub fn end(self, at: Point, mods: Mods, zoom: f64, snap: &mut dyn FnMut(kurbo::Rect) -> Vec2) -> SelectEvent { - let _ = snap; // P3(canvas-widgets-w3): cw.C20 - let after = SelectionDrag { kind: self.kind, delta: whole_pixels(self.gesture.release(at, mods, zoom).delta) }; + let value = self.gesture.release(at, mods, zoom); + let after = SelectionDrag { kind: self.kind, delta: whole_pixels(snapped(self.bounds, &value, snap)) }; let before = SelectionDrag { kind: self.kind, delta: [0, 0] }; SelectEvent::DragSelection(EditEvent::commit(self.id, Mixed::Same(before), after)) } @@ -147,6 +170,18 @@ impl InsideDrag { } } +/// The value's offset plus the snap of the press `bounds` moved by it; the offset itself without bounds. A value that +/// changed nothing (a click) is `Vec2::ZERO` and calls no `snap`. +fn snapped(bounds: Option, value: &MoveValue, snap: &mut dyn FnMut(kurbo::Rect) -> Vec2) -> Vec2 { + if !value.changed() { + return Vec2::ZERO; + } + match bounds { + Some(bounds) => value.delta + snap(bounds + value.delta), + None => value.delta, + } +} + /// The offset rounded per axis and clamped to 10^7. fn whole_pixels(delta: Vec2) -> [i32; 2] { let axis = |v: f64| v.round().clamp(-1e7, 1e7) as i32; diff --git a/crates/imaging/src/ui/select/lasso.rs b/crates/imaging/src/ui/select/lasso.rs index 16f5fda33..b9a34798a 100644 --- a/crates/imaging/src/ui/select/lasso.rs +++ b/crates/imaging/src/ui/select/lasso.rs @@ -1,7 +1,7 @@ //! [`LassoTool`]: the freehand Lasso with Alt-latched straight segments, and the pieces the Polygonal Lasso shares. use craft_behavior::geometry::{ConstrainStyle, DraftEvent, DraftKind, DraftPoint, DraftReach, OutlineDraft, SelectionOperation}; -use craft_behavior::{CancelReason, Cursor, PaintedCursor}; +use craft_behavior::{CancelReason, Cursor, PaintedCursor, PointerButton}; use craft_keymap::Mods; use craft_ui::canvas::{CanvasTool, ToolAccess, ToolAction, ToolClaims, ToolContext, ToolKey, ToolPath, ToolPointer}; use craft_ui::primitives::{Draw, PaintShape, StrokeWidth, ToolIcon}; @@ -39,7 +39,7 @@ pub(super) fn apply( /// What a lasso is doing: a selection drag, an outline with its point count, or nothing. pub(super) fn phase(draft: &OutlineDraft, inside: Option<&InsideDrag>) -> SelectPhase { if let Some(inside) = inside { - return SelectPhase::Dragging(inside.kind()); + return SelectPhase::Dragging(inside.selection_drag()); } if draft.is_open() { SelectPhase::Outline { points: draft.points().len() } } else { SelectPhase::Idle } } @@ -74,7 +74,8 @@ pub(super) fn cursor(shown: &LassoCursor<'_>, probe: &dyn SelectionProbe, cx: &T PaintedCursor::tool(icon.icon(), ICON_HOTSPOT, badge).into() } -/// The outline as marching ants and, between straight segments, the rubber band. +/// The outline as marching ants and, between straight segments, the rubber band: the one painter of an +/// [`OutlineDraft`], for the lassos and the app's Freeform Pen. pub fn paint_outline(draft: &OutlineDraft, draw: &Draw<'_>, cx: &ToolContext<'_>) { let Some(place) = Place::of(cx) else { return }; let points: Vec = draft.points().iter().map(|&at| place.screen(at)).collect(); @@ -100,19 +101,20 @@ pub(super) fn outline_access(points: &[kurbo::Point], cx: &ToolContext<'_>) -> O Some(ToolAccess::new(words.outline.as_str()).value(words.outline_points.text(count, &count.to_string())).bounds(bounds)) } -/// Starts the selection drag for `kind` at the press. +/// Starts the selection drag for `kind` at the press, snapping by the selection's `bounds`. pub(super) fn begin_inside( kind: DragKind, pointer: &ToolPointer, place: &Place, cx: &ToolContext<'_>, + bounds: Option, inside: &mut Option, report: &mut Report, ) { let id = report.gesture(); let label = cx.words::().move_selection.as_str().into(); let style = ConstrainStyle::new(f64::from(cx.slop), f64::from(cx.slop)); - let (drag, event) = InsideDrag::begin(&style, kind, place.doc(pointer.pos), pointer.mods, id, label, None); + let (drag, event) = InsideDrag::begin(&style, kind, place.doc(pointer.pos), pointer.mods, id, label, bounds); *inside = Some(drag); report.push(event); } @@ -182,9 +184,10 @@ pub(super) fn draft_key( /// straight segments (each click adds a vertex, a drag draws freehand again), and releasing Alt with the button up /// closes; Alt held at the press subtracts (the operation) until it is released and pressed again, except with nothing /// selected, where it starts straight segments. Between clicks the outline closes on a click near the first point (3 -/// or more points), on a click at the last, on Enter or on a double-click. Backspace or Delete retract the last -/// vertex (the last one cancels); the tool claims those keys from Edit > Clear (`CanvasTool::claims`) while -/// [`OutlineDraft::takes_retract`]. Escape cancels. The outline is dropped when the document changes +/// or more points), on a click at the last, on Enter or on a double-click. Backspace, Delete or a secondary click +/// retract the last vertex (the last one cancels); the tool claims those keys from Edit > Clear +/// (`CanvasTool::claims`) and takes the secondary button while [`OutlineDraft::takes_retract`], so the app shows no +/// context menu then. Escape cancels. The outline is dropped when the document changes /// ([`SelectionProbe::document`]) and on [`reset`](Self::reset). /// /// A press inside the selection drags it (module docs) instead of drawing; a Cmd press outside it is @@ -272,6 +275,11 @@ impl CanvasTool for SelectToolPass<'_, LassoTool> { if self.tool.draft.takes_retract() { ToolClaims::NONE.keyboard().deletes() } else { ToolClaims::NONE } } + /// The primary button always, the secondary between straight-segment clicks (it retracts the last vertex). + fn takes(&self, button: PointerButton, _mods: Mods) -> bool { + button == PointerButton::Primary || (button == PointerButton::Secondary && self.tool.draft.takes_retract()) + } + fn cursor(&self, cx: &ToolContext<'_>) -> Cursor { let tool = &*self.tool; let shown = LassoCursor { @@ -285,16 +293,22 @@ impl CanvasTool for SelectToolPass<'_, LassoTool> { cursor(&shown, self.probe, cx) } - /// With no outline open: a selection drag inside the selection, `Ignored` for Cmd outside, else the outline begins - /// (`OutlineDraft::press`; the operation resolves from the `Started` intent). With one open: the press goes to - /// the draft (a vertex, or a close). A second click of a run closes (`OutlineDraft::close`). + /// A secondary press retracts the last vertex (`ToolAction::Done`: no drag follows; the last one cancels the + /// outline with no event). With no outline open: a selection drag inside the selection, `Ignored` for Cmd + /// outside, else the outline begins (`OutlineDraft::press`; the operation resolves from the `Started` intent). + /// With one open: the press goes to the draft (a vertex, or a close). A second click of a run closes + /// (`OutlineDraft::close`). fn press(&mut self, pointer: &ToolPointer, cx: &mut ToolContext<'_>) -> ToolAction { let (tool, probe) = (&mut *self.tool, self.probe); + if pointer.button == PointerButton::Secondary { + tool.draft.retract(); + return ToolAction::Done; + } let Some(place) = Place::of(cx) else { return ToolAction::Ignored }; let open = tool.draft.is_open(); if !open { if let Some(kind) = drag_kind(probe, place.doc(pointer.pos), pointer.mods, tool.bar, PressRule::Drags) { - begin_inside(kind, pointer, &place, cx, &mut tool.inside, &mut tool.report); + begin_inside(kind, pointer, &place, cx, probe.bounds(), &mut tool.inside, &mut tool.report); return ToolAction::Claimed; } if pointer.mods.cmd { @@ -311,7 +325,7 @@ impl CanvasTool for SelectToolPass<'_, LassoTool> { let (tool, probe) = (&mut *self.tool, self.probe); let Some(place) = Place::of(cx) else { return }; if let Some(inside) = tool.inside.as_mut() { - if let Some(event) = inside.drag(place.doc(pointer.pos), pointer.mods, place.zoom(), &mut |_| kurbo::Vec2::ZERO) { + if let Some(event) = inside.drag(place.doc(pointer.pos), pointer.mods, place.zoom(), &mut |rect| cx.snap_rect(rect)) { tool.report.push(event); } return; @@ -326,7 +340,7 @@ impl CanvasTool for SelectToolPass<'_, LassoTool> { let (tool, probe) = (&mut *self.tool, self.probe); let Some(place) = Place::of(cx) else { return }; if let Some(inside) = tool.inside.take() { - tool.report.push(inside.end(place.doc(pointer.pos), pointer.mods, place.zoom(), &mut |_| kurbo::Vec2::ZERO)); + tool.report.push(inside.end(place.doc(pointer.pos), pointer.mods, place.zoom(), &mut |rect| cx.snap_rect(rect))); return; } let event = tool.draft.release(sample(pointer, &place)); diff --git a/crates/imaging/src/ui/select/marquee.rs b/crates/imaging/src/ui/select/marquee.rs index 8edca016a..b53ac2649 100644 --- a/crates/imaging/src/ui/select/marquee.rs +++ b/crates/imaging/src/ui/select/marquee.rs @@ -3,12 +3,12 @@ use craft_behavior::geometry::{ ConstrainStyle, Constraint, MarqueeGesture, MarqueeRect, SelectionOperation, fixed_size_pixels, marquee_pixels, square_pixels, }; -use craft_behavior::{CancelReason, Cursor, CursorIcon, PaintedCursor}; -use craft_keymap::Key; +use craft_behavior::{CancelReason, Cursor, CursorIcon, EditEvent, PaintedCursor}; +use craft_keymap::{Key, Mods}; use craft_ui::canvas::{CanvasTool, ToolAccess, ToolAction, ToolContext, ToolPath, ToolPointer}; use craft_ui::primitives::Draw; use egui::Pos2; -use kurbo::{Point, Rect}; +use kurbo::{Point, Rect, Vec2}; use super::drag::{InsideDrag, PressRule, cursor_over, drag_kind}; use super::{Place, Report, SelectEvent, SelectPhase, SelectToolPass, SelectWords, SelectionProbe, SelectionShape}; @@ -32,12 +32,24 @@ pub enum MarqueeKind { } impl MarqueeKind { - /// Whether the marquee is a line across the document, which never drags the selection. + /// Whether the marquee is a line across the document. fn is_line(self) -> bool { matches!(self, MarqueeKind::SingleRow | MarqueeKind::SingleColumn) } } +/// The press of a Single Row or Single Column selection drag: a release that did not move selects the line under +/// it, as a press outside the selection does. +#[derive(Clone, Copy, Debug)] +struct LinePress { + /// The press's document point. + at: Point, + /// The operation the press resolved. + operation: SelectionOperation, + /// The document's size at the press. + size: [u32; 2], +} + /// The press of a marquee drag, kept until the release. #[derive(Clone, Copy, Debug)] struct MarqueePress { @@ -58,17 +70,19 @@ struct MarqueePress { /// /// Pointer, in document units: /// - A drag sizes the marquee from the press: [`Constraint`] (Normal, Fixed Ratio, Fixed Size) from -/// [`constraint`](Self::constraint), Shift square (circle), Alt from the centre, each only when pressed after the -/// press (or released and pressed again: Shift and Alt held at the press are the operation). Space held moves the -/// whole marquee. The rectangle is on whole pixels, exactly as the release commits it; the readout beside the -/// pointer shows W and H. +/// [`constraint`](Self::constraint), Shift square (circle), Alt from the centre. With a selection, Shift and Alt +/// held at the press are the operation and count only when pressed again after the press; with nothing selected +/// they square and centre from the first move. The corner snaps to View > Snap To targets. Space held moves the +/// whole marquee, whose box snaps. The rectangle is on whole pixels, exactly as the release commits it; the readout +/// beside the pointer shows W and H. /// - A release without a drag, or with no area, is a click: [`SelectEvent::Deselect`]. With Fixed Size a click /// places the box there. /// - [`MarqueeKind::SingleRow`] and [`MarqueeKind::SingleColumn`] select the pixel row (column) under the pointer /// across the whole document, following the pointer until the release; a click selects too. -/// - A press inside the selection drags it ([`SelectEvent::DragSelection`], module docs); a Cmd press outside it is -/// `ToolAction::Ignored`. The Single Row and Single Column Marquees never drag the selection: a press inside it -/// draws the line. +/// - A press inside the selection drags it ([`SelectEvent::DragSelection`], module docs), its bounds snapping; a Cmd +/// press outside it is `ToolAction::Ignored`. For the Single Row and Single Column Marquees a press inside that is +/// released without moving a whole pixel selects the line under the press instead: the drag's `Cancel`, then the +/// `Commit`. /// - Escape cancels the drag (the host calls `cancel`): no event. /// /// The operation is latched at the press and the cursor shows its badge before the press, following the live @@ -81,6 +95,8 @@ pub struct MarqueeTool { constraint: Constraint, press: Option, inside: Option, + /// With `inside`, for the Single Row and Single Column Marquees. + line: Option, report: Report, } @@ -130,12 +146,13 @@ impl MarqueeTool { pub fn reset(&mut self) { self.press = None; self.inside = None; + self.line = None; } /// What the tool is doing: the marquee's pixel rectangle, or a selection drag. pub fn phase(&self) -> SelectPhase { if let Some(inside) = &self.inside { - return SelectPhase::Dragging(inside.kind()); + return SelectPhase::Dragging(inside.selection_drag()); } match &self.press { Some(press) => SelectPhase::Marquee { rect: self.pixels(press) }, @@ -167,15 +184,26 @@ impl MarqueeTool { (rect.width() > 0.0 && rect.height() > 0.0).then_some(rect) } - /// Follows the pointer to document point `at`: the gesture records the keys, and once begun sizes the marquee to - /// the pointer (Space moves it). - fn follow(&mut self, pointer: &ToolPointer, at: Point, space: bool) { + /// Follows the pointer to document point `raw` (unsnapped): the gesture records the keys, and once begun sizes the + /// marquee to the snapped pointer, or with Space held moves the whole box by the pointer's step and then onto + /// what the box snaps to. + fn follow(&mut self, pointer: &ToolPointer, raw: Point, cx: &mut ToolContext<'_>) { let (constraint, kind) = (self.constraint, self.kind); + let space = cx.held(Key::Space) && !kind.is_line(); + let at = if space { raw } else { cx.snap(raw) }; let Some(press) = self.press.as_mut() else { return }; press.gesture.follow(Some(pointer.pos), pointer.mods); press.last = at; if press.gesture.has_begun() && !kind.is_line() { - press.corners = Some(press.gesture.size_to(at, space, constraint)); + let mut corners = press.gesture.size_to(at, space, constraint); + if space { + let by = cx.snap_rect(corners.rect()); + if by != Vec2::ZERO { + // A second Space step by the snap offset moves both corners by it. + corners = press.gesture.size_to(at + by, true, constraint); + } + } + press.corners = Some(corners); } } @@ -228,7 +256,6 @@ impl CanvasTool for SelectToolPass<'_, MarqueeTool> { let (Some(pointer), Some(place)) = (cx.pointer, Place::of(cx)) else { return CursorIcon::Crosshair.into() }; let dragging = tool.inside.as_ref().map(InsideDrag::kind); if tool.press.is_none() - && !tool.kind.is_line() && let Some(cursor) = cursor_over(probe, place.doc(pointer.pos), cx.mods, tool.bar, PressRule::Drags, dragging) { return cursor; @@ -242,32 +269,35 @@ impl CanvasTool for SelectToolPass<'_, MarqueeTool> { badge.map_or(CursorIcon::Crosshair.into(), |badge| PaintedCursor::badged(CursorIcon::Crosshair, badge).into()) } - /// A press inside the selection begins a selection drag; a Cmd press outside is `Ignored`; otherwise the marquee - /// begins at the pointer's document point with the operation latched. + /// A press inside the selection begins a selection drag from the unsnapped press point; a Cmd press outside is + /// `Ignored`; otherwise the marquee begins at the pointer's snapped document point with the operation latched. fn press(&mut self, pointer: &ToolPointer, cx: &mut ToolContext<'_>) -> ToolAction { let (tool, probe) = (&mut *self.tool, self.probe); let Some(place) = Place::of(cx) else { return ToolAction::Ignored }; tool.reset(); let raw = place.doc(pointer.pos); - let at = cx.snap(raw); - if !tool.kind.is_line() - && let Some(kind) = drag_kind(probe, raw, pointer.mods, tool.bar, PressRule::Drags) - { + let size = probe.size(); + let operation = SelectionOperation::resolve(tool.bar, pointer.mods, probe.has_selection()); + if let Some(kind) = drag_kind(probe, raw, pointer.mods, tool.bar, PressRule::Drags) { let id = tool.report.gesture(); let label = cx.words::().move_selection.as_str().into(); - let (drag, event) = - InsideDrag::begin(&ConstrainStyle::new(f64::from(cx.slop), f64::from(cx.slop)), kind, at, pointer.mods, id, label, None); + let style = ConstrainStyle::new(f64::from(cx.slop), f64::from(cx.slop)); + let (drag, event) = InsideDrag::begin(&style, kind, raw, pointer.mods, id, label, probe.bounds()); tool.inside = Some(drag); + tool.line = tool.kind.is_line().then_some(LinePress { at: raw, operation, size: [size.width, size.height] }); tool.report.push(event); return ToolAction::Claimed; } if pointer.mods.cmd { return ToolAction::Ignored; } - let size = probe.size(); + let at = cx.snap(raw); + // With a selection the press modifiers pick the operation and must be pressed again to square or centre; + // with nothing selected they square and centre from the first move. + let held = if probe.has_selection() { pointer.mods } else { Mods::NONE }; tool.press = Some(MarqueePress { - gesture: MarqueeGesture::press(pointer.pos, at, pointer.mods), - operation: SelectionOperation::resolve(tool.bar, pointer.mods, probe.has_selection()), + gesture: MarqueeGesture::press(pointer.pos, at, held), + operation, size: [size.width, size.height], last: at, corners: None, @@ -277,18 +307,20 @@ impl CanvasTool for SelectToolPass<'_, MarqueeTool> { if let Some(press) = tool.press.as_mut() { press.gesture.begin(); } - tool.follow(pointer, at, false); + tool.follow(pointer, raw, cx); } tool.show_readout(cx); ToolAction::Claimed } - /// Sizes (or with Space moves) the marquee, or moves the selection drag; sets the W and H readout. + /// Sizes (or with Space moves) the marquee, or moves the selection drag by its snapped bounds; sets the W and H + /// readout. fn drag(&mut self, pointer: &ToolPointer, cx: &mut ToolContext<'_>) { let tool = &mut *self.tool; let Some(place) = Place::of(cx) else { return }; + let raw = place.doc(pointer.pos); if let Some(inside) = tool.inside.as_mut() { - if let Some(event) = inside.drag(cx.snap(place.doc(pointer.pos)), pointer.mods, place.zoom(), &mut |_| kurbo::Vec2::ZERO) { + if let Some(event) = inside.drag(raw, pointer.mods, place.zoom(), &mut |rect| cx.snap_rect(rect)) { tool.report.push(event); } return; @@ -296,22 +328,33 @@ impl CanvasTool for SelectToolPass<'_, MarqueeTool> { if let Some(press) = tool.press.as_mut() { press.gesture.begin(); } - let at = cx.snap(place.doc(pointer.pos)); - tool.follow(pointer, at, cx.held(Key::Space)); + tool.follow(pointer, raw, cx); tool.show_readout(cx); } /// Commits: `Commit { shape, operation }` for a rectangle or ellipse with area, `Deselect` for a click, the - /// drag's `Commit` for a selection drag. + /// drag's `Commit` for a selection drag (a line marquee's drag that did not move selects its line instead). fn release(&mut self, pointer: &ToolPointer, cx: &mut ToolContext<'_>) { let tool = &mut *self.tool; let Some(place) = Place::of(cx) else { return }; - let at = cx.snap(place.doc(pointer.pos)); + let raw = place.doc(pointer.pos); if let Some(inside) = tool.inside.take() { - tool.report.push(inside.end(at, pointer.mods, place.zoom(), &mut |_| kurbo::Vec2::ZERO)); + let line = tool.line.take(); + let unmoved = inside.clone(); + let event = inside.end(raw, pointer.mods, place.zoom(), &mut |rect| cx.snap_rect(rect)); + let still = matches!(&event, SelectEvent::DragSelection(EditEvent::Commit { after, .. }) if after.delta == [0, 0]); + let picked = line.filter(|_| still).and_then(|line| Some((single_line(tool.kind, line.size, line.at)?, line.operation))); + match picked { + Some((rect, operation)) => { + // The press was a click: the drag ends with no change, and the click selects the line. + tool.report.push(unmoved.cancel(CancelReason::Dismissed)); + tool.report.push(SelectEvent::Commit { shape: SelectionShape::Rectangle(rect), operation }); + } + None => tool.report.push(event), + } return; } - tool.follow(pointer, at, cx.held(Key::Space)); + tool.follow(pointer, raw, cx); let Some(press) = tool.press.take() else { return }; let event = match tool.pixels(&press) { Some(rect) if tool.kind == MarqueeKind::Ellipse => { @@ -331,6 +374,7 @@ impl CanvasTool for SelectToolPass<'_, MarqueeTool> { tool.report.push(inside.cancel(reason)); } tool.press = None; + tool.line = None; } /// The ants of the marquee being dragged. diff --git a/crates/imaging/src/ui/select/mod.rs b/crates/imaging/src/ui/select/mod.rs index 4336a5e97..78eb549a4 100644 --- a/crates/imaging/src/ui/select/mod.rs +++ b/crates/imaging/src/ui/select/mod.rs @@ -32,8 +32,9 @@ //! the app needs no call for the right click. //! //! A press inside the selection drags it instead of drawing: the outline with a plain press and the operation New, -//! the selected pixels with Cmd (Cmd+Alt a copy), a floating piece with a plain press. Click-driven tools (the -//! Polygonal Lasso) need Cmd for any of it, and never while an outline is open. A Cmd press outside the selection is +//! the selected pixels with Cmd (Cmd+Alt a copy). On a floating piece Cmd drags the piece and a plain press of a drag +//! tool the outline (the app drops the piece first). Click-driven tools (the Polygonal Lasso) need Cmd for any of it, +//! and never while an outline is open. A dragged selection snaps by its bounds ([`SelectionProbe::bounds`]). A Cmd press outside the selection is //! [`ToolAction::Ignored`](craft_ui::canvas::ToolAction) so the app's Move tool takes it. //! //! [`CanvasTool`]: craft_ui::canvas::CanvasTool @@ -57,6 +58,7 @@ pub use drag::{InsideDrag, PressRule, cursor_over, drag_kind}; pub use lasso::{LassoTool, paint_outline}; pub use magnetic::{EdgeSearch, EdgeTracer, MagneticLassoTool, MagneticSettings}; pub use marquee::{MarqueeKind, MarqueeTool}; +pub use operations::{SelectionOpWords, selection_operations}; pub use polygon::PolygonLassoTool; craft_ui::words! { @@ -99,8 +101,8 @@ pub enum SelectionShape { pub enum DragKind { /// The outline alone. Outline, - /// The selected pixels, or the floating piece: Cmd cuts them out first, Cmd+Alt (`copy`) lifts a copy, a floating - /// piece moves with a plain press. + /// The selected pixels, or the floating piece: Cmd cuts them out first, Cmd+Alt (`copy`) lifts a copy, and Cmd + /// moves a floating piece. #[non_exhaustive] Pixels { /// Lift a copy instead of cutting. @@ -180,8 +182,9 @@ pub enum SelectPhase { /// The point count. points: usize, }, - /// The selection being dragged. - Dragging(DragKind), + /// The selection being dragged: what moves and its whole-pixel offset so far, from which the app offsets the + /// marching ants and the floating piece while the drag runs. + Dragging(SelectionDrag), } impl SelectPhase { diff --git a/crates/imaging/src/ui/select/polygon.rs b/crates/imaging/src/ui/select/polygon.rs index babb1f4ba..87dc9d0ed 100644 --- a/crates/imaging/src/ui/select/polygon.rs +++ b/crates/imaging/src/ui/select/polygon.rs @@ -1,6 +1,5 @@ //! [`PolygonLassoTool`]: the Polygonal Lasso, click by click. -use craft_behavior::geometry::turn_to_45; use craft_behavior::geometry::{DraftKind, DraftPoint, DraftReach, OutlineDraft, SelectionOperation}; use craft_behavior::{CancelReason, Cursor, PointerButton}; use craft_keymap::Mods; @@ -13,8 +12,8 @@ use super::{Place, Report, SelectEvent, SelectPhase, SelectToolPass, SelectionPr /// The Polygonal Lasso: each click adds a vertex; the outline closes into a selection. /// -/// The drawing rules are [`OutlineDraft`]'s with [`DraftKind::Polygonal`]: Shift (without Alt) turns the new segment -/// to a multiple of 45 degrees from the last vertex (not the first vertex), an Alt drag draws freehand. The first +/// The drawing rules are [`OutlineDraft`]'s with [`DraftKind::Polygonal`]: Shift (without Alt) puts the new vertex in +/// the nearest of eight directions from the last vertex (not the first vertex), an Alt drag draws freehand. The first /// click latches the operation (Alt with nothing selected is New). The outline closes on a click near the first /// vertex (3 or more), on a click at the last, on Enter or a double-click. Backspace, Delete or a secondary click /// retract the last vertex (the last one cancels): the tool takes the secondary button while an outline is open, so @@ -145,7 +144,7 @@ impl CanvasTool for SelectToolPass<'_, PolygonLassoTool> { } let open = tool.draft.is_open(); if let Some(kind) = drag_kind(probe, place.doc(pointer.pos), pointer.mods, tool.bar, PressRule::Clicks { outline_open: open }) { - begin_inside(kind, pointer, &place, cx, &mut tool.inside, &mut tool.report); + begin_inside(kind, pointer, &place, cx, probe.bounds(), &mut tool.inside, &mut tool.report); return ToolAction::Claimed; } if pointer.mods.cmd && !open { @@ -161,7 +160,7 @@ impl CanvasTool for SelectToolPass<'_, PolygonLassoTool> { let (tool, probe) = (&mut *self.tool, self.probe); let Some(place) = Place::of(cx) else { return }; if let Some(inside) = tool.inside.as_mut() { - if let Some(event) = inside.drag(place.doc(pointer.pos), pointer.mods, place.zoom(), &mut |_| kurbo::Vec2::ZERO) { + if let Some(event) = inside.drag(place.doc(pointer.pos), pointer.mods, place.zoom(), &mut |rect| cx.snap_rect(rect)) { tool.report.push(event); } return; @@ -175,24 +174,18 @@ impl CanvasTool for SelectToolPass<'_, PolygonLassoTool> { let (tool, probe) = (&mut *self.tool, self.probe); let Some(place) = Place::of(cx) else { return }; if let Some(inside) = tool.inside.take() { - tool.report.push(inside.end(place.doc(pointer.pos), pointer.mods, place.zoom(), &mut |_| kurbo::Vec2::ZERO)); + tool.report.push(inside.end(place.doc(pointer.pos), pointer.mods, place.zoom(), &mut |rect| cx.snap_rect(rect))); return; } let event = tool.draft.release(sample(pointer, &place)); apply(event, tool.bar, probe.has_selection(), &mut tool.operation, &mut tool.report); } - /// The rubber band follows the pointer, constrained to 45 degrees with Shift. + /// The rubber band follows the pointer; it ends where a click would place the vertex. fn hover(&mut self, pointer: &ToolPointer, cx: &mut ToolContext<'_>) { let tool = &mut *self.tool; let Some(place) = Place::of(cx) else { return }; - let mut at = sample(pointer, &place); - if pointer.mods.shift - && !pointer.mods.alt - && let Some(&last) = tool.draft.points().last() - { - at.at = turn_to_45(last, at.at); - } + let at = sample(pointer, &place); if tool.draft.hover(at).is_some() { cx.request_repaint(); } diff --git a/crates/imaging/src/ui/select_mask/tools/canvas.rs b/crates/imaging/src/ui/select_mask/tools/canvas.rs index 4a66f8f73..d21c96a75 100644 --- a/crates/imaging/src/ui/select_mask/tools/canvas.rs +++ b/crates/imaging/src/ui/select_mask/tools/canvas.rs @@ -295,7 +295,7 @@ impl SelectMaskCanvasTool<'_> { } let rows = self.canvas.resize.readout_rows(&cx.units(), &cx.words::()); if !rows.is_empty() { - cx.readout(rows); + cx.hud(rows); } } diff --git a/crates/imaging/tests/it/live_preview.rs b/crates/imaging/tests/it/live_preview.rs index 16e3628fe..2b3bdf9bb 100644 --- a/crates/imaging/tests/it/live_preview.rs +++ b/crates/imaging/tests/it/live_preview.rs @@ -3,7 +3,7 @@ use craft_ui::canvas::PixelRect; use craft_ui::testing::trial; -use craft_imaging::ui::live_preview::{DraftScale, LivePreview, PreviewKey, PreviewLane, PreviewSession}; +use craft_imaging::ui::live_preview::{DraftScale, LivePreview, PreviewKey, PreviewLane, PreviewSession, settings_hash}; const REGION: PixelRect = PixelRect::new(0, 0, 100, 100); const VIEW: PixelRect = PixelRect::new(0, 0, 50, 50); @@ -63,6 +63,40 @@ fn live_preview_uncovered_returns_the_newly_visible_part_once() { assert_eq!(live.uncovered(other, PixelRect::new(0, 0, 100, 100)), None); } +// A tool preview keyed with the area each key changes: a switch damages the union of the two areas (the visible part +// to a preview, the whole area back to NONE, which changes nothing itself); a key without an area gives the region. +// A stage key differs from its settings key and from other stages and stays the session's; a Tool key is foreign to +// the Dialog and Properties lanes. +#[trial] +fn a_key_in_an_area_damages_the_union_of_its_areas_and_a_stage_key_belongs_to_the_session() { + let mut live = started(PreviewLane::Tool, 1); + let left = PixelRect::new(10, 10, 20, 20); + let a = live.key_in(settings_hash(&[b"a"]), 0.0, left); + let b = live.key_in(settings_hash(&[b"b"]), 0.0, PixelRect::new(30, 10, 40, 20)); + let c = live.key_in(settings_hash(&[b"c"]), 0.0, PixelRect::new(40, 40, 60, 60)); + let plain = live.key(settings_hash(&[b"d"]), 0.0); + + assert_eq!(live.changed(a, b), Some(PixelRect::new(10, 10, 40, 20))); + assert_eq!(live.changed(a, plain), None); + assert_eq!(live.switch(PreviewKey::NONE, a, VIEW), Some(left)); + assert_eq!(live.switch(a, b, VIEW), Some(PixelRect::new(10, 10, 40, 20))); + assert_eq!(live.switch(b, c, VIEW), Some(PixelRect::new(30, 10, 50, 50)), "only the visible part of the union"); + assert_eq!(live.switch(c, PreviewKey::NONE, VIEW), Some(PixelRect::new(40, 40, 60, 60)), "back to NONE: the whole area"); + assert_eq!(live.switch(a, plain, VIEW), Some(REGION.intersect(&VIEW))); + + let stage = a.stage(1); + assert_ne!(stage, a); + assert_ne!(stage, a.stage(2)); + assert!(live.owns(stage)); + + let mut dialog = started(PreviewLane::Dialog, 1); + let mut props = started(PreviewLane::Properties, 1); + let (dialog_key, props_key) = (dialog.key(settings_hash(&[b"a"]), 0.0), props.key(settings_hash(&[b"a"]), 0.0)); + assert!(a != dialog_key && a != props_key); + assert!(!live.owns(dialog_key) && !live.owns(props_key)); + assert!(!dialog.owns(a) && !props.owns(a)); +} + /// One drag of `control` on `item`: `drafts` full-size renders of `ms` each, started at `start` /// and ended at `end`. Returns the scale the drag started with. fn drag(d: &mut DraftScale, item: u64, start: f64, end: f64, ms: f64, drafts: u64) -> Option { diff --git a/crates/imaging/tests/it/select.rs b/crates/imaging/tests/it/select.rs index dda8e5e79..6914b7614 100644 --- a/crates/imaging/tests/it/select.rs +++ b/crates/imaging/tests/it/select.rs @@ -1,28 +1,30 @@ //! The selection tools on the tool host: each test drives one tool through a `ToolFixture` with injected pointer input //! and a fake `SelectionProbe`, then reads the events the tool reports. -use craft_behavior::geometry::{Constraint, SelectionOperation}; -use craft_behavior::{CancelReason, EditEvent, PixelSize, PointerButton}; +use craft_behavior::geometry::{Constraint, SelectionOperation, SnapKind, SnapOptions, SnapTarget, SnapTargets}; +use craft_behavior::{Axis, CancelReason, EditEvent, PixelSize, PointerButton}; use craft_imaging::ui::select::{ - EdgeSearch, EdgeTracer, MagneticLassoTool, MarqueeKind, MarqueeTool, PolygonLassoTool, SelectEvent, SelectPhase, SelectToolPass, SelectionProbe, - SelectionShape, + DragKind, EdgeSearch, EdgeTracer, LassoTool, MagneticLassoTool, MarqueeKind, MarqueeTool, PolygonLassoTool, SelectEvent, SelectPhase, + SelectToolPass, SelectionDrag, SelectionProbe, SelectionShape, }; -use craft_keymap::Mods; -use craft_ui::canvas::{CanvasTool, ToolAccess, ToolContext, ToolHost, ToolInput, ToolKey, ToolPath, ToolPointer}; +use craft_keymap::{Mods, Platform}; +use craft_ui::canvas::{CanvasTool, Snap, ToolAccess, ToolContext, ToolHost, ToolInput, ToolKey, ToolPath, ToolPointer}; use craft_ui::primitives::Draw; use craft_ui::testing::{ToolFixture, pointer, trial}; use egui::{Key, Modifiers, Pos2, Rect as ScreenRect, pos2}; use kurbo::{Point, Rect, Vec2}; use std::cell::{Cell, RefCell}; use std::rc::Rc; +use std::sync::Arc; const SIZE: PixelSize = PixelSize::new(400, 300); const NONE: Mods = Mods::NONE; -/// A document with an optional rectangle selection. +/// A document with an optional rectangle selection and an optional floating piece where it is shown. #[derive(Default)] struct Fake { selection: Option, + floating: Option, document: u64, } @@ -34,6 +36,11 @@ impl Fake { fn selected(selection: Rect) -> Self { Fake { selection: Some(selection), ..Fake::empty() } } + + /// A selection whose pixels float, shown at `piece`. + fn floating(selection: Rect, piece: Rect) -> Self { + Fake { floating: Some(piece), ..Fake::selected(selection) } + } } impl SelectionProbe for Fake { @@ -52,6 +59,18 @@ impl SelectionProbe for Fake { fn inside_selection(&self, at: Point) -> bool { self.selection.is_some_and(|rect| rect.contains(at)) } + + fn bounds(&self) -> Option { + self.selection + } + + fn floating(&self) -> bool { + self.floating.is_some() + } + + fn on_floating(&self, at: Point) -> bool { + self.floating.is_some_and(|piece| piece.contains(at)) + } } /// What the tests read from every tool. @@ -80,6 +99,7 @@ macro_rules! reports { } reports!(MarqueeTool); +reports!(LassoTool); reports!(PolygonLassoTool); reports!(MagneticLassoTool, T: EdgeTracer); @@ -166,16 +186,32 @@ where type Rig = ToolFixture>; +/// The view in which a canvas's document point and screen point coincide. +fn same_points(room: ScreenRect) -> craft_behavior::CanvasView { + let centre = room.center(); + craft_behavior::CanvasView::new(room, Point::new(f64::from(centre.x), f64::from(centre.y)), 1.0) +} + /// A canvas whose document point and screen point coincide. fn rig(label: &'static str, tool: T, probe: Fake) -> Rig where for<'a> SelectToolPass<'a, T>: CanvasTool, { - let view = |room: ScreenRect| { - let centre = room.center(); - craft_behavior::CanvasView::new(room, Point::new(f64::from(centre.x), f64::from(centre.y)), 1.0) - }; - ToolFixture::with_view(label, Owned::new(tool, probe), view, |_, _| {}) + ToolFixture::with_view(label, Owned::new(tool, probe), same_points, |_, _| {}) +} + +/// [`rig`] on a canvas that snaps to a vertical guide at x = 100, on macOS, where Control alone suspends snapping. +fn snapped_rig(label: &'static str, tool: T, probe: Fake) -> Rig +where + for<'a> SelectToolPass<'a, T>: CanvasTool, +{ + let mut targets = SnapTargets::new(); + targets.add(SnapTarget::new(Axis::Y, 100.0, SnapKind::Guide)); + let snap = Snap::new(Arc::new(targets), SnapOptions::default()); + let mut rig = ToolFixture::with_snap(label, Owned::new(tool, probe), same_points, snap, |_, _| {}); + rig.fixture().os(Platform::Mac); + rig.fixture().frame(Vec::new()); + rig } fn at(point: (f64, f64)) -> Pos2 { @@ -262,6 +298,10 @@ fn commit(rect: (f64, f64, f64, f64), operation: SelectionOperation) -> SelectEv SelectEvent::commit(SelectionShape::Rectangle(Rect::new(rect.0, rect.1, rect.2, rect.3)), operation) } +fn polygon(points: &[(f64, f64)], operation: SelectionOperation) -> SelectEvent { + SelectEvent::commit(SelectionShape::Polygon(points.iter().map(|&(x, y)| Point::new(x, y)).collect()), operation) +} + /// "begin", "update 1,0", "commit 2,0", "cancel"; other events as `Debug`. fn tags(events: &[SelectEvent]) -> Vec { events @@ -290,30 +330,96 @@ where // ---- the marquees ---- -// Normal style: Shift pressed after the press squares, Alt pressed after it centres, Shift held at the press does not -// (it is Add); Fixed Ratio and Fixed Size give whole-pixel rectangles. +/// The rectangle of the one `Commit` in `events`. +fn committed_rect(events: &[SelectEvent]) -> Rect { + match events { + [SelectEvent::Commit { shape: SelectionShape::Rectangle(rect), .. }] => *rect, + _ => panic!("one rectangle commit: {events:?}"), + } +} + +// Normal style: Shift pressed after the press squares, Alt pressed after it centres. With nothing selected Shift and +// Alt held at the press square and centre from the first move; with a selection they pick the operation only. Fixed +// Ratio and Fixed Size give whole-pixel rectangles, and a Shift square pressed between pixels has equal sides. The +// Single Row and Single Column Marquees keep a one-pixel drag. On a floating piece a plain press drags the outline and +// Cmd the piece; a Single Row press inside the selection drags the outline, and one released where it was pressed +// selects the row under it. #[trial] fn marquee_corners_follow_constraint_and_modifiers() { - let mut rig = rig("Marquee", MarqueeTool::new(MarqueeKind::Rectangle), Fake::empty()); - let events = stroke(&mut rig, (10.5, 10.5), (50.5, 30.5), NONE, NONE); + let mut marquee = rig("Marquee", MarqueeTool::new(MarqueeKind::Rectangle), Fake::empty()); + let events = stroke(&mut marquee, (10.5, 10.5), (50.5, 30.5), NONE, NONE); assert_eq!(events, [commit((10.0, 10.0, 51.0, 31.0), SelectionOperation::New)]); - let events = stroke(&mut rig, (10.5, 10.5), (50.5, 30.5), NONE, Mods::SHIFT); + let events = stroke(&mut marquee, (10.5, 10.5), (50.5, 30.5), NONE, Mods::SHIFT); assert_eq!(events, [commit((10.0, 10.0, 51.0, 51.0), SelectionOperation::New)], "Shift after the press squares"); - let events = stroke(&mut rig, (10.5, 10.5), (50.5, 30.5), Mods::SHIFT, Mods::SHIFT); - assert_eq!(events, [commit((10.0, 10.0, 51.0, 31.0), SelectionOperation::Add)], "Shift at the press is Add, not square"); - - let events = stroke(&mut rig, (100.0, 100.0), (110.0, 120.0), NONE, Mods::ALT); + let events = stroke(&mut marquee, (100.0, 100.0), (110.0, 120.0), NONE, Mods::ALT); assert_eq!(events, [commit((90.0, 80.0, 110.0, 120.0), SelectionOperation::New)], "Alt after the press centres"); - rig.tool_mut().tool().constraint(Constraint::Ratio(2.0, 1.0)); - let events = stroke(&mut rig, (10.0, 10.0), (50.0, 12.0), NONE, NONE); + // #11389: with nothing selected the press modifiers count from the first move. + let events = stroke(&mut marquee, (10.5, 10.5), (50.5, 30.5), Mods::SHIFT, Mods::SHIFT); + assert_eq!(events, [commit((10.0, 10.0, 51.0, 51.0), SelectionOperation::Add)], "Shift at the press squares with nothing selected"); + let events = stroke(&mut marquee, (100.0, 100.0), (110.0, 120.0), Mods::ALT, Mods::ALT); + assert_eq!(events, [commit((90.0, 80.0, 110.0, 120.0), SelectionOperation::New)], "Alt at the press centres with nothing selected"); + + // #5472: a square pressed between pixels. + let square = committed_rect(&stroke(&mut marquee, (10.3, 10.7), (50.6, 30.2), NONE, Mods::SHIFT)); + assert!(square.width() > 0.0 && square.width() == square.height(), "{square:?}"); + + marquee.tool_mut().tool().constraint(Constraint::Ratio(2.0, 1.0)); + let events = stroke(&mut marquee, (10.0, 10.0), (50.0, 12.0), NONE, NONE); assert_eq!(events, [commit((10.0, 10.0, 50.0, 30.0), SelectionOperation::New)]); - rig.tool_mut().tool().constraint(Constraint::Size(10.0, 10.0)); - let events = stroke(&mut rig, (20.0, 20.0), (40.4, 60.4), NONE, NONE); + marquee.tool_mut().tool().constraint(Constraint::Size(10.0, 10.0)); + let events = stroke(&mut marquee, (20.0, 20.0), (40.4, 60.4), NONE, NONE); assert_eq!(events, [commit((40.0, 60.0, 50.0, 70.0), SelectionOperation::New)], "the box follows the pointer"); + // #6015: Fixed Size between pixels is exactly its size. + let fixed = committed_rect(&stroke(&mut marquee, (20.3, 20.6), (40.7, 60.2), NONE, NONE)); + assert_eq!((fixed.width(), fixed.height()), (10.0, 10.0), "{fixed:?}"); + + // With a selection the press modifiers pick the operation and neither square nor centre. + let mut marquee = rig("Marquee", MarqueeTool::new(MarqueeKind::Rectangle), Fake::selected(Rect::new(300.0, 250.0, 350.0, 290.0))); + let events = stroke(&mut marquee, (10.5, 10.5), (50.5, 30.5), Mods::SHIFT, Mods::SHIFT); + assert_eq!(events, [commit((10.0, 10.0, 51.0, 31.0), SelectionOperation::Add)], "Shift at the press is Add, not square"); + let events = stroke(&mut marquee, (100.0, 100.0), (110.0, 120.0), Mods::ALT, Mods::ALT); + assert_eq!(events, [commit((100.0, 100.0, 110.0, 120.0), SelectionOperation::Subtract)], "Alt at the press is Subtract, not centred"); + + // #2391: a one-pixel line drag is a selection. + let mut marquee = rig("Marquee", MarqueeTool::new(MarqueeKind::SingleRow), Fake::empty()); + let events = stroke(&mut marquee, (30.5, 20.5), (31.5, 20.5), NONE, NONE); + assert_eq!(events, [commit((0.0, 20.0, 400.0, 21.0), SelectionOperation::New)]); + marquee.tool_mut().tool().kind(MarqueeKind::SingleColumn); + let events = stroke(&mut marquee, (30.5, 20.5), (30.5, 21.5), NONE, NONE); + assert_eq!(events, [commit((30.0, 0.0, 31.0, 300.0), SelectionOperation::New)]); + + // #11368: on a floating piece (the selection shown 20 pixels to the right) a plain press drags the outline and Cmd + // the piece; a press beside the piece, still inside the selection, starts a new marquee. + let piece = Rect::new(120.0, 100.0, 220.0, 200.0); + let mut marquee = rig("Marquee", MarqueeTool::new(MarqueeKind::Rectangle), Fake::floating(Rect::new(100.0, 100.0, 200.0, 200.0), piece)); + down(&mut marquee, (210.0, 150.0), NONE); + assert_eq!(marquee.tool().phase(), SelectPhase::Dragging(SelectionDrag::new(DragKind::Outline, [0, 0])), "a plain press on the piece"); + up(&mut marquee, (210.0, 150.0), NONE); + assert_eq!(tags(&marquee.tool_mut().events()), ["begin", "commit 0,0"]); + down(&mut marquee, (210.0, 150.0), Mods::CMD); + assert_eq!(marquee.tool().phase(), SelectPhase::Dragging(SelectionDrag::new(DragKind::pixels(false), [0, 0])), "a Cmd press on the piece"); + up(&mut marquee, (210.0, 150.0), Mods::CMD); + marquee.tool_mut().events(); + down(&mut marquee, (110.0, 150.0), NONE); + assert!(matches!(marquee.tool().phase(), SelectPhase::Marquee { .. }), "beside the piece: {:?}", marquee.tool().phase()); + up(&mut marquee, (110.0, 150.0), NONE); + marquee.tool_mut().events(); + + // #11392: a Single Row press inside the selection drags the outline; released where it was pressed it selects the + // row under the press (the drag's Cancel, then the Commit). + let mut marquee = rig("Marquee", MarqueeTool::new(MarqueeKind::SingleRow), Fake::selected(Rect::new(100.0, 100.0, 200.0, 200.0))); + down(&mut marquee, (150.0, 150.5), NONE); + drag_to(&mut marquee, (170.0, 150.5), NONE); + up(&mut marquee, (170.0, 150.5), NONE); + assert_eq!(tags(&marquee.tool_mut().events()), ["begin", "update 20,0", "commit 20,0"]); + click(&mut marquee, (150.0, 120.5), NONE); + let events = marquee.tool_mut().events(); + assert_eq!(tags(&events[..2]), ["begin", "cancel"], "{events:?}"); + assert_eq!(events[2..], [commit((0.0, 120.0, 400.0, 121.0), SelectionOperation::New)]); } // Cmd inside the selection drags pixels, Cmd+Alt a copy; Cmd outside it is the Move tool's, so the host starts no @@ -343,8 +449,83 @@ fn marquee_selection_drag_reports_whole_pixel_deltas_and_cancel() { assert_eq!(rig.tool().phase(), SelectPhase::Idle); } +// A marquee corner snaps to the guide at x = 100. A dragged selection snaps by its bounds, once and before the delta +// rounds: from (35, 45) to (93, 45) its centre lands on the guide (55 pixels), where a second snap of the pointer +// itself would have moved it 70. Control suspends both. +#[trial] +fn a_marquee_corner_and_a_dragged_selection_snap_to_a_guide() { + let mut rig = snapped_rig("Marquee", MarqueeTool::new(MarqueeKind::Rectangle), Fake::empty()); + let events = stroke(&mut rig, (20.0, 20.0), (96.0, 60.0), NONE, NONE); + assert_eq!(events, [commit((20.0, 20.0, 100.0, 60.0), SelectionOperation::New)], "the corner snaps to the guide"); + down(&mut rig, (20.0, 20.0), NONE); + hold(&mut rig, Modifiers::CTRL); + drag_to(&mut rig, (96.0, 60.0), Mods::CTRL); + up(&mut rig, (96.0, 60.0), Mods::CTRL); + hold(&mut rig, Modifiers::NONE); + assert_eq!(rig.tool_mut().events(), [commit((20.0, 20.0, 96.0, 60.0), SelectionOperation::New)], "Control suspends the corner snap"); + + let mut rig = snapped_rig("Marquee", MarqueeTool::new(MarqueeKind::Rectangle), Fake::selected(Rect::new(30.0, 30.0, 60.0, 60.0))); + down(&mut rig, (35.0, 45.0), NONE); + drag_to(&mut rig, (93.0, 45.0), NONE); + up(&mut rig, (93.0, 45.0), NONE); + assert_eq!(tags(&rig.tool_mut().events()), ["begin", "update 55,0", "commit 55,0"], "the bounds snap once"); + down(&mut rig, (35.0, 45.0), NONE); + hold(&mut rig, Modifiers::CTRL); + drag_to(&mut rig, (93.0, 45.0), Mods::CTRL); + up(&mut rig, (93.0, 45.0), Mods::CTRL); + hold(&mut rig, Modifiers::NONE); + assert_eq!(tags(&rig.tool_mut().events()), ["begin", "update 58,0", "commit 58,0"], "Control suspends the box snap"); + + // A click inside a selection whose edge lies within the tolerance of the guide moves nothing and calls no snap. + let near = Rect::new(72.0, 30.0, 97.0, 60.0); + let mut rig = snapped_rig("Marquee", MarqueeTool::new(MarqueeKind::Rectangle), Fake::selected(near)); + click(&mut rig, (80.0, 45.0), NONE); + assert_eq!(tags(&rig.tool_mut().events()), ["begin", "commit 0,0"], "a click commits a zero delta"); + let mut rig = snapped_rig("Marquee", MarqueeTool::new(MarqueeKind::SingleRow), Fake::selected(near)); + click(&mut rig, (80.0, 45.5), NONE); + let events = rig.tool_mut().events(); + assert_eq!(tags(&events[..2]), ["begin", "cancel"], "{events:?}"); + assert_eq!(events[2..], [commit((0.0, 45.0, 400.0, 46.0), SelectionOperation::New)], "the click selects the row"); +} + // ---- the Lasso ---- +// Alt pressed during a freehand drag turns on straight segments, Alt-clicks add vertices and releasing Alt closes. A +// first press with Alt and nothing selected starts straight segments and stays New; Backspace and a secondary press +// each retract one vertex, and a click on the last point closes. +#[trial] +fn lasso_alt_clicks_make_straight_segments_that_retract_and_close() { + let mut rig = rig("Lasso", LassoTool::new(), Fake::empty()); + focus(&mut rig); + down(&mut rig, (100.0, 100.0), NONE); + drag_to(&mut rig, (140.0, 100.0), NONE); + hold(&mut rig, Modifiers::ALT); + up(&mut rig, (140.0, 100.0), Mods::ALT); + assert_eq!(rig.tool().phase(), SelectPhase::Outline { points: 2 }, "with Alt down the release keeps the outline open"); + click(&mut rig, (140.0, 140.0), Mods::ALT); + click(&mut rig, (100.0, 140.0), Mods::ALT); + assert!(rig.tool_mut().events().is_empty(), "Alt-clicks add vertices"); + hold(&mut rig, Modifiers::NONE); + let events = rig.tool_mut().events(); + assert_eq!(events, [polygon(&[(100.0, 100.0), (140.0, 100.0), (140.0, 140.0), (100.0, 140.0)], SelectionOperation::New)], "releasing Alt closes"); + + hold(&mut rig, Modifiers::ALT); + for point in [(100.0, 100.0), (200.0, 100.0), (200.0, 200.0), (100.0, 200.0), (150.0, 250.0)] { + click(&mut rig, point, Mods::ALT); + } + assert_eq!(rig.tool().phase(), SelectPhase::Outline { points: 5 }, "a first Alt press with nothing selected starts straight segments"); + press_key(&mut rig, Key::Backspace, Modifiers::ALT); + assert_eq!(rig.tool().phase(), SelectPhase::Outline { points: 4 }, "Backspace retracts"); + inject(&mut rig, ToolInput::down(PointerButton::Secondary, at((300.0, 300.0))).mods(Mods::ALT)); + inject(&mut rig, ToolInput::up(at((300.0, 300.0))).mods(Mods::ALT)); + assert_eq!(rig.tool().phase(), SelectPhase::Outline { points: 3 }, "a secondary press retracts"); + click(&mut rig, (200.0, 200.0), Mods::ALT); + let events = rig.tool_mut().events(); + assert_eq!(events, [polygon(&[(100.0, 100.0), (200.0, 100.0), (200.0, 200.0)], SelectionOperation::New)], "a click on the last point closes, New"); + hold(&mut rig, Modifiers::NONE); + assert!(rig.tool_mut().events().is_empty(), "nothing is left to close"); +} + // A plain press inside the selection drags the outline instead of drawing. // A press and release that draw fewer than 3 points (a click, or a two-point drag) deselect. @@ -374,6 +555,43 @@ fn polygon_shift_constrains_to_45_degrees() { assert_eq!(points[2], Point::new(140.0, 170.0), "Shift with Alt keeps the point"); } +// One outline: Alt at the first click with a selection latches Subtract for every later click; Backspace and a +// secondary press each retract a vertex; an Alt drag adds freehand points; a double click closes. A second outline +// closes on a click on its start, with the operation New. +#[trial] +fn a_polygonal_lasso_closes_by_double_click_or_its_start_and_retracts_by_backspace_or_secondary_press() { + let mut rig = rig("Polygonal Lasso", PolygonLassoTool::new(), Fake::selected(Rect::new(300.0, 250.0, 350.0, 290.0))); + focus(&mut rig); + hold(&mut rig, Modifiers::ALT); + click(&mut rig, (100.0, 100.0), Mods::ALT); + hold(&mut rig, Modifiers::NONE); + for point in [(200.0, 100.0), (250.0, 150.0), (260.0, 160.0)] { + click(&mut rig, point, NONE); + } + press_key(&mut rig, Key::Backspace, Modifiers::NONE); + assert_eq!(rig.tool().phase(), SelectPhase::Outline { points: 3 }, "Backspace retracts"); + inject(&mut rig, ToolInput::down(PointerButton::Secondary, at((300.0, 50.0)))); + inject(&mut rig, ToolInput::up(at((300.0, 50.0)))); + assert_eq!(rig.tool().phase(), SelectPhase::Outline { points: 2 }, "a secondary press retracts"); + hold(&mut rig, Modifiers::ALT); + down(&mut rig, (200.0, 200.0), Mods::ALT); + drag_to(&mut rig, (180.0, 220.0), Mods::ALT); + drag_to(&mut rig, (160.0, 230.0), Mods::ALT); + up(&mut rig, (160.0, 230.0), Mods::ALT); + hold(&mut rig, Modifiers::NONE); + assert!(rig.tool_mut().events().is_empty(), "the outline stays open"); + rig.double_press_at(at((120.0, 200.0))); + let events = rig.tool_mut().events(); + let drawn = [(100.0, 100.0), (200.0, 100.0), (200.0, 200.0), (180.0, 220.0), (160.0, 230.0), (120.0, 200.0)]; + assert_eq!(events, [polygon(&drawn, SelectionOperation::Subtract)], "a double click closes; the Alt drag is freehand"); + + for point in [(100.0, 100.0), (200.0, 100.0), (200.0, 200.0), (100.0, 100.0)] { + click(&mut rig, point, NONE); + } + let events = rig.tool_mut().events(); + assert_eq!(events, [polygon(&[(100.0, 100.0), (200.0, 100.0), (200.0, 200.0)], SelectionOperation::New)], "a click on the start closes"); +} + // A new outline replaces the selection while it is open: true only for the operation New. // ---- the Magnetic Lasso ---- @@ -510,6 +728,64 @@ fn magnetic_fastens_every_spacing_and_walks_jumps() { assert_eq!(log.snaps.get(), 1 + 256, "the start, then 256 steps"); } +/// The points of the one `Commit` with the operation New in `events`. +fn committed_polygon(events: &[SelectEvent]) -> Vec { + match events { + [SelectEvent::Commit { shape: SelectionShape::Polygon(points), operation: SelectionOperation::New, .. }] => points.clone(), + _ => panic!("one New polygon commit: {events:?}"), + } +} + +// An outline traced along the circle closes on a click on its start, on a double click and on Enter, each into a +// polygon on the circle's edge. Backspace removes the fastening points one by one, the first one last: one press per +// fastening point drops the outline, and nothing is committed. +#[trial] +fn magnetic_closes_by_start_click_double_click_or_enter_and_retracts_to_the_first() { + let on_edge = |points: &[Point]| points.len() >= 3 && points.iter().all(|&p| on_circle(p)); + + let (mut rig, _) = magnetic(); + click(&mut rig, pt(on(0.0)), NONE); + glide_along(&mut rig, 0.0, 5.0); + // A second apart, so the click on the start is not a double click. + rig.fixture().advance(1.0); + click(&mut rig, pt(on(0.0)), NONE); + let points = committed_polygon(&rig.tool_mut().events()); + assert!(on_edge(&points), "a click on the start closes: {points:?}"); + assert_eq!(rig.tool().phase(), SelectPhase::Idle); + + let (mut rig, _) = magnetic(); + click(&mut rig, pt(on(0.0)), NONE); + glide_along(&mut rig, 0.0, 1.5); + rig.double_press_at(at(pt(on(1.5)))); + let points = committed_polygon(&rig.tool_mut().events()); + assert!(on_edge(&points), "a double click closes: {points:?}"); + + let (mut rig, _) = magnetic(); + click(&mut rig, pt(on(0.0)), NONE); + glide_along(&mut rig, 0.0, 1.5); + press_key(&mut rig, Key::Enter, Modifiers::NONE); + let points = committed_polygon(&rig.tool_mut().events()); + assert!(on_edge(&points), "Enter closes: {points:?}"); + + let (mut rig, log) = magnetic(); + click(&mut rig, pt(on(0.0)), NONE); + glide_along(&mut rig, 0.0, 2.5); + let fastened = log.starts(); + assert!(fastened >= 3, "{fastened}"); + let mut presses = 0; + loop { + let phase = rig.tool().phase(); + if phase == SelectPhase::Idle || presses > fastened { + break; + } + assert!(matches!(phase, SelectPhase::Outline { .. }), "{phase:?}"); + press_key(&mut rig, Key::Backspace, Modifiers::NONE); + presses += 1; + } + assert_eq!(presses, fastened, "one Backspace per fastening point, the first one last"); + assert!(rig.tool_mut().events().is_empty(), "retracting commits nothing"); +} + // `[` and `]` change the width by 1 within 1..=256 while an outline is open. // With `pressure_width` on, a pen sample at pressure 0.5 halves the searched width (minus one); a mouse sample never diff --git a/crates/ui-canvas/src/canvas/snap.rs b/crates/ui-canvas/src/canvas/snap.rs index 2f3968553..13c0f6ae9 100644 --- a/crates/ui-canvas/src/canvas/snap.rs +++ b/crates/ui-canvas/src/canvas/snap.rs @@ -28,7 +28,6 @@ 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). - // P3(canvas-widgets-w3): cw.C16 `kinds` pub kinds: craft_behavior::geometry::SnapKinds, } @@ -40,22 +39,32 @@ impl Snap { /// `position` across a guide running `along`, snapped. pub fn apply(&self, along: Axis, position: f64, mods: Mods) -> f64 { - let Some(tolerance) = self.tolerance.filter(|_| self.options.on && !snap_suspended(mods, self.os, false)) else { - return position; - }; + let Some(tolerance) = self.reach(mods, false) else { return position }; self.targets.nearest(along, position, tolerance).map_or(position, |target| target.position) } - /// `point` snapped on both axes, with the lines to draw; the input and no lines when snapping is off. + /// `point` snapped on both axes to the targets of `gesture.kinds`, with the lines to draw; the input and no lines + /// when snapping is off. pub fn point(&self, point: Point, mods: Mods, gesture: GestureSnap) -> (Point, Vec) { - let _ = (point, mods, gesture); - todo!("cw.C16") + match self.reach(mods, gesture.reads_control) { + Some(tolerance) => self.targets.snap_point_of(point, tolerance, gesture.kinds), + None => (point, Vec::new()), + } } /// The offset that moves `rect` onto a snap target, with the lines to draw; zero when snapping is off. pub fn rect(&self, rect: craft_behavior::kurbo::Rect, mods: Mods) -> (Vec2, Vec) { - let _ = (rect, mods); - todo!("cw.C16") + match self.reach(mods, false) { + Some(tolerance) => self.targets.snap_rect(rect, tolerance), + None => (Vec2::ZERO, Vec::new()), + } + } + + /// The snapping distance in document units for this pass, or `None` when snapping is off, the canvas has not given + /// this snap its pass ([`at`](Self::at)) or the Control key suspends it (unless `reads_control`): the one gate of + /// `apply`, `point` and `rect`, and the reach a gesture's snapped lines were found with. + pub fn reach(&self, mods: Mods, reads_control: bool) -> Option { + self.tolerance.filter(|_| self.options.on && !snap_suspended(mods, self.os, reads_control)) } /// The View > Snap To options this snap was built with. @@ -64,7 +73,6 @@ impl Snap { } /// This snap with its tolerance for `view` and the OS set. - #[allow(dead_code)] // P3(canvas-widgets-w3): cw.C16 pub(super) fn at(mut self, view: &CanvasView, os: Platform) -> Self { self.tolerance = Some(view.doc_len(SNAP_PX as f32)); self.os = os; @@ -80,7 +88,8 @@ impl PartialEq for Snap { impl std::fmt::Debug for Snap { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - f.write_str("Snap") + // The targets can number thousands of grid lines, so they are left out. + f.debug_struct("Snap").field("options", &self.options).field("tolerance", &self.tolerance).field("os", &self.os).finish_non_exhaustive() } } diff --git a/crates/ui-canvas/src/canvas/testing/tool_fixture.rs b/crates/ui-canvas/src/canvas/testing/tool_fixture.rs index dc63dcafc..566c263b4 100644 --- a/crates/ui-canvas/src/canvas/testing/tool_fixture.rs +++ b/crates/ui-canvas/src/canvas/testing/tool_fixture.rs @@ -1,7 +1,7 @@ //! `ToolFixture` (22.4, the tool row): drives a [`CanvasTool`] on a [`Canvas`] through press, drag, release and //! Escape, and checks what every tool owes the canvas. -use crate::canvas::{Canvas, CanvasTool, ToolHost, ToolPath}; +use crate::canvas::{Canvas, CanvasTool, Snap, ToolHost, ToolPath}; use crate::contract::{BodyCx, ShowContainer as _}; use crate::runtime::access::Role; use crate::testing::{Fixture, Target, pointer}; @@ -39,7 +39,7 @@ impl ToolFixture { /// A canvas named `label` whose body `body` fills: canvas controls shown at the body's rect join the canvas's /// arena, and a press on one of their parts never reaches the tool. pub fn with_body(label: &'static str, tool: T, body: impl FnMut(&mut Ui, &mut BodyCx<'_>) + 'static) -> Self { - Self::shown(label, tool, None, body) + Self::shown(label, tool, None, None, body) } /// [`ToolFixture::with_body`] over a canvas given the view `view` makes of the canvas's room, so the body's @@ -50,13 +50,26 @@ impl ToolFixture { view: impl Fn(Rect) -> CanvasView + 'static, body: impl FnMut(&mut Ui, &mut BodyCx<'_>) + 'static, ) -> Self { - Self::shown(label, tool, Some(Box::new(view)), body) + Self::shown(label, tool, Some(Box::new(view)), None, body) + } + + /// [`ToolFixture::with_view`] over a canvas that snaps with `snap` ([`Canvas::snap`]): the tool's + /// `ToolContext::snap` and `snap_rect`, and the body's controls through `canvas_snap`, snap to its targets. + pub fn with_snap( + label: &'static str, + tool: T, + view: impl Fn(Rect) -> CanvasView + 'static, + snap: Snap, + body: impl FnMut(&mut Ui, &mut BodyCx<'_>) + 'static, + ) -> Self { + Self::shown(label, tool, Some(Box::new(view)), Some(snap), body) } fn shown( label: &'static str, tool: T, view: Option CanvasView>>, + snap: Option, mut body: impl FnMut(&mut Ui, &mut BodyCx<'_>) + 'static, ) -> Self { let tool = Rc::new(RefCell::new(tool)); @@ -69,6 +82,9 @@ impl ToolFixture { if let Some(view) = &view { shown_canvas = shown_canvas.view(view(ui.available_rect_before_wrap())); } + if let Some(snap) = &snap { + shown_canvas = shown_canvas.snap(snap.clone()); + } let canvas = shown_canvas.show(ui, &mut body); id.set(canvas.output.response.id); let reply = ToolHost::new().enabled(on.get()).run(ui, &canvas.output, &mut *shown.borrow_mut()); diff --git a/crates/ui-canvas/src/canvas_controls/guides/mod.rs b/crates/ui-canvas/src/canvas_controls/guides/mod.rs index ab9ad0548..b21b762b5 100644 --- a/crates/ui-canvas/src/canvas_controls/guides/mod.rs +++ b/crates/ui-canvas/src/canvas_controls/guides/mod.rs @@ -6,6 +6,8 @@ pub mod reading; #[cfg(feature = "testing")] mod stories; +pub use reading::{GuideReading, running}; + use super::words::CanvasControlWords; use crate::canvas::{ CanvasSpace, Guide, GuideDrag, GuideKey, GuideLine, LABEL_STEP_MIN, NUDGE, NUDGE_FAR, Snap, canvas_snap, canvas_space, context_menu, readout, @@ -115,7 +117,8 @@ struct PendingKey(Option); /// The ruler guides of a canvas: drawn, taken by the pointer and moved with the keyboard. /// -/// - The pointer takes an unlocked guide while the guides are [`interactive`](Guides::interactive). A drag moves it; +/// - The pointer takes an unlocked guide while the guides are [`interactive`](Guides::interactive), or with the +/// platform command key held at the press when they [`move with command`](Guides::moves_with_command). A drag moves it; /// the release commits where it is, or removes the guide outside the [`bounds`](Guides::bounds) or the canvas. /// Escape cancels the drag. /// - Shift snaps to the ruler's ticks; otherwise the canvas's [`Snap`] places the guide and gets the @@ -145,7 +148,6 @@ pub struct Guides<'a> { interactive: bool, /// With `interactive` off, a press on an unlocked guide with the platform command key held takes the guide. #[prop] - #[allow(dead_code)] // P3(canvas-widgets-w2): cw.C22 moves_with_command: bool, /// Where guides may live, in document units; a guide released outside is removed. Without bounds, the canvas. #[prop] @@ -456,9 +458,14 @@ impl Component for Guides<'_> { } /// The unlocked guides in view: edge-level drag parts in one roving group, in keyboard order. Page Up and Page - /// Down move the group's arrival; the arrows are the guide's nudge. + /// Down move the group's arrival; the arrows are the guide's nudge. With `interactive` off they are declared only + /// for `moves_with_command`, while the command key is held or the guides' own drag runs, so a guide drag begun + /// with the key keeps its part when the key is let go mid-drag; `run_pointer` reads only declared parts, so this + /// is the one gate of the pointer. fn parts(&mut self, rect: egui::Rect, cx: &mut PartsCx<'_, Self>) { - let (Some(space), Some(guides), true) = (canvas_space(&cx.env), cx.value(), self.interactive) else { return }; + let takes = self.interactive + || (self.moves_with_command && (crate::runtime::pointer::frame(cx.ui.ctx()).mods.cmd || cx.gesture_running())); + let (Some(space), Some(guides), true) = (canvas_space(&cx.env), cx.value(), takes) else { return }; let mut any = false; for &at in &place::keyboard_order(guides) { let guide = &guides[at]; @@ -485,8 +492,9 @@ impl Component for Guides<'_> { if let Some(drag) = self.pending { self.run_pending(cx, &space, &guides, drag); } + // `parts` declares the guides only when the pointer may take them, and `run_pointer` reads declared parts only. + self.run_pointer(cx, &space, &guides); if self.interactive { - self.run_pointer(cx, &space, &guides); self.run_keys(cx, &space, &guides); self.run_canvas_delete(cx, &space, &guides); if space.background().pressed.is_some() && self.selected.is_some() && self.report.select.is_none() { diff --git a/crates/ui-canvas/src/canvas_controls/smart_guides/mod.rs b/crates/ui-canvas/src/canvas_controls/smart_guides/mod.rs index 77ec0dd56..265c9b2b1 100644 --- a/crates/ui-canvas/src/canvas_controls/smart_guides/mod.rs +++ b/crates/ui-canvas/src/canvas_controls/smart_guides/mod.rs @@ -11,7 +11,7 @@ use crate::runtime::env::Units; use crate::style::{ComponentStyle, DataColor, RuleLook, RuleWidth, StyleColor, StyleCx, TypeRole, UiTokens}; use craft_behavior::geometry::SnapLine; use craft_behavior::kurbo::{Point, Rect as DocRect}; -use craft_behavior::{CanvasView, Metrics, Sense}; +use craft_behavior::{Axis, CanvasView, Metrics, Sense}; use craft_theme::{Rgba, contrast_ratio}; use egui::emath::GuiRounding as _; use egui::{Color32, CornerRadius, Pos2, Response, Vec2}; @@ -36,8 +36,14 @@ impl SmartLine { /// The line of `line` the host draws for a snap: a line with no span runs across `visible`. pub fn of(line: &SnapLine, visible: DocRect) -> SmartLine { - let _ = (line, visible); - todo!("cw.C18") + let visible = visible.abs(); + if line.along == Axis::Y { + let (y0, y1) = line.span.unwrap_or((visible.y0, visible.y1)); + SmartLine::new(Point::new(line.position, y0), Point::new(line.position, y1)) + } else { + let (x0, x1) = line.span.unwrap_or((visible.x0, visible.x1)); + SmartLine::new(Point::new(x0, line.position), Point::new(x1, line.position)) + } } /// The same line as a dashed extension. diff --git a/crates/ui-canvas/tests/it/canvas/mod.rs b/crates/ui-canvas/tests/it/canvas/mod.rs index 261607ab9..dc8238b8a 100644 --- a/crates/ui-canvas/tests/it/canvas/mod.rs +++ b/crates/ui-canvas/tests/it/canvas/mod.rs @@ -16,6 +16,8 @@ mod raster; mod scrollbars; +mod snap; + mod split; mod story_canvas; diff --git a/crates/ui-canvas/tests/it/canvas/snap.rs b/crates/ui-canvas/tests/it/canvas/snap.rs new file mode 100644 index 000000000..33792446e --- /dev/null +++ b/crates/ui-canvas/tests/it/canvas/snap.rs @@ -0,0 +1,117 @@ +//! `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. + +use craft_behavior::geometry::{SnapKind, SnapOptions, SnapTarget, SnapTargets}; +use craft_behavior::kurbo::{Point, Rect as DocRect, Vec2}; +use craft_behavior::{Axis, CancelReason, CanvasView}; +use craft_keymap::{Mods, Platform}; +use craft_ui::canvas::{CanvasTool, GestureSnap, Snap, ToolAction, ToolContext, ToolPath, ToolPointer, canvas_snap}; +use craft_ui::primitives::Draw; +use craft_ui::testing::{ToolFixture, trial}; +use egui::{Modifiers, Rect}; +use std::cell::RefCell; +use std::rc::Rc; +use std::sync::Arc; + +/// The point the recording tool snaps each pass: 3 document units from the vertical guide at x = 100 and 2 from the +/// horizontal one at y = 200. +const NEAR: Point = Point::new(103.0, 198.0); + +/// A tool that snaps [`NEAR`] through its context every pass, as a tool snaps the pointer. +#[derive(Default)] +struct Recorder { + snapped: Vec, +} + +impl CanvasTool for Recorder { + fn each_pass(&mut self, cx: &mut ToolContext<'_>) { + self.snapped.push(cx.snap(NEAR)); + } + + fn press(&mut self, _: &ToolPointer, _: &mut ToolContext<'_>) -> ToolAction { + ToolAction::Claimed + } + + fn drag(&mut self, _: &ToolPointer, _: &mut ToolContext<'_>) {} + + fn release(&mut self, _: &ToolPointer, _: &mut ToolContext<'_>) {} + + fn cancel(&mut self, _: CancelReason, _: &mut ToolContext<'_>) {} + + fn paint(&self, _: &Draw<'_>, _: &ToolContext<'_>) {} + + fn command_form(&self) -> ToolPath { + ToolPath::Command("the Select Area... command") + } +} + +fn targets() -> Arc { + let mut targets = SnapTargets::new(); + targets.add(SnapTarget::new(Axis::Y, 100.0, SnapKind::Guide)); + targets.add(SnapTarget::new(Axis::X, 200.0, SnapKind::Guide)); + Arc::new(targets) +} + +/// A canvas at zoom 2 over `snap`, and the snap its body read in the last pass. +fn rig(snap: Snap) -> (ToolFixture, Rc>>) { + let seen = Rc::new(RefCell::new(None)); + let body = Rc::clone(&seen); + let view = |room: Rect| CanvasView::new(room, Point::new(150.0, 150.0), 2.0); + let fixture = ToolFixture::with_snap("Document", Recorder::default(), view, snap, move |_, cx| { + *body.borrow_mut() = canvas_snap(&cx.env); + }); + (fixture, seen) +} + +/// The tool's last snapped point after one pass with `mods` held. +fn snapped_with(fixture: &mut ToolFixture, mods: Modifiers) -> Point { + fixture.fixture().hold(mods).frame(Vec::new()); + *fixture.tool().snapped.last().expect("the tool ran") +} + +// 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. +#[trial] +fn snap_targets_snap_points_and_boxes_unless_control_suspends() { + let options = SnapOptions::default(); + let (mut fixture, seen) = rig(Snap::new(targets(), options)); + fixture.fixture().os(Platform::Mac).frame(Vec::new()); + let snap = seen.borrow().clone().expect("the canvas publishes its snap to its body"); + assert_eq!(snap.options(), options); + + assert_eq!(snap.apply(Axis::Y, 103.0, Mods::NONE), 100.0, "3 units off at zoom 2 snaps"); + assert_eq!(snap.apply(Axis::Y, 105.0, Mods::NONE), 105.0, "5 units off at zoom 2 does not"); + let (point, lines) = snap.point(NEAR, Mods::NONE, GestureSnap::default()); + assert_eq!(point, Point::new(100.0, 200.0)); + assert_eq!(lines.len(), 2, "{lines:?}"); + let (by, lines) = snap.rect(DocRect::new(60.0, 10.0, 97.0, 40.0), Mods::NONE); + assert_eq!(by, Vec2::new(3.0, 0.0), "the right edge meets the guide"); + assert!(lines.iter().any(|line| line.along == Axis::Y && line.position == 100.0 && line.kind == SnapKind::Guide), "{lines:?}"); + assert_eq!(snapped_with(&mut fixture, Modifiers::NONE), Point::new(100.0, 200.0), "the tool snaps through the host"); + + // macOS: Control suspends, Cmd does not. + assert_eq!(snap.apply(Axis::Y, 103.0, Mods::CTRL), 103.0); + assert_eq!(snap.apply(Axis::Y, 103.0, Mods::CMD), 100.0); + assert_eq!(snap.point(NEAR, Mods::CTRL, GestureSnap { reads_control: true, ..GestureSnap::default() }).0, Point::new(100.0, 200.0), "a gesture that reads Control keeps snapping"); + assert_eq!(snap.rect(DocRect::new(60.0, 10.0, 97.0, 40.0), Mods::CTRL), (Vec2::ZERO, Vec::new())); + assert_eq!(snapped_with(&mut fixture, Modifiers::CTRL), NEAR, "Control held suspends the tool's snap"); + + // Elsewhere Ctrl is the command key, and it suspends. + fixture.fixture().hold(Modifiers::NONE).os(Platform::Windows).frame(Vec::new()); + let snap = seen.borrow().clone().expect("the canvas publishes its snap to its body"); + assert_eq!(snap.apply(Axis::Y, 103.0, Mods::CMD), 103.0); + 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"); + + let mut off = options; + off.on = false; + let (mut fixture, seen) = rig(Snap::new(targets(), off)); + fixture.fixture().frame(Vec::new()); + let snap = seen.borrow().clone().expect("the canvas publishes its snap to its body"); + assert_eq!(snap.apply(Axis::Y, 103.0, Mods::NONE), 103.0, "View > Snap off"); + assert_eq!(snap.point(NEAR, Mods::NONE, GestureSnap::default()), (NEAR, Vec::new())); + assert_eq!(snap.rect(DocRect::new(60.0, 10.0, 97.0, 40.0), Mods::NONE), (Vec2::ZERO, Vec::new())); + assert_eq!(snapped_with(&mut fixture, Modifiers::NONE), NEAR); +} diff --git a/crates/ui-canvas/tests/it/canvas_controls/guides.rs b/crates/ui-canvas/tests/it/canvas_controls/guides.rs new file mode 100644 index 000000000..5d6b7c182 --- /dev/null +++ b/crates/ui-canvas/tests/it/canvas_controls/guides.rs @@ -0,0 +1,187 @@ +//! `Guides` on a `Canvas`: which presses take a guide, and where a dragged guide lands or goes. + +use craft_behavior::geometry::{SnapKind, SnapOptions, SnapTarget, SnapTargets}; +use craft_behavior::kurbo::{Point, Rect as DocRect}; +use craft_behavior::{Axis, CancelReason, CanvasView}; +use craft_ui::canvas::{CanvasTool, Guide, GuideKey, Rulers, Snap, ToolAction, ToolContext, ToolPath, ToolPointer}; +use craft_ui::canvas_controls::Guides; +use craft_ui::contract::{Bind, Show as _}; +use craft_ui::primitives::Draw; +use craft_ui::testing::{ToolFixture, pointer, trial}; +use egui::{Modifiers, Pos2, Rect, Vec2, pos2, vec2}; +use std::cell::{Cell, RefCell}; +use std::rc::Rc; +use std::sync::Arc; + +/// A tool that counts the presses that reach it. +#[derive(Default)] +struct Recorder { + presses: usize, +} + +impl CanvasTool for Recorder { + fn press(&mut self, _: &ToolPointer, _: &mut ToolContext<'_>) -> ToolAction { + self.presses += 1; + ToolAction::Claimed + } + + fn drag(&mut self, _: &ToolPointer, _: &mut ToolContext<'_>) {} + + fn release(&mut self, _: &ToolPointer, _: &mut ToolContext<'_>) {} + + fn cancel(&mut self, _: CancelReason, _: &mut ToolContext<'_>) {} + + fn paint(&self, _: &Draw<'_>, _: &ToolContext<'_>) {} + + fn command_form(&self) -> ToolPath { + ToolPath::Command("the Select Area... command") + } +} + +type Shared = Rc>; + +/// The view at `zoom` that shows the room's centre at the same document point, so at zoom 1 document and screen +/// points coincide. +fn view_at(zoom: f64) -> impl Fn(Rect) -> CanvasView + 'static { + move |room: Rect| { + let centre = room.center(); + CanvasView::new(room, Point::new(f64::from(centre.x), f64::from(centre.y)), zoom) + } +} + +fn guide(key: u64, along: Axis, position: f64) -> Guide { + Guide::new(GuideKey::new(key), along, position) +} + +/// The guide at `position` running `along`, if there is one. +fn at(guides: &Shared>, along: Axis, position: f64) -> Option { + guides.borrow().iter().find(|guide| guide.along == along && (guide.position - position).abs() < 1e-9).cloned() +} + +// With `interactive` off and `moves_with_command` on, a Cmd drag on an unlocked guide moves it and the tool gets +// nothing; a plain press on it, and a Cmd press on a locked guide, reach the tool. +#[trial] +fn a_command_press_takes_a_guide_when_the_guides_are_not_interactive() { + let mut locked = guide(2, Axis::Y, 400.0); + locked.locked = true; + let guides: Shared> = Rc::new(RefCell::new(vec![guide(1, Axis::Y, 200.0), locked])); + let shown = Rc::clone(&guides); + let mut fixture = ToolFixture::with_view("Document", Recorder::default(), view_at(1.0), move |ui, cx| { + let _ = Guides::new("Guides", Bind::bound(&mut *shown.borrow_mut())).moves_with_command(true).show_at(ui, cx.rect); + }); + + fixture.fixture().hold(Modifiers::COMMAND); + fixture.drag_from(pos2(200.0, 300.0), vec2(40.0, 0.0)); + assert!(at(&guides, Axis::Y, 240.0).is_some(), "a Cmd drag moves the guide: {:?}", guides.borrow()); + assert_eq!(fixture.tool().presses, 0, "the tool gets nothing"); + + fixture.fixture().hold(Modifiers::NONE); + fixture.drag_from(pos2(240.0, 300.0), vec2(40.0, 0.0)); + assert!(at(&guides, Axis::Y, 240.0).is_some(), "a plain drag leaves the guide: {:?}", guides.borrow()); + assert_eq!(fixture.tool().presses, 1, "a plain press reaches the tool"); + + fixture.fixture().hold(Modifiers::COMMAND); + fixture.drag_from(pos2(400.0, 300.0), vec2(40.0, 0.0)); + fixture.fixture().hold(Modifiers::NONE); + assert!(at(&guides, Axis::Y, 400.0).is_some_and(|guide| guide.locked), "the locked guide stays: {:?}", guides.borrow()); + assert_eq!(fixture.tool().presses, 2, "a Cmd press on a locked guide reaches the tool"); + + // A tool drag begun off every guide with no key crosses the guide at 240: the guide declares no part, so the tool + // keeps the drag and the guide stays. + fixture.drag_from(pos2(100.0, 300.0), vec2(200.0, 0.0)); + assert!(at(&guides, Axis::Y, 240.0).is_some(), "a tool drag across a guide leaves it: {:?}", guides.borrow()); + assert_eq!(fixture.tool().presses, 3, "the press reaches the tool"); +} + +/// Where guides may live, in document units. +const BOUNDS: DocRect = DocRect::new(100.0, 100.0, 600.0, 400.0); + +/// A canvas at `zoom` that snaps to horizontal guide targets at y = 224.3 and y = 250.3, its body showing rulers and +/// interactive guides kept inside [`BOUNDS`], in a room that holds the bounds with a margin, so a release outside them +/// still lands on the canvas; the body's rect, read each pass. +fn ruled(zoom: f64, guides: &Shared>) -> (ToolFixture, Rc>) { + let mut targets = SnapTargets::new(); + targets.add(SnapTarget::new(Axis::X, 224.3, SnapKind::Guide)); + targets.add(SnapTarget::new(Axis::X, 250.3, SnapKind::Guide)); + let snap = Snap::new(Arc::new(targets), SnapOptions::default()); + let (shown, zero) = (Rc::clone(guides), Rc::new(RefCell::new(Point::ZERO))); + let body = Rc::new(Cell::new(Rect::NOTHING)); + let seen = Rc::clone(&body); + let mut fixture = ToolFixture::with_snap("Document", Recorder::default(), view_at(zoom), snap, move |ui, cx| { + seen.set(cx.rect); + let rulers = Rulers::new("Rulers", Bind::bound(&mut *zero.borrow_mut())).show_at(ui, cx.rect); + let mut guides = shown.borrow_mut(); + let mut control = Guides::new("Guides", Bind::bound(&mut *guides)).interactive(true).bounds(BOUNDS); + if let Some(drag) = rulers.guide { + control = control.pending(drag); + } + let _ = control.show_at(ui, cx.rect); + }); + fixture.fixture().room(Vec2::new(700.0, 500.0)).settle(); + (fixture, body) +} + +/// A drag with `mods` held from `from` to `to`. +fn drag_with(fixture: &mut ToolFixture, mods: Modifiers, from: Pos2, to: Pos2) { + fixture.fixture().hold(mods); + fixture.drag_from(from, to - from); + fixture.fixture().hold(Modifiers::NONE); +} + +// At zoom 1 (document and screen points coincide): a guide dragged out of the top ruler is horizontal and snaps to the +// target; with Alt it is vertical; with Shift it lands on a ruler tick, a whole pixel, and not on the target; with +// Shift just inside the document's edge it lands on the edge and stays. A drag out released back on a ruler or +// outside the bounds adds nothing, and a guide dragged off the bounds is removed. At zoom 8 a Shift drag still lands +// on a whole pixel. +#[trial] +fn a_dragged_guide_is_removed_off_the_bounds_or_on_a_ruler_and_alt_and_shift_change_where_it_lands() { + let guides: Shared> = Rc::new(RefCell::new(Vec::new())); + let (mut fixture, body) = ruled(1.0, &guides); + let rect = body.get(); + // Inside the top strip, clear of the corner, and inside the left strip. + let top = |x: f32| pos2(x, rect.min.y + 4.0); + let left = |y: f32| pos2(rect.min.x + 4.0, y); + + drag_with(&mut fixture, Modifiers::NONE, top(300.0), pos2(300.0, 247.6)); + assert!(at(&guides, Axis::X, 250.3).is_some(), "out of the top ruler: horizontal, snapped: {:?}", guides.borrow()); + + // 222.6 is 1.7 from the target at 224.3; the ruler's minor ticks at zoom 1 are 10 pixels apart. + drag_with(&mut fixture, Modifiers::SHIFT, top(300.0), pos2(300.0, 222.6)); + let ticked: Vec = guides.borrow().iter().filter(|guide| guide.along == Axis::X && guide.position != 250.3).map(|guide| guide.position).collect(); + assert!( + matches!(ticked.as_slice(), [tick] if tick.fract() == 0.0 && (tick - 222.6).abs() <= 10.0), + "Shift lands on a tick, not on the snap target: {:?}", + guides.borrow() + ); + + drag_with(&mut fixture, Modifiers::ALT, top(350.0), pos2(350.0, 300.0)); + assert!(at(&guides, Axis::Y, 350.0).is_some(), "Alt turns a guide out of the top ruler vertical: {:?}", guides.borrow()); + + drag_with(&mut fixture, Modifiers::SHIFT, top(300.0), pos2(300.0, 399.4)); + assert!(at(&guides, Axis::X, 400.0).is_some(), "Shift inside the edge lands on it and stays: {:?}", guides.borrow()); + + let count = guides.borrow().len(); + let from = left(300.0); + fixture.fixture().frame(vec![pointer::moved(from)]); + fixture.fixture().frame(vec![pointer::press(from)]); + fixture.fixture().frame(vec![pointer::moved(pos2(380.0, 300.0))]); + fixture.fixture().frame(vec![pointer::moved(from + Vec2::new(0.0, 10.0))]); + fixture.fixture().frame(vec![pointer::release(from + Vec2::new(0.0, 10.0))]); + fixture.fixture().frame(Vec::new()); + assert_eq!(guides.borrow().len(), count, "a guide dropped back on its ruler is not added: {:?}", guides.borrow()); + + drag_with(&mut fixture, Modifiers::NONE, top(300.0), pos2(300.0, 480.0)); + assert_eq!(guides.borrow().len(), count, "a guide dropped outside the bounds is not added: {:?}", guides.borrow()); + + drag_with(&mut fixture, Modifiers::NONE, pos2(450.0, 250.3), pos2(450.0, 450.3)); + assert!(at(&guides, Axis::X, 250.3).is_none(), "a guide dragged off the bounds is removed: {:?}", guides.borrow()); + assert_eq!(guides.borrow().len(), count - 1); + + let deep: Shared> = Rc::new(RefCell::new(Vec::new())); + let (mut fixture, body) = ruled(8.0, &deep); + let rect = body.get(); + let centre = rect.center(); + drag_with(&mut fixture, Modifiers::SHIFT, pos2(centre.x, rect.min.y + 4.0), centre + Vec2::new(0.0, 13.0)); + let landed: Vec = deep.borrow().iter().map(|guide| guide.position).collect(); + assert!(matches!(landed.as_slice(), [tick] if tick.fract() == 0.0), "Shift deep in lands on a whole pixel: {landed:?}"); +} diff --git a/crates/ui-canvas/tests/it/canvas_controls/mod.rs b/crates/ui-canvas/tests/it/canvas_controls/mod.rs index 0cae77564..ba9e9ac03 100644 --- a/crates/ui-canvas/tests/it/canvas_controls/mod.rs +++ b/crates/ui-canvas/tests/it/canvas_controls/mod.rs @@ -4,4 +4,6 @@ mod brush; mod grid; +mod guides; + mod marquee; diff --git a/crates/ui-contract/src/contract/cx/parts.rs b/crates/ui-contract/src/contract/cx/parts.rs index 019678ecc..6aa318dd0 100644 --- a/crates/ui-contract/src/contract/cx/parts.rs +++ b/crates/ui-contract/src/contract/cx/parts.rs @@ -272,6 +272,7 @@ pub struct PartsCx<'a, C: Component> { pub(crate) scrolls: &'a mut Vec, pub(crate) text: &'a mut crate::contract::text::TextStep, pub(crate) last_state: (bool, bool), + pub(crate) gesture_running: bool, pub(crate) measure: MeasureCx<'a, C>, /// What the shape laid out before `parts`: a collection's rows as the item step places them this pass, a /// container's header slots. @@ -341,6 +342,12 @@ impl PartsCx<'_, C> { self.last_state.1 } + /// The component's value gesture runs: begun in an earlier pass and not yet committed or cancelled. A part that + /// only a gesture keeps declared reads it. + pub fn gesture_running(&self) -> bool { + self.gesture_running + } + /// Declares a part; a repeated part is named with its index: `cx.part(POINT.at(id), shape)`. pub fn part(&mut self, part: impl Into, shape: impl Into) -> PartBuilder<'_> { let part = part.into(); diff --git a/crates/ui-contract/src/contract/run/typed.rs b/crates/ui-contract/src/contract/run/typed.rs index 95c6c92ba..92605ddcc 100644 --- a/crates/ui-contract/src/contract/run/typed.rs +++ b/crates/ui-contract/src/contract/run/typed.rs @@ -4,7 +4,7 @@ use super::{Erased, ErasedPass, Host, HostCx, LeafHooks, Measuring, ShapeHooks, ShowAt, TypeFacts, blank_core, paint_ui}; use crate::contract::PaintUi; -use crate::contract::cx::{CxCore, PartsCx}; +use crate::contract::cx::{CxCore, PartsCx, gesture_key}; use crate::contract::steps::{self, MeasureIn, PartsStep, ShapeKind}; use crate::contract::{ Access, BodyCx, Collection, Common, Component, Container, Cx, Inner, Internal, ItemFn, Meta, OverlayUi, Resolved, Show, TipFn, Validity, ValueOf, @@ -19,7 +19,7 @@ use crate::runtime::memory::{MemoryStage, sub}; use crate::runtime::overlay::CloseReason; use crate::runtime::reads::{self, BindKey}; use crate::style::{Flags, StateSet, StyleCx, StyleView, UiTokens}; -use craft_behavior::{EditEvent, Flow, ItemSource, KeyRole, PartRef, Proposal, Roving, Sense}; +use craft_behavior::{EditEvent, Flow, Gesture, ItemSource, KeyRole, PartRef, Proposal, Roving, Sense}; use craft_theme::Variant; use egui::{Context, Id, Rect, Ui, Vec2}; use std::collections::HashMap; @@ -283,6 +283,7 @@ impl<'a, C: Component> ErasedPass<'a> for TypedPass<'_, 'a, C> { scrolls: &mut parts.scrolls, text: &mut parts.text, last_state: last, + gesture_running: self.cx.core.memory.recall::>>(gesture_key(id)).is_running(), measure, items: geometry, }; @@ -740,6 +741,7 @@ pub(crate) fn member_prepare(ui: &Ui, env: &Env, id: Id, row: Rect, hov scrolls: &mut parts.scrolls, text: &mut parts.text, last_state: (hovered, false), + gesture_running: false, measure: steps::measure_cx::(&input, &style, &resolved, shown.as_deref()), items: None, }; diff --git a/migration/api-map/imaging-select-tools.toml b/migration/api-map/imaging-select-tools.toml index 1737ae8db..1bcf8d831 100644 --- a/migration/api-map/imaging-select-tools.toml +++ b/migration/api-map/imaging-select-tools.toml @@ -155,8 +155,20 @@ new = "size() -> craft_behavior::PixelSize" [[setter]] type = "InsideDrag" old = "begin(&ConstrainStyle, DragKind, Point, Modifiers)" -new = "begin(&ConstrainStyle, DragKind, Point, Mods, GestureId, Arc)" -note = "The id and the undo step's name come from the caller; the Begin event carries the zero delta as its value before." +new = "begin(&ConstrainStyle, DragKind, Point, Mods, GestureId, Arc, Option)" +note = "The id and the undo step's name come from the caller; the Begin event carries the zero delta as its value before. The last argument is the selection's bounds at the press (SelectionProbe::bounds), which snap as the drag moves; None leaves the drag unsnapped. The point is the raw document point." + +[[setter]] +type = "InsideDrag" +old = "drag(Point, Modifiers, f64)" +new = "drag(Point, Mods, f64, &mut dyn FnMut(kurbo::Rect) -> Vec2)" +note = "The raw document point; the closure is the tool's ToolContext::snap_rect, called with the press bounds moved by the drag before the delta rounds to whole pixels." + +[[setter]] +type = "InsideDrag" +old = "end(Point, Modifiers, f64)" +new = "end(Point, Mods, f64, &mut dyn FnMut(kurbo::Rect) -> Vec2)" +note = "Snaps as drag does; the Commit carries the whole-pixel delta." [[setter]] type = "InsideDrag"