PhotoCraft: An open-source, photo editor written by scratch in pure Rust
Crop tool: overlay options (thirds, grid, diagonal, triangle, golden ratio/spiral), O / ⇧O (#2026)
David Mann32c918aaeeb4
diff --git a/crates/automation/src/server.rs b/crates/automation/src/server.rsindex 3debf5ed6..ce769065a 100644--- a/crates/automation/src/server.rs+++ b/crates/automation/src/server.rs@@ -233,8 +233,9 @@ pub struct UiSetParams {/// Brush Preset picker there, null closes it), brushPickerView, brushSize, gradientBlendMode/// (a blend mode name, for the Gradient tool), gradientClassic (bool), eyedropperSampleSize/// ("point" or 1, 3, 5, 11, 31, 51, 101), eyedropperSample (current, currentAndBelow, all,- /// allNoAdjustments, currentAndBelowNoAdjustments), eyedropperRing (bool). Other fields are an- /// error.+ /// allNoAdjustments, currentAndBelowNoAdjustments), eyedropperRing (bool), cropOverlay (thirds,+ /// grid, diagonal, triangle, goldenRatio, goldenSpiral), cropOverlayShow (auto, always, never),+ /// cropOverlayOrientation (0..3). Other fields are an error.pub fields: Value,}diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rsindex 5b6d7e606..aa442f17c 100644--- a/crates/ui-egui/src/canvas.rs+++ b/crates/ui-egui/src/canvas.rs@@ -2992,8 +2992,9 @@ fn marching_ants(painter: &egui::Painter, r: Rect, time: f64) {}}-/// Photoshop crop overlay: dimmed outside, bright frame, rule-of-thirds grid, corner and edge handles.-fn crop_overlay(painter: &egui::Painter, r: Rect) {+/// Photoshop crop overlay: dimmed outside, bright frame, the composition `guides` (unit-square+/// polylines, `crop_overlay::guides`), corner and edge handles.+fn crop_overlay(painter: &egui::Painter, r: Rect, guides: &[crate::crop_overlay::Polyline]) {let clip = painter.clip_rect();let dim = Color32::from_black_alpha(130);for band in [@@ -3005,13 +3006,7 @@ fn crop_overlay(painter: &egui::Painter, r: Rect) {painter.rect_filled(band, 0.0, dim);}painter.rect_stroke(r, 0.0, Stroke::new(1.0, Color32::WHITE), egui::StrokeKind::Middle);- let thin = Stroke::new(1.0, Color32::from_white_alpha(90));- for i in 1..3 {- let fx = r.left() + r.width() * i as f32 / 3.0;- let fy = r.top() + r.height() * i as f32 / 3.0;- painter.line_segment([egui::pos2(fx, r.top()), egui::pos2(fx, r.bottom())], thin);- painter.line_segment([egui::pos2(r.left(), fy), egui::pos2(r.right(), fy)], thin);- }+ draw_crop_guides(painter, guides, |a, b| r.min + r.size() * vec2(a, b));let h = Stroke::new(3.0, Color32::WHITE);let l = 14.0f32.min(r.width() / 3.0).min(r.height() / 3.0);for (c, dx, dy) in [(r.left_top(), 1.0, 1.0), (r.right_top(), -1.0, 1.0), (r.left_bottom(), 1.0, -1.0), (r.right_bottom(), -1.0, -1.0)] {@@ -3028,7 +3023,7 @@ fn crop_overlay(painter: &egui::Painter, r: Rect) {/// [`crop_overlay`] for a turned frame (or a rotated view): `q` is the frame's top-left, top-right,/// bottom-right and bottom-left corner on screen, a parallelogram.-fn crop_overlay_turned(painter: &egui::Painter, q: [Pos2; 4]) {+fn crop_overlay_turned(painter: &egui::Painter, q: [Pos2; 4], guides: &[crate::crop_overlay::Polyline]) {let (u, v) = (q[1] - q[0], q[3] - q[0]);let (lu, lv) = (u.length(), v.length());if !(lu.is_finite() && lv.is_finite()) || lu < 1e-3 || lv < 1e-3 {@@ -3052,12 +3047,7 @@ fn crop_overlay_turned(painter: &egui::Painter, q: [Pos2; 4]) {}painter.add(egui::Shape::mesh(mesh));painter.add(egui::Shape::closed_line(q.to_vec(), Stroke::new(1.0, Color32::WHITE)));- let thin = Stroke::new(1.0, Color32::from_white_alpha(90));- for i in 1..3 {- let f = i as f32 / 3.0;- painter.line_segment([at(f, 0.0), at(f, 1.0)], thin);- painter.line_segment([at(0.0, f), at(1.0, f)], thin);- }+ draw_crop_guides(painter, guides, at);let h = Stroke::new(3.0, Color32::WHITE);let l = 14.0f32.min(lu / 3.0).min(lv / 3.0);let (du, dv) = (u / lu, v / lv);@@ -3072,6 +3062,14 @@ fn crop_overlay_turned(painter: &egui::Painter, q: [Pos2; 4]) {}}+/// The crop overlay's guides, each unit-square point placed on screen by `at`.+fn draw_crop_guides(painter: &egui::Painter, guides: &[crate::crop_overlay::Polyline], at: impl Fn(f32, f32) -> Pos2) {+ let thin = Stroke::new(1.0, Color32::from_white_alpha(90));+ for l in guides {+ painter.add(egui::Shape::line(l.iter().map(|p| at(p[0], p[1])).collect(), thin));+ }+}+/// What the Crop tool shows past the canvas, cached per document state ([`draw_beyond_canvas`]).#[derive(Clone)]struct BeyondCanvas {@@ -3222,9 +3220,10 @@ fn draw_tool_state(app: &PhotocraftApp, painter: &egui::Painter, xf: &ViewXform,let deg = crate::crop_ui::angle(app);if deg == 0.0 && xf.rotation == 0.0 {let r = Rect::from_two_pos(xf.to_screen(c[0] as f32, c[1] as f32), xf.to_screen(c[2] as f32, c[3] as f32));- crop_overlay(painter, r);+ crop_overlay(painter, r, &crate::crop_overlay::current_guides(app, r.width(), r.height()));} else {- crop_overlay_turned(painter, crate::crop_ui::corners(c, deg).map(|p| xf.to_screen(p[0] as f32, p[1] as f32)));+ let q = crate::crop_ui::corners(c, deg).map(|p| xf.to_screen(p[0] as f32, p[1] as f32));+ crop_overlay_turned(painter, q, &crate::crop_overlay::current_guides(app, q[0].distance(q[1]), q[0].distance(q[3])));}// The frame's angle beside the pointer while it turns (#1792).if let (Some(a), Some(h)) = (crate::crop_ui::turning(app), hover) {diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rsindex edbfef1a5..ba5f63472 100644--- a/crates/ui-egui/src/control.rs+++ b/crates/ui-egui/src/control.rs@@ -74,7 +74,7 @@ pub enum Outcome {/// field's value is validated before the first one is applied, so a typo, an unknown field, a/// bad value or a bad nested key can't reply with success while nothing — or only half of it —/// changed (#412).-pub const UI_SET_FIELDS: [&str; 25] = [+pub const UI_SET_FIELDS: [&str; 28] = ["tool","panels","dock",@@ -100,6 +100,9 @@ pub const UI_SET_FIELDS: [&str; 25] = ["eyedropperSampleSize","eyedropperSample","eyedropperRing",+ "cropOverlay",+ "cropOverlayShow",+ "cropOverlayOrientation",];/// Most clicks one `ui.click` may queue (#982). Each click is a press and a release that the app@@ -326,6 +329,27 @@ fn dispatch(app: &mut PhotocraftApp, ctx: &egui::Context, req: &ControlRequest)None => None,};let eyedropper_ring = bool_field(p, "eyedropperRing")?;+ // The Crop tool's overlay menu (#1919).+ let crop_overlay = match p.get("cropOverlay") {+ Some(v) => Some(v.as_str().and_then(crate::crop_overlay::CropOverlay::from_id).ok_or_else(|| {+ let ids: Vec<&str> = crate::crop_overlay::CropOverlay::ALL.iter().map(|k| k.id()).collect();+ format!("cropOverlay must be one of {}", ids.join(", "))+ })?),+ None => None,+ };+ let crop_overlay_show = match p.get("cropOverlayShow") {+ Some(v) => Some(+ v.as_str()+ .and_then(crate::crop_overlay::OverlayShow::from_id)+ .ok_or_else(|| "cropOverlayShow must be one of auto, always, never".to_string())?,+ ),+ None => None,+ };+ let crop_overlay_orientation = match uint_field(p, "cropOverlayOrientation")? {+ Some(o) if o < 4 => Some(o as u8),+ Some(_) => return Err("cropOverlayOrientation must be 0, 1, 2 or 3".into()),+ None => None,+ };let panels = merged_object(&app.ui.panels, p.get("panels"), "panels")?;let mask_target = bool_field(p, "maskTarget")?;let vector_mask_target = bool_field(p, "vectorMaskTarget")?;@@ -426,6 +450,15 @@ fn dispatch(app: &mut PhotocraftApp, ctx: &egui::Context, req: &ControlRequest)if let Some(ring) = eyedropper_ring {app.ui.tool_options.eyedropper_ring = ring;}+ if let Some(k) = crop_overlay {+ app.ui.tool_options.crop_overlay = k;+ }+ if let Some(v) = crop_overlay_show {+ app.ui.tool_options.crop_overlay_show = v;+ }+ if let Some(o) = crop_overlay_orientation {+ app.ui.tool_options.crop_overlay_orientation = o;+ }if let Some(v) = panels {app.ui.panels = v;}@@ -1163,6 +1196,38 @@ mod tests {assert_eq!(app.ui.tool_options.eyedropper_size, 1);}+ /// #1919: the Crop tool's overlay menu over the control channel, reported by `ui.inspect`.+ #[test]+ fn ui_set_drives_the_crop_overlay_options() {+ use crate::crop_overlay::{CropOverlay, OverlayShow};+ let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());+ let ctx = egui::Context::default();+ let good =+ call(&mut app, &ctx, "ui.set", json!({"tool": "crop", "cropOverlay": "goldenSpiral", "cropOverlayShow": "always", "cropOverlayOrientation": 2}));+ assert_eq!(good["ok"], true, "{good}");+ let o = &app.ui.tool_options;+ assert_eq!((o.crop_overlay, o.crop_overlay_show, o.crop_overlay_orientation), (CropOverlay::GoldenSpiral, OverlayShow::Always, 2));+ let seen = call(&mut app, &ctx, "ui.inspect", json!({}));+ let t = &seen["result"]["toolOptions"];+ assert_eq!(+ (t["crop_overlay"].as_str(), t["crop_overlay_show"].as_str(), t["crop_overlay_orientation"].as_u64()),+ (Some("goldenSpiral"), Some("always"), Some(2))+ );+ for bad in [+ json!({"cropOverlay": "spiral"}),+ json!({"cropOverlay": 1}),+ json!({"cropOverlayShow": "sometimes"}),+ json!({"cropOverlayOrientation": 4}),+ json!({"cropOverlayOrientation": -1}),+ json!({"cropOverlayOrientation": "1"}),+ json!({"cropOverlay": "grid", "cropOverlayShow": "nope"}),+ ] {+ let r = call(&mut app, &ctx, "ui.set", bad.clone());+ assert_eq!(r["ok"], false, "{bad}: {r}");+ }+ assert_eq!(app.ui.tool_options.crop_overlay, CropOverlay::GoldenSpiral, "a rejected call applies none of its fields");+ }+#[test]fn ui_set_opens_the_brush_preset_picker_and_sets_its_view() {let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());diff --git a/crates/ui-egui/src/crop_overlay.rs b/crates/ui-egui/src/crop_overlay.rsnew file mode 100644index 000000000..b0be59f2b--- /dev/null+++ b/crates/ui-egui/src/crop_overlay.rs@@ -0,0 +1,557 @@+//! The Crop tool's composition overlay (Photoshop's options-bar overlay menu, #1919): which guide+//! the crop box shows (Rule of Thirds, Grid, Diagonal, Triangle, Golden Ratio, Golden Spiral),+//! when it shows it (Auto: only while the box is dragged; Always; Never), and its orientation.+//! With the Crop tool showing a box, O cycles the overlay and ⇧O its orientation (Triangle and+//! Golden Spiral); otherwise O stays the Dodge/Burn/Sponge key.+//!+//! The guides are polylines in the frame's unit square (0..1 along its top edge, 0..1 down its+//! left edge), so the canvas maps the same geometry onto an upright rectangle or a turned frame.+//! The state lives in `ToolOptions` (`crop_overlay`, `crop_overlay_show`,+//! `crop_overlay_orientation`), which `ui.inspect` reports and `ui.set` drives.++use egui::{Key, Modifiers};+use serde::{Deserialize, Serialize};++use crate::PhotocraftApp;+use crate::state::{Tool, ToolOptions};++/// The guide drawn inside the crop box.+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub enum CropOverlay {+ #[default]+ Thirds,+ Grid,+ Diagonal,+ Triangle,+ GoldenRatio,+ GoldenSpiral,+}++impl CropOverlay {+ /// In Photoshop's menu order (the order O cycles through).+ pub const ALL: [CropOverlay; 6] = [Self::Thirds, Self::Grid, Self::Diagonal, Self::Triangle, Self::GoldenRatio, Self::GoldenSpiral];++ pub fn label(self) -> &'static str {+ match self {+ Self::Thirds => "Rule of Thirds",+ Self::Grid => "Grid",+ Self::Diagonal => "Diagonal",+ Self::Triangle => "Triangle",+ Self::GoldenRatio => "Golden Ratio",+ Self::GoldenSpiral => "Golden Spiral",+ }+ }++ /// The `ui.set` / serde name.+ pub fn id(self) -> &'static str {+ match self {+ Self::Thirds => "thirds",+ Self::Grid => "grid",+ Self::Diagonal => "diagonal",+ Self::Triangle => "triangle",+ Self::GoldenRatio => "goldenRatio",+ Self::GoldenSpiral => "goldenSpiral",+ }+ }++ pub fn from_id(id: &str) -> Option<Self> {+ Self::ALL.into_iter().find(|k| k.id() == id)+ }++ /// How many distinct orientations ⇧O steps through: the Triangle's diagonal runs either way,+ /// the Golden Spiral winds into any of the four corners; the others are symmetric.+ pub fn orientations(self) -> u8 {+ match self {+ Self::Triangle => 2,+ Self::GoldenSpiral => 4,+ _ => 1,+ }+ }++ /// The next overlay (O).+ pub fn next(self) -> Self {+ let i = Self::ALL.iter().position(|k| *k == self).unwrap_or(0);+ Self::ALL.get((i + 1) % Self::ALL.len()).copied().unwrap_or_default()+ }+}++/// When the overlay shows.+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub enum OverlayShow {+ /// Only while the crop box is being dragged (drawn, moved, resized or turned).+ #[default]+ Auto,+ Always,+ Never,+}++impl OverlayShow {+ pub const ALL: [OverlayShow; 3] = [Self::Auto, Self::Always, Self::Never];++ pub fn label(self) -> &'static str {+ match self {+ Self::Auto => "Auto Show Overlay",+ Self::Always => "Always Show Overlay",+ Self::Never => "Never Show Overlay",+ }+ }++ pub fn id(self) -> &'static str {+ match self {+ Self::Auto => "auto",+ Self::Always => "always",+ Self::Never => "never",+ }+ }++ pub fn from_id(id: &str) -> Option<Self> {+ Self::ALL.into_iter().find(|k| k.id() == id)+ }++ /// Whether the overlay shows, `gesture` being a crop drag in progress.+ pub fn shows(self, gesture: bool) -> bool {+ match self {+ Self::Auto => gesture,+ Self::Always => true,+ Self::Never => false,+ }+ }+}++/// A guide polyline in the frame's unit square.+pub type Polyline = Vec<[f32; 2]>;++/// Golden section: 1/φ.+const INV_PHI: f32 = 0.618_034;+/// Target spacing (screen points) of the Grid overlay's lines.+const GRID_PX: f32 = 32.0;+/// Most lines the Grid draws per axis, however large the frame is on screen.+const GRID_MAX: usize = 96;++/// The overlay's guides for a frame `w` × `h` screen points (along its own axes), in its unit+/// square. Orientation `orient` is taken modulo the overlay's [`CropOverlay::orientations`].+/// Degenerate or non-finite sizes give no guides.+pub fn guides(kind: CropOverlay, orient: u8, w: f32, h: f32) -> Vec<Polyline> {+ if !(w.is_finite() && h.is_finite()) || w < 1.0 || h < 1.0 {+ return Vec::new();+ }+ let seg = |a: [f32; 2], b: [f32; 2]| vec![a, b];+ let cross = |fs: &[f32]| -> Vec<Polyline> { fs.iter().flat_map(|&f| [seg([f, 0.0], [f, 1.0]), seg([0.0, f], [1.0, f])]).collect() };+ let lines = match kind {+ CropOverlay::Thirds => cross(&[1.0 / 3.0, 2.0 / 3.0]),+ CropOverlay::GoldenRatio => cross(&[1.0 - INV_PHI, INV_PHI]),+ CropOverlay::Grid => {+ let axis = |len: f32, vertical: bool| -> Vec<Polyline> {+ // Square cells of about GRID_PX on screen, at most GRID_MAX lines per axis.+ let n = ((len / GRID_PX) as usize).clamp(2, GRID_MAX);+ (1..n)+ .map(|i| {+ let f = i as f32 / n as f32;+ if vertical { seg([f, 0.0], [f, 1.0]) } else { seg([0.0, f], [1.0, f]) }+ })+ .collect()+ };+ let mut v = axis(w, true);+ v.extend(axis(h, false));+ v+ }+ CropOverlay::Diagonal => {+ // 45° on screen from each corner until the line meets the far edge.+ let m = w.min(h);+ let (u, v) = (m / w, m / h);+ vec![seg([0.0, 0.0], [u, v]), seg([1.0, 0.0], [1.0 - u, v]), seg([0.0, 1.0], [u, 1.0 - v]), seg([1.0, 1.0], [1.0 - u, 1.0 - v])]+ }+ CropOverlay::Triangle => {+ // The top-left to bottom-right diagonal, and the perpendiculars to it (on screen) from+ // the other two corners; their feet sit at `t` and `s` along it.+ // t = w² / (w² + h²) and s = 1 - t, from the smaller ratio so huge sizes can't overflow.+ let (t, s) = if w >= h {+ let t = 1.0 / (1.0 + (h / w).powi(2));+ (t, 1.0 - t)+ } else {+ let s = 1.0 / (1.0 + (w / h).powi(2));+ (1.0 - s, s)+ };+ vec![seg([0.0, 0.0], [1.0, 1.0]), seg([1.0, 0.0], [t, t]), seg([0.0, 1.0], [s, s])]+ }+ CropOverlay::GoldenSpiral => vec![golden_spiral()],+ };+ let o = orient % kind.orientations().max(1);+ let (fx, fy) = (o & 1 != 0, o & 2 != 0);+ lines.into_iter().map(|l| l.into_iter().map(|[x, y]| [if fx { 1.0 - x } else { x }, if fy { 1.0 - y } else { y }]).collect()).collect()+}++/// The golden spiral: quarter arcs through nested golden rectangles, squares cut off the left,+/// top, right and bottom in turn, winding in towards the lower right. Stretched to the unit square.+fn golden_spiral() -> Polyline {+ const PHI: f32 = 1.0 + INV_PHI;+ const STEPS: usize = 12;+ // The remaining rectangle [x0, y0, x1, y1] in a φ × 1 space, and the spiral's current point.+ let mut r = [0.0f32, 0.0, PHI, 1.0];+ let mut p = [0.0f32, 1.0];+ let mut pts = vec![p];+ for i in 0..12 {+ let (w, h) = (r[2] - r[0], r[3] - r[1]);+ let s = w.min(h);+ if s < 1e-4 {+ break;+ }+ // The square cut off, the arc's centre (a corner of it) and the end point; the rest stays.+ let (centre, end) = match i % 4 {+ 0 => {+ r[0] += s;+ ([r[0], r[3]], [r[0], r[1]])+ }+ 1 => {+ r[1] += s;+ ([r[0], r[1]], [r[2], r[1]])+ }+ 2 => {+ r[2] -= s;+ ([r[2], r[1]], [r[2], r[3]])+ }+ _ => {+ r[3] -= s;+ ([r[2], r[3]], [r[0], r[3]])+ }+ };+ let a0 = (p[1] - centre[1]).atan2(p[0] - centre[0]);+ let a1 = (end[1] - centre[1]).atan2(end[0] - centre[0]);+ let mut da = a1 - a0;+ if da > std::f32::consts::PI {+ da -= std::f32::consts::TAU;+ } else if da < -std::f32::consts::PI {+ da += std::f32::consts::TAU;+ }+ for k in 1..=STEPS {+ let a = a0 + da * k as f32 / STEPS as f32;+ pts.push([centre[0] + s * a.cos(), centre[1] + s * a.sin()]);+ }+ p = end;+ }+ pts.into_iter().map(|[x, y]| [(x / PHI).clamp(0.0, 1.0), y.clamp(0.0, 1.0)]).collect()+}++/// The guides the pending crop box shows now: none when the options say not to.+pub fn current_guides(app: &PhotocraftApp, w: f32, h: f32) -> Vec<Polyline> {+ let o = &app.ui.tool_options;+ if app.ui.tool != Tool::Crop || !o.crop_overlay_show.shows(app.crop.drag.is_some()) {+ return Vec::new();+ }+ guides(o.crop_overlay, o.crop_overlay_orientation, w, h)+}++/// O: the next overlay (the orientation starts over).+pub fn cycle(o: &mut ToolOptions) {+ o.crop_overlay = o.crop_overlay.next();+ o.crop_overlay_orientation = 0;+}++/// ⇧O: the overlay's next orientation (nothing for a symmetric one).+pub fn cycle_orientation(o: &mut ToolOptions) {+ let n = o.crop_overlay.orientations().max(1);+ o.crop_overlay_orientation = (o.crop_overlay_orientation % n + 1) % n;+}++/// O / ⇧O with the Crop tool showing a box and no drag in progress. Returns true when a key was+/// used; otherwise O stays the Dodge/Burn/Sponge tool key.+pub fn keys(app: &mut PhotocraftApp, ctx: &egui::Context) -> bool {+ if app.ui.tool != Tool::Crop || app.ui.crop_rect.is_none() || app.crop.drag.is_some() {+ return false;+ }+ if ctx.input_mut(|i| i.consume_key(Modifiers::SHIFT, Key::O)) {+ cycle_orientation(&mut app.ui.tool_options);+ return true;+ }+ if ctx.input_mut(|i| i.consume_key(Modifiers::NONE, Key::O)) {+ cycle(&mut app.ui.tool_options);+ return true;+ }+ false+}++/// The options bar's overlay button and its menu (Photoshop's "Set the overlay options for the+/// Crop tool").+pub fn options_button(o: &mut ToolOptions, ui: &mut egui::Ui) {+ let r =+ crate::icons::button(ui, "grid-3x3", 24.0, false, &format!("{} ({})", tl!("Set the overlay options for the Crop tool"), tl!(o.crop_overlay.label())));+ egui::Popup::menu(&r).show(|ui| {+ ui.set_min_width(220.0);+ let item = |ui: &mut egui::Ui, on: bool, label: &str, key: Option<&str>| {+ let mut b = egui::Button::new(format!("{} {}", if on { "✔" } else { " " }, label));+ if let Some(k) = key {+ b = b.shortcut_text(crate::shortcuts::pretty(k));+ }+ ui.add(b).clicked()+ };+ for k in CropOverlay::ALL {+ if item(ui, o.crop_overlay == k, tl!(k.label()), None) {+ if o.crop_overlay != k {+ o.crop_overlay_orientation = 0;+ }+ o.crop_overlay = k;+ ui.close();+ }+ }+ ui.separator();+ for s in OverlayShow::ALL {+ if item(ui, o.crop_overlay_show == s, tl!(s.label()), None) {+ o.crop_overlay_show = s;+ ui.close();+ }+ }+ ui.separator();+ if item(ui, false, tl!("Cycle Overlay"), Some("O")) {+ cycle(o);+ ui.close();+ }+ let turns = o.crop_overlay.orientations() > 1;+ let b = egui::Button::new(format!(" {}", tl!("Cycle Orientation"))).shortcut_text(crate::shortcuts::pretty("Shift+O"));+ if ui.add_enabled(turns, b).clicked() {+ cycle_orientation(o);+ ui.close();+ }+ });+}++#[cfg(test)]+mod tests {+ use super::*;++ fn all_points(g: &[Polyline]) -> impl Iterator<Item = [f32; 2]> + '_ {+ g.iter().flatten().copied()+ }++ #[test]+ fn every_guide_stays_in_the_unit_square() {+ for kind in CropOverlay::ALL {+ for o in 0..8 {+ for (w, h) in [(1.0, 1.0), (300.0, 200.0), (200.0, 300.0), (5000.0, 3.0), (3.0, 5000.0), (1e7, 1e7), (1e30, 2.0)] {+ let g = guides(kind, o, w, h);+ assert!(!g.is_empty(), "{kind:?} {w}x{h}");+ for p in all_points(&g) {+ assert!(p.iter().all(|v| v.is_finite() && (-1e-5..=1.0 + 1e-5).contains(v)), "{kind:?} o{o} {w}x{h}: {p:?}");+ }+ assert!(g.iter().all(|l| l.len() >= 2));+ }+ }+ }+ }++ #[test]+ fn degenerate_frames_have_no_guides() {+ for kind in CropOverlay::ALL {+ for (w, h) in [(0.0, 10.0), (10.0, 0.0), (f32::NAN, 10.0), (f32::INFINITY, 10.0), (-5.0, -5.0), (0.5, 100.0)] {+ assert!(guides(kind, 0, w, h).is_empty(), "{kind:?} {w}x{h}");+ }+ }+ }++ #[test]+ fn thirds_and_golden_ratio_positions() {+ let xs = |g: Vec<Polyline>| -> Vec<f32> { g.iter().filter(|l| l[0][1] == 0.0 && l[1][1] == 1.0).map(|l| l[0][0]).collect() };+ let t = xs(guides(CropOverlay::Thirds, 0, 300.0, 200.0));+ assert_eq!(t.len(), 2);+ assert!((t[0] - 1.0 / 3.0).abs() < 1e-6 && (t[1] - 2.0 / 3.0).abs() < 1e-6);+ let g = xs(guides(CropOverlay::GoldenRatio, 0, 300.0, 200.0));+ assert!((g[0] - 0.381_966).abs() < 1e-5 && (g[1] - 0.618_034).abs() < 1e-5, "{g:?}");+ assert_eq!(guides(CropOverlay::GoldenRatio, 0, 300.0, 200.0).len(), 4);+ }++ #[test]+ fn grid_spacing_is_bounded() {+ for (w, h) in [(10.0, 10.0), (64.0, 64.0), (640.0, 320.0), (1e6, 1e6)] {+ let g = guides(CropOverlay::Grid, 0, w, h);+ let v = g.iter().filter(|l| l[0][0] == l[1][0]).count();+ let hz = g.len() - v;+ assert!((1..GRID_MAX).contains(&v) && (1..GRID_MAX).contains(&hz), "{w}x{h}: {v} {hz}");+ }+ // About one line per GRID_PX on screen.+ let g = guides(CropOverlay::Grid, 0, 640.0, 320.0);+ assert_eq!(g.iter().filter(|l| l[0][0] == l[1][0]).count(), 19);+ assert_eq!(g.iter().filter(|l| l[0][1] == l[1][1]).count(), 9);+ }++ #[test]+ fn diagonals_run_at_45_degrees_on_screen() {+ let (w, h) = (300.0f32, 200.0f32);+ for l in guides(CropOverlay::Diagonal, 0, w, h) {+ let (dx, dy) = ((l[1][0] - l[0][0]) * w, (l[1][1] - l[0][1]) * h);+ assert!((dx.abs() - dy.abs()).abs() < 1e-3 && (dx.abs() - 200.0).abs() < 1e-3, "{l:?}");+ }+ // A square frame: corner to corner.+ let g = guides(CropOverlay::Diagonal, 0, 100.0, 100.0);+ assert_eq!(g[0], vec![[0.0, 0.0], [1.0, 1.0]]);+ }++ #[test]+ fn triangle_perpendiculars_meet_the_diagonal_at_right_angles() {+ let (w, h) = (300.0f32, 200.0f32);+ let g = guides(CropOverlay::Triangle, 0, w, h);+ let diag = [w, h];+ for l in &g[1..] {+ let d = [(l[1][0] - l[0][0]) * w, (l[1][1] - l[0][1]) * h];+ assert!((d[0] * diag[0] + d[1] * diag[1]).abs() < 1e-2, "{l:?}");+ assert!((l[1][0] - l[1][1]).abs() < 1e-6, "foot on the diagonal: {l:?}");+ }+ // The other orientation mirrors it: the diagonal runs top-right to bottom-left.+ let m = guides(CropOverlay::Triangle, 1, w, h);+ assert_eq!(m[0], vec![[1.0, 0.0], [0.0, 1.0]]);+ for (a, b) in g.iter().zip(&m) {+ for (p, q) in a.iter().zip(b) {+ assert!((p[0] - (1.0 - q[0])).abs() < 1e-6 && (p[1] - q[1]).abs() < 1e-6);+ }+ }+ // Two orientations: 2 is 0 again.+ assert_eq!(guides(CropOverlay::Triangle, 2, w, h), g);+ }++ #[test]+ fn golden_spiral_orientations_mirror_it_into_each_corner() {+ let base = guides(CropOverlay::GoldenSpiral, 0, 300.0, 200.0);+ let pts = &base[0];+ assert!(pts.len() > 40);+ // It starts at the bottom-left corner and winds in towards the golden point (lower right).+ assert_eq!(pts[0], [0.0, 1.0]);+ let end = pts[pts.len() - 1];+ assert!((end[0] - 0.7236).abs() < 0.02 && (end[1] - 0.7236).abs() < 0.02, "{end:?}");+ for o in 1..4u8 {+ let g = guides(CropOverlay::GoldenSpiral, o, 300.0, 200.0);+ for (p, q) in pts.iter().zip(&g[0]) {+ let x = if o & 1 != 0 { 1.0 - p[0] } else { p[0] };+ let y = if o & 2 != 0 { 1.0 - p[1] } else { p[1] };+ assert!((x - q[0]).abs() < 1e-6 && (y - q[1]).abs() < 1e-6);+ }+ }+ assert_eq!(guides(CropOverlay::GoldenSpiral, 4, 300.0, 200.0), base);+ // Symmetric overlays ignore the orientation.+ assert_eq!(guides(CropOverlay::Thirds, 3, 300.0, 200.0), guides(CropOverlay::Thirds, 0, 300.0, 200.0));+ }++ #[test]+ fn cycling_overlays_and_orientations() {+ let mut o = ToolOptions::default();+ assert_eq!((o.crop_overlay, o.crop_overlay_show, o.crop_overlay_orientation), (CropOverlay::Thirds, OverlayShow::Auto, 0));+ let mut seen = vec![o.crop_overlay];+ for _ in 0..6 {+ cycle(&mut o);+ seen.push(o.crop_overlay);+ }+ assert_eq!(&seen[..6], &CropOverlay::ALL);+ assert_eq!(seen[6], CropOverlay::Thirds, "wraps around");+ cycle_orientation(&mut o);+ assert_eq!(o.crop_overlay_orientation, 0, "thirds has one orientation");+ o.crop_overlay = CropOverlay::GoldenSpiral;+ let turns: Vec<u8> = (0..5)+ .map(|_| {+ cycle_orientation(&mut o);+ o.crop_overlay_orientation+ })+ .collect();+ assert_eq!(turns, [1, 2, 3, 0, 1]);+ cycle(&mut o);+ assert_eq!((o.crop_overlay, o.crop_overlay_orientation), (CropOverlay::Thirds, 0));+ // A stray orientation (an old or hand-edited state) still cycles in range.+ o.crop_overlay = CropOverlay::Triangle;+ o.crop_overlay_orientation = 200;+ cycle_orientation(&mut o);+ assert!(o.crop_overlay_orientation < 2);+ }++ #[test]+ fn visibility_modes() {+ assert!(OverlayShow::Auto.shows(true) && !OverlayShow::Auto.shows(false));+ assert!(OverlayShow::Always.shows(true) && OverlayShow::Always.shows(false));+ assert!(!OverlayShow::Never.shows(true) && !OverlayShow::Never.shows(false));+ for k in CropOverlay::ALL {+ assert_eq!(CropOverlay::from_id(k.id()), Some(k));+ }+ for s in OverlayShow::ALL {+ assert_eq!(OverlayShow::from_id(s.id()), Some(s));+ }+ assert_eq!(CropOverlay::from_id("spiral"), None);+ }++ /// One key press through the shortcut handler, as egui delivers it.+ fn press(app: &mut PhotocraftApp, mods: Modifiers) {+ let ctx = egui::Context::default();+ ctx.input_mut(|i| {+ i.modifiers = mods;+ i.events.push(egui::Event::Key { key: Key::O, physical_key: None, pressed: true, repeat: false, modifiers: mods });+ });+ crate::shortcuts::handle(app, &ctx);+ }++ fn crop_app() -> PhotocraftApp {+ let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", serde_json::json!({"width": 200, "height": 120})).unwrap();+ app.ui.tool = Tool::Crop;+ crate::crop_ui::ensure_frame(&mut app);+ assert!(app.ui.crop_rect.is_some());+ app+ }++ #[test]+ fn o_cycles_the_overlay_while_the_crop_tool_shows_a_box() {+ let mut app = crop_app();+ press(&mut app, Modifiers::NONE);+ assert_eq!((app.ui.tool, app.ui.tool_options.crop_overlay), (Tool::Crop, CropOverlay::Grid));+ // ⇧O on a symmetric overlay changes nothing, and doesn't switch tools either.+ press(&mut app, Modifiers::SHIFT);+ assert_eq!((app.ui.tool, app.ui.tool_options.crop_overlay, app.ui.tool_options.crop_overlay_orientation), (Tool::Crop, CropOverlay::Grid, 0));+ press(&mut app, Modifiers::NONE);+ press(&mut app, Modifiers::NONE);+ assert_eq!(app.ui.tool_options.crop_overlay, CropOverlay::Triangle);+ press(&mut app, Modifiers::SHIFT);+ assert_eq!(app.ui.tool_options.crop_overlay_orientation, 1);+ assert_eq!(app.ui.tool, Tool::Crop);+ }++ #[test]+ fn o_stays_the_dodge_key_without_a_crop_box() {+ // No document: the Crop tool shows no box, so O picks the Dodge tool.+ let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());+ app.ui.tool = Tool::Crop;+ press(&mut app, Modifiers::NONE);+ assert_eq!(app.ui.tool, Tool::Dodge);+ assert_eq!(app.ui.tool_options.crop_overlay, CropOverlay::Thirds);+ // Another tool: O is its tool key as before.+ let mut app = crop_app();+ app.ui.tool = Tool::Brush;+ press(&mut app, Modifiers::NONE);+ assert_eq!((app.ui.tool, app.ui.tool_options.crop_overlay), (Tool::Dodge, CropOverlay::Thirds));+ // A crop drag in progress leaves the overlay alone.+ let mut app = crop_app();+ app.crop.drag = Some(crate::crop_ui::CropDrag::Move { start: [0.0, 0.0], rect: [0.0, 0.0, 10.0, 10.0] });+ let ctx = egui::Context::default();+ ctx.input_mut(|i| i.events.push(egui::Event::Key { key: Key::O, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::NONE }));+ assert!(!keys(&mut app, &ctx));+ assert_eq!(app.ui.tool_options.crop_overlay, CropOverlay::Thirds);+ }++ #[test]+ fn the_overlay_shows_by_mode_and_gesture() {+ let mut app = crop_app();+ assert!(current_guides(&app, 300.0, 200.0).is_empty(), "Auto: no guides without a drag");+ app.crop.drag = Some(crate::crop_ui::CropDrag::Move { start: [0.0, 0.0], rect: [0.0, 0.0, 10.0, 10.0] });+ assert_eq!(current_guides(&app, 300.0, 200.0).len(), 4, "Auto: the thirds while dragging");+ app.ui.tool_options.crop_overlay_show = OverlayShow::Never;+ assert!(current_guides(&app, 300.0, 200.0).is_empty());+ app.crop.drag = None;+ app.ui.tool_options.crop_overlay_show = OverlayShow::Always;+ app.ui.tool_options.crop_overlay = CropOverlay::Triangle;+ assert_eq!(current_guides(&app, 300.0, 200.0).len(), 3);+ app.ui.tool = Tool::Brush;+ assert!(current_guides(&app, 300.0, 200.0).is_empty(), "a pending frame under another tool shows no guide");+ }++ #[test]+ fn old_state_files_get_photoshops_defaults() {+ let o: ToolOptions = serde_json::from_str(r#"{"crop_ratio": "1:1"}"#).unwrap();+ assert_eq!((o.crop_overlay, o.crop_overlay_show, o.crop_overlay_orientation), (CropOverlay::Thirds, OverlayShow::Auto, 0));+ let o: ToolOptions = serde_json::from_str(r#"{"crop_overlay": "goldenSpiral", "crop_overlay_show": "always", "crop_overlay_orientation": 3}"#).unwrap();+ assert_eq!((o.crop_overlay, o.crop_overlay_show, o.crop_overlay_orientation), (CropOverlay::GoldenSpiral, OverlayShow::Always, 3));+ }+}diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsvindex 2d5b7f773..30f7b3d91 100644--- a/crates/ui-egui/src/i18n/cs.tsv+++ b/crates/ui-egui/src/i18n/cs.tsv@@ -2279,3 +2279,13 @@ fontWeight Italic KurzívaColor to Alpha… Barva na alfu…Transparency Threshold Práh průhlednostiOpacity Threshold Práh krytí+ Rule of Thirds Pravidlo třetin+ Triangle Trojúhelník+ Golden Ratio Zlatý řez+ Golden Spiral Zlatá spirála+ Auto Show Overlay Automaticky zobrazit překryv+ Always Show Overlay Vždy zobrazit překryv+ Never Show Overlay Nikdy nezobrazit překryv+ Cycle Overlay Přepnout překryv+ Cycle Orientation Přepnout orientaci+ Set the overlay options for the Crop tool Nastavit volby překryvu pro nástroj Oříznutídiff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsvindex f0e398d53..02da857ec 100644--- a/crates/ui-egui/src/i18n/de.tsv+++ b/crates/ui-egui/src/i18n/de.tsv@@ -2317,3 +2317,13 @@ fontWeight Italic KursivColor to Alpha… Farbe zu Alpha…Transparency Threshold Transparenz-SchwellenwertOpacity Threshold Deckkraft-Schwellenwert+ Rule of Thirds Drittel-Regel+ Triangle Dreieck+ Golden Ratio Goldener Schnitt+ Golden Spiral Goldene Spirale+ Auto Show Overlay Überlagerung automatisch anzeigen+ Always Show Overlay Überlagerung immer anzeigen+ Never Show Overlay Überlagerung nie anzeigen+ Cycle Overlay Überlagerung wechseln+ Cycle Orientation Ausrichtung wechseln+ Set the overlay options for the Crop tool Überlagerungsoptionen für das Freistellungswerkzeug festlegendiff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsvindex 87cc5003a..21d52448f 100644--- a/crates/ui-egui/src/i18n/el.tsv+++ b/crates/ui-egui/src/i18n/el.tsv@@ -3389,3 +3389,12 @@ fontWeight Thin Πολύ λεπτάColor to Alpha… Χρώμα σε άλφα…Transparency Threshold Κατώφλι διαφάνειαςOpacity Threshold Κατώφλι αδιαφάνειας+ Rule of Thirds Κανόνας των τρίτων+ Golden Ratio Χρυσή τομή+ Golden Spiral Χρυσή σπείρα+ Auto Show Overlay Αυτόματη εμφάνιση επικάλυψης+ Always Show Overlay Πάντα εμφάνιση επικάλυψης+ Never Show Overlay Ποτέ εμφάνιση επικάλυψης+ Cycle Overlay Εναλλαγή επικάλυψης+ Cycle Orientation Εναλλαγή προσανατολισμού+ Set the overlay options for the Crop tool Ορισμός επιλογών επικάλυψης για το εργαλείο Περικοπήdiff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsvindex b7ea6a985..a15f24d2d 100644--- a/crates/ui-egui/src/i18n/es.tsv+++ b/crates/ui-egui/src/i18n/es.tsv@@ -2347,3 +2347,13 @@ fontWeight Italic CursivaColor to Alpha… Color a alfa…Transparency Threshold Umbral de transparenciaOpacity Threshold Umbral de opacidad+ Rule of Thirds Regla de los tercios+ Triangle Triángulo+ Golden Ratio Proporción áurea+ Golden Spiral Espiral áurea+ Auto Show Overlay Mostrar superposición automáticamente+ Always Show Overlay Mostrar siempre la superposición+ Never Show Overlay No mostrar nunca la superposición+ Cycle Overlay Alternar superposición+ Cycle Orientation Alternar orientación+ Set the overlay options for the Crop tool Definir las opciones de superposición de la herramienta Recortardiff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsvindex c556da626..06876c76f 100644--- a/crates/ui-egui/src/i18n/fr.tsv+++ b/crates/ui-egui/src/i18n/fr.tsv@@ -2700,3 +2700,13 @@ fontWeight Italic ItaliqueColor to Alpha… Couleur vers alpha…Transparency Threshold Seuil de transparenceOpacity Threshold Seuil d'opacité+ Rule of Thirds Règle des tiers+ Triangle Triangle+ Golden Ratio Nombre d’or+ Golden Spiral Spirale d’or+ Auto Show Overlay Afficher automatiquement la superposition+ Always Show Overlay Toujours afficher la superposition+ Never Show Overlay Ne jamais afficher la superposition+ Cycle Overlay Changer de superposition+ Cycle Orientation Changer d’orientation+ Set the overlay options for the Crop tool Définir les options de superposition de l’outil Recadragediff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsvindex 7137a8b24..8d3f87f6f 100644--- a/crates/ui-egui/src/i18n/id.tsv+++ b/crates/ui-egui/src/i18n/id.tsv@@ -2687,3 +2687,13 @@ fontWeight Italic MiringColor to Alpha… Warna ke Alpha…Transparency Threshold Ambang transparansiOpacity Threshold Ambang opasitas+ Rule of Thirds Aturan Sepertiga+ Triangle Segitiga+ Golden Ratio Rasio Emas+ Golden Spiral Spiral Emas+ Auto Show Overlay Tampilkan Overlay Otomatis+ Always Show Overlay Selalu Tampilkan Overlay+ Never Show Overlay Jangan Tampilkan Overlay+ Cycle Overlay Ganti Overlay+ Cycle Orientation Ganti Orientasi+ Set the overlay options for the Crop tool Atur opsi overlay untuk alat Cropdiff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsvindex 3b90d4f3f..5a56a33ad 100644--- a/crates/ui-egui/src/i18n/it.tsv+++ b/crates/ui-egui/src/i18n/it.tsv@@ -2348,3 +2348,13 @@ fontWeight Italic CorsivoColor to Alpha… Colore ad alfa…Transparency Threshold Soglia di trasparenzaOpacity Threshold Soglia di opacità+ Rule of Thirds Regola dei terzi+ Triangle Triangolo+ Golden Ratio Sezione aurea+ Golden Spiral Spirale aurea+ Auto Show Overlay Mostra sovrapposizione automaticamente+ Always Show Overlay Mostra sempre sovrapposizione+ Never Show Overlay Non mostrare mai sovrapposizione+ Cycle Overlay Cambia sovrapposizione+ Cycle Orientation Cambia orientamento+ Set the overlay options for the Crop tool Imposta le opzioni di sovrapposizione dello strumento Taglierinadiff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsvindex 0fbd3f5d7..6c2a6c45a 100644--- a/crates/ui-egui/src/i18n/ja.tsv+++ b/crates/ui-egui/src/i18n/ja.tsv@@ -3304,3 +3304,12 @@ fontWeight Italic 斜体Color to Alpha… カラーを透明に…Transparency Threshold 透明のしきい値Opacity Threshold 不透明度のしきい値+ Rule of Thirds 三分割法+ Golden Ratio 黄金比+ Golden Spiral 黄金螺旋+ Auto Show Overlay オーバーレイを自動表示+ Always Show Overlay オーバーレイを常に表示+ Never Show Overlay オーバーレイを表示しない+ Cycle Overlay オーバーレイを切り替え+ Cycle Orientation 方向を切り替え+ Set the overlay options for the Crop tool 切り抜きツールのオーバーレイオプションを設定diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsvindex 4f108e0f1..019caba47 100644--- a/crates/ui-egui/src/i18n/ko.tsv+++ b/crates/ui-egui/src/i18n/ko.tsv@@ -2858,3 +2858,12 @@ fontWeight Italic 기울임Color to Alpha… 색상을 알파로…Transparency Threshold 투명도 한계값Opacity Threshold 불투명도 한계값+ Rule of Thirds 삼등분 법칙+ Golden Ratio 황금 비율+ Golden Spiral 황금 나선+ Auto Show Overlay 오버레이 자동 표시+ Always Show Overlay 오버레이 항상 표시+ Never Show Overlay 오버레이 표시 안 함+ Cycle Overlay 오버레이 순환+ Cycle Orientation 방향 순환+ Set the overlay options for the Crop tool 자르기 도구의 오버레이 옵션 설정diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsvindex e992b479e..fc01d9076 100644--- a/crates/ui-egui/src/i18n/nl.tsv+++ b/crates/ui-egui/src/i18n/nl.tsv@@ -3464,3 +3464,12 @@ cameraRaw Whites WittenDual Axis Dubbele asDiagonal DiagonaalTransform Symmetry Symmetrie transformeren+ Rule of Thirds Regel van derden+ Golden Ratio Gulden snede+ Golden Spiral Gulden spiraal+ Auto Show Overlay Overlay automatisch tonen+ Always Show Overlay Overlay altijd tonen+ Never Show Overlay Overlay nooit tonen+ Cycle Overlay Overlay wisselen+ Cycle Orientation Oriëntatie wisselen+ Set the overlay options for the Crop tool Overlay-opties voor het gereedschap Uitsnijden instellendiff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsvindex 387c0e4e9..147f4ca72 100644--- a/crates/ui-egui/src/i18n/pl.tsv+++ b/crates/ui-egui/src/i18n/pl.tsv@@ -3302,3 +3302,12 @@ cameraRaw Roughness ChropowatośćColor to Alpha… Kolor na alfę…Transparency Threshold Próg przezroczystościOpacity Threshold Próg krycia+ Rule of Thirds Zasada trójpodziału+ Golden Ratio Złoty podział+ Golden Spiral Złota spirala+ Auto Show Overlay Pokazuj nakładkę automatycznie+ Always Show Overlay Zawsze pokazuj nakładkę+ Never Show Overlay Nigdy nie pokazuj nakładki+ Cycle Overlay Przełącz nakładkę+ Cycle Orientation Przełącz orientację+ Set the overlay options for the Crop tool Ustaw opcje nakładki narzędzia Kadrowaniediff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsvindex a0052dc7c..01469534b 100644--- a/crates/ui-egui/src/i18n/pt-br.tsv+++ b/crates/ui-egui/src/i18n/pt-br.tsv@@ -2707,3 +2707,13 @@ fontWeight Italic ItálicoColor to Alpha… Cor para alfa…Transparency Threshold Limiar de transparênciaOpacity Threshold Limiar de opacidade+ Rule of Thirds Regra dos terços+ Triangle Triângulo+ Golden Ratio Proporção áurea+ Golden Spiral Espiral áurea+ Auto Show Overlay Mostrar sobreposição automaticamente+ Always Show Overlay Sempre mostrar sobreposição+ Never Show Overlay Nunca mostrar sobreposição+ Cycle Overlay Alternar sobreposição+ Cycle Orientation Alternar orientação+ Set the overlay options for the Crop tool Definir as opções de sobreposição da ferramenta Corte demarcadodiff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsvindex 6c312893c..6d73e1284 100644--- a/crates/ui-egui/src/i18n/ru.tsv+++ b/crates/ui-egui/src/i18n/ru.tsv@@ -2552,3 +2552,13 @@ fontWeight Italic КурсивColor to Alpha… Цвет в альфа-канал…Transparency Threshold Порог прозрачностиOpacity Threshold Порог непрозрачности+ Rule of Thirds Правило третей+ Triangle Треугольник+ Golden Ratio Золотое сечение+ Golden Spiral Золотая спираль+ Auto Show Overlay Показывать перекрытие автоматически+ Always Show Overlay Всегда показывать перекрытие+ Never Show Overlay Никогда не показывать перекрытие+ Cycle Overlay Сменить перекрытие+ Cycle Orientation Сменить ориентацию+ Set the overlay options for the Crop tool Задать параметры перекрытия для инструмента «Рамка»diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsvindex dbfdcb549..91472e10e 100644--- a/crates/ui-egui/src/i18n/uk.tsv+++ b/crates/ui-egui/src/i18n/uk.tsv@@ -3389,3 +3389,12 @@ cameraRaw Masking МаскуванняDual Axis Подвійна вісьDiagonal ДіагональнаTransform Symmetry Трансформувати симетрію+ Rule of Thirds Правило третин+ Golden Ratio Золотий перетин+ Golden Spiral Золота спіраль+ Auto Show Overlay Показувати накладання автоматично+ Always Show Overlay Завжди показувати накладання+ Never Show Overlay Ніколи не показувати накладання+ Cycle Overlay Змінити накладання+ Cycle Orientation Змінити орієнтацію+ Set the overlay options for the Crop tool Задати параметри накладання для інструмента «Рамка»diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsvindex b05c97096..b6684dba3 100644--- a/crates/ui-egui/src/i18n/zh-hans.tsv+++ b/crates/ui-egui/src/i18n/zh-hans.tsv@@ -2287,3 +2287,13 @@ fontWeight Italic 斜体Color to Alpha… 颜色转为 Alpha…Transparency Threshold 透明度阈值Opacity Threshold 不透明度阈值+ Rule of Thirds 三等分+ Triangle 三角形+ Golden Ratio 黄金比例+ Golden Spiral 金色螺线+ Auto Show Overlay 自动显示叠加+ Always Show Overlay 总是显示叠加+ Never Show Overlay 从不显示叠加+ Cycle Overlay 循环切换叠加+ Cycle Orientation 循环切换取向+ Set the overlay options for the Crop tool 设置裁剪工具的叠加选项diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsvindex 7968d0d5d..f3e832efa 100644--- a/crates/ui-egui/src/i18n/zh-hant.tsv+++ b/crates/ui-egui/src/i18n/zh-hant.tsv@@ -2256,3 +2256,13 @@ fontWeight Italic 斜體Color to Alpha… 顏色轉為 Alpha…Transparency Threshold 透明度臨界值Opacity Threshold 不透明度臨界值+ Rule of Thirds 三等分+ Triangle 三角形+ Golden Ratio 黃金比例+ Golden Spiral 黃金螺旋+ Auto Show Overlay 自動顯示覆蓋+ Always Show Overlay 永遠顯示覆蓋+ Never Show Overlay 永不顯示覆蓋+ Cycle Overlay 循環切換覆蓋+ Cycle Orientation 循環切換方向+ Set the overlay options for the Crop tool 設定裁切工具的覆蓋選項diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rsindex 3a76df933..dd9e4c32a 100644--- a/crates/ui-egui/src/lib.rs+++ b/crates/ui-egui/src/lib.rs@@ -45,6 +45,7 @@ pub mod color_range_ui;pub mod comps_ui;pub mod control;pub mod credits;+pub mod crop_overlay;pub mod crop_ui;pub mod dialog_blend_ui;pub mod dialogs;diff --git a/crates/ui-egui/src/panels.rs b/crates/ui-egui/src/panels.rsindex 328cc6d79..54d88fb00 100644--- a/crates/ui-egui/src/panels.rs+++ b/crates/ui-egui/src/panels.rs@@ -988,7 +988,7 @@ pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui) {if widgets::secondary_button(ui, tl!("Clear"), 0.0).clicked() {o.crop_ratio.clear();}- let _ = icons::button(ui, "grid-3x3", 24.0, true, tl!("Overlay: Rule of Thirds"));+ crate::crop_overlay::options_button(o, ui);widgets::checkbox(ui, &mut o.crop_delete, tl!("Delete Cropped Pixels"));ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {if icons::button(diff --git a/crates/ui-egui/src/shortcuts.rs b/crates/ui-egui/src/shortcuts.rsindex c3462947e..d303b0297 100644--- a/crates/ui-egui/src/shortcuts.rs+++ b/crates/ui-egui/src/shortcuts.rs@@ -370,6 +370,10 @@ pub fn handle(app: &mut PhotocraftApp, ctx: &egui::Context) {if editing {return;}+ // Crop tool showing a box: O cycles its overlay, ⇧O the overlay's orientation (#1919).+ if crate::crop_overlay::keys(app, ctx) {+ return;+ }// Single-key tools (no modifiers). D and X (`tools.defaultColors` / `tools.swapColors`) and the// brush keys [ ] ⇧[ ⇧] (`tools.decreaseBrushSize`…) are commands, dispatched above with any// Keyboard Shortcuts override.diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rsindex d350a3054..6010df9d0 100644--- a/crates/ui-egui/src/state.rs+++ b/crates/ui-egui/src/state.rs@@ -504,6 +504,14 @@ pub struct ToolOptions {pub crop_ratio: String,#[serde(default = "yes")]pub crop_delete: bool,+ /// Crop overlay (#1919): the guide in the crop box, when it shows and its orientation+ /// (Photoshop's defaults: Rule of Thirds, Auto Show Overlay). See `crop_overlay`.+ #[serde(default)]+ pub crop_overlay: crate::crop_overlay::CropOverlay,+ #[serde(default)]+ pub crop_overlay_show: crate::crop_overlay::OverlayShow,+ #[serde(default)]+ pub crop_overlay_orientation: u8,/// Magic Eraser opacity % (tolerance, anti-alias, contiguous and sample-all are shared with the/// Magic Wand and Paint Bucket).pub magic_eraser_opacity: f32,@@ -631,6 +639,9 @@ impl Default for ToolOptions {move_show_transform: false,crop_ratio: String::new(),crop_delete: true,+ crop_overlay: Default::default(),+ crop_overlay_show: Default::default(),+ crop_overlay_orientation: 0,magic_eraser_opacity: 100.0,bg_sampling: "continuous".into(),bg_limits: "contiguous".into(),diff --git a/docs/control-protocol.md b/docs/control-protocol.mdindex 45dab6570..7d61641e6 100644--- a/docs/control-protocol.md+++ b/docs/control-protocol.md@@ -43,6 +43,7 @@ The transport is `apps/photocraft/src/control_server.rs`, and the handlers are i- `ui.set` also accepts `gradientBlendMode` (a layer blend mode name, such as `Difference`) and `gradientClassic` (boolean) for the Gradient tool options bar.- Each painting tool keeps its own brush, as in Photoshop: `tools.setBrush` and `ui.set {brushSize}` change the active tool's brush, and switching tools swaps in that tool's own (size, hardness, mode, opacity, flow, dynamics, smoothing). A tool used for the first time starts from the brush in hand. The colours, the erase flag and the stroke seed stay shared. So `ui.set {tool: "eraser", brushSize: 12}` sets the Eraser's size, and `ui.set {tool: "brush"}` afterwards brings the Brush's own size back.- `ui.set` also accepts the Eyedropper options bar (#1649): `eyedropperSampleSize` (`"point"` or 1, 3, 5, 11, 31, 51, 101: the side of the averaged square, shared by the Eyedropper, a painting tool's Alt-click eyedropper, the Curves/Color Picker eyedroppers and the Info panel), `eyedropperSample` (`current`, `currentAndBelow`, `all`, `allNoAdjustments`, `currentAndBelowNoAdjustments`) and `eyedropperRing` (boolean, Show Sampling Ring). `ui.inspect` reports them under `toolOptions` (`eyedropper_size`, `eyedropper_sample`, `eyedropper_ring`). The engine command `document.sampleColor {x, y, size, sampleLayer}` returns the colour such a sample picks.+- `ui.set` also accepts the Crop tool's overlay menu (#1919): `cropOverlay` (`thirds`, `grid`, `diagonal`, `triangle`, `goldenRatio`, `goldenSpiral`), `cropOverlayShow` (`auto`: only while the crop box is dragged, Photoshop's default; `always`; `never`) and `cropOverlayOrientation` (0..3; Triangle has two orientations and Golden Spiral four, the others ignore it). `ui.inspect` reports them under `toolOptions` (`crop_overlay`, `crop_overlay_show`, `crop_overlay_orientation`). In the app, O cycles the overlay and ⇧O its orientation while the Crop tool shows a box.Both gradient modes use the current preset, including its opacity stops. Select `Foreground to Transparent` through `gradient.presets.select`, or pass custom `stops` and `transparency: [[0,100],[1,0]]` (location 0..1, opacity 0..100). Use `applyToLayer: false` to edit only the tool preset. Classic gradient drags dispatch `paint.gradient` without overriding them.- `ui.dialog.open {kind, fields?}` (kinds `newDocument`, `about`, `layerStyle {effect?}`, `colorPicker {target: foreground|background}`, `command {command}`) / `ui.dialog.set {dialog, field, value}` / `ui.dialog.confirm {dialog, wait?}` / `ui.dialog.cancel {dialog}`. Like `ui.menu.invoke`, `ui.dialog.confirm` waits for a background job its command starts (a filter dialog's OK) and replies with the result; `"wait": false` replies `{job, pending: true}` at once- The shell's own dialogs (Window › Workspace › New Workspace / Delete Workspace, View › Pixel Aspect Ratio › Custom Pixel Aspect Ratio…, View › Show › Show Extras Options…, View › 32-bit Preview Options…) are listed in `ui.inspect`'s `dialogs` with the id `"shell"` (at most one is open). `ui.dialog.set`, `ui.dialog.confirm` and `ui.dialog.cancel` take `{"dialog": "shell"}`; OK runs the dialog's command and keeps the dialog open if it failsdiff --git a/docs/scorecard.md b/docs/scorecard.mdindex 1a84ef908..1d65ce188 100644--- a/docs/scorecard.md+++ b/docs/scorecard.md@@ -8,7 +8,7 @@ Generated by `cargo xtask scorecard` from `perf/budgets.toml`, `perf/baseline.js|---|---:|---:|---:|---|| [Performance](#performance) | 3 | 22 | 14 | 48 scenarios: 3 within budget, 22 over budget or failing, 9 tracked only, 7 not run, 7 not measurable yet (baseline 2026-10-05) || [File compatibility](#file-compatibility) | 4 | 12 | 11 | io corpus: oracle ≥ 146/170, round trip ≥ 169/170; psd-tools corpus: oracle ≥ 236/309, round trip ≥ 307/309; photoshop oracles: oracle ≥ 133/256, round trip ≥ 258/256 |-| [Tools](#tools) | 14 | 14 | 8 | |+| [Tools](#tools) | 15 | 14 | 8 | || [Workspace and UI](#workspace-and-ui) | 5 | 6 | 12 | settings that do nothing: 48 of 141 (target 0) || [Type](#type) | 0 | 3 | 6 | || [Automation](#automation) | 3 | 2 | 6 | 627 of 627 menu items live (100.0%) |@@ -156,6 +156,7 @@ Corpus floors (`crates/io/tests/corpus.rs`): the enforced minimums; the corpus t| TOOL-213-17 | Red Eye tool: click a pupil to neutralize the red reflection | done | [#213](https://github.com/storytold/photocraft/issues/213) | paint.redEye (redeye_cmds.rs) + Tool::RedEye in the J flyout; Pupil Size and Darken Amount; catchlights kept; a miss is an error || TOOL-214-17 | Rotate View tool: drag to turn the view, Reset View, Match Rotation copies the angle | done | [#214](https://github.com/storytold/photocraft/issues/214) | Tool::RotateView in the Hand flyout; view.rotateView / view.resetView; Match Rotation copies views[].rotation; enhanced_controls.rotate_view_with_trackpad is read || TOOL-1649-1 | Eyedropper Sample Size (Point, 3×3 … 101×101 Average), Sample layers, Show Sampling Ring | done | [#1649](https://github.com/storytold/photocraft/issues/1649) | document.sampleColor (sample_cmds.rs): average of the square clipped to the canvas, in the document's model and depth; eyedropper_ui.rs options bar; shared with Alt-click, dialog eyedroppers and the Info panel; ui.set eyedropperSampleSize/eyedropperSample/eyedropperRing. Color Sampler tool still missing |+| TOOL-214-20 | Crop overlay options: Rule of Thirds, Grid, Diagonal, Triangle, Golden Ratio, Golden Spiral; Auto / Always / Never Show Overlay; O cycles the overlay, Shift+O its orientation | done | [#1919](https://github.com/storytold/photocraft/issues/1919) | crop_overlay.rs: unit-square guides shared by upright and turned frames (canvas.rs), options-bar menu, O / Shift+O ahead of the tool keys in shortcuts.rs; ToolOptions crop_overlay / crop_overlay_show / crop_overlay_orientation, ui.set cropOverlay / cropOverlayShow / cropOverlayOrientation || TOOL-214-18 | Crop: drag outside the frame to rotate it (Shift 15 deg steps, angle readout); Enter rotates and crops in one step | done | [#1792](https://github.com/storytold/photocraft/issues/1792) | image.crop angle param (image_cmds.rs: Image Rotation > Arbitrary + crop, one undo step); crop_ui.rs turns, moves and resizes the frame along its axes (Classic Mode visuals); UiState.crop_angle || TOOL-214-19 | Crop: arrow keys nudge the crop box (Shift 10 px), X swaps portrait/landscape, W x H readout while drawing or resizing | done | [#1919](https://github.com/storytold/photocraft/issues/1919) | crop_ui.rs keys/nudge/swap_orientation (ahead of the selection nudge and tools.swapColors in shortcuts.rs; X also swaps the options-bar ratio) and sizing (canvas.rs draws it with the marquee readout); turned frames included |diff --git a/scorecard/tools.toml b/scorecard/tools.tomlindex b258e6ce6..e3e093cb3 100644--- a/scorecard/tools.toml+++ b/scorecard/tools.toml@@ -243,6 +243,13 @@ status = "done"issue = 1649note = "document.sampleColor (sample_cmds.rs): average of the square clipped to the canvas, in the document's model and depth; eyedropper_ui.rs options bar; shared with Alt-click, dialog eyedroppers and the Info panel; ui.set eyedropperSampleSize/eyedropperSample/eyedropperRing. Color Sampler tool still missing"+[[item]]+id = "TOOL-214-20"+target = "Crop overlay options: Rule of Thirds, Grid, Diagonal, Triangle, Golden Ratio, Golden Spiral; Auto / Always / Never Show Overlay; O cycles the overlay, Shift+O its orientation"+status = "done"+issue = 1919+note = "crop_overlay.rs: unit-square guides shared by upright and turned frames (canvas.rs), options-bar menu, O / Shift+O ahead of the tool keys in shortcuts.rs; ToolOptions crop_overlay / crop_overlay_show / crop_overlay_orientation, ui.set cropOverlay / cropOverlayShow / cropOverlayOrientation"+[[item]]id = "TOOL-214-18"target = "Crop: drag outside the frame to rotate it (Shift 15 deg steps, angle readout); Enter rotates and crops in one step"