tools-w15: net change of 3 commits

- tools-w15: written by an agent
- tools-w15: review fixes (review-1)
- tools-w15: the crop rig records only the real run of each pass, not the canvas body's measuring run (tools run round)
This commit is contained in:
aiongg
2026-11-15 04:46:08 +00:00
parent ff439373ec
commit a9b04134a8
12 changed files with 1248 additions and 226 deletions
+109 -43
View File
@@ -24,6 +24,13 @@ pub struct CropBox {
pub angle: f64,
}
/// How far (document units) a turned frame's corner may lie past the bounds and still count as inside them: rounding,
/// not a visible gap.
const FIT_TOLERANCE: f64 = 1e-6;
/// The most lines per axis [`turn_grid`] gives: a bound on hostile viewport sizes, far past any screen.
const TURN_GRID_MAX: usize = 4096;
/// What a resize holds about the frame's proportions.
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum AspectHold {
@@ -31,20 +38,11 @@ pub enum AspectHold {
Free,
/// The set ratio, width over height.
Ratio(f64),
/// The box's own ratio, the corner following the diagonal (Shift on a corner with no set ratio).
/// The box's own ratio, the corner following the diagonal (Shift on a corner with no set ratio). An edge holds the
/// box's own ratio as [`Ratio`](Self::Ratio) does.
Diagonal,
}
impl AspectHold {
/// The ratio the current resize reads; `Diagonal` holds none until tl.T41 is written.
fn ratio(self) -> Option<f64> {
match self {
AspectHold::Ratio(r) => Some(r),
AspectHold::Free | AspectHold::Diagonal => None,
}
}
}
impl CropBox {
/// The frame `rect` turned `angle` degrees about its centre.
pub const fn new(rect: Rect, angle: f64) -> Self {
@@ -137,7 +135,7 @@ impl CropBox {
/// The frame after an arrow key moves `part` by `by`, as a plain drag of the part would, with `ratio` held.
pub fn nudged(&self, part: BoxPart, by: Vec2, ratio: Option<f64>) -> Self {
match part_handle(part) {
Some((hx, hy)) => resized_turned(self, hx, hy, by, ratio, false),
Some((hx, hy)) => resized_turned(self, hx, hy, by, ratio.map_or(AspectHold::Free, AspectHold::Ratio), false),
None => self.moved(by),
}
}
@@ -155,13 +153,14 @@ impl CropBox {
}
/// The frame with `part` dragged by the page vector `by`: along the frame's own axes, the opposite edges kept on
/// the page (or the centre with `alt`), `ratio` (width over height) held. A part that is not a corner or an
/// the page (or the centre with `alt`), the proportions held as `hold` says. With [`AspectHold::Diagonal`] a
/// corner follows the frame's diagonal: the drag is projected onto it, so both sides scale by the same factor
/// (800 × 500 dragged by (−100, −50) at the bottom right gives 705.6 × 441). A part that is not a corner or an
/// edge leaves the frame as it is.
#[must_use]
pub fn resized(&self, part: BoxPart, by: Vec2, hold: AspectHold, alt: bool) -> Self {
let ratio = hold.ratio(); // P3(tools-w15): tl.T41
match part_handle(part) {
Some((hx, hy)) => resized_turned(self, hx, hy, by, ratio, alt),
Some((hx, hy)) => resized_turned(self, hx, hy, by, hold, alt),
None => *self,
}
}
@@ -171,12 +170,11 @@ impl CropBox {
/// opposite edge stays put on the image (the centre with `alt`), so the frame's centre moves by the difference
/// and the view follows it. `None` when the result is not finite or `part` is not a corner or an edge.
pub fn resized_centred(&self, part: BoxPart, by: Vec2, hold: AspectHold, alt: bool) -> Option<Self> {
let ratio = hold.ratio(); // P3(tools-w15): tl.T41
let (hx, hy) = part_handle(part)?;
let r = self.rect.abs();
let (w0, h0) = (r.width(), r.height());
let local = turn(Point::new(by.x, by.y), Point::ZERO, -self.angle);
let n = resized(Rect::new(-w0 / 2.0, -h0 / 2.0, w0 / 2.0, h0 / 2.0), hx, hy, Vec2::new(local.x, local.y), ratio, true);
let n = resized(Rect::new(-w0 / 2.0, -h0 / 2.0, w0 / 2.0, h0 / 2.0), hx, hy, Vec2::new(local.x, local.y), hold, true);
let (w1, h1) = (n.width(), n.height());
let shift = if alt { Point::ZERO } else { Point::new(f64::from(hx) * (w1 - w0) / 2.0, f64::from(hy) * (h1 - h0) / 2.0) };
let s = turn(shift, Point::ZERO, self.angle);
@@ -220,6 +218,49 @@ impl CropBox {
Some(self.moved(by))
}
/// The frame at its angle kept inside `bounds` (#10869, an image-mode turn): `self`, bit for bit, when its turned
/// corners are inside (also when a rounding error puts them a hair past an edge); else moved the shortest way in
/// on each axis, its size kept; else shrunk about its centre to the largest size with its proportions that fits,
/// then moved in. `None` when a size or the angle is not finite or a size is not positive.
pub fn kept_inside(&self, bounds: Rect) -> Option<Self> {
let (r, b) = (self.rect.abs(), bounds.abs());
let (w, h, bw, bh) = (r.width(), r.height(), b.width(), b.height());
let finite = [w, h, bw, bh, r.x0, r.y0, b.x0, b.y0, self.angle].iter().all(|v| v.is_finite());
if !finite || w <= 0.0 || h <= 0.0 || bw <= 0.0 || bh <= 0.0 {
return None;
}
let (s, c) = self.angle.to_radians().sin_cos();
let (s, c) = (s.abs(), c.abs());
// Half the turned frame's bounds: its corners are inside when these are.
let (ex, ey) = ((w * c + h * s) / 2.0, (w * s + h * c) / 2.0);
if !(ex.is_finite() && ey.is_finite()) || ex <= 0.0 || ey <= 0.0 {
return None;
}
let m = r.center();
let fits = |v: f64, e: f64, lo: f64, hi: f64| v - e >= lo - FIT_TOLERANCE && v + e <= hi + FIT_TOLERANCE;
if fits(m.x, ex, b.x0, b.x1) && fits(m.y, ey, b.y0, b.y1) {
return Some(*self);
}
// The scale that makes the turned bounds fit; a rounding error short of 1 (a half turn) fits.
let k = (bw / (2.0 * ex)).min(bh / (2.0 * ey));
let k = if k >= 1.0 - 1e-9 { 1.0 } else { k };
if !(k.is_finite() && k > 0.0) {
return None;
}
// Each axis on its own: the nearest centre that keeps the turned bounds inside. `max` then `min` rather than
// `clamp`, which panics when rounding puts the two limits a hair the wrong way round.
let along = |v: f64, e: f64, lo: f64, hi: f64| if 2.0 * e >= hi - lo { (lo + hi) / 2.0 } else { v.max(lo + e).min(hi - e) };
let n = Point::new(along(m.x, ex * k, b.x0, b.x1), along(m.y, ey * k, b.y0, b.y1));
let rect = if k == 1.0 {
r + (n - m)
} else {
let (hw, hh) = (w * k / 2.0, h * k / 2.0);
Rect::new(n.x - hw, n.y - hh, n.x + hw, n.y + hh)
};
let next = Self { rect, angle: self.angle };
next.is_finite().then_some(next)
}
/// The frame angle (degrees, clockwise on the page, in -45..=45) that makes the line from `a` to `b` level, or
/// plumb when it is nearer vertical; `None` for a point or a line that is not finite.
pub fn level_angle(a: Point, b: Point) -> Option<f64> {
@@ -372,10 +413,29 @@ pub fn hit_rect(rect: Rect, point: Point, reach: f64) -> BoxPart {
CropBox::upright(rect).part_at(point, reach)
}
/// Frame `r` with handle (`hx`, `hy`) dragged by `d`. `alt` resizes about the centre; `ratio` (width / height) keeps
/// the proportions, the larger relative extent winning at a corner.
fn resized(r: Rect, hx: i8, hy: i8, d: Vec2, ratio: Option<f64>, alt: bool) -> Rect {
/// The drag and the ratio a resize of handle (`hx`, `hy`) of frame `r` by `d` applies for `hold`: a `Diagonal` corner
/// takes the drag projected onto the frame's diagonal through that corner and holds no ratio (the projection keeps
/// the proportions, about the opposite corner and about the centre alike); a `Diagonal` edge holds the frame's own
/// ratio. A frame with no diagonal takes the drag as it is.
fn held(r: Rect, hx: i8, hy: i8, d: Vec2, hold: AspectHold) -> (Vec2, Option<f64>) {
let (w, h) = (r.width(), r.height());
match hold {
AspectHold::Free => (d, None),
AspectHold::Ratio(k) => (d, Some(k)),
AspectHold::Diagonal if hx != 0 && hy != 0 => {
let v = Vec2::new(f64::from(hx) * w, f64::from(hy) * h);
let t = d.dot(v) / v.hypot2();
if t.is_finite() { (v * t, None) } else { (d, None) }
}
AspectHold::Diagonal => (d, (w > 0.0 && h > 0.0).then(|| w / h)),
}
}
/// Frame `r` with handle (`hx`, `hy`) dragged by `d`, its proportions held as `hold` says. `alt` resizes about the
/// centre; a ratio (width / height) keeps the proportions, the larger relative extent winning at a corner.
fn resized(r: Rect, hx: i8, hy: i8, d: Vec2, hold: AspectHold, alt: bool) -> Rect {
let r = r.abs();
let (d, ratio) = held(r, hx, hy, d, hold);
// Per axis: the fixed point, the signed extent from it, and whether it is centred (the extent is then a
// half-extent).
let axis = |lo: f64, hi: f64, h: i8, d: f64| -> (f64, f64, bool) {
@@ -413,13 +473,13 @@ fn resized(r: Rect, hx: i8, hy: i8, d: Vec2, ratio: Option<f64>, alt: bool) -> R
/// [`resized`] for a frame turned by its angle: the handle moves along the frame's own axes by the page drag `d`,
/// and the edges opposite stay where they are on the page.
fn resized_turned(b: &CropBox, hx: i8, hy: i8, d: Vec2, ratio: Option<f64>, alt: bool) -> CropBox {
fn resized_turned(b: &CropBox, hx: i8, hy: i8, d: Vec2, hold: AspectHold, alt: bool) -> CropBox {
if b.angle == 0.0 {
return CropBox::upright(resized(b.rect, hx, hy, d, ratio, alt));
return CropBox::upright(resized(b.rect, hx, hy, d, hold, alt));
}
let c = b.center();
let local = turn(Point::new(d.x, d.y), Point::ZERO, -b.angle);
let n = resized(b.rect, hx, hy, Vec2::new(local.x, local.y), ratio, alt);
let n = resized(b.rect, hx, hy, Vec2::new(local.x, local.y), hold, alt);
let nc = turn(n.center(), c, b.angle);
let (hw, hh) = (n.width() / 2.0, n.height() / 2.0);
CropBox { rect: Rect::new(nc.x - hw, nc.y - hh, nc.x + hw, nc.y + hh), angle: b.angle }
@@ -500,12 +560,32 @@ pub enum CropGuide {
GoldenSpiral,
}
/// The lines of the grid a default-mode turn shows over a `w` by `h` frame: `step` apart counted from the frame's
/// centre, none on the outline, only inside `visible`; empty for a frame under one point or non-finite input.
#[allow(dead_code)] // P3(tools-w15): tl.T43
pub fn turn_grid(w: f64, h: f64, step: f64, visible: kurbo::Rect) -> Vec<Vec<Point>> {
let _ = (w, h, step, visible);
todo!("tl.T43")
/// The lines of the grid a default-mode turn shows over a `w` by `h` frame (screen points), in the frame's unit square
/// as [`CropGuide::guides`] gives them: `step` apart counted from the frame's centre, none on the outline, and only
/// those whose position lies inside `visible` (the part of the frame on screen, in the frame's own axes), so a frame
/// zoomed far past the screen gives only the lines that show. Empty for a frame under one point, a step that is not
/// positive, or non-finite input.
pub fn turn_grid(w: f64, h: f64, step: f64, visible: Rect) -> Vec<Vec<Point>> {
let v = visible.abs();
if ![w, h, step, v.x0, v.y0, v.x1, v.y1].iter().all(|x| x.is_finite()) || w < 1.0 || h < 1.0 || step <= 0.0 {
return Vec::new();
}
let (x0, x1, y0, y1) = (v.x0.max(0.0), v.x1.min(w), v.y0.max(0.0), v.y1.min(h));
if x1 <= x0 || y1 <= y0 {
return Vec::new();
}
let axis = |len: f64, lo: f64, hi: f64, vertical: bool| {
let mid = len / 2.0;
// Lines counted from the centre, indexed straight into the visible range; those on the outline are left out.
let first = ((lo - mid) / step).ceil().max((-mid / step).floor() + 1.0);
let last = ((hi - mid) / step).floor().min((mid / step).ceil() - 1.0);
let count = if first.is_finite() && last.is_finite() { (last - first + 1.0).clamp(0.0, TURN_GRID_MAX as f64) as usize } else { 0 };
(0..count).map(move |i| {
let f = (mid + (first + i as f64) * step) / len;
if vertical { vec![Point::new(f, 0.0), Point::new(f, 1.0)] } else { vec![Point::new(0.0, f), Point::new(1.0, f)] }
})
};
axis(w, x0, x1, true).chain(axis(h, y0, y1, false)).collect()
}
impl CropGuide {
@@ -670,17 +750,3 @@ impl GuideShow {
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn angles_wrap_into_the_half_open_turn() {
assert_eq!(normalized_angle(-180.0), 180.0, "-180 is 180");
assert_eq!(normalized_angle(-0.1), -0.1, "an angle in range comes back exactly");
assert_eq!(normalized_angle(f64::NAN), 0.0);
assert_eq!(snap_angle(-170.0, 45.0), 180.0, "a snap past -180 wraps");
assert_eq!(snap_angle(37.5, 0.0), 37.5, "a step of 0 is ignored");
}
}
+2 -1
View File
@@ -1,6 +1,7 @@
//! Pure canvas geometry in document units: the transform box ([`quad`]), snapping ([`snap`]), the
//! outline being drawn by a lasso ([`draft`]), how a selection combines with the current one
//! ([`selection_op`]), the marquee drag rules ([`marquee`]), direction locking ([`lock`]), the move gesture and stroke lock ([`move_gesture`]) and
//! ([`selection_op`]), the marquee drag rules ([`marquee`]), direction locking ([`lock`]), the move gesture and stroke lock ([`move_gesture`]),
//! the crop frame ([`crop`]), the area outside a crop frame as convex pieces ([`outside`]) and
//! plane helpers ([`geom`]). Nothing here reads a `Ui`; modifier keys arrive as
//! [`craft_keymap::Mods`].
+59 -2
View File
@@ -2,10 +2,67 @@
use kurbo::Point;
/// Share of the canvas's area under which a piece or a hole counts as having none: rounding at the hole's edges.
const TINY_AREA: f64 = 1e-12;
/// Convex pieces that cover the canvas quad outside the convex `hole` exactly once: the canvas clipped by each
/// hole edge's outer half-plane in turn. Empty for a hole with fewer than three finite points or no area; the whole
/// canvas for a hole outside it.
pub fn outside_pieces(canvas: [Point; 4], hole: &[Point]) -> Vec<Vec<Point>> {
let _ = (canvas, hole);
todo!("tl.T42")
let finite = |p: &Point| p.x.is_finite() && p.y.is_finite();
if hole.len() < 3 || !hole.iter().all(finite) || !canvas.iter().all(finite) {
return Vec::new();
}
let canvas_area = area(&canvas).abs();
let tiny = TINY_AREA * canvas_area.max(1.0);
let hole_area = area(hole);
if !(canvas_area > tiny && hole_area.abs() > tiny) {
return Vec::new();
}
// The hole's inside lies left of each edge (positive cross product) when its points run counter-clockwise in the
// plane's own orientation; a hole given the other way round has it on the right.
let inside_left = hole_area > 0.0;
let mut rest = canvas.to_vec();
let mut pieces = Vec::new();
for (&a, &b) in hole.iter().zip(hole.iter().cycle().skip(1)) {
// A repeated point has no edge to cut along.
if (b - a).hypot2() <= f64::EPSILON * canvas_area.max(1.0) {
continue;
}
let outside = clipped(&rest, a, b, !inside_left);
if area(&outside).abs() > tiny {
pieces.push(outside);
}
rest = clipped(&rest, a, b, inside_left);
if area(&rest).abs() <= tiny {
break;
}
}
pieces
}
/// `poly` cut to the side of the line from `a` to `b` that is to the left (`left`) or the right of it, points on the
/// line kept (Sutherland–Hodgman against one half-plane).
fn clipped(poly: &[Point], a: Point, b: Point, left: bool) -> Vec<Point> {
let side = |p: Point| {
let c = (b - a).cross(p - a);
if left { c } else { -c }
};
let mut out = Vec::with_capacity(poly.len() + 1);
for (&p, &q) in poly.iter().zip(poly.iter().cycle().skip(1)) {
let (sp, sq) = (side(p), side(q));
if sp >= 0.0 {
out.push(p);
}
// The signs differ, so `sp - sq` is not zero.
if (sp >= 0.0) != (sq >= 0.0) {
out.push(p.lerp(q, sp / (sp - sq)));
}
}
out
}
/// The signed area of `poly`: positive when its points run counter-clockwise with y up (clockwise on a y-down screen).
fn area(poly: &[Point]) -> f64 {
poly.iter().zip(poly.iter().cycle().skip(1)).map(|(p, q)| p.x * q.y - q.x * p.y).sum::<f64>() / 2.0
}
+212 -3
View File
@@ -1,6 +1,7 @@
//! The crop frame's geometry: resizing and fitting into the canvas.
//! The crop frame's geometry: resizing, fitting into the canvas, keeping a turned frame inside, the guides and the
//! turn grid.
use craft_behavior::geometry::{AspectHold, BoxPart, CropBox};
use craft_behavior::geometry::{AspectHold, BoxPart, CropBox, CropGuide, turn_grid};
use kurbo::{Point, Rect, Size, Vec2};
#[test]
@@ -8,7 +9,7 @@ fn handles_resize_with_shift_alt_and_a_ratio() {
let d = Vec2::new;
let resize = |r: Rect, part: BoxPart, by: Vec2, ratio: Option<f64>, alt: bool| {
CropBox::upright(r).resized(part, by, ratio.map_or(AspectHold::Free, AspectHold::Ratio), alt).rect
}; // P3(tools-w15): tl.T41
};
let r = Rect::new(20.0, 20.0, 100.0, 60.0);
assert_eq!(resize(r, BoxPart::Edge(1), d(20.0, 10.0), None, false), Rect::new(20.0, 20.0, 120.0, 60.0));
assert_eq!(resize(r, BoxPart::Corner(2), d(40.0, 10.0), None, false), Rect::new(20.0, 20.0, 140.0, 70.0));
@@ -56,3 +57,211 @@ fn fitted_is_the_largest_frame_of_the_same_proportions_inside_the_canvas() {
assert_eq!(frame.fitted(canvas, f64::NAN), None);
assert_eq!(CropBox::upright(Rect::new(1.0, 1.0, 1.0, 5.0)).fitted(canvas, 0.0), None);
}
#[test]
fn guides_stay_in_the_frame_and_orient_by_corner() {
let near = |a: f64, b: f64| (a - b).abs() < 1e-9;
for guide in CropGuide::ALL {
for orientation in 0..guide.orientations() {
for (w, h) in [(300.0, 200.0), (200.0, 300.0), (1.0, 4000.0)] {
for line in guide.guides(orientation, w, h, 50.0, 96) {
assert!(line.len() >= 2, "{guide:?} {orientation}: a line has two ends");
for p in line {
let inside = (-1e-9..=1.0 + 1e-9).contains(&p.x) && (-1e-9..=1.0 + 1e-9).contains(&p.y);
assert!(inside, "{guide:?} {orientation} at {w} x {h}: {p:?} leaves the frame");
}
}
}
}
assert!(guide.guides(0, 0.5, 200.0, 50.0, 96).is_empty(), "{guide:?}: a frame under one point has no guide");
assert!(guide.guides(0, f64::NAN, 200.0, 50.0, 96).is_empty(), "{guide:?}: a size that is not finite has no guide");
}
// Where a straight guide crosses each axis.
let positions = |guide: CropGuide| {
let lines = guide.guides(0, 300.0, 200.0, 50.0, 96);
let mut xs: Vec<f64> = lines.iter().filter(|l| near(l[0].x, l[1].x)).map(|l| l[0].x).collect();
let mut ys: Vec<f64> = lines.iter().filter(|l| near(l[0].y, l[1].y)).map(|l| l[0].y).collect();
xs.sort_by(f64::total_cmp);
ys.sort_by(f64::total_cmp);
(xs, ys)
};
let (xs, ys) = positions(CropGuide::Thirds);
assert!(xs.len() == 2 && near(xs[0], 1.0 / 3.0) && near(xs[1], 2.0 / 3.0), "thirds across: {xs:?}");
assert!(ys.len() == 2 && near(ys[0], 1.0 / 3.0) && near(ys[1], 2.0 / 3.0), "thirds down: {ys:?}");
let golden = 0.618_033_988_749_894_9;
let (xs, ys) = positions(CropGuide::GoldenRatio);
assert!(xs.len() == 2 && near(xs[0], 1.0 - golden) && near(xs[1], golden), "golden section across: {xs:?}");
assert!(ys.len() == 2 && near(ys[0], 1.0 - golden) && near(ys[1], golden), "golden section down: {ys:?}");
// The Triangle's perpendiculars meet its diagonal at right angles on screen, whichever way the frame lies.
for (w, h) in [(300.0, 200.0), (200.0, 300.0)] {
let lines = CropGuide::Triangle.guides(0, w, h, 50.0, 96);
assert_eq!(lines.len(), 3, "a diagonal and two perpendiculars");
let screen = |p: Point| Vec2::new(p.x * w, p.y * h);
let diagonal = screen(lines[0][1]) - screen(lines[0][0]);
for perpendicular in &lines[1..] {
let foot = perpendicular[1];
assert!(near(foot.x, foot.y), "the foot lies on the diagonal: {foot:?}");
let across = screen(foot) - screen(perpendicular[0]);
assert!(across.dot(diagonal).abs() < 1e-6, "{w} x {h}: a right angle, {across:?} on {diagonal:?}");
}
// The other orientation runs the diagonal from the top right.
let mirrored = CropGuide::Triangle.guides(1, w, h, 50.0, 96);
assert!(mirrored[0][0].distance(Point::new(1.0, 0.0)) < 1e-9 && mirrored[0][1].distance(Point::new(0.0, 1.0)) < 1e-9, "{mirrored:?}");
}
// The Golden Spiral starts in a different corner in each of its four orientations.
let mut starts: Vec<(i64, i64)> = (0..4)
.map(|o| {
let spiral = CropGuide::GoldenSpiral.guides(o, 300.0, 200.0, 50.0, 96);
let start = spiral[0][0];
assert!(near(start.x, start.x.round()) && near(start.y, start.y.round()), "orientation {o} starts in a corner: {start:?}");
(start.x.round() as i64, start.y.round() as i64)
})
.collect();
starts.sort_unstable();
assert_eq!(starts, [(0, 0), (0, 1), (1, 0), (1, 1)]);
}
#[test]
fn the_turn_grid_has_centred_cells_and_only_visible_lines() {
// Where the vertical and the horizontal lines lie, in screen points of a `w` by `h` frame.
let positions = |w: f64, h: f64, step: f64, visible: Rect| {
let lines = turn_grid(w, h, step, visible);
let mut xs = Vec::new();
let mut ys = Vec::new();
for line in &lines {
assert_eq!(line.len(), 2);
if line[0].x == line[1].x {
assert!(line[0].y == 0.0 && line[1].y == 1.0, "a line crosses the whole frame: {line:?}");
xs.push((line[0].x * w * 1e6).round() / 1e6);
} else {
assert!(line[0].x == 0.0 && line[1].x == 1.0 && line[0].y == line[1].y, "{line:?}");
ys.push((line[0].y * h * 1e6).round() / 1e6);
}
}
(xs, ys)
};
let whole = |w: f64, h: f64| Rect::new(0.0, 0.0, w, h);
// Counted from the centre, 48 points apart.
let (xs, ys) = positions(200.0, 100.0, 48.0, whole(200.0, 100.0));
assert_eq!(xs, [4.0, 52.0, 100.0, 148.0, 196.0]);
assert_eq!(ys, [2.0, 50.0, 98.0]);
// A line that would lie on the outline is left out.
let (xs, ys) = positions(96.0, 96.0, 48.0, whole(96.0, 96.0));
assert_eq!((xs, ys), (vec![48.0], vec![48.0]));
// Only the lines inside the part of the frame that shows.
let (xs, ys) = positions(200.0, 100.0, 48.0, Rect::new(60.0, 0.0, 120.0, 100.0));
assert_eq!(xs, [100.0]);
assert_eq!(ys, [2.0, 50.0, 98.0]);
// A frame zoomed far past the screen still gives only the few lines in view.
let (xs, _) = positions(1e7, 1e7, 48.0, Rect::new(5e6, 5e6, 5e6 + 100.0, 5e6 + 100.0));
assert_eq!(xs, [5e6, 5e6 + 48.0, 5e6 + 96.0]);
assert!(turn_grid(200.0, 100.0, 48.0, Rect::new(300.0, 0.0, 400.0, 100.0)).is_empty(), "nothing of the frame shows");
assert!(turn_grid(0.5, 100.0, 48.0, whole(0.5, 100.0)).is_empty(), "a frame under one point");
assert!(turn_grid(f64::NAN, 100.0, 48.0, whole(200.0, 100.0)).is_empty());
assert!(turn_grid(200.0, 100.0, 0.0, whole(200.0, 100.0)).is_empty(), "no step");
assert!(turn_grid(200.0, 100.0, 48.0, Rect::new(f64::NAN, 0.0, 200.0, 100.0)).is_empty());
}
#[test]
fn a_turned_frame_is_kept_inside_the_bounds_moved_then_shrunk() {
let bounds = Rect::new(0.0, 0.0, 800.0, 500.0);
let inside = |b: &CropBox| {
let t = b.turned_bounds();
t.x0 >= -1e-6 && t.y0 >= -1e-6 && t.x1 <= 800.0 + 1e-6 && t.y1 <= 500.0 + 1e-6
};
// A frame that fits stays bit for bit, also one that a rounding error puts a hair past the edge.
let small = CropBox::new(Rect::new(300.0, 200.0, 500.0, 300.0), 10.0);
assert_eq!(small.kept_inside(bounds), Some(small));
let touching = CropBox::upright(bounds).fitted(Size::new(800.0, 500.0), 7.0).unwrap();
assert_eq!(touching.kept_inside(bounds), Some(touching));
// Fitted at 7°, its turned bounds span the whole height: 1e-9 down is a rounding error past the edge.
let hair = touching.moved(Vec2::new(0.0, 1e-9));
assert_eq!(hair.kept_inside(bounds), Some(hair));
// Too far right but small enough: moved in the shortest way on that axis only, its size and angle kept.
let past = CropBox::new(Rect::new(650.0, 200.0, 790.0, 300.0), 30.0);
let moved = past.kept_inside(bounds).unwrap();
assert!(inside(&moved), "{moved:?}");
assert!((moved.rect.width() - past.rect.width()).abs() < 1e-9 && (moved.rect.height() - past.rect.height()).abs() < 1e-9, "{moved:?}");
assert_eq!(moved.angle, past.angle);
assert!((moved.turned_bounds().x1 - 800.0).abs() < 1e-9, "moved the least: {moved:?}");
assert!((moved.center().y - past.center().y).abs() < 1e-12, "the axis that fits is kept: {moved:?}");
// Too large at its angle: shrunk about its centre, proportions kept, to the largest that fits.
let whole = CropBox::new(bounds, 30.0);
let shrunk = whole.kept_inside(bounds).unwrap();
assert!(inside(&shrunk), "{shrunk:?}");
assert!((shrunk.rect.width() / shrunk.rect.height() - 1.6).abs() < 1e-9, "8 : 5 kept: {shrunk:?}");
assert!(shrunk.rect.width() < 800.0, "{shrunk:?}");
assert!(shrunk.center().distance(Point::new(400.0, 250.0)) < 1e-9, "{shrunk:?}");
let t = shrunk.turned_bounds();
assert!((t.height() - 500.0).abs() < 1e-6 || (t.width() - 800.0).abs() < 1e-6, "the largest that fits touches the bounds: {t:?}");
// A large frame off the centre is shrunk, then moved in.
let off = CropBox::new(Rect::new(300.0, 100.0, 1100.0, 600.0), 30.0);
let kept = off.kept_inside(bounds).unwrap();
assert!(inside(&kept) && (kept.rect.width() - shrunk.rect.width()).abs() < 1e-9, "{kept:?}");
// A quarter turn swaps which side binds; a half turn fits as it is.
let quarter = CropBox::new(bounds, 90.0).kept_inside(bounds).unwrap();
assert!((quarter.rect.width() - 500.0).abs() < 1e-9 && (quarter.rect.height() - 312.5).abs() < 1e-9, "{quarter:?}");
assert!(quarter.center().distance(Point::new(400.0, 250.0)) < 1e-9);
let half = CropBox::new(bounds, 180.0);
assert_eq!(half.kept_inside(bounds), Some(half));
// Nothing to keep.
assert_eq!(CropBox::upright(Rect::new(10.0, 10.0, 10.0, 50.0)).kept_inside(bounds), None);
assert_eq!(CropBox::new(Rect::new(10.0, 10.0, 50.0, 50.0), f64::NAN).kept_inside(bounds), None);
assert_eq!(small.kept_inside(Rect::new(0.0, 0.0, 0.0, 500.0)), None);
}
#[test]
fn degenerate_frames_give_none_or_finite_results() {
let rects = [
Rect::new(10.0, 10.0, 10.0, 10.0),
Rect::new(10.0, 10.0, 10.0, 50.0),
Rect::new(-1e300, -1e300, 1e300, 1e300),
Rect::new(0.0, 0.0, 800.0, 500.0),
];
let angles = [0.0, 30.0, -90.0, 1e300];
let holds = [AspectHold::Free, AspectHold::Ratio(1.6), AspectHold::Diagonal];
let parts = [BoxPart::Corner(2), BoxPart::Edge(1), BoxPart::Inside];
let bounds = Rect::new(0.0, 0.0, 800.0, 500.0);
for rect in rects {
for angle in angles {
let b = CropBox::new(rect, angle);
for part in parts {
for hold in holds {
for alt in [false, true] {
let by = Vec2::new(-5.0, 7.0);
let resized = b.resized(part, by, hold, alt);
assert!(resized.is_finite(), "{b:?} {part:?} {hold:?}: {resized:?}");
if let Some(centred) = b.resized_centred(part, by, hold, alt) {
assert!(centred.is_finite(), "{centred:?}");
}
}
}
}
assert!(b.turned_to(0.3, Point::new(5.0, 9.0), Some(15.0), true).is_finite(), "{b:?}");
if let Some(fitted) = b.fitted(Size::new(800.0, 500.0), angle) {
assert!(fitted.is_finite(), "{fitted:?}");
}
if let Some(kept) = b.kept_inside(bounds) {
assert!(kept.is_finite(), "{kept:?}");
}
}
}
// Input that is not finite gives nothing rather than a panic.
for b in [CropBox::new(Rect::new(f64::NAN, 0.0, 10.0, 10.0), 0.0), CropBox::new(Rect::new(0.0, 0.0, 10.0, 10.0), f64::INFINITY)] {
let _ = b.resized(BoxPart::Corner(0), Vec2::new(1.0, 1.0), AspectHold::Diagonal, false);
assert_eq!(b.resized_centred(BoxPart::Corner(0), Vec2::new(1.0, 1.0), AspectHold::Diagonal, false), None);
assert_eq!(b.kept_inside(bounds), None);
}
let huge = Rect::new(0.0, 0.0, 1e300, 1e300);
for (w, h, step, visible) in [
(1e300, 1e300, 48.0, huge),
(1e300, 1e300, 1e-300, huge),
(f64::INFINITY, 100.0, 48.0, huge),
(200.0, 100.0, f64::NAN, huge),
(200.0, 100.0, -1.0, huge),
] {
let lines = turn_grid(w, h, step, visible);
assert!(lines.len() <= 2 * 4096, "bounded: {}", lines.len());
assert!(lines.iter().flatten().all(|p| p.x.is_finite() && p.y.is_finite()), "{w} x {h} by {step}");
}
}
+2 -1
View File
@@ -1,10 +1,11 @@
//! Canvas geometry rules: the transform box, snapping, the outline draft, the marquee gesture,
//! the move gesture and the ⇧ direction rules.
//! the move gesture, the ⇧ direction rules, the crop frame and the area outside it.
mod crop;
mod draft;
mod lock;
mod marquee;
mod move_gesture;
mod outside;
mod quad;
mod snap;
+81
View File
@@ -0,0 +1,81 @@
//! The canvas outside a crop frame, as the convex pieces the shield fills.
use craft_behavior::geometry::crop::turn;
use craft_behavior::geometry::outside_pieces;
use kurbo::Point;
const CANVAS: [Point; 4] = [Point::new(0.0, 0.0), Point::new(400.0, 0.0), Point::new(400.0, 300.0), Point::new(0.0, 300.0)];
fn quad(x0: f64, y0: f64, x1: f64, y1: f64) -> Vec<Point> {
vec![Point::new(x0, y0), Point::new(x1, y0), Point::new(x1, y1), Point::new(x0, y1)]
}
fn area(poly: &[Point]) -> f64 {
poly.iter().zip(poly.iter().cycle().skip(1)).map(|(p, q)| p.x * q.y - q.x * p.y).sum::<f64>().abs() / 2.0
}
/// Whether `p` lies strictly inside the convex `poly`, either way round; repeated points are skipped.
fn contains(poly: &[Point], p: Point) -> bool {
let sides: Vec<f64> =
poly.iter().zip(poly.iter().cycle().skip(1)).filter(|(a, b)| a.distance(**b) > 1e-12).map(|(a, b)| (*b - *a).cross(p - *a)).collect();
sides.iter().all(|s| *s > 0.0) || sides.iter().all(|s| *s < 0.0)
}
/// How far `p` is from the outline of `poly`.
fn to_outline(poly: &[Point], p: Point) -> f64 {
poly.iter()
.zip(poly.iter().cycle().skip(1))
.map(|(a, b)| {
let d = *b - *a;
let t = ((p - *a).dot(d) / d.hypot2()).clamp(0.0, 1.0);
p.distance(*a + d * t)
})
.fold(f64::INFINITY, f64::min)
}
/// Every sample point of the canvas outside `hole` lies in exactly one piece, every one inside it in none, and the
/// pieces' areas add up to the canvas's outside the hole (`hole_on_canvas`, the hole's area on the canvas).
fn covers_once(hole: &[Point], hole_on_canvas: f64) {
let pieces = outside_pieces(CANVAS, hole);
for i in 0..40 {
for j in 0..30 {
let p = Point::new(f64::from(i) * 10.0 + 3.7, f64::from(j) * 10.0 + 4.3);
if to_outline(hole, p) < 1e-6 {
continue;
}
let count = pieces.iter().filter(|piece| contains(piece, p)).count();
let want = usize::from(!contains(hole, p));
assert_eq!(count, want, "{p:?} with the hole {hole:?}: in {count} pieces");
}
}
let total: f64 = pieces.iter().map(|piece| area(piece)).sum();
assert!((total - (area(&CANVAS) - hole_on_canvas)).abs() < 1e-6, "{total} for the hole {hole:?}");
}
#[test]
fn outside_pieces_cover_the_canvas_outside_the_hole_once() {
// An upright frame, the same frame given the other way round, and turned frames.
let upright = quad(100.0, 80.0, 300.0, 220.0);
covers_once(&upright, 200.0 * 140.0);
covers_once(&upright.iter().rev().copied().collect::<Vec<_>>(), 200.0 * 140.0);
for angle in [15.0, -40.0, 90.0] {
let turned: Vec<Point> = upright.iter().map(|p| turn(*p, Point::new(200.0, 150.0), angle)).collect();
covers_once(&turned, 200.0 * 140.0);
}
// A hole past the canvas edge, one off the canvas, and one that covers it all.
covers_once(&quad(300.0, 200.0, 500.0, 400.0), 100.0 * 100.0);
covers_once(&quad(500.0, 0.0, 600.0, 100.0), 0.0);
assert!(outside_pieces(CANVAS, &quad(-10.0, -10.0, 410.0, 310.0)).is_empty(), "nothing of the canvas is outside");
// Holes with no area, too few points, or points that are not finite give nothing.
let point = Point::new(50.0, 50.0);
for hole in [
vec![],
vec![point, Point::new(80.0, 80.0)],
vec![point, Point::new(80.0, 80.0), Point::new(110.0, 110.0)],
vec![point; 4],
vec![point, Point::new(f64::NAN, 80.0), Point::new(110.0, 50.0), Point::new(80.0, 20.0)],
vec![point, Point::new(f64::INFINITY, 80.0), Point::new(110.0, 50.0)],
] {
assert!(outside_pieces(CANVAS, &hole).is_empty(), "{hole:?}");
}
}
+108 -28
View File
@@ -1,14 +1,14 @@
//! What a pointer drag does to the crop frame: the kinds of drag, the frame each step gives, and how image mode moves
//! the view with it.
use craft_behavior::CanvasView;
use craft_behavior::geometry::crop::{direction, drawn, image_turn, normalized_angle};
use craft_behavior::geometry::{BoxPart, CropBox, SnapLine, SnapTargets, crop_view_about, screen_step};
use craft_behavior::geometry::{AspectHold, BoxPart, CropBox, SnapLine, crop_view_about, screen_step};
use craft_behavior::kurbo::{Point, Rect, Vec2};
use craft_behavior::{Axis, CanvasView};
use craft_keymap::{Mods, Platform};
use egui::Pos2;
use crate::canvas::snap_tolerance;
use crate::canvas::{GestureSnap, Snap, snap_tolerance};
/// What a drag does to the frame.
#[derive(Clone, Copy, Debug, PartialEq)]
@@ -39,21 +39,51 @@ pub(super) struct Drag {
pub press_view: Option<CanvasView>,
/// The frame the drag last produced.
pub last: CropBox,
/// A step of this drag has proposed a frame other than the press frame. It stays set until the drag ends, so a
/// drag that brings the frame back keeps the started look.
pub changed: bool,
/// The pointer of the last step, in screen points.
pub pointer: Pos2,
}
impl Drag {
/// The pointer that asks to scroll the view past the canvas edge: a draw, a classic move, and a resize the view
/// does not keep centred. A turn, an image-mode move (the view follows the frame) and a Straighten line never
/// scroll. Read from the running drag, not this pass's input, so every pass of a frame reports the same.
pub fn scrolls_at(&self, image: bool, auto_center: bool) -> Option<Pos2> {
let scrolls = match self.kind {
Kind::Draw { .. } => true,
Kind::Move => !image,
Kind::Resize(_) => !(image && auto_center),
Kind::Turn { .. } | Kind::Line { .. } => false,
};
scrolls.then_some(self.pointer)
}
}
/// The rules every step of a drag follows.
#[derive(Clone, Copy)]
pub(super) struct Rules<'a> {
#[derive(Clone)]
pub(super) struct Rules {
pub ratio: Option<f64>,
pub bounds: Option<Rect>,
pub turn_step: f64,
pub image: bool,
pub auto_center: bool,
pub snap: Option<&'a SnapTargets>,
/// The canvas's snapping, with this pass's tolerance.
pub snap: Option<Snap>,
pub os: Platform,
}
impl Rules<'_> {
impl Rules {
/// What a resize holds: the set ratio; else, with Shift, the frame's own proportions along its diagonal.
fn hold(&self, mods: Mods) -> AspectHold {
match self.ratio {
Some(k) => AspectHold::Ratio(k),
None if mods.shift => AspectHold::Diagonal,
None => AspectHold::Free,
}
}
/// The frame a drag gives with the pointer at document point `to`, kept inside the bounds; `None` when the frame is
/// as it was (a draw not yet sized) or cannot be kept inside.
pub fn proposal(&self, drag: &mut Drag, to: Point, mods: Mods, space: bool) -> Option<CropBox> {
@@ -77,22 +107,29 @@ impl Rules<'_> {
Kind::Move if self.image => (at.moved(drag.from - to), false, false),
Kind::Move => (at.moved(to - drag.from), false, false),
Kind::Resize(part) => {
let r = at.rect.abs();
let keep = (r.width() > 0.0 && r.height() > 0.0).then(|| r.width() / r.height());
let ratio = self.ratio.or(if mods.shift { keep } else { None });
let by = to - drag.from;
// P3(tools-w15): tl.T41
let hold = ratio.map_or(craft_behavior::geometry::AspectHold::Free, craft_behavior::geometry::AspectHold::Ratio);
let hold = self.hold(mods);
let next = if self.image && self.auto_center {
at.resized_centred(*part, by, hold, mods.alt)?
} else {
at.resized(*part, by, hold, mods.alt)
};
(next, true, ratio.is_some())
(next, true, self.ratio.is_some() || mods.shift)
}
Kind::Turn { grab } => {
let step = mods.shift.then_some(self.turn_step);
(at.turned_to(*grab, to, step, self.image), true, false)
let turned = at.turned_to(*grab, to, step, self.image);
match self.bounds.filter(|_| self.image) {
// An image-mode turn keeps the frame inside the turned image (#10869), each step from the press
// frame so turning back gives it back. ⌘ keeps the press frame, and so does a press frame that
// was already past the bounds.
Some(bounds) => {
let keeps_press = mods.cmd || at.kept_inside(bounds) != Some(at);
let kept = if keeps_press { Some(turned) } else { turned.kept_inside(bounds) };
return kept.filter(CropBox::is_finite).or(Some(drag.last));
}
None => (turned, true, false),
}
}
Kind::Line { .. } => return None,
};
@@ -105,34 +142,49 @@ impl Rules<'_> {
}
}
/// The screen point of `pos` after the snap targets: an end of the Straighten line.
/// The screen point of `pos` after the canvas's snapping: an end of the Straighten line.
pub fn snap_screen(&self, view: &CanvasView, pos: Pos2, mods: Mods) -> Pos2 {
let (Some(targets), Some(tolerance)) = (self.snap, snap_tolerance(view, mods, self.os, false)) else { return pos };
let (point, _) = targets.snap_point(view.to_doc(pos), tolerance);
view.to_screen(point)
let Some(snap) = &self.snap else { return pos };
let (point, lines) = snap.point(view.to_doc(pos), mods, GestureSnap::default());
if lines.is_empty() { pos } else { view.to_screen(point) }
}
/// The drag's document point for the pointer at `to` after the host's snap targets, with the lines that snapped. In
/// The drag's document point for the pointer at `to` after the canvas's snapping, with the lines that snapped. In
/// image mode the point is in the view of the press, which the moving view never feeds back into: the correction
/// is turned back into pointer travel.
/// is turned back into pointer travel. A corner that holds its proportions (a ratio, or Shift) slides along its
/// diagonal onto the line it snapped to, so the handle lands on the line with the proportions kept.
pub fn snapped(&self, drag: &Drag, view: &CanvasView, to: Point, mods: Mods, space: bool) -> (Point, Vec<SnapLine>) {
let tolerance = snap_tolerance(drag.press_view.as_ref().unwrap_or(view), mods, self.os, false);
let (Some(targets), Some(tolerance)) = (self.snap, tolerance) else { return (to, Vec::new()) };
let Some(snap) = &self.snap else { return (to, Vec::new()) };
let mut probe = drag.clone();
let Some(candidate) = self.proposal(&mut probe, to, mods, space) else { return (to, Vec::new()) };
let (by, lines, travel_per_unit) = match probe.kind {
Kind::Draw { cur, .. } => {
let (snapped, lines) = targets.snap_point(cur, tolerance);
let (snapped, lines) = snap.point(cur, mods, GestureSnap::default());
(snapped - cur, lines, 1.0)
}
Kind::Move => {
let (by, lines) = targets.snap_rect(candidate.turned_bounds(), tolerance);
let (by, lines) = snap.rect(candidate.turned_bounds(), mods);
(by, lines, if self.image { -1.0 } else { 1.0 })
}
Kind::Resize(part) => {
let Some(point) = candidate.part_point(part) else { return (to, Vec::new()) };
let (snapped, lines) = targets.snap_point(point, tolerance);
(snapped - point, lines, if self.image && self.auto_center && !mods.alt { 0.5 } else { 1.0 })
let (snapped, lines) = snap.point(point, mods, GestureSnap::default());
let travel = if self.image && self.auto_center && !mods.alt { 0.5 } else { 1.0 };
let corner = matches!(part, BoxPart::Corner(_));
if corner && !lines.is_empty() && self.hold(mods) != AspectHold::Free {
// The reach at the press view: the rule `Snap::at` sets the tolerance with; a crop drag never
// changes the zoom.
let Some(reach) = snap_tolerance(drag.press_view.as_ref().unwrap_or(view), mods, self.os, false) else {
return (to, Vec::new());
};
match slid_along(point, point - candidate.center(), lines, reach) {
Some((by, lines)) => (by, lines, travel),
// The diagonal meets no snapped line within reach: the handle stays where the drag put it.
None => return (to, Vec::new()),
}
} else {
(snapped - point, lines, travel)
}
}
Kind::Turn { .. } | Kind::Line { .. } => return (to, Vec::new()),
};
@@ -140,6 +192,32 @@ impl Rules<'_> {
}
}
/// 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.
fn slid_along(point: Point, along: Vec2, lines: Vec<SnapLine>, reach: f64) -> Option<(Vec2, Vec<SnapLine>)> {
// A vertical line (along y) is met where x reaches it, a horizontal one where y does.
let gap = |line: &SnapLine| if matches!(line.along, Axis::Y) { (line.position - point.x, along.x) } else { (line.position - point.y, along.y) };
let s = lines
.iter()
.filter_map(|line| {
let (gap, step) = gap(line);
(step.abs() > 1e-9).then(|| gap / step)
})
.filter(|s| s.is_finite() && (s * along.x).abs() <= reach && (s * along.y).abs() <= reach)
.min_by(|a, b| a.abs().total_cmp(&b.abs()))?;
let by = along * s;
let at = point + by;
let on = lines
.into_iter()
.filter(|line| {
let v = if matches!(line.along, Axis::Y) { at.x } else { at.y };
(v - line.position).abs() < 1e-6
})
.collect();
Some((by, on))
}
/// The view after a drag step that gave frame `next`, from the view of the press, so the view moving with the image
/// never feeds back into the drag. `None` outside image mode.
pub(super) fn followed(drag: &Drag, auto_center: bool, next: &CropBox) -> Option<CanvasView> {
@@ -152,7 +230,9 @@ pub(super) fn followed(drag: &Drag, auto_center: bool, next: &CropBox) -> Option
Some(match drag.kind {
Kind::Move => slid(),
Kind::Resize(_) if auto_center => slid(),
Kind::Turn { .. } => crop_view_about(next, &press, drag.at_press.center()),
// The view first follows the frame's centre, which a turn kept inside the image may move, then turns about
// it: the box stays put on screen.
Kind::Turn { .. } => crop_view_about(next, &slid(), next.center()),
Kind::Draw { .. } | Kind::Resize(_) | Kind::Line { .. } => press,
})
}
@@ -171,7 +251,7 @@ pub(super) fn centred(drag: &Drag, auto_center: bool, view: &CanvasView, shown:
/// The frame after an arrow key moved `part` by the screen vector `by`, or X swapped it, with the view image mode
/// moves along. `None` when the key changes nothing.
pub(super) fn nudged(frame: &CropBox, part: BoxPart, by: Vec2, view: &CanvasView, rules: &Rules<'_>) -> (CropBox, Option<CanvasView>) {
pub(super) fn nudged(frame: &CropBox, part: BoxPart, by: Vec2, view: &CanvasView, rules: &Rules) -> (CropBox, Option<CanvasView>) {
let step = screen_step(view, by);
if part == BoxPart::Inside && rules.image {
// The image moves under the frame: the frame goes the other way and the view follows it.
+78 -35
View File
@@ -9,7 +9,7 @@ mod shield;
mod stories;
use super::words::CanvasWords;
use super::{CanvasSpace, NUDGE, NUDGE_FAR, canvas_space, readout};
use super::{CanvasSpace, NUDGE, NUDGE_FAR, canvas_snap, canvas_space, readout};
use crate::contract::{
Access, Bind, BindMut, Common, Component, Cx, Edit as _, EditResponse, Focus as _, MeasureCx, Name, Outcome, PaintUi, PartsCx, Pointer as _,
Props as _, Remember as _, Role, WordSetCx as _,
@@ -17,13 +17,14 @@ use crate::contract::{
use crate::runtime::env::Label;
use crate::runtime::focus::KeyUse;
use crate::style::{ComponentStyle, StyleColor, StyleCx};
use craft_behavior::geometry::{BoxPart, CropBox, CropGuide, GuideShow, SnapLine, SnapTargets};
use craft_behavior::geometry::{BoxPart, CropBox, CropGuide, GuideShow, SnapLine};
use craft_behavior::kurbo::{Point, Rect as DocRect, Vec2 as DocVec};
use craft_behavior::{
Axis, CancelReason, CanvasView, CursorIcon, CursorPriority, HitLevel, HitPriority, HitShape, Intent, Metrics, NavShape, PaintedCursor, PartKey,
PointerButton, PressPhase, Roving, Sense, resize_cursor,
};
use craft_keymap::{Chord, Key, Mods, Platform};
use crate::runtime::env::EnvView;
use craft_keymap::{Chord, Key, Mods};
use egui::{Pos2, Rect, Response, Vec2};
use gesture::{Drag, Kind, Rules};
@@ -58,7 +59,8 @@ pub struct CropStyle {
halo: StyleColor,
/// The composition guide lines.
guide: StyleColor,
/// The canvas colour the shield matches.
/// The theme's canvas colour: the guide fades toward it, and the shield matches it on a canvas whose pasteboard
/// takes the theme's colour.
canvas: StyleColor,
/// The line of a frame the binding refuses.
invalid: StyleColor,
@@ -94,6 +96,8 @@ struct Report {
nudged: bool,
turning: Option<f64>,
sizing: Option<(f64, f64)>,
scrolls_at: Option<Pos2>,
straighten_ended: bool,
}
/// What a pass leaves for the next and for paint.
@@ -105,11 +109,15 @@ struct Live {
/// The crop frame of a document, edited by dragging it as Photoshop's Classic crop does (or moving and turning the image
/// 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 ratio, 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.
/// - 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.
/// - 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,
/// `KeyUse::session`, before the canvas's tool): Enter applies; Escape cancels a drag, else discards; the arrows
/// nudge the picked part, the whole frame when no part has focus (Shift by ten). On a focused part X swaps portrait
@@ -144,7 +152,8 @@ pub struct CropOverlay<'a> {
/// angle that levels it.
#[prop(flag)]
straighten: bool,
/// The area the frame may not leave, in document units.
/// The area the frame may not leave, in document units. An image-mode turn moves or shrinks the frame to keep it
/// inside (Command keeps it as it was at the press).
#[prop]
bounds: Option<DocRect>,
/// Image mode: the frame stays upright on screen and a move or turn moves or turns the view instead.
@@ -157,9 +166,6 @@ pub struct CropOverlay<'a> {
/// Nothing is painted and a press anywhere on the canvas draws a new frame.
#[prop(flag)]
hidden: bool,
/// The snap targets a dragged part snaps to.
#[prop]
snap: Option<&'a SnapTargets>,
report: Report,
}
@@ -180,24 +186,36 @@ impl<'a> CropOverlay<'a> {
image_mode: false,
auto_center: false,
hidden: false,
snap: None,
report: Report::default(),
}
.label(label)
}
fn rules(&self, os: Platform) -> Rules<'a> {
/// The rules of a drag step, with the canvas's snapping as this pass has it.
fn rules(&self, env: &EnvView<'_>) -> Rules {
Rules {
ratio: self.ratio.filter(|k| k.is_finite() && *k > 0.0),
bounds: self.bounds,
turn_step: self.turn_step,
image: self.image_mode,
auto_center: self.auto_center,
snap: self.snap,
os,
snap: canvas_snap(env),
os: env.shell().os,
}
}
/// Whether the crop has started: anything but the untouched default frame in image mode, or a drag that changed
/// the frame, or a turn or Straighten line running (their guides aim the gesture). Until then no shield and no
/// guide show and the outline is dashed (#10930).
fn started(&self, drag: Option<&Drag>) -> bool {
!self.default_frame || !self.image_mode || drag.is_some_and(|drag| drag.changed || matches!(drag.kind, Kind::Turn { .. } | Kind::Line { .. }))
}
/// A press inside the frame draws a new one: on the default frame, and anywhere while the overlay is hidden.
fn draws(&self) -> bool {
self.default_frame || self.hidden
}
/// The frame to show: the value, or the whole document while the value is mixed.
fn shown(&self, value: Option<&CropBox>, view: &CanvasView) -> CropBox {
value.copied().unwrap_or_else(|| CropBox::upright(self.bounds.unwrap_or_else(|| view.visible())))
@@ -270,24 +288,25 @@ impl CropOverlay<'_> {
let from = view.to_doc(origin);
let kind = match grab {
Grab::Line => {
let from = self.rules(cx.env.shell().os).snap_screen(&view, origin, mods);
let from = self.rules(&cx.env).snap_screen(&view, origin, mods);
Kind::Line { from, to: from }
}
Grab::Turn => Kind::Turn { grab: gesture::grab(frame, from) },
Grab::Part(BoxPart::Inside) if !self.default_frame => Kind::Move,
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),
};
if !matches!(kind, Kind::Line { .. }) {
cx.begin();
}
Drag { kind, at_press: *frame, from, press_view: self.image_mode.then_some(view), last: *frame }
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`.
fn step(&mut self, cx: &mut Cx<'_, Self>, space: &CanvasSpace, drag: &mut Drag, pos: Pos2, mods: Mods) {
let view = space.view;
let rules = self.rules(cx.env.shell().os);
let rules = self.rules(&cx.env);
drag.pointer = pos;
if let Kind::Line { from, to } = &mut drag.kind {
*to = rules.snap_screen(&view, pos, mods);
self.report.dragging = true;
@@ -302,6 +321,7 @@ impl CropOverlay<'_> {
self.report.snapped = lines;
if let Some(next) = rules.proposal(drag, to, mods, held_space) {
drag.last = next;
drag.changed |= next != drag.at_press;
// A frame with no extent on screen declares no parts, which would end the press with the edit still open: it
// is remembered (the release cancels the edit) but not proposed.
if !degenerate(&screen_corners(&view, &next)) {
@@ -325,15 +345,14 @@ impl CropOverlay<'_> {
readout(cx, pos, &rows);
}
/// The button released after a drag at screen point `pos`.
fn finish(&mut self, cx: &mut Cx<'_, Self>, space: &CanvasSpace, drag: Drag, pos: Pos2) {
/// The button released after a drag.
fn finish(&mut self, cx: &mut Cx<'_, Self>, space: &CanvasSpace, drag: Drag) {
if let Kind::Line { from, to } = drag.kind {
if f64::from((to - from).length()) >= STRAIGHTEN_MIN {
self.report.straightened = CropBox::level_angle(space.view.to_doc(from), space.view.to_doc(to));
}
return;
}
let _ = pos;
if drag.last.is_finite() && drag.last.size_ok() {
if let Some(view) = gesture::centred(&drag, self.auto_center, &space.view, &drag.last) {
self.report.view = Some(view);
@@ -362,7 +381,11 @@ impl CropOverlay<'_> {
if cx.intents().take(Intent::Cancel) {
self.report.discard = true;
}
let rules = self.rules(cx.env.shell().os);
// A hidden frame is not shown to move.
if self.hidden {
return;
}
let rules = self.rules(&cx.env);
let mut next = None;
if let Some((direction, mods)) = cx.intents().take_nudge() {
let step = if mods.shift { NUDGE_FAR } else { NUDGE };
@@ -421,8 +444,9 @@ pub struct CropOverlayOutput {
pub turning: Option<f64>,
/// The size Enter would crop to while the frame is drawn or resized.
pub sizing: Option<(f64, f64)>,
/// The pointer of a draw, a classic move or a resize that is not live-centred: the crop tool hands it to
/// `ToolContext::autoscroll_at`; `None` for a turn, an image-mode move and a Straighten line.
/// The pointer of a draw, a classic move or a resize that is not live-centred, in every pass while the drag runs:
/// the crop tool hands it to `ToolContext::autoscroll_at`; `None` for a turn, an image-mode move and a Straighten
/// line.
pub scrolls_at: Option<Pos2>,
/// True in the pass a Straighten press is released or cancelled, whatever its length.
pub straighten_ended: bool,
@@ -489,6 +513,15 @@ impl Component for CropOverlay<'_> {
.cursor(CursorIcon::Crosshair)
.pointer_only("the options bar's angle field sets the straightened angle");
}
if self.hidden {
// No frame to grab: the whole canvas is the default frame's inside, where a press draws a new frame.
cx.part(FRAME.at(BoxPart::Inside.index()), HitShape::Rect(rect))
.sense(Sense::DRAG)
.priority(HitPriority::BODY)
.cursor(CursorIcon::Crosshair)
.pointer_only("the options bar's size fields set the frame while it is hidden");
return;
}
let q = screen_corners(&view, &frame);
if !frame.is_finite() || degenerate(&q) {
return;
@@ -557,7 +590,7 @@ impl Component for CropOverlay<'_> {
let mods = press.mods;
match press.phase {
PressPhase::Down { start, .. } if start.button == PointerButton::Primary => {
if grab == Grab::Part(BoxPart::Inside) && press.double_pressed() && !self.default_frame {
if grab == Grab::Part(BoxPart::Inside) && press.double_pressed() && !self.draws() {
self.report.apply = true;
}
}
@@ -572,12 +605,16 @@ impl Component for CropOverlay<'_> {
live.drag = Some(drag);
}
}
PressPhase::Release { pos, click: false, .. } => {
if let Some(drag) = live.drag.take() {
self.finish(cx, &space, drag, pos);
// The press phases reach only the pass that has the frame's input, so a second pass of the frame
// reports no Straighten end and finishes no drag a second time.
PressPhase::Release { start, click, .. } => {
self.report.straighten_ended |= grab == Grab::Line && start.button == PointerButton::Primary;
if !click && let Some(drag) = live.drag.take() {
self.finish(cx, &space, drag);
}
}
PressPhase::Cancel { .. } => {
self.report.straighten_ended |= grab == Grab::Line;
if let Some(drag) = live.drag.take() {
self.report.view = drag.press_view;
}
@@ -597,6 +634,7 @@ impl Component for CropOverlay<'_> {
.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));
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>() = live;
}
@@ -607,7 +645,9 @@ impl Component for CropOverlay<'_> {
let picked =
cx.focus_visible().then(|| cx.active_part()).flatten().filter(|part| part.key == FRAME).and_then(|part| part.index).and_then(frame_part);
let refused = matches!(cx.validity(), crate::contract::Validity::Refuse(_) | crate::contract::Validity::Error(_));
paint::paint(ui, cx, &paint::Scene { space: &space, frame, drag: live.drag.as_ref(), picked, refused, overlay: self });
let drag = live.drag.as_ref();
let started = self.started(drag);
paint::paint(ui, cx, &paint::Scene { space: &space, frame, drag, picked, refused, started, overlay: self });
}
fn access(&self, access: &mut Access, cx: &Cx<'_, Self>) {
@@ -620,6 +660,9 @@ impl Component for CropOverlay<'_> {
let (w, h) = (frame.rect.width(), frame.rect.height());
let angle = units.number_ungrouped(gesture::turn_degrees(&frame, false), 1..=1);
access.value(format!("{} × {}, {angle}°", x.format_value(&units, w, 0.0), y.format_value(&units, h, 0.0)));
if self.hidden {
return;
}
let names = [
(BoxPart::Inside, &words.crop_whole),
(BoxPart::Corner(0), &words.crop_top_left),
@@ -638,7 +681,7 @@ impl Component for CropOverlay<'_> {
fn finish(self, cx: Cx<'_, Self>) -> CropOverlayOutput {
let picked = cx.active_part().filter(|part| part.key == FRAME).and_then(|part| part.index).and_then(frame_part);
let Report { apply, discard, straightened, view, snapped, hovered, dragging, nudged, turning, sizing } = self.report;
let Report { apply, discard, straightened, view, snapped, hovered, dragging, nudged, turning, sizing, scrolls_at, straighten_ended } = self.report;
CropOverlayOutput {
edit: cx.edit_response(),
apply,
@@ -652,8 +695,8 @@ impl Component for CropOverlay<'_> {
nudged,
turning,
sizing,
scrolls_at: None, // P3(tools-w15): tl.T43
straighten_ended: false, // P3(tools-w15): tl.T43
scrolls_at,
straighten_ended,
}
}
}
+73 -48
View File
@@ -1,44 +1,49 @@
//! Painting the crop overlay: shield, frame line, guides, corner brackets, edge bars, focus and the Straighten line.
use super::gesture::{Drag, Kind};
use super::{BAR_SHARE, CropOverlay, GRID_MAX, STRAIGHTEN_MIN, screen_corners};
use super::{BAR_SHARE, CropOverlay, GRID_MAX, screen_corners};
use crate::canvas::CanvasSpace;
use crate::contract::{Cx, PaintUi};
use crate::primitives::{PaintShape, StrokeWidth};
use crate::primitives::{Draw, PaintShape, StrokeWidth};
use crate::style::DataColor;
use craft_behavior::geometry::{BoxPart, CropBox};
use craft_behavior::geometry::{BoxPart, CropBox, turn_grid};
use craft_behavior::kurbo::{Point, Rect as DocRect};
use egui::{CornerRadius, Pos2, Rect, Vec2};
/// How many Grid guide steps apart the turn grid's lines are: production's 48 points.
const TURN_GRID_STEPS: f64 = 3.0;
pub(super) struct Scene<'a, 'b> {
pub space: &'a CanvasSpace,
pub frame: CropBox,
pub drag: Option<&'a Drag>,
pub picked: Option<BoxPart>,
pub refused: bool,
/// The crop has started (`CropOverlay::started`): the shield and the guide show and the outline is solid.
pub started: bool,
pub overlay: &'a CropOverlay<'b>,
}
/// Whether the screen quad `q` has horizontal and vertical sides.
fn axis_aligned(q: &[Pos2; 4]) -> bool {
(0..4).all(|i| {
let d = q[(i + 1) % 4] - q[i];
d.x.abs() < 0.01 || d.y.abs() < 0.01
})
}
pub(super) fn paint(ui: &mut PaintUi<'_>, cx: &Cx<'_, CropOverlay<'_>>, scene: &Scene<'_, '_>) {
if scene.overlay.hidden {
return;
}
let style = cx.style;
let draw = ui.draw();
let overlay = scene.overlay;
let view = &scene.space.view;
let area = cx.rect;
paint_frame(&draw, cx, scene);
if let Some(Drag { kind: Kind::Line { from, to }, .. }) = scene.drag {
let line = PaintShape::Path(vec![*from, *to]);
draw.stroke(&line, StrokeWidth::Thick, style.halo);
draw.stroke(&line, StrokeWidth::Medium, style.straighten);
let _ = STRAIGHTEN_MIN;
return;
}
}
/// The shield, the frame line, the guide, the brackets, the bars and the focus line.
fn paint_frame(draw: &Draw<'_>, cx: &Cx<'_, CropOverlay<'_>>, scene: &Scene<'_, '_>) {
let style = cx.style;
let overlay = scene.overlay;
let view = &scene.space.view;
let area = cx.rect;
let q = screen_corners(view, &scene.frame);
let (u, v) = (q[1] - q[0], q[3] - q[0]);
let (lu, lv) = (u.length(), v.length());
@@ -46,41 +51,35 @@ pub(super) fn paint(ui: &mut PaintUi<'_>, cx: &Cx<'_, CropOverlay<'_>>, scene: &
return;
}
let editing = scene.drag.is_some();
let canvas = style.canvas.egui();
if let Some(fill) = overlay.shield.fill(canvas, editing) {
let fill = DataColor::new(fill);
if axis_aligned(&q) {
let r = Rect::from_points(&q);
for band in [
Rect::from_min_max(area.min, Pos2::new(area.max.x, r.min.y)),
Rect::from_min_max(Pos2::new(area.min.x, r.max.y), area.max),
Rect::from_min_max(Pos2::new(area.min.x, r.min.y), Pos2::new(r.min.x, r.max.y)),
Rect::from_min_max(Pos2::new(r.max.x, r.min.y), Pos2::new(area.max.x, r.max.y)),
] {
if band.is_positive() {
draw.data_fill(&PaintShape::Rect(band, CornerRadius::ZERO), fill);
}
}
} else {
// Four trapezoids from the frame out to the frame grown past the whole area.
let at = |a: f32, b: f32| q[0] + u * a + v * b;
let reach = area.size().length() + (area.center() - at(0.5, 0.5)).length();
let (eu, ev) = (reach / lu, reach / lv);
let outer = [at(-eu, -ev), at(1.0 + eu, -ev), at(1.0 + eu, 1.0 + ev), at(-eu, 1.0 + ev)];
for i in 0..4 {
let j = (i + 1) % 4;
draw.data_fill(&PaintShape::Polygon(vec![q[i], q[j], outer[j], outer[i]]), fill);
}
if scene.started {
if let Some(fill) = overlay.shield.fill_on(scene.space, style.canvas.egui(), editing) {
let corners = [area.left_top(), area.right_top(), area.right_bottom(), area.left_bottom()];
super::paint_outside(draw, corners, &q, DataColor::new(fill));
}
}
let line = if scene.refused { style.invalid } else { style.line };
let outline = PaintShape::Polygon(q.to_vec());
draw.stroke(&outline, StrokeWidth::Thin, line);
if let Some((guide, orientation)) = overlay.guide
&& overlay.guide_show.shows(editing)
{
let at = |p: craft_behavior::kurbo::Point| q[0] + u * p.x as f32 + v * p.y as f32;
for polyline in guide.guides(orientation, f64::from(lu), f64::from(lv), f64::from(style.grid_step), GRID_MAX) {
if scene.started {
draw.stroke(&PaintShape::Polygon(q.to_vec()), StrokeWidth::Thin, line);
} else {
let mut ring = q.to_vec();
ring.push(q[0]);
draw.dashed(&ring, draw.dashes(), StrokeWidth::Thin, line);
}
if scene.started && overlay.guide_show.shows(editing) {
let turning = overlay.image_mode && matches!(scene.drag, Some(Drag { kind: Kind::Turn { .. }, .. }));
let lines = if turning {
// An image-mode turn shows its own grid in place of the chosen guide (#10931).
match visible_frame(&q, area, lu, lv) {
Some(visible) => turn_grid(f64::from(lu), f64::from(lv), TURN_GRID_STEPS * f64::from(style.grid_step), visible),
None => Vec::new(),
}
} else {
overlay.guide.map_or_else(Vec::new, |(guide, orientation)| {
guide.guides(orientation, f64::from(lu), f64::from(lv), f64::from(style.grid_step), GRID_MAX)
})
};
let at = |p: Point| q[0] + u * p.x as f32 + v * p.y as f32;
for polyline in lines {
draw.stroke(&PaintShape::Path(polyline.into_iter().map(at).collect()), StrokeWidth::Thin, style.guide);
}
}
@@ -128,3 +127,29 @@ pub(super) fn paint(ui: &mut PaintUi<'_>, cx: &Cx<'_, CropOverlay<'_>>, scene: &
}
}
}
/// The part of the control's rect `clip` inside the frame `q` (screen corners clockwise from the top left of the
/// upright frame, sides `w` and `h` long), in the frame's own screen axes: 0..`w` along its top edge, 0..`h` down
/// its left. A turned, flipped or stretched view maps through the inverse of the frame's axes. `None` when the
/// frame has no area on screen or anything is not finite.
fn visible_frame(q: &[Pos2; 4], clip: Rect, w: f32, h: f32) -> Option<DocRect> {
if !(clip.is_finite() && clip.is_positive()) {
return None;
}
let (u, v) = (q[1] - q[0], q[3] - q[0]);
let det = f64::from(u.x) * f64::from(v.y) - f64::from(u.y) * f64::from(v.x);
if !det.is_finite() || det.abs() < f64::EPSILON {
return None;
}
let (w, h) = (f64::from(w), f64::from(h));
let mut corners = [clip.left_top(), clip.right_top(), clip.right_bottom(), clip.left_bottom()].into_iter().map(|p| {
let d = p - q[0];
let x = (f64::from(d.x) * f64::from(v.y) - f64::from(d.y) * f64::from(v.x)) / det * w;
let y = (f64::from(u.x) * f64::from(d.y) - f64::from(u.y) * f64::from(d.x)) / det * h;
Point::new(x, y)
});
let first = corners.next()?;
let visible = corners.fold(DocRect::from_points(first, first), |acc, p| acc.union_pt(p));
let bounded = DocRect::new(visible.x0.max(0.0), visible.y0.max(0.0), visible.x1.min(w), visible.y1.min(h));
[bounded.x0, bounded.y0, bounded.x1, bounded.y1].iter().all(|c| c.is_finite()).then_some(bounded)
}
@@ -1,5 +1,6 @@
//! The crop shield: the options that dim the area outside the frame.
use crate::canvas::CanvasSpace;
use crate::primitives::{Draw, PaintShape};
use crate::style::DataColor;
use craft_behavior::geometry::outside_pieces;
@@ -97,6 +98,13 @@ impl CropShield {
o.clamp(0.0, 100.0) / 100.0
}
/// [`fill`](Self::fill) over the canvas colour of `space`: its pasteboard's colour when it has one, else
/// `theme_canvas`. The one rule both crops use to pick the Match Canvas colour.
pub fn fill_on(&self, space: &CanvasSpace, theme_canvas: Color32, editing: bool) -> Option<Color32> {
let canvas = space.pasteboard().fill().map_or(theme_canvas, |fill| fill.0);
self.fill(canvas, editing)
}
/// What to paint over the area outside the frame, `canvas` being the canvas colour and `editing` a crop drag in
/// progress: the opaque canvas colour when Show Cropped Area is off, nothing when the shield is disabled or fully
/// transparent, otherwise its colour at its opacity.
@@ -122,3 +122,24 @@ fn image_mode(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)).image_mode().auto_center().show_at(ui, at))
}
/// The default frame over the whole picture before any drag changed it: a dashed outline, no shield, no guide.
#[story(CropOverlay<'static>, covers = [Default], drive = Drive::Custom(drag_top_left))]
fn untouched(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
let rect = data.value("crop", CropBox::upright(StoryDocument::STANDARD.rect()));
on_landscape(ui, 0.0, |ui, at| {
CropOverlay::new("Crop", Bind::bound(&mut *rect))
.default_frame()
.image_mode()
.guide((CropGuide::Thirds, 0))
.guide_show(GuideShow::Always)
.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 {
let rect = data.value("crop", CropBox::upright(StoryDocument::STANDARD.rect()));
on_landscape(ui, 0.0, |ui, at| CropOverlay::new("Crop", Bind::bound(&mut *rect)).default_frame().image_mode().hidden().show_at(ui, at))
}
+495 -65
View File
@@ -1,14 +1,19 @@
//! `CropOverlay`: the frame's gestures and keys through real input.
//! `CropOverlay`: the frame's gestures, keys and look through real input.
use craft_behavior::geometry::{BoxPart, CropBox, SnapKind, SnapLine, SnapTarget, SnapTargets, crop_view};
use craft_behavior::geometry::{
AspectHold, BoxPart, CropBox, CropGuide, GuideShow, SNAP_PX, SnapKind, SnapLine, SnapOptions, SnapTarget, SnapTargets, crop_view,
};
use craft_behavior::kurbo::{Point, Rect};
use craft_behavior::{Axis, CanvasView, EditEvent};
use craft_ui::canvas::{Canvas, CropOverlay};
use craft_behavior::{Axis, CancelReason, CanvasView, EditEvent};
use craft_ui::canvas::{Canvas, CanvasTool, CropOverlay, Snap, ToolAction, ToolContext, ToolHost, ToolPath, ToolPointer};
use craft_ui::contract::{Bind, Show as _, ShowContainer as _};
use craft_ui::testing::{Frames, layout, pointer, trial};
use craft_ui::primitives::Draw;
use craft_ui::runtime::access::Role;
use craft_ui::testing::{Fixture, Frames, focus, input, layout, pointer, trial};
use egui::{Event, Modifiers, Pos2, Vec2};
use std::cell::RefCell;
use std::cell::{Cell, RefCell};
use std::rc::Rc;
use std::sync::Arc;
// Real input through the canvas: a frame per event batch, the view and the shown options held by the rig.
@@ -18,16 +23,22 @@ const ROOM: Vec2 = Vec2::new(400.0, 300.0);
/// The frame the drags start from, centred in the room's default view.
const RECT: Rect = Rect::new(100.0, 80.0, 300.0, 220.0);
/// The shortest painted line that counts as a guide line: longer than any corner bracket or edge bar.
const GUIDE_MIN: f32 = 40.0;
#[derive(Clone)]
struct Setup {
ratio: Option<f64>,
default_frame: bool,
image_mode: bool,
auto_center: bool,
hidden: bool,
bounds: Option<Rect>,
snap_x: Option<f64>,
snap_y: Option<f64>,
straighten: bool,
guide: Option<(CropGuide, u8)>,
guide_show: GuideShow,
view: CanvasView,
}
@@ -38,10 +49,13 @@ impl Setup {
default_frame: false,
image_mode: false,
auto_center: false,
hidden: false,
bounds: None,
snap_x: None,
snap_y: None,
straighten: false,
guide: None,
guide_show: GuideShow::Auto,
view: CanvasView::new(egui::Rect::ZERO, Point::new(200.0, 150.0), 1.0),
}
}
@@ -54,6 +68,15 @@ impl Setup {
setup.view = crop_view(&CropBox::new(RECT, angle), &setup.view);
setup
}
/// The default mode's untouched default frame, its thirds always shown.
fn untouched() -> Self {
let mut setup = Setup::image(0.0, false);
setup.default_frame = true;
setup.guide = Some((CropGuide::Thirds, 0));
setup.guide_show = GuideShow::Always;
setup
}
}
/// What the overlay reported across the passes.
@@ -68,6 +91,10 @@ struct Seen {
sizing: Option<(f64, f64)>,
turning: Option<f64>,
events: Vec<&'static str>,
/// `scrolls_at` of every pass, in order.
scrolls_at: Vec<Option<Pos2>>,
/// The passes that reported `straighten_ended`.
straighten_ended: usize,
}
struct Rig {
@@ -76,32 +103,39 @@ struct Rig {
crop: Rc<RefCell<CropBox>>,
setup: Rc<RefCell<Setup>>,
seen: Rc<RefCell<Seen>>,
/// While set, the first pass of each frame asks egui to run the frame again.
rerun: Rc<Cell<bool>>,
}
impl Rig {
fn new(crop: CropBox, setup: Setup) -> Self {
let (crop, setup, seen) = (Rc::new(RefCell::new(crop)), Rc::new(RefCell::new(setup)), Rc::new(RefCell::new(Seen::default())));
let (c, st, sn) = (Rc::clone(&crop), Rc::clone(&setup), Rc::clone(&seen));
let rerun = Rc::new(Cell::new(false));
let (c, st, sn, again) = (Rc::clone(&crop), Rc::clone(&setup), Rc::clone(&seen), Rc::clone(&rerun));
let show = move |ui: &mut egui::Ui| {
let mut s = st.borrow().clone();
s.view.rect = ui.available_rect_before_wrap();
st.borrow_mut().view.rect = s.view.rect;
let _ = Canvas::new("Document").view(s.view).show(ui, |ui, body| {
let mut targets = SnapTargets::new();
if let Some(x) = s.snap_x {
targets.add(SnapTarget::new(Axis::Y, x, SnapKind::Guide));
}
if let Some(y) = s.snap_y {
targets.add(SnapTarget::new(Axis::X, y, SnapKind::Guide));
}
let mut targets = SnapTargets::new();
if let Some(x) = s.snap_x {
targets.add(SnapTarget::new(Axis::Y, x, SnapKind::Guide));
}
if let Some(y) = s.snap_y {
targets.add(SnapTarget::new(Axis::X, y, SnapKind::Guide));
}
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)).snap(&targets);
let mut overlay = CropOverlay::new("Crop", Bind::bound(&mut *value)).guide_show(s.guide_show);
if let Some(ratio) = s.ratio {
overlay = overlay.ratio(ratio);
}
if let Some(bounds) = s.bounds {
overlay = overlay.bounds(bounds);
}
if let Some(guide) = s.guide {
overlay = overlay.guide(guide);
}
if s.default_frame {
overlay = overlay.default_frame();
}
@@ -114,7 +148,14 @@ impl Rig {
if s.straighten {
overlay = overlay.straighten();
}
if s.hidden {
overlay = overlay.hidden();
}
let out = overlay.show_at(ui, body.rect);
// A measuring run of the canvas body (a sizing ui) senses nothing: only the real run of a pass reports.
if ui.is_sizing_pass() {
return;
}
let mut seen = sn.borrow_mut();
if let Some(view) = out.view {
st.borrow_mut().view = view;
@@ -140,9 +181,14 @@ impl Rig {
seen.hovered = out.hovered;
seen.sizing = out.sizing;
seen.turning = out.turning;
seen.scrolls_at.push(out.scrolls_at);
seen.straighten_ended += usize::from(out.straighten_ended);
});
if again.get() && ui.ctx().current_pass_index() == 0 {
ui.ctx().request_discard("the trial runs the frame twice");
}
};
let mut rig = Rig { frames: Frames::new(), show: Box::new(show), crop, setup, seen };
let mut rig = Rig { frames: Frames::new(), show: Box::new(show), crop, setup, seen, rerun };
for _ in 0..4 {
rig.frame(Vec::new());
}
@@ -153,10 +199,26 @@ impl Rig {
Rig::new(CropBox::upright(RECT), Setup::new())
}
fn frame(&mut self, events: Vec<Event>) {
/// One frame with `events`; returns how many passes it ran.
fn frame(&mut self, events: Vec<Event>) -> usize {
let room = egui::Rect::from_min_size(Pos2::ZERO, ROOM);
let show = &mut self.show;
self.frames.frame(events, |ui| layout::in_region(ui, room, |ui| show(ui)));
self.frames.frame(events, |ui| layout::in_region(ui, room, |ui| show(ui)))
}
/// One frame with `events` that runs twice: its second pass has no input of its own.
fn frame_twice(&mut self, events: Vec<Event>) {
self.rerun.set(true);
let passes = self.frame(events);
self.rerun.set(false);
assert_eq!(passes, 2, "the frame ran twice");
}
/// What one frame with no input paints.
fn look(&mut self) -> Look {
let room = egui::Rect::from_min_size(Pos2::ZERO, ROOM);
let show = &mut self.show;
Look::of(&self.frames.frame_shapes(|ui| layout::in_region(ui, room, |ui| show(ui))))
}
fn view(&self) -> CanvasView {
@@ -194,6 +256,12 @@ impl Rig {
self.frame(Vec::new());
}
/// Press and release at `at` without moving.
fn click(&mut self, at: Pos2) {
self.press(at);
self.release(at);
}
/// Press at `from`, move through the middle to `to`, release, with `mods` held.
fn drag(&mut self, from: Pos2, to: Pos2, mods: Modifiers) {
self.frames.hold(mods);
@@ -205,10 +273,73 @@ impl Rig {
}
}
/// What a frame painted, as the overlay's parts tell apart: the shield fills translucent meshes, the untouched outline
/// is dashes, the started outline one closed path, and the guides open paths from edge to edge of the outline.
struct Look {
shield: usize,
dashes: usize,
outline: Option<[Pos2; 4]>,
guides: Vec<(Pos2, Pos2)>,
}
impl Look {
fn of(shapes: &[egui::Shape]) -> Look {
let (mut shield, mut dashes, mut outline, mut open) = (0, 0, None, Vec::new());
for shape in shapes {
match shape {
egui::Shape::Mesh(mesh) if mesh.vertices.iter().any(|v| (1..255).contains(&v.color.a())) => shield += 1,
egui::Shape::LineSegment { .. } => dashes += 1,
egui::Shape::Path(path) if path.closed && path.points.len() == 4 && outline.is_none() => {
outline = <[Pos2; 4]>::try_from(path.points.as_slice()).ok();
}
egui::Shape::Path(path) if !path.closed && path.points.len() >= 2 => {
if let (Some(first), Some(last)) = (path.points.first(), path.points.last()) {
open.push((*first, *last));
}
}
_ => {}
}
}
let on_outline = |p: Pos2| outline.is_none_or(|q: [Pos2; 4]| (0..4).any(|i| to_segment(p, q[i], q[(i + 1) % 4]) < 0.75));
let guides = open.into_iter().filter(|(a, b)| a.distance(*b) > GUIDE_MIN && on_outline(*a) && on_outline(*b)).collect();
Look { shield, dashes, outline, guides }
}
/// No shield, a dashed outline and no guide (#10930).
fn untouched(&self) -> bool {
self.shield == 0 && self.dashes > 0 && self.outline.is_none() && self.guides.is_empty()
}
/// The shield and a solid outline.
fn started(&self) -> bool {
self.shield > 0 && self.dashes == 0 && self.outline.is_some()
}
/// A guide line runs through the middle of the frame: the turn grid has one, thirds do not.
fn through_centre(&self) -> bool {
let Some(q) = self.outline else { return false };
let centre = Pos2::new((q[0].x + q[2].x) / 2.0, (q[0].y + q[2].y) / 2.0);
self.guides.iter().any(|(a, b)| a.lerp(*b, 0.5).distance(centre) < 1.0)
}
}
/// How far `p` is from the segment from `a` to `b`.
fn to_segment(p: Pos2, a: Pos2, b: Pos2) -> f32 {
let d = b - a;
let t = if d.length_sq() > 0.0 { ((p - a).dot(d) / d.length_sq()).clamp(0.0, 1.0) } else { 0.0 };
p.distance(a + d * t)
}
fn near(a: &CropBox, b: &CropBox) -> bool {
a.corners().iter().zip(b.corners()).all(|(p, q)| p.distance(q) < 1e-6) && (a.angle - b.angle).abs() < 1e-6
}
/// Whether the turned frame lies inside `bounds`, rounding aside.
fn inside(b: &CropBox, bounds: Rect) -> bool {
let t = b.turned_bounds();
t.x0 >= bounds.x0 - 1e-6 && t.y0 >= bounds.y0 - 1e-6 && t.x1 <= bounds.x1 + 1e-6 && t.y1 <= bounds.y1 + 1e-6
}
#[trial]
fn a_corner_drag_resizes_along_the_frame_axes_in_a_turned_view() {
let b = CropBox::new(RECT, 20.0);
@@ -221,7 +352,7 @@ fn a_corner_drag_resizes_along_the_frame_axes_in_a_turned_view() {
let view = rig.view();
let corner = view.to_screen(b.corners()[2]);
let to = corner + Vec2::new(14.0, -9.0);
let want = b.resized(BoxPart::Corner(2), view.to_doc(to) - view.to_doc(corner), craft_behavior::geometry::AspectHold::Free, false); // P3(tools-w15): tl.T41
let want = b.resized(BoxPart::Corner(2), view.to_doc(to) - view.to_doc(corner), AspectHold::Free, false);
rig.drag(corner, to, Modifiers::NONE);
assert!(near(&rig.crop(), &want), "{:?} vs {want:?}", rig.crop());
assert_eq!(rig.seen.borrow().picked, Some(BoxPart::Corner(2)));
@@ -265,53 +396,352 @@ fn the_control_key_held_during_a_resize_turns_snapping_off() {
}
}
// Straighten.
// Image mode.
#[trial]
fn image_mode_auto_center_keeps_the_frame_centre_on_screen_and_the_handle_under_the_pointer() {
for angle in [0.0, 30.0] {
let b0 = CropBox::new(RECT, angle);
let mut rig = Rig::new(b0, Setup::image(angle, true));
let view0 = rig.view();
let centre = view0.to_screen(b0.center());
let corner = view0.to_screen(b0.corners()[2]);
let to = corner + Vec2::new(40.0, 25.0);
rig.press(corner);
rig.move_to(to);
rig.frame(Vec::new());
let (b, view) = (rig.crop(), rig.view());
assert!((b.rect.width() - RECT.width()).abs() > 1.0, "resized");
assert!(view.to_screen(b.center()).distance(centre) < 1e-2, "centre kept at {angle}");
assert!(view.to_screen(b.corners()[2]).distance(to) < 1e-1, "handle follows at {angle}");
assert_eq!(view.rotation, -angle);
assert!(b.corners()[0].distance(b0.corners()[0]) < 1e-6, "the opposite corner stays put on the image");
rig.release(to);
}
}
#[trial]
fn image_mode_a_move_snaps_and_stays_snapped_while_the_pointer_is_still() {
for auto_center in [false, true] {
let mut rig = Rig::new(CropBox::upright(RECT), {
let mut s = Setup::image(0.0, auto_center);
s.snap_x = Some(0.0);
s
});
let from = rig.at(200.0, 150.0);
rig.press(from);
// The frame moves against the pointer: raw, its left edge would be at x = -3; the image follows the frame.
let at = from + Vec2::new(103.0, 20.0);
for pass in 0..4 {
rig.move_to(at);
let r = rig.rect();
assert!(r.x0.abs() < 1e-3, "pass {pass}, auto_center={auto_center}: {r:?}");
assert!((r.y0 - (RECT.y0 - 20.0)).abs() < 1e-3, "pass {pass}: {r:?}");
fn a_click_with_snapping_on_changes_nothing() {
for angle in [0.0, 20.0] {
let b = CropBox::new(RECT, angle);
let mut setup = Setup::new();
// Guides just past the right and bottom edges, in reach of the edges and the corner between them.
setup.snap_x = Some(RECT.x1 + 3.0);
setup.snap_y = Some(RECT.y1 + 3.0);
for part in [BoxPart::Inside, BoxPart::Edge(1), BoxPart::Corner(2)] {
let mut rig = Rig::new(b, setup.clone());
let Some(at) = b.part_point(part) else { continue };
rig.click(rig.view().to_screen(at));
assert_eq!(rig.crop(), b, "a click on {part:?} at {angle} degrees");
assert!(rig.events().is_empty(), "{part:?} at {angle} degrees: {:?}", rig.events());
}
assert!(!rig.seen.borrow().snapped.is_empty(), "the snap line is reported");
rig.release(at);
}
}
// The shield and the saved settings.
#[trial]
fn space_moves_the_frame_being_drawn_at_its_size() {
let mut setup = Setup::new();
setup.default_frame = true;
let mut rig = Rig::new(CropBox::upright(RECT), setup);
rig.press(rig.at(150.0, 120.0));
rig.move_to(rig.at(200.0, 160.0));
rig.move_to(rig.at(250.0, 200.0));
assert!(near(&rig.crop(), &CropBox::upright(Rect::new(150.0, 120.0, 250.0, 200.0))), "drawn: {:?}", rig.rect());
// Space held: the pointer's step moves the whole frame.
rig.frame(vec![input::key_press(egui::Key::Space, Modifiers::NONE)]);
rig.move_to(rig.at(270.0, 210.0));
assert!(near(&rig.crop(), &CropBox::upright(Rect::new(170.0, 130.0, 270.0, 210.0))), "moved at its size: {:?}", rig.rect());
// Space let go: the corner follows the pointer again from where the frame went.
rig.frame(vec![focus::key_release(egui::Key::Space, Modifiers::NONE)]);
rig.move_to(rig.at(290.0, 220.0));
rig.release(rig.at(290.0, 220.0));
assert!(near(&rig.crop(), &CropBox::upright(Rect::new(170.0, 130.0, 290.0, 220.0))), "drawn on: {:?}", rig.rect());
}
#[trial]
fn an_untouched_default_frame_shows_no_shield_or_guide_until_a_drag_changes_it() {
let mut rig = Rig::new(CropBox::upright(RECT), Setup::untouched());
assert!(rig.look().untouched(), "the default frame before anything happens");
// A press that has not moved, and clicks inside and on a handle, keep the untouched look.
let corner = rig.at(RECT.x1, RECT.y1);
rig.press(corner);
assert!(rig.look().untouched(), "a press that has not moved");
rig.release(corner);
rig.click(rig.at(200.0, 150.0));
assert!(rig.look().untouched(), "after clicks on a handle and inside");
// A drag that changes the frame starts it, and keeps it started when it brings the frame back, a second pass of
// the frame included.
rig.press(corner);
rig.move_to(corner + Vec2::new(30.0, 20.0));
assert!(rig.look().started(), "the drag changed the frame");
rig.frame_twice(vec![pointer::moved(corner)]);
assert_eq!(rig.rect(), RECT, "the frame came back");
let back = rig.look();
assert!(back.started() && !back.guides.is_empty(), "the frame drawn again stays started, its guide shown");
rig.release(corner);
assert!(rig.look().untouched(), "the drag over, the app still says the frame is the default");
// A turn shows its guides from its start.
let outside = rig.at(40.0, 150.0);
rig.press(outside);
rig.move_to(outside + Vec2::new(0.0, -2.0 * input::slop(&rig.frames.ctx)));
let turning = rig.look();
assert!(turning.started() && !turning.guides.is_empty(), "a turn starts the crop");
rig.release(outside);
// Classic Mode is always started.
let mut classic = Setup::untouched();
classic.image_mode = false;
let mut rig = Rig::new(CropBox::upright(RECT), classic);
assert!(rig.look().started(), "Classic Mode");
}
#[trial]
fn a_handle_held_past_the_edge_scrolls_and_a_turn_does_not() {
let past = Pos2::new(ROOM.x + 20.0, 150.0);
// A resize past the edge asks to scroll at the pointer, in every pass of the frames while it is held.
let mut rig = Rig::upright();
rig.press(rig.at(RECT.x1, 150.0));
rig.move_to(past);
rig.seen.borrow_mut().scrolls_at.clear();
rig.frame_twice(Vec::new());
assert_eq!(rig.seen.borrow().scrolls_at, [Some(past), Some(past)], "both passes ask");
rig.release(past);
assert_eq!(rig.seen.borrow().scrolls_at.last(), Some(&None), "the release ends it");
// What each drag asks for, held past the edge.
let cases = [
("a classic move", Setup::new(), Point::new(200.0, 150.0), true),
("a turn", Setup::new(), Point::new(40.0, 150.0), false),
("an image-mode move", Setup::image(0.0, false), Point::new(200.0, 150.0), false),
("an image-mode resize", Setup::image(0.0, false), Point::new(RECT.x1, 150.0), true),
("a live-centred resize", Setup::image(0.0, true), Point::new(RECT.x1, 150.0), false),
];
for (what, setup, from, scrolls) in cases {
let mut rig = Rig::new(CropBox::upright(RECT), setup);
rig.press(rig.at(from.x, from.y));
rig.move_to(rig.at(from.x, from.y) + Vec2::new(20.0, 0.0));
rig.move_to(past);
assert_eq!(rig.seen.borrow().scrolls_at.last().copied().flatten().is_some(), scrolls, "{what}");
rig.release(past);
}
// Through a tool host, the tool's `autoscroll_at` makes the pass report how far past the edge the pointer is.
let (mut fixture, past_edge) = scrolling_host();
let canvas = fixture.by_role(Role::CANVAS)[0].rect;
let corner = fixture.by_label("Crop corner, bottom right").expect("the crop shows its corners").center();
let beyond = Pos2::new(canvas.right() + 20.0, corner.y);
fixture.frame(vec![pointer::moved(corner)]).frame(vec![pointer::press(corner)]);
fixture.frame(vec![pointer::moved(corner + Vec2::new(20.0, 0.0))]).frame(vec![pointer::moved(beyond)]);
assert!(past_edge.get().is_some_and(|by| by.x > 0.0), "past the right edge: {:?}", past_edge.get());
fixture.frame(vec![pointer::release(beyond)]).frame(Vec::new());
assert_eq!(past_edge.get(), None, "released");
let turn = canvas.left_top() + Vec2::splat(10.0);
fixture.frame(vec![pointer::moved(turn)]).frame(vec![pointer::press(turn)]);
fixture.frame(vec![pointer::moved(turn + Vec2::new(0.0, 20.0))]).frame(vec![pointer::moved(Pos2::new(canvas.left() - 20.0, turn.y))]);
assert_eq!(past_edge.get(), None, "a turn never scrolls");
}
/// A tool that only hands on what the crop overlay asks for, as the crop tool does.
struct Scrolling {
asked: Rc<Cell<Option<Pos2>>>,
}
impl CanvasTool for Scrolling {
fn each_pass(&mut self, cx: &mut ToolContext<'_>) {
if let Some(at) = self.asked.get() {
cx.autoscroll_at(at);
}
}
fn press(&mut self, _: &ToolPointer, _: &mut ToolContext<'_>) -> ToolAction {
ToolAction::Ignored
}
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 options bar's size fields")
}
}
/// A canvas with the crop overlay in its body and [`Scrolling`] as its tool; returns the fixture and the host's
/// `past_edge` of the last pass.
fn scrolling_host() -> (Fixture, Rc<Cell<Option<Vec2>>>) {
let crop = Rc::new(RefCell::new(CropBox::upright(RECT)));
let asked = Rc::new(Cell::new(None::<Pos2>));
let past_edge = Rc::new(Cell::new(None::<Vec2>));
let tool = Rc::new(RefCell::new(Scrolling { asked: Rc::clone(&asked) }));
let (seen, reported) = (Rc::clone(&asked), Rc::clone(&past_edge));
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 shown = Canvas::new("Document").view(view).show(ui, |ui, body| {
let out = CropOverlay::new("Crop", Bind::bound(&mut *crop.borrow_mut())).show_at(ui, body.rect);
seen.set(out.scrolls_at);
});
let reply = ToolHost::new().run(ui, &shown.output, &mut *tool.borrow_mut());
reported.set(reply.past_edge);
});
fixture.settle();
(fixture, past_edge)
}
#[trial]
fn a_default_turn_shows_the_turn_grid_and_release_restores_the_guide() {
let thirds = |image: bool, show: GuideShow| {
let mut s = if image { Setup::image(0.0, false) } else { Setup::new() };
s.guide = Some((CropGuide::Thirds, 0));
s.guide_show = show;
s
};
let outside = Point::new(40.0, 150.0);
let turn = |rig: &mut Rig| {
let from = rig.at(outside.x, outside.y);
rig.press(from);
rig.move_to(from + Vec2::new(0.0, -12.0));
rig.move_to(from + Vec2::new(0.0, -24.0));
from
};
// An image-mode turn: the turn grid in place of the thirds; after it, the thirds again.
let mut rig = Rig::new(CropBox::upright(RECT), thirds(true, GuideShow::Always));
let before = rig.look();
assert!(!before.guides.is_empty() && !before.through_centre(), "the thirds before the turn");
let from = turn(&mut rig);
let turning = rig.look();
assert!(turning.through_centre(), "the turn grid while the image turns: {:?}", turning.guides);
rig.release(from);
let after = rig.look();
assert!(!after.guides.is_empty() && !after.through_centre(), "the thirds back after the release");
// Never shows nothing, the turn grid included.
let mut rig = Rig::new(CropBox::upright(RECT), thirds(true, GuideShow::Never));
let from = turn(&mut rig);
assert!(rig.look().guides.is_empty(), "Never");
rig.release(from);
// A Classic Mode turn keeps the thirds.
let mut rig = Rig::new(CropBox::upright(RECT), thirds(false, GuideShow::Auto));
let from = turn(&mut rig);
let classic = rig.look();
assert!(!classic.guides.is_empty() && !classic.through_centre(), "a Classic Mode turn: {:?}", classic.guides);
rig.release(from);
// A Straighten line keeps the thirds, and its release ends Straighten once, a second pass of the frame aside.
let mut setup = thirds(true, GuideShow::Auto);
setup.straighten = true;
let mut rig = Rig::new(CropBox::upright(RECT), setup);
let (from, to) = (rig.at(150.0, 120.0), rig.at(260.0, 140.0));
rig.press(from);
rig.move_to(from.lerp(to, 0.5));
rig.move_to(to);
let line = rig.look();
assert!(!line.guides.is_empty() && !line.through_centre(), "a Straighten line: {:?}", line.guides);
rig.frame_twice(vec![pointer::release(to)]);
rig.frame(Vec::new());
assert_eq!(rig.seen.borrow().straighten_ended, 1, "the release frame's two passes end Straighten once");
}
#[trial]
fn a_default_turn_keeps_the_frame_inside_the_turned_image() {
let image = Rect::new(0.0, 0.0, 400.0, 300.0);
// The image-mode rig over `frame`, the view showing it upright, the image as the bounds.
let rig_for = |frame: CropBox, image_mode: bool| {
let mut s = Setup::new();
s.image_mode = image_mode;
s.bounds = Some(image);
if image_mode {
s.view = crop_view(&frame, &s.view);
}
Rig::new(frame, s)
};
// Presses above the frame's centre and moves round it by `degrees`, `radius` screen points out.
let turn_by = |rig: &mut Rig, degrees: &[f64], radius: f32, mods: Modifiers| {
let centre = rig.view().to_screen(rig.crop().center());
let at = |deg: f64| {
let (s, c) = (deg.to_radians().sin() as f32, deg.to_radians().cos() as f32);
centre + Vec2::new(radius * s, -radius * c)
};
rig.frames.hold(mods);
rig.press(at(0.0));
for deg in degrees {
rig.move_to(at(*deg));
}
(centre, at(degrees.last().copied().unwrap_or(0.0)))
};
// A frame that fits keeps its size and place.
let fits = CropBox::upright(Rect::new(40.0, 40.0, 360.0, 260.0));
let mut rig = rig_for(fits, true);
let (centre, end) = turn_by(&mut rig, &[3.0, 5.0], 140.0, Modifiers::NONE);
assert_eq!(rig.rect(), fits.rect, "a small turn fits");
assert!(rig.crop().angle.abs() > 1.0, "it turned: {:?}", rig.crop());
// Turned further it would leave the image: shrunk, its proportions kept; turned back, the frame comes back.
let (s, c) = (30f64.to_radians().sin() as f32, 30f64.to_radians().cos() as f32);
rig.move_to(centre + Vec2::new(140.0 * s, -140.0 * c));
let shrunk = rig.crop();
assert!(shrunk.rect.width() < fits.rect.width() - 1.0 && inside(&shrunk, image), "{shrunk:?}");
assert!((shrunk.rect.width() / shrunk.rect.height() - fits.rect.width() / fits.rect.height()).abs() < 1e-9, "{shrunk:?}");
rig.move_to(centre + Vec2::new(0.0, -140.0));
assert_eq!(rig.rect(), fits.rect, "turning back gives the frame back");
rig.release(end);
rig.frames.hold(Modifiers::NONE);
// A frame near the edge moves in at its size, and the view follows it: the box stays put on screen.
let edge = CropBox::upright(Rect::new(150.0, 100.0, 390.0, 260.0));
let mut rig = rig_for(edge, true);
let (centre, end) = turn_by(&mut rig, &[10.0, 20.0], 120.0, Modifiers::NONE);
let moved = rig.crop();
assert!(inside(&moved, image), "{moved:?}");
assert!((moved.rect.width() - edge.rect.width()).abs() < 1e-9 && (moved.rect.height() - edge.rect.height()).abs() < 1e-9, "{moved:?}");
assert!(moved.center().x < edge.center().x - 1.0, "moved in from the right edge: {moved:?}");
assert!(rig.view().to_screen(moved.center()).distance(centre) < 1e-2, "the box stays put on screen");
rig.release(end);
// Command keeps the press frame.
let mut rig = rig_for(edge, true);
let (_, end) = turn_by(&mut rig, &[10.0, 20.0], 120.0, Modifiers::COMMAND);
assert_eq!(rig.rect(), edge.rect, "Command held");
rig.release(end);
rig.frames.hold(Modifiers::NONE);
// A press frame already past the image is kept.
let past = CropBox::new(Rect::new(150.0, 100.0, 390.0, 260.0), 20.0);
let mut rig = rig_for(past, true);
let (_, end) = turn_by(&mut rig, &[5.0, 10.0], 120.0, Modifiers::NONE);
assert_eq!(rig.rect(), past.rect, "the frame was past the image at the press");
rig.release(end);
// A Classic Mode turn that would leave the image is refused: both steps leave it.
let mut rig = rig_for(fits, false);
let (_, end) = turn_by(&mut rig, &[30.0, 40.0], 140.0, Modifiers::NONE);
assert_eq!(rig.crop(), fits, "a classic turn out of the image");
rig.release(end);
}
#[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.
let whole = CropBox::upright(Rect::new(0.0, 0.0, 800.0, 500.0));
let setup = |ratio: Option<f64>, snap_x: Option<f64>, snap_y: Option<f64>, at: Point| {
let mut s = Setup::new();
s.ratio = ratio;
(s.snap_x, s.snap_y) = (snap_x, snap_y);
s.view.center = at;
s
};
let drag = |rig: &mut Rig, corner: Point, by: Vec2| {
let from = rig.at(corner.x, corner.y);
rig.drag(from, from + by, Modifiers::SHIFT);
};
// Measured: (-100, -50) on the corner gives 706 x 441.
let mut rig = Rig::new(whole, setup(None, None, None, Point::new(700.0, 400.0)));
drag(&mut rig, Point::new(800.0, 500.0), Vec2::new(-100.0, -50.0));
let (w, h) = rig.crop().crop_size().unwrap();
assert!((w - 706.0).abs() <= 1.0 && (h - 441.0).abs() <= 1.0, "{w} x {h}");
// A ratio preset keeps the larger relative extent: a 1 : 1 frame of 500 gives 450 square.
let square = CropBox::upright(Rect::new(150.0, 0.0, 650.0, 500.0));
let mut rig = Rig::new(square, setup(Some(1.0), None, None, Point::new(550.0, 400.0)));
drag(&mut rig, Point::new(650.0, 500.0), Vec2::new(-100.0, -50.0));
let r = rig.rect();
assert!((r.width() - 450.0).abs() < 1e-3 && (r.height() - 450.0).abs() < 1e-3, "{r:?}");
// A guide in reach: the handle slides along the diagonal onto it, the proportions kept.
let free = 800.0 * (1.0 - 105_000.0 / 890_000.0);
let guide = free - 0.7 * SNAP_PX;
let mut rig = Rig::new(whole, setup(None, Some(guide), None, Point::new(700.0, 400.0)));
drag(&mut rig, Point::new(800.0, 500.0), Vec2::new(-100.0, -50.0));
let r = rig.rect();
assert!((r.x1 - guide).abs() < 1e-6, "the handle on the guide: {r:?}");
assert!((r.width() / r.height() - 1.6).abs() < 1e-9, "8 : 5 kept: {r:?}");
// Turned -31 degrees, the diagonal runs a degree off level: a level guide 3 points from the handle crosses it
// far outside the reach and is ignored.
let turned = CropBox::new(Rect::new(100.0, 60.0, 500.0, 310.0), -31.0);
let corner = turned.corners()[2];
let by = craft_behavior::geometry::crop::turn(Point::new(-50.0, -25.0), Point::ZERO, -31.0);
let by = Vec2::new(by.x as f32, by.y as f32);
let at = corner - craft_behavior::kurbo::Vec2::new(100.0, 80.0);
let mut rig = Rig::new(turned, setup(None, None, None, at));
drag(&mut rig, corner, by);
let want = rig.crop();
let handle = want.corners()[2];
let mut rig = Rig::new(turned, setup(None, None, Some(handle.y + 3.0), at));
drag(&mut rig, corner, by);
assert!(near(&rig.crop(), &want), "as with no guide: {:?} vs {want:?}", rig.crop());
assert!(rig.seen.borrow().snapped.is_empty(), "no snap line reported");
}