LightCraft: An open-source non-destructive photo editor written by scratch in pure Rust
Merge PR #739
Claude1d11e5bd8927
diff --cc crates/ui-egui/src/panels/detail.rsindex f901028d4,24bf60fc0..18291f60a--- a/crates/ui-egui/src/panels/detail.rs+++ b/crates/ui-egui/src/panels/detail.rs@@@ -1253,25 -1215,10 +1253,12 @@@ fn crop_overlay(app: &mut LightcraftApplet quad = frame_crop_quad(d, frame);let pts: Vec<Pos2> = quad.iter().map(|q| map.screen(*q)).collect();let p = ui.painter();-- // darken outside the crop- let img = map.rect;- let shade = Color32::from_black_alpha(150);- let mut mesh = egui::epaint::Mesh::default();- let outer = [img.left_top(), img.right_top(), img.right_bottom(), img.left_bottom()];- // the box's corners in screen order (a flipped photo shows its top-left corner elsewhere)- let on_screen = flipped_corners(&pts, frame.flip_h, frame.flip_v);- for i in 0..4 {- let a = outer[i];- let b = outer[(i + 1) % 4];- let c = on_screen[(i + 1) % 4];- let dd = on_screen[i];- let base = mesh.vertices.len() as u32;- for v in [a, b, c, dd] {- mesh.vertices.push(egui::epaint::Vertex { pos: v, uv: Pos2::ZERO, color: shade });- }- mesh.indices.extend([base, base + 1, base + 2, base, base + 2, base + 3]);- if let Ok(quad) = <[Pos2; 4]>::try_from(pts.as_slice()) {++ // darken outside the crop (the box's corners in screen order: a flipped photo shows its++ // top-left corner elsewhere)++ let quad = flipped_corners(&pts, frame.flip_h, frame.flip_v);++ if pts.len() == 4 {+ p.add(outside_crop_mesh(map.rect, &quad, Color32::from_black_alpha(150)));}- p.add(mesh);p.add(egui::Shape::closed_line(pts.clone(), Stroke::new(1.0, Color32::WHITE)));// overlay guideslet lerp = |a: Pos2, b: Pos2, t: f32| a + (b - a) * t;@@@ -1514,19 -1438,62 +1501,75 @@@ fn to_straight(n: Point, angle: f64, frPoint::new(r.x / w, r.y / h)}+/// A crop box's corners (top-left, top-right, bottom-right, bottom-left of the unflipped photo)+/// in the order they appear on screen when the photo is shown flipped.+fn flipped_corners(pts: &[Pos2], flip_h: bool, flip_v: bool) -> [Pos2; 4] {+ let at = |i: usize| pts.get(i).copied().unwrap_or(Pos2::ZERO);+ let order = match (flip_h, flip_v) {+ (false, false) => [0, 1, 2, 3],+ (true, false) => [1, 0, 3, 2],+ (false, true) => [3, 2, 1, 0],+ (true, true) => [2, 3, 0, 1],+ };+ order.map(at)+}++ /// The dimming outside the crop box: the photo's rectangle minus the crop quad, as one mesh of+ /// non-overlapping convex pieces. The quad is a rotated rectangle, so its opposite sides are+ /// parallel and the plane outside it splits into four disjoint half-strips: outside edge `i`+ /// and inside edge `i + 1`. Each is clipped to the photo and fanned into triangles.+ ///+ /// Issue #731: joining photo corner `i` to crop corner `i` with a quad per side only works while+ /// the two rectangles are aligned. Rotated, those quads cross themselves and each other, which+ /// showed as dimmed wedges inside the crop and doubly dark ones outside, growing with the angle.+ /// A degenerate quad (a point, a line, a non-finite corner) dims nothing.+ fn outside_crop_mesh(img: Rect, quad: &[Pos2; 4], color: Color32) -> egui::epaint::Mesh {+ let mut mesh = egui::epaint::Mesh::default();+ if !quad.iter().all(|q| q.x.is_finite() && q.y.is_finite()) || !img.is_finite() {+ return mesh;+ }+ let centre = pos2((quad[0].x + quad[1].x + quad[2].x + quad[3].x) / 4.0, (quad[0].y + quad[1].y + quad[2].y + quad[3].y) / 4.0);+ // signed distance from edge i's line, positive towards the crop's centre+ let side = |i: usize, q: Pos2| -> Option<f32> {+ let (a, b) = (quad[i % 4], quad[(i + 1) % 4]);+ let n = vec2(a.y - b.y, b.x - a.x);+ let orient = n.dot(centre - a);+ // an edge the centre lies on: the box is flat+ (orient.abs() > 1e-6 * n.length().max(1.0)).then(|| n.dot(q - a) * orient.signum())+ };+ // Sutherland–Hodgman: the part of a convex polygon where `keep` is at or above zero+ let clip = |poly: &[Pos2], keep: &dyn Fn(Pos2) -> Option<f32>| -> Option<Vec<Pos2>> {+ let mut out = Vec::with_capacity(poly.len() + 2);+ for (k, &a) in poly.iter().enumerate() {+ let b = *poly.get((k + 1) % poly.len())?;+ let (da, db) = (keep(a)?, keep(b)?);+ if da >= 0.0 {+ out.push(a);+ }+ if (da < 0.0) != (db < 0.0) && (da - db).abs() > f32::EPSILON {+ let t = da / (da - db);+ out.push(a + (b - a) * t);+ }+ }+ Some(out)+ };+ let photo = [img.left_top(), img.right_top(), img.right_bottom(), img.left_bottom()];+ for i in 0..4 {+ let outside = |q: Pos2| side(i, q).map(|d| -d);+ let inside_next = |q: Pos2| side(i + 1, q);+ let Some(strip) = clip(&photo, &outside).and_then(|poly| clip(&poly, &inside_next)) else { return egui::epaint::Mesh::default() };+ if strip.len() < 3 {+ continue;+ }+ let base = mesh.vertices.len() as u32;+ mesh.vertices.extend(strip.iter().map(|&pos| egui::epaint::Vertex { pos, uv: Pos2::ZERO, color }));+ for k in 1..(strip.len() as u32).saturating_sub(1) {+ mesh.indices.extend([base, base + k, base + k + 1]);+ }+ }+ mesh+ }+fn frame_crop_quad(d: &DevelopSettings, frame: &Frame) -> [Point; 4] {let f = Frame { crop: d.crop.geometry, ..frame.clone() };f.crop_quad_norm()@@@ -2260,42 -2186,94 +2303,128 @@@ fn straighten_overlay(app: &mut Lightcr#[cfg(test)]mod tests {- use super::{film_label, outside_crop_mesh, texture_side};+ /// The rotation pointer's arc bulges away from the side of the crop box it is on, and follows+ /// a box that is itself rotated.+ #[test]+ fn rotate_cursor_faces_away_from_the_crop_box() {+ use egui::{Pos2, pos2};+ use std::f32::consts::{FRAC_PI_2, FRAC_PI_4, PI};+ let near = |a: f32, b: f32| ((a - b + PI).rem_euclid(2.0 * PI) - PI).abs() < 1e-3;+ let pts = [pos2(100.0, 100.0), pos2(300.0, 100.0), pos2(300.0, 200.0), pos2(100.0, 200.0)];+ let turn = |x: f32, y: f32| super::rotate_cursor_turn(&pts, pos2(x, y), false);+ assert!(near(turn(200.0, 80.0), 0.0), "above: as drawn");+ assert!(near(turn(320.0, 150.0), FRAC_PI_2), "right");+ assert!(near(turn(200.0, 230.0), PI), "below");+ assert!(near(turn(70.0, 150.0), -FRAC_PI_2), "left");+ assert!(near(turn(290.0, 60.0), 0.0), "above the top edge near its end: still up");+ // off each corner: diagonally out from it+ assert!(near(turn(80.0, 80.0), -FRAC_PI_4), "top-left corner");+ assert!(near(turn(320.0, 80.0), FRAC_PI_4), "top-right corner");+ assert!(near(turn(320.0, 220.0), 3.0 * FRAC_PI_4), "bottom-right corner");+ assert!(near(turn(80.0, 220.0), -3.0 * FRAC_PI_4), "bottom-left corner");+ assert!(near(super::rotate_cursor_turn(&pts, pos2(200.0, 110.0), true), 0.0), "dragged back over the top edge: still up");+ // a box turned 90°: its top edge is now on the right+ let turned = [pts[3], pts[0], pts[1], pts[2]].map(|p| pos2(400.0 - p.y, p.x));+ assert!(near(super::rotate_cursor_turn(&turned, pos2(420.0, 200.0), false), FRAC_PI_2));+ // a box turned 30°: straight out from its top edge is 30° clockwise of up+ let c = pos2(200.0, 150.0);+ let rot = |p: Pos2| {+ let (s, co) = (30f32.to_radians().sin(), 30f32.to_radians().cos());+ let d = p - c;+ pos2(c.x + d.x * co - d.y * s, c.y + d.x * s + d.y * co)+ };+ let tilted = pts.map(rot);+ assert!(near(super::rotate_cursor_turn(&tilted, rot(pos2(200.0, 60.0)), false), 30f32.to_radians()));+ }+- use super::{film_label, flipped_corners, texture_side};- use egui::pos2;++ use super::{film_label, flipped_corners, outside_crop_mesh, texture_side};+ use egui::{Color32, Pos2, Rect, pos2};++ /// A rotated `w` × `h` box centred on `centre`.+ fn box_at(centre: Pos2, w: f32, h: f32, angle: f32) -> [Pos2; 4] {+ let (s, c) = angle.to_radians().sin_cos();+ [(-w, -h), (w, -h), (w, h), (-w, h)].map(|(x, y)| pos2(centre.x + (x * c - y * s) / 2.0, centre.y + (x * s + y * c) / 2.0))+ }++ /// Signed distances from a convex polygon's edges, positive inwards (its winding either way).+ fn sides(poly: &[Pos2], p: Pos2) -> Vec<f32> {+ let n = poly.len() as f32;+ let centre = pos2(poly.iter().map(|q| q.x).sum::<f32>() / n, poly.iter().map(|q| q.y).sum::<f32>() / n);+ (0..poly.len())+ .map(|i| {+ let (a, b) = (poly[i], poly[(i + 1) % poly.len()]);+ let nrm = egui::vec2(a.y - b.y, b.x - a.x).normalized();+ nrm.dot(p - a) * nrm.dot(centre - a).signum()+ })+ .collect()+ }++ /// Issue #731: the dimming is the photo minus the crop box at any angle. Every point of the+ /// photo outside the box lies in exactly one of the mesh's triangles; no point inside the box+ /// or outside the photo lies in any. (Four quads joining photo and box corners crossed and+ /// overlapped once the box was rotated.)+ #[test]+ fn the_dimming_outside_a_rotated_crop_is_exactly_the_photo_minus_the_box() {+ let img = Rect::from_min_max(pos2(100.0, 50.0), pos2(500.0, 650.0));+ // boxes inside the photo, poking out of it, and bigger than it+ for (w, h) in [(240.0, 360.0), (420.0, 300.0), (700.0, 900.0)] {+ for angle in [0.0f32, 5.0, 15.0, 30.0, -45.0, 90.0, 137.0, 200.0] {+ let quad = box_at(img.center() + egui::vec2(30.0, -20.0), w, h, angle);+ let mesh = outside_crop_mesh(img, &quad, Color32::BLACK);+ let tris: Vec<[Pos2; 3]> = mesh+ .indices+ .chunks(3)+ .map(|t| [mesh.vertices[t[0] as usize].pos, mesh.vertices[t[1] as usize].pos, mesh.vertices[t[2] as usize].pos])+ .collect();+ let (mut inside, mut outside) = (0, 0);+ let mut y = img.top() - 20.0;+ while y < img.bottom() + 20.0 {+ let mut x = img.left() - 20.0;+ while x < img.right() + 20.0 {+ let p = pos2(x, y);+ let in_box = sides(&quad, p);+ let in_img = sides(&[img.left_top(), img.right_top(), img.right_bottom(), img.left_bottom()], p);+ // a pixel on an edge may fall either way: skip the boundaries themselves+ if in_box.iter().chain(&in_img).any(|d| d.abs() < 1.0) {+ x += 7.0;+ continue;+ }+ let expected = if in_img.iter().all(|d| *d > 0.0) && !in_box.iter().all(|d| *d > 0.0) { 1 } else { 0 };+ // a sample on the seam between two of a strip's fan triangles is in both+ // or in neither, depending on rounding: count it both ways+ let covered = |eps: f32| tris.iter().filter(|t| sides(*t, p).iter().all(|d| *d > eps)).count();+ let (at_least, at_most) = (covered(0.01), covered(-0.01));+ assert!(+ at_least <= expected && expected <= at_most,+ "{w}×{h} box at {angle}°: ({x}, {y}) lies in {at_least}..={at_most} triangle(s), not {expected}"+ );+ if expected == 1 {+ outside += 1+ } else if in_img.iter().all(|d| *d > 0.0) {+ inside += 1+ }+ x += 7.0;+ }+ y += 7.0;+ }+ // (a box bigger than the photo swallows it whole at some angles)+ assert!(inside > 50 && (outside > 50 || w > img.width()), "{w}×{h} at {angle}°: {outside} dimmed, {inside} clear samples");+ }+ }+ }++ /// A flat or broken box dims nothing rather than something arbitrary (or panicking).+ #[test]+ fn a_degenerate_crop_box_dims_nothing() {+ let img = Rect::from_min_max(pos2(0.0, 0.0), pos2(400.0, 300.0));+ let point = [pos2(10.0, 10.0); 4];+ let line = [pos2(10.0, 10.0), pos2(90.0, 10.0), pos2(90.0, 10.0), pos2(10.0, 10.0)];+ let nan = [pos2(f32::NAN, 10.0), pos2(90.0, 10.0), pos2(90.0, 50.0), pos2(10.0, 50.0)];+ for quad in [point, line, nan] {+ assert!(outside_crop_mesh(img, &quad, Color32::BLACK).indices.is_empty(), "{quad:?}");+ }+ assert!(outside_crop_mesh(Rect::NAN, &box_at(pos2(50.0, 50.0), 20.0, 20.0, 10.0), Color32::BLACK).indices.is_empty());+ }/// Issue #652: a native host reports the GPU's texture limit in the first frame's input only./// The loupe must still know it in every later frame (it read the raw input, found nothing anddiff --cc docs/parity-checklist.mdindex 43074692a,a48fa596c..322d7bf29--- a/docs/parity-checklist.md+++ b/docs/parity-checklist.md@@@ -246,11 -246,11 +246,11 @@@ differences and missing bindings are i|---|---|---|---|---|---|| LR-CROP-RECT | Crop rectangle | P0 | ✅ | `cmd:crop.set`, `cmd:crop.drag`, `crates/geom/src/crop_drag.rs`, `crates/ui-egui/src/panels/detail.rs` | double-click inside the box applies the crop (like Return) || LR-CROP-ASPECT | Aspect ratios | P0 | ✅ | `cmd:crop.aspect`, `cmd:crop.rotateAspect`, `crates/ui-egui/src/panels/right.rs` | menu with presets + custom W × H, visible Lock toggle (also A), button names the active ratio; every handle honours the lock and the drag stops at the image edge instead of shifting the frame (issue #295); "Original" is the photo's own shape (no separate As Shot) |- | LR-CROP-STRAIGHTEN | Straighten tool | P0 | ✅ | `cmd:crop.straighten`, `cmd:crop.autoStraighten`, `crates/ui-egui/src/panels/detail.rs` (`rotate_cursor`, `angle_readout`), `crates/ui-egui/src/panels/right.rs` (Angle field), `crates/ui-egui/src/tests_crop_rotate.rs` | Straighten Tool button: drag along a horizon/vertical; double-click or Auto levels automatically. Dragging outside the crop box rotates it: there the pointer is a curved double arrow that bulges away from the side of the box it is on, diagonally off a corner and following a rotated box (`rotate_cursor_turn`, tested by `rotate_cursor_faces_away_from_the_crop_box`) (with ⌘ held, the straighten crosshair), and while rotating the angle shows next to it, kept on the canvas (issue #534); an exact angle goes in the Angle field under Straighten (`cropAngleField`: applies on Return or leaving it, Esc keeps the old angle, takes a decimal comma; a drag on it is one undo step) or by clicking the Straighten value (its hover says so). Every way of setting the angle (rotate handle, Straighten slider, Angle field, `crop.straighten`, `crop.set {angle}`, and the generic `develop.set` / `develop.adjust` / `develop.quickAdjust` / `develop.resetControl` on `crop.angle`, as MCP, the control channel and `lightcraft-cli render --set` use them) keeps the crop if it still fits, else shrinks it to the largest crop of its aspect inside the photo (`CropGeometry::with_angle`, `crates/engine/src/tests_crop_angle.rs`; before issue #742 the generic path left the box, and the export, past the photo with smeared edge pixels in the corners) |-| LR-CROP-STRAIGHTEN | Straighten tool | P0 | ✅ | `cmd:crop.straighten`, `cmd:crop.autoStraighten`, `crates/ui-egui/src/panels/detail.rs` (`rotate_cursor`, `angle_readout`), `crates/ui-egui/src/panels/right.rs` (Angle field), `crates/ui-egui/src/tests_crop_rotate.rs` | Straighten Tool button: drag along a horizon/vertical; double-click or Auto levels automatically. Dragging outside the crop box rotates it: there the pointer is a curved double arrow (with ⌘ held, the straighten crosshair), and while rotating the angle shows next to it, kept on the canvas (issue #534); an exact angle goes in the Angle field under Straighten (`cropAngleField`: applies on Return or leaving it, Esc keeps the old angle, takes a decimal comma; a drag on it is one undo step) or by clicking the Straighten value (its hover says so). The dimming outside the box is the photo minus the (rotated) box, drawn as one mesh (`outside_crop_mesh`), so rotating never dims wedges inside the box or doubles them outside (issue #731) |++| LR-CROP-STRAIGHTEN | Straighten tool | P0 | ✅ | `cmd:crop.straighten`, `cmd:crop.autoStraighten`, `crates/ui-egui/src/panels/detail.rs` (`rotate_cursor`, `angle_readout`), `crates/ui-egui/src/panels/right.rs` (Angle field), `crates/ui-egui/src/tests_crop_rotate.rs` | Straighten Tool button: drag along a horizon/vertical; double-click or Auto levels automatically. Dragging outside the crop box rotates it: there the pointer is a curved double arrow that bulges away from the side of the box it is on, diagonally off a corner and following a rotated box (`rotate_cursor_turn`, tested by `rotate_cursor_faces_away_from_the_crop_box`) (with ⌘ held, the straighten crosshair), and while rotating the angle shows next to it, kept on the canvas (issue #534); an exact angle goes in the Angle field under Straighten (`cropAngleField`: applies on Return or leaving it, Esc keeps the old angle, takes a decimal comma; a drag on it is one undo step) or by clicking the Straighten value (its hover says so). Every way of setting the angle (rotate handle, Straighten slider, Angle field, `crop.straighten`, `crop.set {angle}`, and the generic `develop.set` / `develop.adjust` / `develop.quickAdjust` / `develop.resetControl` on `crop.angle`, as MCP, the control channel and `lightcraft-cli render --set` use them) keeps the crop if it still fits, else shrinks it to the largest crop of its aspect inside the photo (`CropGeometry::with_angle`, `crates/engine/src/tests_crop_angle.rs`; before issue #742 the generic path left the box, and the export, past the photo with smeared edge pixels in the corners). The dimming outside the box is the photo minus the (rotated) box, drawn as one mesh (`outside_crop_mesh`), so rotating never dims wedges inside the box or doubles them outside (issue #731) || LR-CROP-AUTO | Auto straighten | P1 | ✅ | `cmd:crop.autoStraighten` | crop-angle leveling from detected horizon/plumb lines (consensus required) |-| LR-CROP-ANGLE | Angle slider | P0 | ✅ | `ctl:crop.angle`, `crates/ui-egui/src/panels/right.rs` | the Straighten slider; an exact angle can also be typed in the Angle field under it (see LR-CROP-STRAIGHTEN) |+| LR-CROP-ANGLE | Angle slider | P0 | ✅ | `ctl:crop.angle`, `crates/ui-egui/src/panels/right.rs` | the Straighten slider; an exact angle can also be typed in the Angle field under it (see LR-CROP-STRAIGHTEN); setting `crop.angle` through `develop.set` fits the crop inside the photo as Straighten does (issue #742) || LR-CROP-ROTATE90 | Rotate 90° | P0 | ✅ | `cmd:photo.rotateLeft`, `cmd:photo.rotateRight` | |-| LR-CROP-FLIP | Flip | P0 | ✅ | `cmd:photo.flipHorizontal`, `cmd:photo.flipVertical` | |+| LR-CROP-FLIP | Flip | P0 | ✅ | `cmd:photo.flipHorizontal`, `cmd:photo.flipVertical`, `crates/pipeline/src/geometry.rs` | the crop tool's uncropped view shows the flips too, with the crop box and its dimming mirrored to match || LR-CROP-OVERLAY | Crop overlays | P1 | ✅ | `cmd:view.cropOverlay`, `cmd:view.cropOverlayOrientation`, `crates/ui-egui/src/panels/crop_overlay.rs` | thirds, grid, golden ratio, diagonal, triangle, golden spiral (mirrored with ⇧O while cropping); no aspect-ratio overlays || LR-CROP-ZOOM | Zoom while cropping | P1 | ✅ | `cmd:view.zoom100`, `cmd:view.zoomIn`, `crates/ui-egui/src/panels/detail.rs` | zoom levels apply with the crop tool open (verified: 100% shows the photo at native size with the crop frame) || LR-CROP-GENEXPAND | Generative expand | OOS | 🚫 | | |