diff --git a/crates/behavior/src/geometry/crop.rs b/crates/behavior/src/geometry/crop.rs index 30bc702e1..7fa042277 100644 --- a/crates/behavior/src/geometry/crop.rs +++ b/crates/behavior/src/geometry/crop.rs @@ -148,10 +148,11 @@ impl CropBox { (w.is_finite() && h.is_finite()).then(|| (w.round().max(1.0), h.round().max(1.0))) } - /// Whether both sides are at least `min`, and at least one document unit. + /// Whether both sides are at least `min`, and never under one document unit whatever `min` says (a `min` that is + /// not a number counts as one unit). pub fn size_ok(&self, min: f64) -> bool { - let _ = min; // P3(pdf-edit-w4): ED-F9 - self.rect.width() >= MIN_FRAME && self.rect.height() >= MIN_FRAME + let min = min.max(MIN_FRAME); + self.rect.width() >= min && self.rect.height() >= min } /// The frame with `part` dragged by the page vector `by`: along the frame's own axes, the opposite edges kept on diff --git a/crates/ui-canvas/src/canvas/crop/gesture.rs b/crates/ui-canvas/src/canvas/crop/gesture.rs index 17fc6511e..5d6cd7bcb 100644 --- a/crates/ui-canvas/src/canvas/crop/gesture.rs +++ b/crates/ui-canvas/src/canvas/crop/gesture.rs @@ -70,6 +70,10 @@ pub(super) struct Rules { pub image: bool, pub auto_center: bool, pub fills_uncovered: bool, + /// The smallest side a resize may leave, in document units: a step that would go under it keeps the last frame. + pub min_side: f64, + /// The quad the frame is bounded to: a step that would leave the frame outside it keeps the last frame. + pub area: Option<[Point; 4]>, /// The canvas's snapping, with this pass's tolerance. pub snap: Option, pub os: Platform, @@ -115,6 +119,11 @@ impl Rules { } else { at.resized(*part, by, hold, mods.alt) }; + // A step that would leave a side under the minimum keeps the last frame, as a step the bounds refuse + // does: the resize stops there instead of crossing it. + if !next.size_ok(self.min_side) { + return Some(drag.last); + } (next, true, self.ratio.is_some() || mods.shift) } Kind::Turn { grab } => { @@ -137,10 +146,11 @@ impl Rules { if !next.is_finite() { return None; } - match self.bounds { - Some(bounds) => next.within(bounds, resizing, held).or(Some(drag.last)), + let kept = match self.bounds { + Some(bounds) => next.within(bounds, resizing, held), None => Some(next), - } + }; + kept.filter(|kept| self.area.is_none_or(|area| inside_quad(kept, &area))).or(Some(drag.last)) } /// The screen point of `pos` after the canvas's snapping: an end of the Straighten line. @@ -193,6 +203,22 @@ impl Rules { } } +/// How far (a cross product, in document units squared) a corner may lie past a quad's edge and still count as inside +/// it: rounding, not a visible gap. +const QUAD_TOLERANCE: f64 = 1e-6; + +/// Whether every corner of `frame` lies in the convex `quad`, whichever way the quad winds. A quad with no area bounds +/// nothing. +fn inside_quad(frame: &CropBox, quad: &[Point; 4]) -> bool { + let side = |a: Point, b: Point, p: Point| (b.x - a.x) * (p.y - a.y) - (b.y - a.y) * (p.x - a.x); + let winding = side(quad[0], quad[1], quad[2]); + if !winding.is_finite() || winding == 0.0 { + return true; + } + let sign = winding.signum(); + frame.corners().iter().all(|p| (0..4).all(|i| side(quad[i], quad[(i + 1) % 4], *p) * sign >= -QUAD_TOLERANCE)) +} + /// The move that slides corner `point` along direction `along` (its diagonal) onto the nearest of `lines` it crosses /// within `reach` of `point` on each axis, the box the snap read the handle in, with the lines the slid corner lies /// on. `None` when the diagonal meets none of them that near: a diagonal nearly parallel to a line meets it far along. diff --git a/crates/ui-canvas/src/canvas/crop/mod.rs b/crates/ui-canvas/src/canvas/crop/mod.rs index 01e6f80aa..433ccbf19 100644 --- a/crates/ui-canvas/src/canvas/crop/mod.rs +++ b/crates/ui-canvas/src/canvas/crop/mod.rs @@ -1,6 +1,6 @@ //! `CropOverlay`: the crop frame of a document, a canvas control (20.6). The frame, its corners and its edges are -//! parts in the canvas's arena; the outside of the frame turns it and, while Straighten is armed, the whole canvas draws -//! the straighten line. The value is a [`CropBox`] in document units. +//! parts in the canvas's arena; the outside of the frame turns it, applies the crop or draws a new frame, and, while +//! Straighten is armed, the whole canvas draws the straighten line. The value is a [`CropBox`] in document units. mod gesture; mod paint; @@ -33,8 +33,14 @@ pub use shield::{CropShield, ShieldColor, paint_outside}; /// A part of the frame: `FRAME.at(part.index())` with the whole frame at 0, the corners at 1 to 4 and the edges at 5 /// to 8, so the keyboard order is the whole frame and then the corners and the edges clockwise. pub(super) const FRAME: PartKey = PartKey::new("frame"); -/// The outside of the frame: a press there turns it. +/// The outside of the frame with [`CropOutside::Turn`]: a press there turns it. const TURN: PartKey = PartKey::new("turn"); +/// The outside of the frame with [`CropOutside::Apply`] (a click applies) or [`CropOutside::NewFrame`] (a drag draws a +/// new frame). +const OUTSIDE: PartKey = PartKey::new("outside"); +/// With [`CropOutside::Apply`], the cut-away area between the frame and the area's outline: a press there is taken and +/// does nothing. +const CUT: PartKey = PartKey::new("cut"); /// The whole canvas while Straighten is armed. const STRAIGHTEN: PartKey = PartKey::new("straighten"); @@ -42,6 +48,9 @@ const STRAIGHTEN: PartKey = PartKey::new("straighten"); const STRAIGHTEN_MIN: f64 = 3.0; /// The step of a Shift turn, in degrees. const TURN_STEP: f64 = 15.0; +/// The smallest side by default, in document units: none beyond the floor of one document unit (`MIN_FRAME`), which +/// [`CropBox::size_ok`] always applies. +const MIN_SIDE: f64 = 0.0; /// X swaps portrait and landscape. const SWAP: Chord = Chord::plain(Key::X); @@ -111,12 +120,16 @@ struct Live { /// behind it in image mode) and by the keyboard. /// /// - Pointer: a corner or an edge resizes along the frame's own axes (Shift keeps the proportions, a corner following -/// the frame's diagonal; Alt resizes about the centre); inside moves; outside turns the frame about its centre (Shift -/// in steps). Inside the [default frame](CropOverlay::default_frame) a drag draws a new frame (Shift square, Alt from -/// the centre, Space moves it while it is drawn). A [ratio](CropOverlay::ratio) is held by every gesture. A drag -/// begins on the first move; a press released without moving changes nothing, and a drag that leaves a side under -/// one document unit is cancelled. The canvas's snapping ([`canvas_snap`]) applies to draws, moves, resizes and the -/// Straighten line. +/// the frame's diagonal; Alt resizes about the centre); inside moves. A press outside does what +/// [`outside`](CropOverlay::outside) says: [`Turn`](CropOutside::Turn) turns the frame about its centre (Shift in +/// steps); [`Apply`](CropOutside::Apply) applies the crop on a primary click, while a press in the cut-away +/// [area](CropOverlay::area) between the frame and its outline is taken and does nothing; +/// [`NewFrame`](CropOutside::NewFrame) draws a new frame, kept inside the bounds. Inside the +/// [default frame](CropOverlay::default_frame) a drag draws a new frame (Shift square, Alt from the centre, Space +/// moves it while it is drawn). A [ratio](CropOverlay::ratio) is held by every gesture. A drag begins on the first +/// move; a press released without moving changes nothing. A resize stops before a side goes under the +/// [minimum side](CropOverlay::min_side) (the floor of one document unit always applies), and a drag released with a side under it +/// is cancelled. The canvas's snapping ([`canvas_snap`]) applies to draws, moves, resizes and the Straighten line. /// - Look: until a drag changes the untouched default frame in image mode, the outline is dashed and no shield or /// guide shows. While an image-mode turn runs, a turn grid replaces the chosen guide. /// - Keys, on a focused part, on the focused canvas or with nothing focused (the overlay holds the canvas's session, @@ -173,13 +186,14 @@ pub struct CropOverlay<'a> { hidden: bool, /// What a press outside the frame does: turns it, applies the crop, or draws a new frame. #[prop] - #[allow(dead_code)] // P3(pdf-edit-w4): ED-F8 outside: CropOutside, - /// The quad the frame is bounded to, drawn as an outline in the guide colour. + /// With [`CropOutside::Apply`], the quad of what is cropped (a placed picture) in document units, the frame is bounded + /// to it: a step that would leave the frame outside it keeps the last frame. It is drawn as a faint outline, and a + /// press between it and the frame is taken and does nothing. Without it the bounds serve for the outline. #[prop] - #[allow(dead_code)] // P3(pdf-edit-w4): ED-F8 area: Option<[Point; 4]>, - /// The smallest side a drawn frame keeps. + /// The smallest side, in document units, a resize may leave and a drag may be released with; the floor of one document + /// unit (`MIN_FRAME`) always applies. #[prop(quantity = "document units")] min_side: f64, report: Report, @@ -218,7 +232,7 @@ impl<'a> CropOverlay<'a> { hidden: false, outside: CropOutside::default(), area: None, - min_side: 0.0, + min_side: MIN_SIDE, report: Report::default(), } .label(label) @@ -233,6 +247,8 @@ impl<'a> CropOverlay<'a> { image: self.image_mode, auto_center: self.auto_center, fills_uncovered: self.fills_uncovered, + min_side: self.min_side, + area: self.area, snap: canvas_snap(env), os: env.shell().os, } @@ -254,6 +270,19 @@ impl<'a> CropOverlay<'a> { fn shown(&self, value: Option<&CropBox>, view: &CanvasView) -> CropBox { value.copied().unwrap_or_else(|| CropBox::upright(self.bounds.unwrap_or_else(|| view.visible()))) } + + /// With [`CropOutside::Apply`], the cut-away area's corners on screen: the area, else the bounds. `None` in the + /// other modes, with neither, or when it has no extent on screen. + fn cut_area(&self, view: &CanvasView) -> Option<[Pos2; 4]> { + if self.outside != CropOutside::Apply { + return None; + } + let corners = self.area.or_else(|| { + self.bounds.map(|b| [Point::new(b.x0, b.y0), Point::new(b.x1, b.y0), Point::new(b.x1, b.y1), Point::new(b.x0, b.y1)]) + })?; + let q = corners.map(|p| view.to_screen(p)); + (!degenerate(&q)).then_some(q) + } } /// How the overlay maps the document: the canvas's space, or, in a canvas with no view, the shown rect at one to one @@ -286,6 +315,8 @@ fn frame_part(index: u64) -> Option { enum Grab { Part(BoxPart), Turn, + Outside, + Cut, Line, } @@ -294,6 +325,8 @@ impl Grab { match self { Grab::Part(part) => (FRAME, Some(part.index())), Grab::Turn => (TURN, None), + Grab::Outside => (OUTSIDE, None), + Grab::Cut => (CUT, None), Grab::Line => (STRAIGHTEN, None), } } @@ -316,8 +349,8 @@ fn angle_row(cx: &Cx<'_, CropOverlay<'_>>, degrees: f64) -> Vec<(Label, String)> } impl CropOverlay<'_> { - /// Starts the drag of `grab` pressed at screen point `origin`. - fn begin(&mut self, cx: &mut Cx<'_, Self>, space: &CanvasSpace, frame: &CropBox, grab: Grab, origin: Pos2, mods: Mods) -> Drag { + /// Starts the drag of `grab` pressed at screen point `origin`; `None` for a press that is taken and moves nothing. + fn begin(&mut self, cx: &mut Cx<'_, Self>, space: &CanvasSpace, frame: &CropBox, grab: Grab, origin: Pos2, mods: Mods) -> Option { let view = space.view; let from = view.to_doc(origin); let kind = match grab { @@ -326,6 +359,9 @@ impl CropOverlay<'_> { Kind::Line { from, to: from } } Grab::Turn => Kind::Turn { grab: gesture::grab(frame, from) }, + Grab::Outside if self.outside == CropOutside::NewFrame => Kind::Draw { anchor: from, cur: from, last: from }, + // The cut-away area takes a press and does nothing; the outside of an Apply crop senses no drag. + Grab::Outside | Grab::Cut => return None, Grab::Part(BoxPart::Inside) if !self.draws() => Kind::Move, Grab::Part(BoxPart::Inside) => Kind::Draw { anchor: from, cur: from, last: from }, Grab::Part(part) => Kind::Resize(part), @@ -333,7 +369,7 @@ impl CropOverlay<'_> { if !matches!(kind, Kind::Line { .. }) { cx.begin(); } - Drag { kind, at_press: *frame, from, press_view: self.image_mode.then_some(view), last: *frame, changed: false, pointer: origin } + Some(Drag { kind, at_press: *frame, from, press_view: self.image_mode.then_some(view), last: *frame, changed: false, pointer: origin }) } /// One step of the drag with the pointer at screen point `pos`. @@ -388,7 +424,6 @@ impl CropOverlay<'_> { return; } if drag.last.is_finite() && drag.last.size_ok(self.min_side) { - // P3(pdf-edit-w4): ED-F9 if let Some(view) = gesture::centred(&drag, self.auto_center, &space.view, &drag.last) { self.report.view = Some(view); } @@ -457,11 +492,11 @@ impl CropOverlay<'_> { #[derive(Debug)] #[non_exhaustive] pub struct CropOverlayOutput { - /// The edit of the frame: a drag is one `Begin` to `Commit` (a `Cancel` on Escape or when a side ends under one - /// document unit); a key is a `Set`. + /// The edit of the frame: a drag is one `Begin` to `Commit` (a `Cancel` on Escape or when a side ends under the + /// minimum side); a key is a `Set`. pub edit: EditResponse, - /// Apply the crop: Enter (see the overlay's keys), or a double click inside a drawn frame (not a handle, not the - /// default frame). + /// Apply the crop: Enter (see the overlay's keys), a double click inside a drawn frame (not a handle, not the + /// default frame), or with [`CropOutside::Apply`] a primary click outside the frame and its cut-away area. pub apply: bool, /// Close the frame without applying it: Escape with no drag. pub discard: bool, @@ -542,8 +577,8 @@ impl Component for CropOverlay<'_> { Some(self.crop.reborrow()) } - /// The frame, its corners and its edges as one roving group in keyboard order, the outside that turns it, and the - /// Straighten surface while that is armed. + /// The frame, its corners and its edges as one roving group in keyboard order, the outside as [`CropOutside`] + /// says (with `Apply`, the cut-away area above it), and the Straighten surface while that is armed. fn parts(&mut self, rect: Rect, cx: &mut PartsCx<'_, Self>) { let space = space_of(&cx.env, rect); let view = space.view; @@ -605,10 +640,36 @@ impl Component for CropOverlay<'_> { } let _ = declared; } - cx.part(TURN, HitShape::Rect(rect)) - .sense(Sense::DRAG | Sense::CONTEXT_CLICK) - .priority(HitPriority::new(HitLevel::Background, u8::MAX)) - .pointer_only("the options bar's angle field sets the frame's angle"); + let outside = HitPriority::new(HitLevel::Background, u8::MAX); + match self.outside { + CropOutside::Turn => { + cx.part(TURN, HitShape::Rect(rect)) + .sense(Sense::DRAG | Sense::CONTEXT_CLICK) + .priority(outside) + .pointer_only("the options bar's angle field sets the frame's angle"); + } + CropOutside::Apply => { + cx.part(OUTSIDE, HitShape::Rect(rect)) + .sense(Sense::CLICK | Sense::CONTEXT_CLICK) + .priority(outside) + .pointer_only("Enter applies the crop"); + // One step stronger than the outside, below the frame's parts: a press between the frame and the + // area's outline lands here. + if let Some(cut) = self.cut_area(&view) { + cx.part(CUT, HitShape::Polygon(cut.to_vec())) + .sense(Sense::DRAG | Sense::CLICK) + .priority(HitPriority::new(HitLevel::Background, u8::MAX - 1)) + .pointer_only("a press on the cut-away area does nothing, so it has no keyboard path"); + } + } + CropOutside::NewFrame => { + cx.part(OUTSIDE, HitShape::Rect(rect)) + .sense(Sense::DRAG | Sense::CONTEXT_CLICK) + .priority(outside) + .cursor(CursorIcon::Crosshair) + .pointer_only("the options bar's size fields set the frame"); + } + } cx.roving(Roving::new(NavShape::Flat).page(Some(1))); } @@ -620,7 +681,7 @@ impl Component for CropOverlay<'_> { return; } let mut live = cx.memory::().clone(); - let grabs = [Grab::Line, Grab::Turn].into_iter().chain((0..=8).filter_map(frame_part).map(Grab::Part)).collect::>(); + let grabs = [Grab::Line, Grab::Turn, Grab::Outside, Grab::Cut].into_iter().chain((0..=8).filter_map(frame_part).map(Grab::Part)).collect::>(); for grab in grabs { let (key, index) = grab.key(); let part = match index { @@ -637,9 +698,10 @@ impl Component for CropOverlay<'_> { } } PressPhase::DragStart { start, pos, .. } if start.button == PointerButton::Primary => { - let mut drag = self.begin(cx, &space, &frame, grab, start.origin, mods); - self.step(cx, &space, &mut drag, pos, mods); - live.drag = Some(drag); + if let Some(mut drag) = self.begin(cx, &space, &frame, grab, start.origin, mods) { + self.step(cx, &space, &mut drag, pos, mods); + live.drag = Some(drag); + } } PressPhase::Drag { pos, .. } => { if let Some(mut drag) = live.drag.take() { @@ -654,6 +716,8 @@ impl Component for CropOverlay<'_> { self.report.context = Some((at, press.mods)); } self.report.straighten_ended |= grab == Grab::Line && start.button == PointerButton::Primary; + self.report.apply |= + click && grab == Grab::Outside && self.outside == CropOutside::Apply && start.button == PointerButton::Primary; if !click && let Some(drag) = live.drag.take() { self.finish(cx, &space, drag); } @@ -677,7 +741,7 @@ impl Component for CropOverlay<'_> { self.report.hovered = (0..=8) .filter_map(frame_part) .find(|part| cx.hover_pos(craft_behavior::PartRef { key: FRAME, index: Some(part.index()) }).is_some()) - .or_else(|| cx.hover_pos(TURN).map(|_| BoxPart::Outside)); + .or_else(|| [TURN, OUTSIDE].into_iter().find_map(|key| cx.hover_pos(key)).map(|_| BoxPart::Outside)); self.run_keys(cx, &space, &frame, live.drag.is_some()); self.report.scrolls_at = live.drag.as_ref().and_then(|drag| drag.scrolls_at(self.image_mode, self.auto_center)); *cx.memory::() = live; diff --git a/crates/ui-canvas/src/canvas/crop/paint.rs b/crates/ui-canvas/src/canvas/crop/paint.rs index 07328b505..dce6dae84 100644 --- a/crates/ui-canvas/src/canvas/crop/paint.rs +++ b/crates/ui-canvas/src/canvas/crop/paint.rs @@ -57,6 +57,9 @@ fn paint_frame(draw: &Draw<'_>, cx: &Cx<'_, CropOverlay<'_>>, scene: &Scene<'_, let corners = [area.left_top(), area.right_top(), area.right_bottom(), area.left_bottom()]; super::paint_outside(draw, corners, &q, DataColor::new(fill)); } + if let Some(cut) = overlay.cut_area(view) { + draw.stroke(&PaintShape::Polygon(cut.to_vec()), StrokeWidth::Thin, style.guide); + } let line = if scene.refused { style.invalid } else { style.line }; if scene.started { draw.stroke(&PaintShape::Polygon(q.to_vec()), StrokeWidth::Thin, line); diff --git a/crates/ui-canvas/src/canvas/crop/stories.rs b/crates/ui-canvas/src/canvas/crop/stories.rs index e0dcbe78e..509610364 100644 --- a/crates/ui-canvas/src/canvas/crop/stories.rs +++ b/crates/ui-canvas/src/canvas/crop/stories.rs @@ -1,6 +1,6 @@ //! Stories of the crop overlay. -use super::{CropOverlay, CropOverlayOutput, FRAME}; +use super::{CropOutside, CropOverlay, CropOverlayOutput, FRAME}; use crate::canvas::RasterSource as _; use crate::canvas::testing::canvas_story::{self, StoryDocument, StoryPicture, StoryShape, paint_shapes}; use crate::contract::{Bind, Show as _, Validity}; @@ -17,6 +17,12 @@ const STRAIGHTEN_TILT: f64 = 6.0; /// The narrowest crop the invalid story accepts, in document units. const LEAST_WIDTH: f64 = 100.0; +/// How far the placed picture story's picture is turned on the page, in degrees. +const PLACED_TURN: f64 = 4.0; + +/// The smallest side the placed picture story's crop keeps, in document units. +const PLACED_MIN_SIDE: f64 = 6.0; + fn crop() -> CropBox { CropBox::upright(DocRect::new(240.0, 145.0, 400.0, 255.0)) } @@ -137,6 +143,26 @@ fn untouched(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { }) } +/// A placed picture cropped on its page: the picture's turned outline in the guide's faint line round the shielded +/// frame; a click away from the picture applies, and a press between the frame and the outline does nothing. +#[story(CropOverlay<'static>, covers = [Default])] +fn placed_picture(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { + let rect = data.value("crop", crop()); + let area = CropBox::new(DocRect::new(200.0, 110.0, 440.0, 290.0), PLACED_TURN).corners(); + on_landscape(ui, 0.0, |ui, at| { + CropOverlay::new("Crop", Bind::bound(&mut *rect)).outside(CropOutside::Apply).area(area).min_side(PLACED_MIN_SIDE).show_at(ui, at) + }) +} + +/// A scanned photo's crop: no turn, and a press outside the frame draws a new frame inside the page. +#[story(CropOverlay<'static>, covers = [Default])] +fn scan_photo(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { + let rect = data.value("crop", crop()); + on_landscape(ui, 0.0, |ui, at| { + CropOverlay::new("Crop", Bind::bound(&mut *rect)).outside(CropOutside::NewFrame).bounds(StoryDocument::STANDARD.rect()).show_at(ui, at) + }) +} + /// The frame hidden: nothing shows over the picture, and a press anywhere draws a new frame. #[story(CropOverlay<'static>, covers = [Default])] fn hidden(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { diff --git a/crates/ui-canvas/tests/it/canvas/crop.rs b/crates/ui-canvas/tests/it/canvas/crop.rs index b618876c1..05066b5a4 100644 --- a/crates/ui-canvas/tests/it/canvas/crop.rs +++ b/crates/ui-canvas/tests/it/canvas/crop.rs @@ -5,7 +5,7 @@ use craft_behavior::geometry::{ }; use craft_behavior::kurbo::{Point, Rect}; use craft_behavior::{Axis, CancelReason, CanvasView, EditEvent}; -use craft_ui::canvas::{Canvas, CanvasTool, CropOverlay, Snap, ToolAction, ToolContext, ToolHost, ToolPath, ToolPointer, tool_pass}; +use craft_ui::canvas::{Canvas, CanvasTool, CropOutside, CropOverlay, Snap, ToolAction, ToolContext, ToolHost, ToolPath, ToolPointer, tool_pass}; use craft_ui::contract::{Bind, Show as _, ShowContainer as _}; use craft_ui::primitives::Draw; use craft_ui::runtime::access::Role; @@ -40,6 +40,9 @@ struct Setup { straighten: bool, guide: Option<(CropGuide, u8)>, guide_show: GuideShow, + outside: CropOutside, + area: Option<[Point; 4]>, + min_side: Option, view: CanvasView, } @@ -58,6 +61,9 @@ impl Setup { straighten: false, guide: None, guide_show: GuideShow::Auto, + outside: CropOutside::default(), + area: None, + min_side: None, view: CanvasView::new(egui::Rect::ZERO, Point::new(200.0, 150.0), 1.0), } } @@ -128,7 +134,13 @@ impl Rig { let snap = Snap::new(Arc::new(targets), SnapOptions::default()); let _ = Canvas::new("Document").view(s.view).snap(snap).show(ui, |ui, body| { let mut value = c.borrow_mut(); - let mut overlay = CropOverlay::new("Crop", Bind::bound(&mut *value)).guide_show(s.guide_show); + let mut overlay = CropOverlay::new("Crop", Bind::bound(&mut *value)).guide_show(s.guide_show).outside(s.outside); + if let Some(area) = s.area { + overlay = overlay.area(area); + } + if let Some(min_side) = s.min_side { + overlay = overlay.min_side(min_side); + } if let Some(ratio) = s.ratio { overlay = overlay.ratio(ratio); } @@ -730,6 +742,97 @@ fn a_default_turn_keeps_the_frame_inside_the_turned_image() { rig.release(end); } +#[trial] +fn a_placed_picture_crop_applies_on_a_click_away_keeps_the_cut_area_and_stops_at_its_minimum_side() { + // An 80 x 60 frame at 100 %: its corners and edges reach at most a quarter of its short side, 15 points, past it. + let start = CropBox::upright(Rect::new(160.0, 120.0, 240.0, 180.0)); + let mut setup = Setup::new(); + setup.outside = CropOutside::Apply; + // The placed picture, turned 8 degrees about the frame's centre. + setup.area = Some(CropBox::new(Rect::new(100.0, 70.0, 300.0, 230.0), 8.0).corners()); + setup.min_side = Some(6.0); + let mut rig = Rig::new(start, setup); + // Between the frame and the picture's outline: a click and a drag are taken, and nothing applies, turns or moves. + let cut = rig.at(200.0, 95.0); + rig.click(cut); + rig.drag(cut, cut + Vec2::new(30.0, 0.0), Modifiers::NONE); + assert!(!rig.seen.borrow().applied, "a press in the cut-away area does not apply"); + assert_eq!(rig.crop(), start, "nothing turned or moved"); + assert!(rig.events().is_empty(), "{:?}", rig.events()); + // Away from the picture: a click applies, the frame as it was. + rig.click(rig.at(40.0, 40.0)); + assert!(rig.seen.borrow().applied, "a click away from the picture applies"); + assert_eq!(rig.crop(), start); + // A corner dragged past the minimum side stops at the last step that kept it: narrower than it was, not under the + // minimum, the opposite corner where it was. + rig.drag(rig.at(240.0, 180.0), rig.at(164.0, 190.0), Modifiers::NONE); + let kept = rig.rect(); + assert!(kept.width() >= 6.0 && kept.width() < 80.0, "{kept:?}"); + assert!((kept.x0 - 160.0).abs() < 1e-9 && (kept.y0 - 120.0).abs() < 1e-9, "the opposite corner stayed: {kept:?}"); + assert_eq!(rig.events().last(), Some(&"commit"), "{:?}", rig.events()); +} + +#[trial] +fn a_resize_and_a_move_toward_the_outside_of_a_turned_area_stop_at_its_edge() { + let start = CropBox::upright(Rect::new(160.0, 120.0, 240.0, 180.0)); + let mut setup = Setup::new(); + setup.outside = CropOutside::Apply; + setup.area = Some(CropBox::new(Rect::new(100.0, 70.0, 300.0, 230.0), 8.0).corners()); + let mut rig = Rig::new(start, setup); + // A move far past the picture keeps the frame where it was. + rig.drag(rig.at(200.0, 150.0), rig.at(400.0, 150.0), Modifiers::NONE); + assert_eq!(rig.crop(), start, "a move out of the area"); + // A resize inside the area follows the pointer; one past it keeps the frame as the last step left it. + rig.drag(rig.at(240.0, 150.0), rig.at(270.0, 150.0), Modifiers::NONE); + let grown = rig.rect(); + assert!(grown.x1 > 240.0 && (grown.x0 - 160.0).abs() < 1e-9, "a resize inside the area: {grown:?}"); + let edge = rig.at(grown.x1, 150.0); + rig.drag(edge, rig.at(500.0, 150.0), Modifiers::NONE); + assert_eq!(rig.rect(), grown, "a resize out of the area"); +} + +#[trial] +fn a_press_outside_a_new_frame_crop_draws_a_new_frame_inside_the_bounds() { + let start = CropBox::upright(RECT); + let mut setup = Setup::new(); + setup.outside = CropOutside::NewFrame; + setup.bounds = Some(Rect::new(50.0, 30.0, 350.0, 270.0)); + let mut rig = Rig::new(start, setup); + // Outside the frame, past the reach of its corners and edges. + let from = rig.at(60.0, 40.0); + rig.click(from); + assert_eq!(rig.crop(), start, "a click with no drag changes nothing"); + assert!(rig.events().is_empty(), "{:?}", rig.events()); + // A drag draws a new frame from the press, cut to the bounds; nothing turns. + rig.drag(from, rig.at(380.0, 290.0), Modifiers::NONE); + let drawn = CropBox::upright(Rect::new(60.0, 40.0, 350.0, 270.0)); + assert!(near(&rig.crop(), &drawn), "{:?} vs {drawn:?}", rig.crop()); + assert_eq!(rig.crop().angle, start.angle, "no turn"); + let events = rig.events(); + assert_eq!((events.first(), events.last()), (Some(&"begin"), Some(&"commit")), "{events:?}"); +} + +#[trial] +fn a_corner_drag_on_an_area_smaller_than_the_minimum_side_changes_nothing_and_does_not_panic() { + // A 5 x 5 placed picture cropped to itself, under the 6-unit minimum, zoomed in so its grips show. + let tiny = Rect::new(100.0, 100.0, 105.0, 105.0); + let start = CropBox::upright(tiny); + let mut setup = Setup::new(); + setup.outside = CropOutside::Apply; + setup.area = Some(start.corners()); + setup.min_side = Some(6.0); + setup.view = CanvasView::new(egui::Rect::ZERO, tiny.center(), 8.0); + let mut rig = Rig::new(start, setup); + // The bottom right grip across the frame to the opposite corner. + rig.drag(rig.at(105.0, 105.0), rig.at(100.0, 100.0), Modifiers::NONE); + assert_eq!(rig.crop(), start, "the frame is as it was"); + let events = rig.events(); + assert_eq!(events.first(), Some(&"begin"), "the grip was taken: {events:?}"); + assert_eq!(events.last(), Some(&"cancel"), "a release under the minimum cancels: {events:?}"); + assert!(!events.contains(&"commit"), "{events:?}"); + assert!(!rig.seen.borrow().applied, "a grip drag does not apply"); +} + #[trial] fn a_shift_corner_follows_the_diagonal_and_snaps_along_it() { // An 800 x 500 frame at 100 %, its bottom right corner on screen.