diff --git a/crates/draw/src/ui/crop/perspective_crop.rs b/crates/draw/src/ui/crop/perspective_crop.rs index 413a3edde..8799a0a4e 100644 --- a/crates/draw/src/ui/crop/perspective_crop.rs +++ b/crates/draw/src/ui/crop/perspective_crop.rs @@ -119,6 +119,9 @@ struct Report { /// - Shift on a corner drag keeps the axis the pointer moved less along; Alt on a corner of an upright quad moves the /// neighbouring corners too, so it stays a rectangle. /// - With a `shield` the document outside a valid quad is dimmed, under the grid. +/// - With `bounds` a drag or an arrow key stops each corner it moves at the bounds' edge; a whole-quad move stops when +/// its farthest corner reaches the edge, so the quad keeps its shape. The shield then dims the bounds outside the +/// quad. /// - The corners stay where the user puts them: a quad wound counter-clockwise (a box flipped on one axis) applies /// mirrored, a box turned half way round applies upside down. /// - A quad that is not convex draws in the invalid colour without the grid and cannot be committed. @@ -140,10 +143,9 @@ pub struct PerspectiveCropQuad<'a> { /// The shield painted over the document outside a valid quad; `None` paints none. #[prop] shield: Option, - /// The rectangle every corner stays inside while dragged or moved by keys, in document units; `None` leaves the - /// corners unbounded. + /// The rectangle every corner stays inside while dragged or moved by keys, in document units; the shield covers it + /// outside the quad. `None` leaves the corners unbounded and shields the whole document. #[prop] - #[allow(dead_code)] // P3(pdf-print-ocr-w3): PO-P16 bounds: Option, report: Report, } @@ -239,6 +241,43 @@ fn dragged(drag: &Drag, to: Point, mods: Mods) -> [Point; 4] { } } +/// The quad `after` that `grab` made of `before`, kept inside `bounds`. +/// +/// - A corner grab clamps each coordinate it moved. A coordinate nothing moved stays as it lies, even outside the +/// bounds: that corner is the caller's. So a click with no drag changes nothing, and Alt's neighbours, clamped from +/// the same coordinate as the corner, keep the rectangle. +/// - A move shifts the whole quad back by the overshoot of its farthest corner on each axis, so it keeps its shape. +/// - Nothing is pushed further out than `before` lay: the allowed range on each axis takes in what `before` covered. +fn clamped(before: &[Point; 4], after: [Point; 4], grab: Grab, bounds: Option) -> [Point; 4] { + let Some(b) = bounds.map(|b| b.abs()) else { return after }; + match grab { + Grab::Corner { .. } => { + // `max` then `min` rather than `f64::clamp`, which panics on reversed or NaN limits. + let keep = |was: f64, to: f64, lo: f64, hi: f64| to.max(lo.min(was)).min(hi.max(was)); + std::array::from_fn(|i| Point::new(keep(before[i].x, after[i].x, b.x0, b.x1), keep(before[i].y, after[i].y, b.y0, b.y1))) + } + Grab::Move => { + let span = |q: &[Point; 4], axis: fn(&Point) -> f64| { + q.iter().map(axis).fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), v| (lo.min(v), hi.max(v))) + }; + let x = kept_in(span(before, |p| p.x), span(&after, |p| p.x), b.x0, b.x1); + let y = kept_in(span(before, |p| p.y), span(&after, |p| p.y), b.y0, b.y1); + after.map(|p| p + DocVec::new(x, y)) + } + } +} + +/// The shift along one axis that brings the span `after` (min, max) inside `lo..hi`, widened to the span `before` +/// covered: the max side is pulled back first, then the min side while the span fits. +fn kept_in(before: (f64, f64), after: (f64, f64), lo: f64, hi: f64) -> f64 { + let (lo, hi) = (lo.min(before.0), hi.max(before.1)); + let mut shift = (hi - after.1).min(0.0); + if after.1 - after.0 <= hi - lo { + shift += (lo - (after.0 + shift)).max(0.0); + } + shift +} + impl PerspectiveCropQuad<'_> { /// Starts the drag of the part pressed at screen point `origin`. fn begin(cx: &mut Cx<'_, Self>, view: &CanvasView, quad: [Point; 4], corner: Option, origin: Pos2) -> Drag { @@ -251,9 +290,9 @@ impl PerspectiveCropQuad<'_> { Drag { grab, at_press: quad, from } } - /// Follows the pointer at screen point `pos`. - fn step(cx: &mut Cx<'_, Self>, view: &CanvasView, drag: &Drag, pos: Pos2, mods: Mods) { - let next = dragged(drag, view.to_doc(pos), mods); + /// Follows the pointer at screen point `pos`, inside `bounds`. + fn step(cx: &mut Cx<'_, Self>, view: &CanvasView, drag: &Drag, pos: Pos2, mods: Mods, bounds: Option) { + let next = clamped(&drag.at_press, dragged(drag, view.to_doc(pos), mods), drag.grab, bounds); if finite(&next) { cx.propose(Some(next)); } @@ -271,15 +310,18 @@ impl PerspectiveCropQuad<'_> { let Some((direction, mods)) = cx.intents().take_nudge() else { return }; let distance = if mods.shift { NUDGE_FAR } else { NUDGE }; let by = screen_step(view, DocVec::new(f64::from(direction.x), f64::from(direction.y)) * distance); - let next = match corner { + let (next, grab) = match corner { Some(index) => { + let index = index as usize; let mut moved = quad; - moved[index as usize] += by; - moved + moved[index] += by; + (moved, Grab::Corner { index, offset: DocVec::ZERO }) } - None => quad.map(|p| p + by), + None => (quad.map(|p| p + by), Grab::Move), }; - if finite(&next) { + let next = clamped(&quad, next, grab, self.bounds); + // A nudge into the bounds' edge leaves the quad as it is and sets nothing. + if finite(&next) && next != quad { cx.set(Some(next)); } } @@ -341,6 +383,7 @@ impl Component for PerspectiveCropQuad<'_> { let space = space_of(&cx.env, cx.rect); let Some(quad) = shown(cx.value()) else { return }; let view = space.view; + let bounds = self.bounds; let mut live = cx.memory::().clone(); let grabs = std::iter::once((PartRef::from(INSIDE), None)).chain((0..CORNERS).map(|at| (CORNER.at(at), Some(at as usize)))); for (part, corner) in grabs { @@ -351,12 +394,12 @@ impl Component for PerspectiveCropQuad<'_> { match press.phase { PressPhase::DragStart { start, pos, .. } if start.button == PointerButton::Primary => { let drag = Self::begin(cx, &view, quad, corner, start.origin); - Self::step(cx, &view, &drag, pos, mods); + Self::step(cx, &view, &drag, pos, mods, bounds); live.drag = Some(drag); } PressPhase::Drag { pos, .. } => { if let Some(drag) = live.drag { - Self::step(cx, &view, &drag, pos, mods); + Self::step(cx, &view, &drag, pos, mods, bounds); } } PressPhase::Release { start, pos, click: false, .. } => { @@ -367,7 +410,7 @@ impl Component for PerspectiveCropQuad<'_> { None => None, }; if let Some(drag) = drag { - Self::step(cx, &view, &drag, pos, mods); + Self::step(cx, &view, &drag, pos, mods, bounds); cx.commit(); } } @@ -388,10 +431,11 @@ impl Component for PerspectiveCropQuad<'_> { let style = &cx.style; let draw = ui.draw(); let screen: Vec = quad.iter().map(|p| view.to_screen(*p)).collect(); - // The shield dims the document outside a quad that can be committed, before the grid. + // The shield dims the bounds, or the whole document, outside a quad that can be committed, before the grid. if valid && let (Some(shield), Some(document)) = (&self.shield, space.document()) { - let (w, h) = (document.width, document.height); - let canvas = [Point::new(0.0, 0.0), Point::new(w, 0.0), Point::new(w, h), Point::new(0.0, h)].map(|p| view.to_screen(p)); + let area = self.bounds.unwrap_or_else(|| DocRect::new(0.0, 0.0, document.width, document.height)); + let canvas = [Point::new(area.x0, area.y0), Point::new(area.x1, area.y0), Point::new(area.x1, area.y1), Point::new(area.x0, area.y1)] + .map(|p| view.to_screen(p)); if let Some(fill) = shield.fill_on(&space, style.canvas.egui(), self.report.dragging) { paint_outside(&draw, canvas, &screen, DataColor::new(fill)); } diff --git a/crates/draw/src/ui/crop/perspective_crop/stories.rs b/crates/draw/src/ui/crop/perspective_crop/stories.rs index 59aa1e1b9..3e3275eed 100644 --- a/crates/draw/src/ui/crop/perspective_crop/stories.rs +++ b/crates/draw/src/ui/crop/perspective_crop/stories.rs @@ -4,7 +4,7 @@ use super::super::{PerspectiveCropTool, PerspectiveInput}; use super::{CORNER, PerspectiveCropQuad, PerspectiveQuad}; use craft_behavior::CanvasView; -use craft_behavior::kurbo::{BezPath, Point}; +use craft_behavior::kurbo::{BezPath, Point, Rect as DocRect}; use craft_ui::canvas::{CropShield, RasterSource as _}; use craft_ui::contract::{Bind, Show as _, Validity}; use craft_ui::runtime::env::Message; @@ -16,6 +16,8 @@ use egui::{Color32, Ui}; const PAGE: [Point; 4] = [Point::new(250.0, 110.0), Point::new(430.0, 130.0), Point::new(400.0, 290.0), Point::new(220.0, 250.0)]; /// The same corners with the last one pulled in: the quad is not convex. const BENT: [Point; 4] = [Point::new(250.0, 110.0), Point::new(430.0, 130.0), Point::new(400.0, 290.0), Point::new(380.0, 150.0)]; +/// A frame a little larger than the page, inside the larger document: the corners of a bounded quad stay in it. +const FRAME: DocRect = DocRect::new(200.0, 90.0, 450.0, 310.0); /// The story document with the page the quad is marked on, as the camera saw it: blue with a dark grey edge. fn paper() -> StoryPicture Color32> { @@ -42,6 +44,21 @@ fn skewed_page(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { on_canvas(ui, |ui, at| PerspectiveCropQuad::new("Perspective crop", Bind::bound(&mut *quad)).shield(CropShield::PERSPECTIVE).show_at(ui, at).edit) } +/// The page's quad kept inside a frame around the page: a corner dragged past the frame stops at its edge, and the +/// shield dims the frame outside the quad. +#[story(PerspectiveCropQuad<'static>, covers = [], drive = Drive::Drag(Grip::part(CORNER.at(0))))] +fn bounded_quad(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { + let quad = data.value("quad", Some(PAGE)); + on_canvas(ui, |ui, at| { + PerspectiveCropQuad::new("Perspective crop", Bind::bound(&mut *quad)) + .show_grid(false) + .shield(CropShield::PERSPECTIVE) + .bounds(FRAME) + .show_at(ui, at) + .edit + }) +} + #[story(PerspectiveCropQuad<'static>, covers = [Invalid], drive = Drive::Drag(Grip::part(CORNER.at(0))))] fn bent_page(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { let quad = data.value("quad", Some(BENT)); diff --git a/crates/draw/tests/it/perspective_crop.rs b/crates/draw/tests/it/perspective_crop.rs index 98e29cccd..57f95daba 100644 --- a/crates/draw/tests/it/perspective_crop.rs +++ b/crates/draw/tests/it/perspective_crop.rs @@ -6,10 +6,12 @@ use std::rc::Rc; use craft_behavior::CanvasView; use craft_behavior::geometry::Constraint; -use craft_behavior::kurbo::{Point, Size}; -use craft_draw::ui::crop::{CropDocKey, PerspectiveCropEvent, PerspectiveCropTool, PerspectiveInput, grid_lines, grid_steps, is_valid}; +use craft_behavior::kurbo::{Point, Rect as DocRect, Size}; +use craft_draw::ui::crop::{ + CropDocKey, PerspectiveCropEvent, PerspectiveCropQuad, PerspectiveCropTool, PerspectiveInput, grid_lines, grid_steps, is_valid, +}; use craft_ui::canvas::{Canvas, ToolHost, tool_pass}; -use craft_ui::contract::ShowContainer as _; +use craft_ui::contract::{Bind, Show as _, ShowContainer as _}; use craft_ui::runtime::access::Role; use craft_ui::testing::{Fixture, trial}; use egui::{Event, Key, Modifiers, PointerButton, Pos2, Vec2}; @@ -18,6 +20,35 @@ const SIZE: Size = Size::new(400.0, 300.0); const SHIFT: Modifiers = Modifiers { shift: true, ..Modifiers::NONE }; const ALT: Modifiers = Modifiers { alt: true, ..Modifiers::NONE }; const BOTH: Modifiers = Modifiers { shift: true, alt: true, ..Modifiers::NONE }; +/// The bounds of the bounded quad, around the upright quad of the trials. +const BOUNDS: DocRect = DocRect::new(60.0, 50.0, 340.0, 240.0); + +/// The screen point of document point `(x, y)` on the fixture's canvas: the view shows (200, 150) at its centre. +fn screen(fixture: &Fixture, x: f64, y: f64) -> Pos2 { + let canvas = fixture.by_role(Role::CANVAS).into_iter().next().expect("a canvas"); + canvas.center() + Vec2::new(x as f32 - 200.0, y as f32 - 150.0) +} + +fn button(fixture: &mut Fixture, at: Pos2, pressed: bool, modifiers: Modifiers) { + fixture.hold(modifiers); + fixture.frame(vec![Event::PointerButton { pos: at, button: PointerButton::Primary, pressed, modifiers }]); +} + +/// A drag in document points over four moves; the last move and the release hold `last`, the others `first`. +fn drag_on(fixture: &mut Fixture, from: (f64, f64), to: (f64, f64), first: Modifiers, last: Modifiers) { + let (from, to) = (screen(fixture, from.0, from.1), screen(fixture, to.0, to.1)); + fixture.hold(first); + fixture.frame(vec![Event::PointerMoved(from)]); + button(fixture, from, true, first); + for step in 1..=4 { + let mods = if step == 4 { last } else { first }; + fixture.hold(mods); + fixture.frame(vec![Event::PointerMoved(from + (to - from) * (step as f32 / 4.0))]); + } + button(fixture, to, false, last); + fixture.hold(Modifiers::NONE); + fixture.frame(Vec::new()); +} /// The tool on a canvas showing its quad, driven by pointer events. struct Rig { @@ -55,29 +86,16 @@ impl Rig { /// The screen point of document point `(x, y)`: the view shows (200, 150) at the canvas's centre. fn at(&self, x: f64, y: f64) -> Pos2 { - let canvas = self.fixture.by_role(Role::CANVAS).into_iter().next().expect("a canvas"); - canvas.center() + Vec2::new(x as f32 - 200.0, y as f32 - 150.0) + screen(&self.fixture, x, y) } fn button(&mut self, at: Pos2, pressed: bool, modifiers: Modifiers) { - self.fixture.hold(modifiers); - self.fixture.frame(vec![Event::PointerButton { pos: at, button: PointerButton::Primary, pressed, modifiers }]); + button(&mut self.fixture, at, pressed, modifiers); } /// A drag over four moves; the last move and the release hold `last`, the others `first`. fn drag_with(&mut self, from: (f64, f64), to: (f64, f64), first: Modifiers, last: Modifiers) { - let (from, to) = (self.at(from.0, from.1), self.at(to.0, to.1)); - self.fixture.hold(first); - self.fixture.frame(vec![Event::PointerMoved(from)]); - self.button(from, true, first); - for step in 1..=4 { - let mods = if step == 4 { last } else { first }; - self.fixture.hold(mods); - self.fixture.frame(vec![Event::PointerMoved(from + (to - from) * (step as f32 / 4.0))]); - } - self.button(to, false, last); - self.fixture.hold(Modifiers::NONE); - self.fixture.frame(Vec::new()); + drag_on(&mut self.fixture, from, to, first, last); } fn drag(&mut self, from: (f64, f64), to: (f64, f64), mods: Modifiers) { @@ -136,6 +154,36 @@ fn rectangle((a, b): (Point, Point)) -> [(f64, f64); 4] { [(x0, y0), (x1, y0), (x1, y1), (x0, y1)] } +/// The quad alone on a canvas, kept inside [`BOUNDS`], starting at `start`; and its value. +fn bounded(start: [Point; 4]) -> (Fixture, Rc>>) { + let quad = Rc::new(RefCell::new(Some(start))); + let shown = Rc::clone(&quad); + let mut fixture = Fixture::new(move |ui| { + let room = ui.available_rect_before_wrap(); + let view = CanvasView::new(room, Point::new(200.0, 150.0), 1.0); + let _ = Canvas::new("Document").document(SIZE).view(view).show(ui, |ui, body| { + let mut quad = shown.borrow_mut(); + let _ = PerspectiveCropQuad::new("Perspective crop", Bind::bound(&mut *quad)).bounds(BOUNDS).show_at(ui, body.rect); + }); + }); + fixture.settle(); + (fixture, quad) +} + +fn inside(q: &[Point; 4]) -> bool { + q.iter().all(|p| p.x >= BOUNDS.x0 - 1e-6 && p.x <= BOUNDS.x1 + 1e-6 && p.y >= BOUNDS.y0 - 1e-6 && p.y <= BOUNDS.y1 + 1e-6) +} + +/// Whether `b` is `a` moved without a change of shape. +fn same_shape(a: &[Point; 4], b: &[Point; 4]) -> bool { + let by = b[0] - a[0]; + a.iter().zip(b).all(|(p, q)| ((*q - *p) - by).hypot() < 1e-6) +} + +fn on_right_edge(x: f64) -> bool { + (x - BOUNDS.x1).abs() < 1e-6 +} + #[trial] fn grid_lines_meet_at_the_quads_vanishing_points() { let view = CanvasView::new(egui::Rect::from_min_size(Pos2::ZERO, Vec2::new(400.0, 300.0)), Point::new(200.0, 150.0), 1.0); @@ -242,6 +290,56 @@ fn perspective_box_and_corner_modifiers_and_clicks() { assert!(near(rig.quad(), upright), "a click moves nothing: {:?}", rig.quad()); } +#[trial] +fn a_bounded_quad_stays_inside_its_bounds_whatever_moves_it() { + let upright = [(100.0, 80.0), (300.0, 80.0), (300.0, 220.0), (100.0, 220.0)].map(|(x, y)| Point::new(x, y)); + let (mut fixture, quad) = bounded(upright); + let value = |quad: &Rc>>| quad.borrow().expect("a quad"); + + // An Alt corner drag past the bounds' corner: the corner and its moved neighbours stop at the edges. + drag_on(&mut fixture, (300.0, 220.0), (370.0, 270.0), ALT, ALT); + let q = value(&quad); + assert!(inside(&q), "an Alt corner drag stays inside: {q:?}"); + assert!(on_right_edge(q[2].x) && (q[2].y - BOUNDS.y1).abs() < 1e-6, "the dragged corner stops at the edges: {q:?}"); + assert!((q[1].x - q[2].x).abs() < 1e-6 && (q[3].y - q[2].y).abs() < 1e-6 && q[0] == upright[0], "Alt still keeps the rectangle: {q:?}"); + + // A whole-quad drag past the bounds keeps its shape: the farthest corner stops at the edge, the rest follow. + *quad.borrow_mut() = Some(upright); + fixture.frame(Vec::new()); + drag_on(&mut fixture, (200.0, 150.0), (290.0, 180.0), Modifiers::NONE, Modifiers::NONE); + let moved = value(&quad); + assert!(inside(&moved) && same_shape(&upright, &moved), "a moved quad stays inside with its shape: {moved:?}"); + assert!(on_right_edge(moved[1].x) && moved != upright, "the move stops at the edge: {moved:?}"); + + // The arrows on the whole quad: one step in, then a far step out stops at the edge. + fixture.key(Key::ArrowLeft, Modifiers::NONE); + fixture.frame(Vec::new()); + let left = value(&quad); + assert!(left[1].x < moved[1].x && same_shape(&moved, &left), "an arrow moves the whole quad: {left:?}"); + fixture.key(Key::ArrowRight, SHIFT); + fixture.frame(Vec::new()); + let back = value(&quad); + assert!(inside(&back) && same_shape(&moved, &back) && on_right_edge(back[1].x), "a nudge out stops at the edge: {back:?}"); + + // The arrows on a picked corner: a press on it picks it, and a far nudge out stops it at the edge. + let corner = screen(&fixture, back[2].x, back[2].y); + fixture.frame(vec![Event::PointerMoved(corner)]); + button(&mut fixture, corner, true, Modifiers::NONE); + button(&mut fixture, corner, false, Modifiers::NONE); + fixture.frame(Vec::new()); + assert_eq!(value(&quad), back, "a click on a corner moves nothing"); + fixture.key(Key::ArrowLeft, SHIFT); + fixture.frame(Vec::new()); + let pulled = value(&quad); + assert!(pulled[2].x < back[2].x && pulled[1] == back[1], "an arrow moves the picked corner alone: {pulled:?}"); + for _ in 0..2 { + fixture.key(Key::ArrowRight, SHIFT); + fixture.frame(Vec::new()); + } + let pushed = value(&quad); + assert!(inside(&pushed) && on_right_edge(pushed[2].x), "a corner nudged out stops at the edge: {pushed:?}"); +} + #[trial] fn a_session_starts_once_and_a_document_switch_discards_it() { let mut rig = Rig::new();