Skip to content

PhotoCraft: An open-source, photo editor written by scratch in pure Rust

Crop tool: Straighten button and ⌘/Ctrl-drag level the frame (#1919) (#2127)

David Mann35010f5138fa
diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs
index 92288e24a..52d25d341 100644
--- a/crates/ui-egui/src/canvas.rs
+++ b/crates/ui-egui/src/canvas.rs
@@ -2456,6 +2456,8 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect:
// drawn; otherwise Space is the Hand and ⌘Space / ⌘⌥Space the Zoom tool while held.
let reposition = crate::hold_keys::reposition_held(app, &ctx);
crate::crop_ui::set_space(app, reposition);
+ // ⌘ (Ctrl) held: a temporary Straighten with the Crop tool.
+ crate::crop_straighten::set_held(app, !ctx.text_edit_focused() && ui.input(|i| i.modifiers.command));
// A tab switched this frame drops the other document's pending crop (#1918).
crate::crop_ui::cancel_stale(app);
crate::crop_ui::ensure_frame(app);
@@ -3289,6 +3291,7 @@ fn draw_tool_state(app: &PhotocraftApp, painter: &egui::Painter, xf: &ViewXform,
// Just the outline and its rubber band: the vertices aren't handles to grab.
crate::tool_feedback::draw_ants(painter, &pts, false);
}
+ crate::crop_straighten::draw(app, painter, |p| xf.to_screen(p[0] as f32, p[1] as f32), hover);
if let Some(c) = app.ui.crop_rect {
let deg = crate::crop_ui::angle(app);
if deg == 0.0 && xf.rotation == 0.0 {
diff --git a/crates/ui-egui/src/crop_straighten.rs b/crates/ui-egui/src/crop_straighten.rs
new file mode 100644
index 000000000..286f04253
--- /dev/null
+++ b/crates/ui-egui/src/crop_straighten.rs
@@ -0,0 +1,349 @@
+//! The Crop tool's Straighten (Photoshop's options-bar level button, #1919): draw a line along
+//! something that should be level (a horizon) or plumb (a wall), and the crop frame turns so that
+//! line ends up horizontal, or vertical when it is nearer vertical (the Ruler's Straighten
+//! convention, `analysis_cmds::straighten_angle`).
+//!
+//! - The options-bar button arms it for one line, then disarms (one-shot); clicking it again
+//! disarms it without a line.
+//! - Holding ⌘ (Ctrl off the Mac) with the Crop tool is a temporary Straighten: a ⌘-drag draws the
+//! line; releasing ⌘ gives the normal crop gestures back.
+//!
+//! While the line is drawn its angle shows beside the pointer. As the Crop tool works in
+//! Photoshop's Classic Mode (the frame turns over a fixed image, `crop_ui`), Straighten sets the
+//! frame's angle and fits the frame to the image ([`fitted`]). It is only a pending frame edit:
+//! ↵ commits it and Esc cancels it as any crop. A line shorter than [`MIN_LINE_PX`] screen points
+//! does nothing.
+
+use egui::{Modifiers, Pos2};
+
+use crate::PhotocraftApp;
+use crate::canvas::ToolEvent;
+use crate::state::Tool;
+
+/// The shortest line (screen points) that straightens.
+pub const MIN_LINE_PX: f64 = 3.0;
+
+/// Straighten state (not serialized: it only lasts for a line or while a key is held).
+#[derive(Clone, Copy, Debug, Default, PartialEq)]
+pub struct Straighten {
+ /// The options-bar button is on: the next drag draws a straighten line.
+ pub armed: bool,
+ /// ⌘ (Ctrl) is held: set by the canvas every frame.
+ pub held: bool,
+ /// The line being drawn: start and end in document px.
+ pub line: Option<[[f64; 2]; 2]>,
+}
+
+/// ⌘ (Ctrl) is held over the canvas.
+pub fn set_held(app: &mut PhotocraftApp, down: bool) {
+ app.crop.straighten.held = down;
+}
+
+/// A drag with the Crop tool now draws a straighten line (or one is being drawn): the canvas
+/// shows the straighten cursor instead of the frame's.
+pub fn mode(app: &PhotocraftApp) -> bool {
+ let s = &app.crop.straighten;
+ app.ui.tool == Tool::Crop && app.crop.drag.is_none() && (s.armed || s.held || s.line.is_some())
+}
+
+impl Straighten {
+ /// The options-bar button: arms (or disarms) Straighten for one line.
+ pub fn toggle(&mut self) {
+ self.armed = !self.armed;
+ self.line = None;
+ }
+}
+
+/// [`Straighten::toggle`] for the app's Crop tool.
+pub fn toggle(app: &mut PhotocraftApp) {
+ app.crop.straighten.toggle();
+}
+
+/// Drops the armed button and any line (Esc, another tool).
+pub fn reset(app: &mut PhotocraftApp) {
+ app.crop.straighten.armed = false;
+ app.crop.straighten.line = None;
+}
+
+/// Pointer input for Straighten, called by the Crop tool first (finite `p`, a document open).
+/// Returns true when the event drew a straighten line.
+pub fn pointer(app: &mut PhotocraftApp, ev: ToolEvent, mods: Modifiers) -> bool {
+ match ev {
+ ToolEvent::Down { x, y, .. } => {
+ let s = app.crop.straighten;
+ if app.crop.drag.is_some() || !(s.armed || mods.command) {
+ return false;
+ }
+ app.crop.straighten.line = Some([[x, y], [x, y]]);
+ app.crop.editing = app.ui.crop_rect.is_some();
+ true
+ }
+ ToolEvent::Move { x, y, .. } => {
+ let Some(l) = app.crop.straighten.line.as_mut() else { return false };
+ l[1] = [x, y];
+ true
+ }
+ ToolEvent::Up { x, y } => {
+ let Some([a, _]) = app.crop.straighten.line.take() else { return false };
+ // One line per click of the button.
+ app.crop.straighten.armed = false;
+ let zoom = f64::from(app.point_zoom());
+ apply(app, a, [x, y], zoom);
+ true
+ }
+ }
+}
+
+/// The frame's angle (degrees, clockwise on screen) that makes the line from `a` to `b` level, or
+/// plumb when it is nearer vertical; `None` for a line shorter than `min_len` or not finite.
+pub fn frame_angle(a: [f64; 2], b: [f64; 2], min_len: f64) -> Option<f64> {
+ let (dx, dy) = (b[0] - a[0], b[1] - a[1]);
+ let len = dx.hypot(dy);
+ if !len.is_finite() || len < min_len.max(f64::MIN_POSITIVE) {
+ return None;
+ }
+ let rot = photocraft_engine::analysis_cmds::straighten_angle(&photocraft_doc::Ruler { start: a, end: b, protractor: None });
+ // ↵ turns the document back by the frame's angle; turning it by `rot` levels the line.
+ rot.is_finite().then(|| crate::crop_ui::normalized_angle(-rot) + 0.0)
+}
+
+/// The largest frame with the proportions of `w`×`h`, turned `deg` degrees, that stays inside a
+/// `cw`×`ch` canvas, centred on the canvas. `None` when a size is not a positive finite number.
+///
+/// Kept apart on purpose: whether Photoshop's Classic Mode fits the frame exactly this way after
+/// Straighten (keeping the frame's proportions, centred on the image) is not verified.
+pub fn fitted(w: f64, h: f64, cw: f64, ch: f64, deg: f64) -> Option<[f64; 4]> {
+ if ![w, h, cw, ch, deg].iter().all(|v| v.is_finite()) || w <= 0.0 || h <= 0.0 || cw <= 0.0 || ch <= 0.0 {
+ return None;
+ }
+ let (s, c) = deg.to_radians().sin_cos();
+ let (s, c) = (s.abs(), c.abs());
+ // The turned frame's bounds, scaled by `k`, must fit the canvas on both axes.
+ let k = (cw / (w * c + h * s)).min(ch / (w * s + h * c));
+ if !k.is_finite() || k <= 0.0 {
+ return None;
+ }
+ let (hw, hh, cx, cy) = (w * k / 2.0, h * k / 2.0, cw / 2.0, ch / 2.0);
+ Some([cx - hw, cy - hh, cx + hw, cy + hh])
+}
+
+/// The line from `a` to `b` (document px, at `zoom` screen points per px) straightens the frame.
+fn apply(app: &mut PhotocraftApp, a: [f64; 2], b: [f64; 2], zoom: f64) {
+ let min_len = if zoom.is_finite() && zoom > 0.0 { MIN_LINE_PX / zoom } else { MIN_LINE_PX };
+ let Some(deg) = frame_angle(a, b, min_len) else { return };
+ let Some(size) = app.session.active().map(|st| (f64::from(st.doc.size.width), f64::from(st.doc.size.height))) else { return };
+ // The frame keeps its proportions (an options-bar ratio is already the frame's); no frame
+ // takes the canvas's.
+ let (w, h) = app.ui.crop_rect.filter(|r| r.iter().all(|v| v.is_finite())).map_or(size, |r| (r[2] - r[0], r[3] - r[1]));
+ let Some(r) = fitted(w, h, size.0, size.1, deg) else { return };
+ if app.ui.crop_rect == Some(r) && crate::crop_ui::angle(app) == deg {
+ return;
+ }
+ app.ui.crop_rect = Some(r);
+ app.ui.crop_angle = deg;
+ app.crop.default_frame = false;
+ app.crop.editing = true;
+}
+
+/// The line being drawn and its angle beside the pointer. `to_screen` maps document px to the
+/// screen.
+pub fn draw(app: &PhotocraftApp, painter: &egui::Painter, to_screen: impl Fn([f64; 2]) -> Pos2, hover: Option<Pos2>) {
+ let Some([a, b]) = app.crop.straighten.line.filter(|_| app.ui.tool == Tool::Crop) else { return };
+ let t = crate::theme::Tokens::get(painter.ctx());
+ let seg = [to_screen(a), to_screen(b)];
+ painter.line_segment(seg, egui::Stroke::new(3.0, t.shadow));
+ painter.line_segment(seg, egui::Stroke::new(1.0, t.accent_text));
+ let (dx, dy) = (b[0] - a[0], b[1] - a[1]);
+ let deg = (-dy).atan2(dx).to_degrees();
+ if let Some(h) = hover.filter(|_| deg.is_finite() && (dx != 0.0 || dy != 0.0)) {
+ crate::canvas::draw_readout(painter.ctx(), "crop-straighten-readout", h, ["Angle:"], [format!("{deg:.1}°")]);
+ }
+}
+
+/// The options-bar Straighten button (Photoshop's level icon), lit while armed.
+pub fn options_button(s: &mut Straighten, ui: &mut egui::Ui) {
+ if crate::icons::button(ui, "ruler", 24.0, s.armed, tl!("Straighten the image by drawing a line on it")).clicked() {
+ s.toggle();
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::canvas::tool_event;
+ use crate::crop_ui::{CropDrag, ensure_frame};
+ use photocraft_doc::{Color, ColorMode, Document, SampleType, Size};
+
+ const NONE: Modifiers = Modifiers::NONE;
+ const CMD: Modifiers = Modifiers::COMMAND;
+
+ fn app(depth: SampleType) -> PhotocraftApp {
+ let doc = Document::with_background("straighten", Size::new(200, 100), ColorMode::Rgb, depth, Color::WHITE);
+ let mut s = photocraft_engine::Session::new();
+ s.add_document(doc, None);
+ let mut app = PhotocraftApp::new(s, crate::Services::default());
+ app.ui.tool = Tool::Crop;
+ app.ui.extras.snap = false;
+ app.ui.view.show.smart_guides = false;
+ ensure_frame(&mut app);
+ app
+ }
+
+ fn drag(app: &mut PhotocraftApp, pts: &[[f64; 2]], mods: Modifiers) {
+ let (first, last) = (pts[0], pts[pts.len() - 1]);
+ tool_event(app, ToolEvent::Down { x: first[0], y: first[1], pressure: 1.0 }, mods);
+ for p in &pts[1..] {
+ tool_event(app, ToolEvent::Move { x: p[0], y: p[1], pressure: 1.0 }, mods);
+ }
+ tool_event(app, ToolEvent::Up { x: last[0], y: last[1] }, mods);
+ }
+
+ fn near(a: f64, b: f64) -> bool {
+ (a - b).abs() < 1e-6
+ }
+
+ /// Every corner of frame `r` turned `deg` lies inside the `w`×`h` canvas.
+ fn inside(r: [f64; 4], deg: f64, w: f64, h: f64) -> bool {
+ crate::crop_ui::corners(r, deg).iter().all(|p| p[0] >= -1e-6 && p[1] >= -1e-6 && p[0] <= w + 1e-6 && p[1] <= h + 1e-6)
+ }
+
+ #[test]
+ fn the_frame_turns_with_a_horizon_and_nearly_vertical_lines_turn_it_plumb() {
+ // A horizon falling 10° to the right: the frame turns 10° clockwise, so ↵ levels it.
+ let d = 10.0f64.to_radians();
+ assert!(near(frame_angle([0.0, 0.0], [100.0 * d.cos(), 100.0 * d.sin()], 1.0).unwrap(), 10.0));
+ // Rising to the right: counter-clockwise. Drawn right to left: the same line.
+ assert!(near(frame_angle([0.0, 50.0], [100.0, 40.0], 1.0).unwrap(), -(10.0f64 / 100.0).atan().to_degrees()));
+ assert!(near(frame_angle([100.0, 40.0], [0.0, 50.0], 1.0).unwrap(), -(10.0f64 / 100.0).atan().to_degrees()));
+ // A wall leaning 5° (nearer vertical) is made plumb, not level.
+ let a = frame_angle([50.0, 0.0], [50.0 + 100.0 * 5.0f64.to_radians().tan(), 100.0], 1.0).unwrap();
+ assert!(near(a, -5.0), "{a}");
+ // Level and plumb lines need no turn.
+ assert_eq!(frame_angle([0.0, 0.0], [40.0, 0.0], 1.0), Some(0.0));
+ assert_eq!(frame_angle([0.0, 0.0], [0.0, 40.0], 1.0), Some(0.0));
+ // Too short, zero-length or not finite: nothing.
+ assert_eq!(frame_angle([5.0, 5.0], [5.0, 5.0], 0.0), None);
+ assert_eq!(frame_angle([5.0, 5.0], [6.0, 6.0], 3.0), None);
+ assert_eq!(frame_angle([f64::NAN, 0.0], [10.0, 0.0], 1.0), None);
+ assert_eq!(frame_angle([0.0, 0.0], [f64::INFINITY, 1.0], 1.0), None);
+ }
+
+ #[test]
+ fn the_fitted_frame_is_the_largest_of_its_proportions_inside_the_canvas() {
+ // Upright, the canvas's own proportions fill it.
+ assert_eq!(fitted(200.0, 100.0, 200.0, 100.0, 0.0), Some([0.0, 0.0, 200.0, 100.0]));
+ for deg in [-45.0, -10.0, 3.0, 10.0, 30.0, 45.0, 90.0] {
+ let r = fitted(200.0, 100.0, 200.0, 100.0, deg).unwrap();
+ assert!(inside(r, deg, 200.0, 100.0), "{deg}: {r:?}");
+ assert!(near((r[2] - r[0]) / (r[3] - r[1]), 2.0), "keeps 2:1 at {deg}");
+ assert!(near((r[0] + r[2]) / 2.0, 100.0) && near((r[1] + r[3]) / 2.0, 50.0), "centred at {deg}");
+ // As large as possible: 1% larger would leave the canvas.
+ let c = crate::crop_ui::center(r);
+ let g = [c[0] - (c[0] - r[0]) * 1.01, c[1] - (c[1] - r[1]) * 1.01, c[0] + (r[2] - c[0]) * 1.01, c[1] + (r[3] - c[1]) * 1.01];
+ assert!(!inside(g, deg, 200.0, 100.0), "{deg}: not the largest");
+ }
+ for bad in [
+ [0.0, 1.0, 1.0, 1.0, 0.0],
+ [1.0, -1.0, 1.0, 1.0, 0.0],
+ [1.0, 1.0, 0.0, 1.0, 0.0],
+ [1.0, 1.0, 1.0, 1.0, f64::NAN],
+ [f64::INFINITY, 1.0, 1.0, 1.0, 0.0],
+ ] {
+ assert_eq!(fitted(bad[0], bad[1], bad[2], bad[3], bad[4]), None, "{bad:?}");
+ }
+ }
+
+ #[test]
+ fn the_button_straightens_one_line_then_disarms() {
+ for depth in [SampleType::U8, SampleType::U16] {
+ let mut app = app(depth);
+ assert!(app.crop.default_frame && !mode(&app));
+ toggle(&mut app);
+ assert!(mode(&app), "armed");
+ // A line inside the frame straightens instead of drawing a new frame.
+ drag(&mut app, &[[20.0, 40.0], [100.0, 50.0], [180.0, 60.0]], NONE);
+ let want = (20.0f64 / 160.0).atan().to_degrees();
+ assert!(near(app.ui.crop_angle, want), "{depth:?}: {}", app.ui.crop_angle);
+ let r = app.ui.crop_rect.unwrap();
+ assert!(inside(r, want, 200.0, 100.0) && near((r[2] - r[0]) / (r[3] - r[1]), 2.0), "{r:?}");
+ assert!(!app.crop.default_frame && app.crop.editing && crate::crop_ui::pending(&app));
+ assert!(!app.crop.straighten.armed && app.crop.straighten.line.is_none(), "one-shot");
+ // The next drag is a normal crop gesture again: inside the frame it moves it.
+ let before = app.ui.crop_rect.unwrap();
+ drag(&mut app, &[[100.0, 50.0], [105.0, 50.0]], NONE);
+ let after = app.ui.crop_rect.unwrap();
+ assert!(near(after[0] - before[0], 5.0) && near(app.ui.crop_angle, want), "{depth:?}");
+ // ↵ commits the turn and the crop in one step.
+ let steps = app.session.active().unwrap().history.past_len();
+ crate::canvas::commit_crop(&mut app);
+ let st = app.session.active().unwrap();
+ assert_eq!(st.history.past_len(), steps + 1);
+ assert_eq!((st.doc.depth, app.ui.crop_angle), (depth, 0.0));
+ }
+ }
+
+ #[test]
+ fn clicking_the_button_again_disarms_it_and_esc_drops_it() {
+ let mut app = app(SampleType::U8);
+ toggle(&mut app);
+ toggle(&mut app);
+ assert!(!app.crop.straighten.armed);
+ toggle(&mut app);
+ crate::crop_ui::cancel(&mut app);
+ assert!(!app.crop.straighten.armed && !mode(&app));
+ // Leaving the tool drops it too.
+ toggle(&mut app);
+ app.ui.tool = Tool::Brush;
+ ensure_frame(&mut app);
+ assert!(!app.crop.straighten.armed);
+ }
+
+ #[test]
+ fn a_tiny_or_level_line_changes_nothing() {
+ let mut app = app(SampleType::U8);
+ toggle(&mut app);
+ // A click (zero length), then a line under 3 screen points.
+ drag(&mut app, &[[50.0, 50.0]], NONE);
+ assert_eq!((app.ui.crop_rect, app.ui.crop_angle), (Some([0.0, 0.0, 200.0, 100.0]), 0.0));
+ assert!(app.crop.default_frame, "the untouched frame stays the default");
+ assert!(!app.crop.straighten.armed, "the click used the button");
+ let zoom = f64::from(app.point_zoom());
+ toggle(&mut app);
+ drag(&mut app, &[[50.0, 50.0], [50.0 + 2.0 / zoom, 50.0 + 1.0 / zoom]], NONE);
+ assert_eq!(app.ui.crop_angle, 0.0);
+ assert!(app.ui.crop_rect.unwrap().iter().all(|v| v.is_finite()));
+ // An already level line on the default frame leaves it as it is.
+ toggle(&mut app);
+ drag(&mut app, &[[10.0, 50.0], [190.0, 50.0]], NONE);
+ assert_eq!((app.ui.crop_rect, app.ui.crop_angle), (Some([0.0, 0.0, 200.0, 100.0]), 0.0));
+ // Non-finite pointer positions never reach it.
+ toggle(&mut app);
+ drag(&mut app, &[[f64::NAN, 50.0], [190.0, f64::INFINITY]], NONE);
+ assert!(app.ui.crop_angle.is_finite() && app.ui.crop_rect.unwrap().iter().all(|v| v.is_finite()));
+ }
+
+ #[test]
+ fn holding_command_is_a_temporary_straighten() {
+ let mut app = app(SampleType::U8);
+ set_held(&mut app, true);
+ assert!(mode(&app));
+ assert_eq!(crate::crop_ui::cursor(&app, [100.0, 50.0]), Some(egui::CursorIcon::Crosshair));
+ assert_eq!(crate::crop_ui::turn_cursor_dir(&app, [300.0, 50.0]), None, "no turn cursor while straightening");
+ // A ⌘-drag outside the frame draws the line instead of turning the frame about the pointer.
+ tool_event(&mut app, ToolEvent::Down { x: 250.0, y: 60.0, pressure: 1.0 }, CMD);
+ tool_event(&mut app, ToolEvent::Move { x: 150.0, y: 0.0, pressure: 1.0 }, CMD);
+ assert!(app.crop.straighten.line.is_some() && app.crop.drag.is_none());
+ tool_event(&mut app, ToolEvent::Up { x: 0.0, y: 0.0 }, CMD);
+ // From (250, 60) to (0, 0): nearer horizontal, rising to the left.
+ let want = (60.0f64 / 250.0).atan().to_degrees();
+ assert!(near(app.ui.crop_angle, want), "{}", app.ui.crop_angle);
+ // Released: the same drag outside turns the frame again.
+ set_held(&mut app, false);
+ assert!(!mode(&app));
+ drag(&mut app, &[[300.0, 50.0], [300.0, 90.0]], NONE);
+ assert!(app.crop.drag.is_none() && app.ui.crop_angle > want, "{}", app.ui.crop_angle);
+ // And a ⌘-drag in the middle of a crop gesture doesn't hijack it.
+ app.crop.drag = Some(CropDrag::Move { start: [100.0, 50.0], rect: app.ui.crop_rect.unwrap() });
+ assert!(!pointer(&mut app, ToolEvent::Down { x: 100.0, y: 50.0, pressure: 1.0 }, CMD));
+ }
+}
diff --git a/crates/ui-egui/src/crop_ui.rs b/crates/ui-egui/src/crop_ui.rs
index 519e11bf5..38b144145 100644
--- a/crates/ui-egui/src/crop_ui.rs
+++ b/crates/ui-egui/src/crop_ui.rs
@@ -56,6 +56,8 @@ pub struct CropState {
pub editing: bool,
/// The document the pending frame (or gesture) belongs to ([`cancel_stale`], #1918).
doc: Option<photocraft_doc::DocId>,
+ /// The options-bar Straighten button and ⌘-drag (`crop_straighten`).
+ pub straighten: crate::crop_straighten::Straighten,
}
/// A crop gesture in progress. Rects are `[x0, y0, x1, y1]` in document coordinates.
@@ -252,6 +254,7 @@ pub fn set_space(app: &mut PhotocraftApp, down: bool) {
pub fn ensure_frame(app: &mut PhotocraftApp) {
if app.ui.tool != Tool::Crop {
app.crop.editing = false;
+ crate::crop_straighten::reset(app);
// Leaving the tool drops an untouched default frame (a drawn one stays pending).
if app.crop.default_frame {
app.ui.crop_rect = None;
@@ -302,6 +305,7 @@ pub fn cancel(app: &mut PhotocraftApp) {
app.crop.default_frame = false;
app.crop.frame_for = None;
app.crop.editing = false;
+ crate::crop_straighten::reset(app);
}
/// The pending frame belongs to the active document.
@@ -515,6 +519,11 @@ pub fn pointer(app: &mut PhotocraftApp, ev: ToolEvent, mods: Modifiers) -> bool
if app.session.active().is_none() || !p[0].is_finite() || !p[1].is_finite() {
return true;
}
+ // The Straighten button, or ⌘ held: the drag draws a line to level the frame on.
+ if crate::crop_straighten::pointer(app, ev, mods) {
+ claim(app);
+ return true;
+ }
match ev {
ToolEvent::Down { .. } => {
claim(app);
@@ -603,6 +612,9 @@ pub fn cursor(app: &PhotocraftApp, p: [f64; 2]) -> Option<CursorIcon> {
if app.ui.tool != Tool::Crop {
return None;
}
+ if crate::crop_straighten::mode(app) {
+ return Some(CursorIcon::Crosshair);
+ }
let deg = angle(app);
let h = match app.crop.drag {
Some(CropDrag::Move { .. }) => Hit::Inside,
@@ -623,7 +635,7 @@ pub fn cursor(app: &PhotocraftApp, p: [f64; 2]) -> Option<CursorIcon> {
/// it): towards the frame corner of `p`'s quadrant, along the diagonal of the frame's own axes.
/// As in Photoshop that gives four cursors, one per corner; they turn with the frame.
pub fn turn_cursor_dir(app: &PhotocraftApp, p: [f64; 2]) -> Option<[f64; 2]> {
- if app.ui.tool != Tool::Crop {
+ if app.ui.tool != Tool::Crop || crate::crop_straighten::mode(app) {
return None;
}
let r = app.ui.crop_rect.filter(|r| r.iter().all(|v| v.is_finite()))?;
diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv
index d15b3c27a..85adb69f4 100644
--- a/crates/ui-egui/src/i18n/cs.tsv
+++ b/crates/ui-egui/src/i18n/cs.tsv
@@ -2293,3 +2293,4 @@ fontWeight Italic Kurzíva
Cycle Orientation Přepnout orientaci
Set the overlay options for the Crop tool Nastavit volby překryvu pro nástroj Oříznutí
Alt-click went to the desktop, which moves windows with Alt-drag. Set its window-move key to Super, or latch Alt in Window › Modifier Keys. Alt+klik převzalo pracovní prostředí, které pomocí Alt+tažení přesouvá okna. Nastavte jeho klávesu pro přesun oken na Super, nebo zamkněte Alt v nabídce Okno › Modifikační klávesy.
+ Straighten the image by drawing a line on it Narovnat obraz nakreslením čáry
diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv
index 6e05025b5..fd02bff73 100644
--- a/crates/ui-egui/src/i18n/de.tsv
+++ b/crates/ui-egui/src/i18n/de.tsv
@@ -2331,3 +2331,4 @@ fontWeight Italic Kursiv
Cycle Orientation Ausrichtung wechseln
Set the overlay options for the Crop tool Überlagerungsoptionen für das Freistellungswerkzeug festlegen
Alt-click went to the desktop, which moves windows with Alt-drag. Set its window-move key to Super, or latch Alt in Window › Modifier Keys. Der Alt-Klick ging an die Arbeitsumgebung, die Fenster mit Alt-Ziehen verschiebt. Stelle dort die Taste zum Verschieben von Fenstern auf Super oder raste Alt unter Fenster › Modifikatortasten ein.
+ Straighten the image by drawing a line on it Bild durch Ziehen einer Linie gerade ausrichten
diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv
index 2ba8fcf1e..56b2938e5 100644
--- a/crates/ui-egui/src/i18n/el.tsv
+++ b/crates/ui-egui/src/i18n/el.tsv
@@ -3402,3 +3402,4 @@ fontWeight Thin Πολύ λεπτά
Cycle Orientation Εναλλαγή προσανατολισμού
Set the overlay options for the Crop tool Ορισμός επιλογών επικάλυψης για το εργαλείο Περικοπή
Alt-click went to the desktop, which moves windows with Alt-drag. Set its window-move key to Super, or latch Alt in Window › Modifier Keys. Το Alt-κλικ πήγε στο περιβάλλον εργασίας, που μετακινεί παράθυρα με Alt-σύρσιμο. Ορίστε το πλήκτρο μετακίνησης παραθύρων του σε Super ή κλειδώστε το Alt στο Παράθυρο › Πλήκτρα τροποποίησης.
+ Straighten the image by drawing a line on it Ευθυγράμμιση της εικόνας σχεδιάζοντας μια γραμμή πάνω της
diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv
index 8d47e2c87..ef5fe91d5 100644
--- a/crates/ui-egui/src/i18n/es.tsv
+++ b/crates/ui-egui/src/i18n/es.tsv
@@ -2361,3 +2361,4 @@ fontWeight Italic Cursiva
Cycle Orientation Alternar orientación
Set the overlay options for the Crop tool Definir las opciones de superposición de la herramienta Recortar
Alt-click went to the desktop, which moves windows with Alt-drag. Set its window-move key to Super, or latch Alt in Window › Modifier Keys. El Alt+clic lo recibió el escritorio, que mueve ventanas con Alt+arrastrar. Cambia su tecla para mover ventanas a Super o bloquea Alt en Ventana › Teclas modificadoras.
+ Straighten the image by drawing a line on it Enderezar la imagen dibujando una línea en ella
diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv
index d726d11ed..28bf67888 100644
--- a/crates/ui-egui/src/i18n/fr.tsv
+++ b/crates/ui-egui/src/i18n/fr.tsv
@@ -2714,3 +2714,4 @@ fontWeight Italic Italique
Cycle Orientation Changer d’orientation
Set the overlay options for the Crop tool Définir les options de superposition de l’outil Recadrage
Alt-click went to the desktop, which moves windows with Alt-drag. Set its window-move key to Super, or latch Alt in Window › Modifier Keys. L’Alt-clic a été intercepté par le bureau, qui déplace les fenêtres avec Alt-glisser. Réglez sa touche de déplacement des fenêtres sur Super, ou verrouillez Alt dans Fenêtre › Touches de modification.
+ Straighten the image by drawing a line on it Redresser l’image en traçant une ligne dessus
diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv
index 6a710ec17..65847f646 100644
--- a/crates/ui-egui/src/i18n/id.tsv
+++ b/crates/ui-egui/src/i18n/id.tsv
@@ -2701,3 +2701,4 @@ fontWeight Italic Miring
Cycle Orientation Ganti Orientasi
Set the overlay options for the Crop tool Atur opsi overlay untuk alat Crop
Alt-click went to the desktop, which moves windows with Alt-drag. Set its window-move key to Super, or latch Alt in Window › Modifier Keys. Alt-klik diambil oleh desktop, yang memindahkan jendela dengan Alt-seret. Atur tombol pemindah jendelanya ke Super, atau kunci Alt di Jendela › Tombol Pengubah.
+ Straighten the image by drawing a line on it Luruskan gambar dengan menggambar garis di atasnya
diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv
index 001319973..a2e30cdb0 100644
--- a/crates/ui-egui/src/i18n/it.tsv
+++ b/crates/ui-egui/src/i18n/it.tsv
@@ -2362,3 +2362,4 @@ fontWeight Italic Corsivo
Cycle Orientation Cambia orientamento
Set the overlay options for the Crop tool Imposta le opzioni di sovrapposizione dello strumento Taglierina
Alt-click went to the desktop, which moves windows with Alt-drag. Set its window-move key to Super, or latch Alt in Window › Modifier Keys. L’Alt-click è andato al desktop, che sposta le finestre con Alt-trascina. Imposta il suo tasto per spostare le finestre su Super, oppure blocca Alt in Finestra › Tasti modificatori.
+ Straighten the image by drawing a line on it Raddrizza l’immagine tracciando una linea
diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv
index 75266fd88..05538638c 100644
--- a/crates/ui-egui/src/i18n/ja.tsv
+++ b/crates/ui-egui/src/i18n/ja.tsv
@@ -3317,3 +3317,4 @@ fontWeight Italic 斜体
Cycle Orientation 方向を切り替え
Set the overlay options for the Crop tool 切り抜きツールのオーバーレイオプションを設定
Alt-click went to the desktop, which moves windows with Alt-drag. Set its window-move key to Super, or latch Alt in Window › Modifier Keys. Alt+クリックはデスクトップに取られました(Alt+ドラッグでウィンドウを移動する設定です)。デスクトップのウィンドウ移動キーを Super に変更するか、ウィンドウ › 修飾キーで Alt を固定してください。
+ Straighten the image by drawing a line on it 画像上に線を描いて角度を補正
diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv
index 5bd32ca91..a6ab44da1 100644
--- a/crates/ui-egui/src/i18n/ko.tsv
+++ b/crates/ui-egui/src/i18n/ko.tsv
@@ -2871,3 +2871,4 @@ fontWeight Italic 기울임
Cycle Orientation 방향 순환
Set the overlay options for the Crop tool 자르기 도구의 오버레이 옵션 설정
Alt-click went to the desktop, which moves windows with Alt-drag. Set its window-move key to Super, or latch Alt in Window › Modifier Keys. Alt 클릭이 데스크톱으로 전달되었습니다. 데스크톱이 Alt 드래그로 창을 이동합니다. 창 이동 키를 Super로 바꾸거나 창 › 보조 키에서 Alt를 고정하세요.
+ Straighten the image by drawing a line on it 이미지에 선을 그려 수평 맞추기
diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv
index 120b8a599..833efb366 100644
--- a/crates/ui-egui/src/i18n/nl.tsv
+++ b/crates/ui-egui/src/i18n/nl.tsv
@@ -3477,3 +3477,4 @@ cameraRaw Whites Witten
Cycle Orientation Oriëntatie wisselen
Set the overlay options for the Crop tool Overlay-opties voor het gereedschap Uitsnijden instellen
Alt-click went to the desktop, which moves windows with Alt-drag. Set its window-move key to Super, or latch Alt in Window › Modifier Keys. De Alt-klik ging naar het bureaublad, dat vensters verplaatst met Alt-slepen. Stel daar de toets voor het verplaatsen van vensters in op Super, of vergrendel Alt via Venster › Wijzigingstoetsen.
+ Straighten the image by drawing a line on it Recht de afbeelding uit door er een lijn op te tekenen
diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv
index f480c9a60..215008d7c 100644
--- a/crates/ui-egui/src/i18n/pl.tsv
+++ b/crates/ui-egui/src/i18n/pl.tsv
@@ -3315,3 +3315,4 @@ cameraRaw Roughness Chropowatość
Cycle Orientation Przełącz orientację
Set the overlay options for the Crop tool Ustaw opcje nakładki narzędzia Kadrowanie
Alt-click went to the desktop, which moves windows with Alt-drag. Set its window-move key to Super, or latch Alt in Window › Modifier Keys. Alt+kliknięcie przejęło środowisko pulpitu, które przesuwa okna przez Alt+przeciąganie. Ustaw w nim klawisz przesuwania okien na Super lub zablokuj Alt w Okno › Klawisze modyfikujące.
+ Straighten the image by drawing a line on it Wyprostuj obraz, rysując na nim linię
diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv
index e6a6e27db..282d74d58 100644
--- a/crates/ui-egui/src/i18n/pt-br.tsv
+++ b/crates/ui-egui/src/i18n/pt-br.tsv
@@ -2721,3 +2721,4 @@ fontWeight Italic Itálico
Cycle Orientation Alternar orientação
Set the overlay options for the Crop tool Definir as opções de sobreposição da ferramenta Corte demarcado
Alt-click went to the desktop, which moves windows with Alt-drag. Set its window-move key to Super, or latch Alt in Window › Modifier Keys. O Alt-clique foi para o desktop, que move janelas com Alt-arrastar. Mude a tecla de mover janelas dele para Super ou trave o Alt em Janela › Teclas modificadoras.
+ Straighten the image by drawing a line on it Endireitar a imagem desenhando uma linha sobre ela
diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv
index 7f6baef25..7069ccfd4 100644
--- a/crates/ui-egui/src/i18n/ru.tsv
+++ b/crates/ui-egui/src/i18n/ru.tsv
@@ -2567,3 +2567,4 @@ fontWeight Italic Курсив
Cycle Orientation Сменить ориентацию
Set the overlay options for the Crop tool Задать параметры перекрытия для инструмента «Рамка»
Alt-click went to the desktop, which moves windows with Alt-drag. Set its window-move key to Super, or latch Alt in Window › Modifier Keys. Alt+щелчок перехватило окружение рабочего стола: оно перемещает окна через Alt+перетаскивание. Назначьте для перемещения окон клавишу Super или зафиксируйте Alt в меню Окно › Клавиши-модификаторы.
+ Straighten the image by drawing a line on it Выровнять изображение, нарисовав на нем линию
diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv
index 0e3ed88ef..48803b39a 100644
--- a/crates/ui-egui/src/i18n/uk.tsv
+++ b/crates/ui-egui/src/i18n/uk.tsv
@@ -3402,3 +3402,4 @@ cameraRaw Masking Маскування
Cycle Orientation Змінити орієнтацію
Set the overlay options for the Crop tool Задати параметри накладання для інструмента «Рамка»
Alt-click went to the desktop, which moves windows with Alt-drag. Set its window-move key to Super, or latch Alt in Window › Modifier Keys. Alt-клік перехопило робоче середовище, яке переміщує вікна через Alt-перетягування. Призначте для переміщення вікон клавішу Super або зафіксуйте Alt у меню Вікно › Клавіші-модифікатори.
+ Straighten the image by drawing a line on it Вирівняти зображення, намалювавши на ньому лінію
diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv
index 9c04f9fb9..51853f038 100644
--- a/crates/ui-egui/src/i18n/zh-hans.tsv
+++ b/crates/ui-egui/src/i18n/zh-hans.tsv
@@ -2301,3 +2301,4 @@ fontWeight Italic 斜体
Cycle Orientation 循环切换取向
Set the overlay options for the Crop tool 设置裁剪工具的叠加选项
Alt-click went to the desktop, which moves windows with Alt-drag. Set its window-move key to Super, or latch Alt in Window › Modifier Keys. Alt 单击被桌面环境截获了,它用 Alt 拖动来移动窗口。请把桌面的窗口移动键改为 Super,或在 窗口 › 修饰键 中锁定 Alt。
+ Straighten the image by drawing a line on it 通过在图像上画一条线来拉直图像
diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv
index 7c6e52bf5..2b2bdf4ea 100644
--- a/crates/ui-egui/src/i18n/zh-hant.tsv
+++ b/crates/ui-egui/src/i18n/zh-hant.tsv
@@ -2270,3 +2270,4 @@ fontWeight Italic 斜體
Cycle Orientation 循環切換方向
Set the overlay options for the Crop tool 設定裁切工具的覆蓋選項
Alt-click went to the desktop, which moves windows with Alt-drag. Set its window-move key to Super, or latch Alt in Window › Modifier Keys. Alt 按一下被桌面環境攔截了,它用 Alt 拖曳來移動視窗。請把桌面的視窗移動鍵改為 Super,或在 視窗 › 輔助鍵 中鎖定 Alt。
+ Straighten the image by drawing a line on it 在影像上繪製一條線以拉直影像
diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs
index 1e37b7a52..aaf809fab 100644
--- a/crates/ui-egui/src/lib.rs
+++ b/crates/ui-egui/src/lib.rs
@@ -47,6 +47,7 @@ pub mod comps_ui;
pub mod control;
pub mod credits;
pub mod crop_overlay;
+pub mod crop_straighten;
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.rs
index 7355c9669..609ddacf8 100644
--- a/crates/ui-egui/src/panels.rs
+++ b/crates/ui-egui/src/panels.rs
@@ -990,6 +990,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();
}
+ crate::crop_straighten::options_button(&mut app.crop.straighten, ui);
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| {
diff --git a/docs/scorecard.md b/docs/scorecard.md
index 334a3b19c..5c021e556 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) | 15 | 14 | 8 | |
+| [Tools](#tools) | 16 | 14 | 8 | |
| [Workspace and UI](#workspace-and-ui) | 5 | 7 | 11 | 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%) |
@@ -145,7 +145,7 @@ Corpus floors (`crates/io/tests/corpus.rs`): the enforced minimums; the corpus t
| TOOL-214-6 | Puppet Warp mesh follows the object outline (constrained triangulation) | missing | [#214](https://github.com/storytold/photocraft/issues/214) | algo/puppet.rs:136 builds a block-grid mesh |
| TOOL-214-7 | Content-Aware Scale through the Free Transform box with a live proxy preview | partial | [#214](https://github.com/storytold/photocraft/issues/214) | edit.contentAwareScale (edit_menu_cmds.rs:899) behind a parameter dialog |
| TOOL-214-8 | A measured ruler angle prefills Image Rotation > Arbitrary (0.01 deg) | missing | [#214](https://github.com/storytold/photocraft/issues/214) | Arbitrary rotation is a generic dialog; ruler only feeds straighten |
-| TOOL-214-9 | Crop: W x H x Resolution with units, saved crop presets, Straighten in the options bar | partial | [#214](https://github.com/storytold/photocraft/issues/214) | Ratio dropdown and fields only (panels.rs:551-579) |
+| TOOL-214-9 | Crop: W x H x Resolution with units, saved crop presets, Straighten in the options bar | partial | [#214](https://github.com/storytold/photocraft/issues/214) | Ratio dropdown and fields, Straighten (TOOL-214-21); no W x H x Resolution with units or saved presets |
| TOOL-214-10 | Pen: Alt breaks a handle, Shift 45 deg, Ctrl direct-selects, Backspace, close-drag handle | partial | [#214](https://github.com/storytold/photocraft/issues/214) | Ctrl/Cmd = Direct Selection and Alt = Convert Point on existing paths (direct_select.rs, #790); no Shift 45 deg, Backspace or Alt while drawing |
| TOOL-214-11 | Stroke Path dialog: pick any brush-based tool, Simulate Pressure | partial | [#214](https://github.com/storytold/photocraft/issues/214) | path.stroke brush, pencil, eraser (vector_cmds.rs:1170); brush-only button, no dialog |
| TOOL-214-12 | Shapes: on-canvas corner radius handles, shape feather, selection to shape with tolerance | partial | [#214](https://github.com/storytold/photocraft/issues/214) | select.convertToShape with tolerance (vector_cmds.rs:1256); radius as a field only |
@@ -159,6 +159,7 @@ Corpus floors (`crates/io/tests/corpus.rs`): the enforced minimums; the corpus t
| 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 |
+| TOOL-214-21 | Crop: Straighten button in the options bar and Cmd/Ctrl-drag draw a line; the frame turns so the line ends up level (or plumb when nearer vertical), with an angle readout | done | [#1919](https://github.com/storytold/photocraft/issues/1919) | crop_straighten.rs: one-shot options-bar button, Cmd/Ctrl held is a temporary Straighten (ui.pointer command flag); the Ruler's straighten_angle convention; the frame is fitted to the largest of its proportions inside the image (Classic Mode); a pending edit committed by Enter |
## Workspace and UI
diff --git a/scorecard/tools.toml b/scorecard/tools.toml
index e3e093cb3..80b6ee1c8 100644
--- a/scorecard/tools.toml
+++ b/scorecard/tools.toml
@@ -171,7 +171,7 @@ id = "TOOL-214-9"
target = "Crop: W x H x Resolution with units, saved crop presets, Straighten in the options bar"
status = "partial"
issue = 214
-note = "Ratio dropdown and fields only (panels.rs:551-579)"
+note = "Ratio dropdown and fields, Straighten (TOOL-214-21); no W x H x Resolution with units or saved presets"
[[item]]
id = "TOOL-214-10"
@@ -263,3 +263,10 @@ target = "Crop: arrow keys nudge the crop box (Shift 10 px), X swaps portrait/la
status = "done"
issue = 1919
note = "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"
+
+[[item]]
+id = "TOOL-214-21"
+target = "Crop: Straighten button in the options bar and Cmd/Ctrl-drag draw a line; the frame turns so the line ends up level (or plumb when nearer vertical), with an angle readout"
+status = "done"
+issue = 1919
+note = "crop_straighten.rs: one-shot options-bar button, Cmd/Ctrl held is a temporary Straighten (ui.pointer command flag); the Ruler's straighten_angle convention; the frame is fitted to the largest of its proportions inside the image (Classic Mode); a pending edit committed by Enter"