PhotoCraft: An open-source, photo editor written by scratch in pure Rust
Crop tool: rotate the crop frame by dragging outside it (#1879)
David Mann147ee7efa05a
diff --git a/crates/engine/src/analysis_cmds.rs b/crates/engine/src/analysis_cmds.rsindex 21b527798..3855290ff 100644--- a/crates/engine/src/analysis_cmds.rs+++ b/crates/engine/src/analysis_cmds.rs@@ -172,7 +172,7 @@ fn set_quiet(s: &mut Session, f: impl FnOnce(&mut Document)) -> Result<()> {}/// Run several commands as one history step labelled `label`.-fn compound<R>(s: &mut Session, label: &str, f: impl FnOnce(&mut Session) -> Result<R>) -> Result<R> {+pub(crate) fn compound<R>(s: &mut Session, label: &str, f: impl FnOnce(&mut Session) -> Result<R>) -> Result<R> {let st = s.active().ok_or(EngineError::NoDocument)?;let (before, history, prior) = (st.doc.clone(), st.history.clone(), st.layer_target());let r = f(s);diff --git a/crates/engine/src/image_cmds.rs b/crates/engine/src/image_cmds.rsindex bf0c9d7de..077512047 100644--- a/crates/engine/src/image_cmds.rs+++ b/crates/engine/src/image_cmds.rs@@ -329,6 +329,10 @@ fn crop(s: &mut Session, p: &Value) -> Result<Value> {}_ => None,};+ if let Some(a) = crop_angle(p)? {+ let rect = explicit.ok_or_else(|| bad("image.crop", "an `angle` needs an explicit `x`, `y`, `width` and `height`"))?;+ return rotated_crop(s, rect, a, delete);+ }// An explicit rectangle (the Crop tool) may extend past the canvas; a selection crop is clamped.let r = explicit.or_else(|| s.active().and_then(|d| d.doc.selection.as_ref().map(|sel| sel.content_bounds().intersect(&d.doc.bounds()))))@@ -344,6 +348,62 @@ fn crop(s: &mut Session, p: &Value) -> Result<Value> {Ok(json!({ "x": r.x0, "y": r.y0, "width": r.width(), "height": r.height() }))}+/// The largest crop angle accepted (degrees), as for Image Rotation › Arbitrary.+const MAX_CROP_ANGLE: f64 = 3600.0;++/// `image.crop`'s optional `angle` in degrees, normalised to (-180, 180]; `None` when it is absent,+/// null or (after normalising) zero, so an unrotated crop takes the plain, resampling-free path.+fn crop_angle(p: &Value) -> Result<Option<f64>> {+ let a = match p.get("angle") {+ None | Some(Value::Null) => return Ok(None),+ Some(v) => v.as_f64().ok_or_else(|| bad("image.crop", "`angle` must be a number of degrees"))?,+ };+ if !a.is_finite() || a.abs() > MAX_CROP_ANGLE {+ return Err(bad("image.crop", format!("`angle` must be a finite number of degrees within ±{MAX_CROP_ANGLE}")));+ }+ let a = a.rem_euclid(360.0);+ let a = if a > 180.0 { a - 360.0 } else { a };+ Ok((a.abs() >= 1e-9).then_some(a))+}++/// The Crop tool's rotated frame: `r` (document px) turned clockwise on screen by `angle` degrees+/// about its centre. The document is rotated counter-clockwise by `angle` (Image Rotation ›+/// Arbitrary: the canvas grows to fit, the Background fills what the rotation uncovers with the+/// background colour, other layers keep transparency there and every pixel of theirs), which makes+/// the frame upright, then cropped to it (`deleteCroppedPixels` as for an unrotated crop), all in+/// one undo step.+fn rotated_crop(s: &mut Session, r: Rect, angle: f64, delete: bool) -> Result<Value> {+ const CMD: &str = "image.crop";+ let size = s.active().ok_or(EngineError::NoDocument)?.doc.size;+ let (w, h) = (f64::from(r.width()), f64::from(r.height()));+ let (cx, cy) = (f64::from(r.x0) + w / 2.0, f64::from(r.y0) + h / 2.0);+ // Where the frame's centre lands: the rotation `image.rotation.arbitrary` applies, clockwise+ // by `-angle` (x' = c·x − s·y, y' = s·x + c·y) about the old and new canvas centres.+ let new = crate::mode_cmds::rotated_size(size, -angle);+ let (sn, cs) = (-angle).to_radians().sin_cos();+ let (dx, dy) = (cx - f64::from(size.width) / 2.0, cy - f64::from(size.height) / 2.0);+ let (ncx, ncy) = (f64::from(new.width) / 2.0 + cs * dx - sn * dy, f64::from(new.height) / 2.0 + sn * dx + cs * dy);+ let (x, y) = ((ncx - w / 2.0).round(), (ncy - h / 2.0).round());+ let far = || bad(CMD, "the rotated frame is outside the 32-bit coordinate range");+ let limit = f64::from(i32::MAX / 2);+ if !(x.is_finite() && y.is_finite()) || x.abs() > limit || y.abs() > limit {+ return Err(far());+ }+ let (x, y) = (x as i32, y as i32);+ let end = |o: i32, len: u32| i32::try_from(len).ok().and_then(|l| o.checked_add(l));+ let (Some(x1), Some(y1)) = (end(x, r.width()), end(y, r.height())) else { return Err(far()) };+ let target = Rect::new(x, y, x1, y1);+ crate::analysis_cmds::compound(s, "Crop", |s| {+ crate::mode_cmds::rotate_arbitrary(s, &json!({"angle": angle, "direction": "ccw"}))?;+ s.edit("Crop", |doc, _| {+ crop_doc(doc, CMD, target, delete)?;+ doc.selection = None;+ Ok(())+ })+ })?;+ Ok(json!({ "x": r.x0, "y": r.y0, "width": r.width(), "height": r.height(), "angle": angle }))+}+/// Image → Trim.fn trim(s: &mut Session, p: &Value) -> Result<Value> {let d = s.active().ok_or(EngineError::NoDocument)?;@@ -451,7 +511,14 @@ pub fn specs() -> Vec<CommandSpec> {has_doc,canvas_size),- spec!("image.crop", "Crop", ["Image"], r##"{"x":px,"y":px,"width":px,"height":px,"deleteCroppedPixels":bool=true}"##, has_doc, crop),+ spec!(+ "image.crop",+ "Crop",+ ["Image"],+ r##"{"x":px,"y":px,"width":px,"height":px,"angle":-3600..3600=0,"deleteCroppedPixels":bool=true}"##,+ has_doc,+ crop+ ),spec!("image.trim","Trim…",@@ -740,6 +807,143 @@ mod tests {assert_eq!(doc(&s).layers[1].surface().unwrap().pixel(20, 5), vec![1.0, 0.0, 0.0, 1.0]);}+ /// A document (`mode`, `depth`) with a white Background and a layer holding a red pixel at+ /// (12, 8) and a blue one at (30, 3).+ fn marked(mode: &str, depth: u32) -> Session {+ let mut s = Session::new();+ s.execute("file.new", json!({"width": 40, "height": 20, "mode": mode, "depth": depth, "background": "white"})).unwrap();+ s.execute("layer.new.layer", json!({})).unwrap();+ for (x, y, c) in [(12, 8, "#ff0000"), (30, 3, "#0000ff")] {+ s.execute("select.rect", json!({"x": x, "y": y, "width": 1, "height": 1})).unwrap();+ s.execute("edit.fill", json!({"color": c})).unwrap();+ }+ s.execute("select.deselect", json!({})).unwrap();+ s+ }++ fn layer_rgba(s: &Session, layer: usize, x: i32, y: i32) -> [f32; 4] {+ doc(s).layers[layer].surface().unwrap().rgba(x, y)+ }++ /// #1792: a frame turned 90° clockwise crops what Image Rotation › Arbitrary 90° CCW and a+ /// plain crop give, in one undo step that restores the document, at 8, 16 and 32 bits.+ #[test]+ fn crop_at_90_degrees_is_rotate_then_crop_in_one_step() {+ for depth in [8, 16, 32] {+ let mut s = marked("rgb", depth);+ let before = doc(&s).clone();+ let past = s.active().unwrap().history.past_len();+ // The 10 × 20 frame at (10, 0), turned 90° about (15, 10), covers x 5..25, y 5..15.+ let r = s.execute("image.crop", json!({"x": 10, "y": 0, "width": 10, "height": 20, "angle": 90})).unwrap();+ assert_eq!(r["angle"], json!(90.0), "{depth}");+ assert_eq!(doc(&s).size, Size::new(10, 20), "{depth}");+ assert_eq!(s.active().unwrap().history.past_len(), past + 1, "{depth}: one undo step");+ // (12, 8) is 2.5 left of and 1.5 above the centre: in the upright frame, 1.5 left of+ // and 2.5 below its centre (5, 10).+ let red = layer_rgba(&s, 1, 3, 12);+ assert!(red[0] > 0.9 && red[1] < 0.1 && red[3] > 0.9, "{depth}: {red:?}");+ let mut reference = marked("rgb", depth);+ reference.execute("image.rotation.arbitrary", json!({"angle": 90, "direction": "ccw"})).unwrap();+ reference.execute("image.crop", json!({"x": 5, "y": 15, "width": 10, "height": 20})).unwrap();+ for l in 0..2 {+ for y in 0..20 {+ for x in 0..10 {+ let (a, b) = (layer_rgba(&s, l, x, y), layer_rgba(&reference, l, x, y));+ assert!(a.iter().zip(b).all(|(p, q)| (p - q).abs() < 1e-3), "{depth} layer {l} ({x}, {y}): {a:?} vs {b:?}");+ }+ }+ }+ s.execute("edit.undo", json!({})).unwrap();+ let d = doc(&s);+ assert_eq!(d.size, before.size, "{depth}");+ assert_eq!(d.depth, before.depth);+ for y in 0..20 {+ for x in 0..40 {+ assert_eq!(layer_rgba(&s, 1, x, y), before.layers[1].surface().unwrap().rgba(x, y), "{depth} undo at ({x}, {y})");+ }+ }+ }+ }++ /// A slightly turned frame keeps its own size, the pixel under its centre and the Background's+ /// colour; the turn's sign matters (a counter-clockwise frame is a negative angle).+ #[test]+ fn crop_at_a_small_angle_keeps_the_frame_size_in_every_mode() {+ for (mode, depth) in [("rgb", 8), ("rgb", 16), ("rgb", 32), ("grayscale", 16), ("cmyk", 8), ("lab", 16)] {+ for angle in [5.0, -7.5, 365.0] {+ let mut s = marked(mode, depth);+ s.execute("image.crop", json!({"x": 2, "y": 1, "width": 21, "height": 15, "angle": angle})).unwrap();+ let d = doc(&s);+ assert_eq!(d.size, Size::new(21, 15), "{mode} {depth} {angle}");+ assert_eq!(d.depth.bytes() * 8, depth as usize, "{mode} {depth}");+ assert_eq!(format!("{:?}", d.mode).to_lowercase(), mode, "{mode} {depth}");+ assert_eq!(d.layers.len(), 2);+ // The frame's centre (12.5, 8.5) is the red pixel (the layer's only paint nearby);+ // it stays at the centre, its colour kept.+ let want = layer_rgba(&marked(mode, depth), 1, 12, 8);+ let red = layer_rgba(&s, 1, 10, 7);+ assert!(red[3] > 0.5 && (0..3).all(|c| (red[c] - want[c]).abs() < 0.2), "{mode} {depth} {angle}: {red:?} vs {want:?}");+ // The Background stays opaque white inside the canvas it came from.+ let bg = layer_rgba(&s, 0, 10, 7);+ assert!(bg.iter().all(|v| (v - 1.0).abs() < 0.02), "{mode} {depth} {angle}: {bg:?}");+ }+ }+ }++ /// Angle 0 (or a whole turn) is the plain crop: no resampling, the same document.+ #[test]+ fn crop_at_angle_zero_is_the_plain_crop() {+ let mut plain = marked("rgb", 16);+ plain.execute("image.crop", json!({"x": 3, "y": 2, "width": 30, "height": 10})).unwrap();+ for angle in [json!(0), json!(0.0), json!(360), json!(-720), json!(null)] {+ let mut s = marked("rgb", 16);+ let r = s.execute("image.crop", json!({"x": 3, "y": 2, "width": 30, "height": 10, "angle": angle})).unwrap();+ assert!(r.get("angle").is_none(), "{angle}: {r}");+ assert_eq!(doc(&s).size, Size::new(30, 10));+ for l in 0..2 {+ for y in 0..10 {+ for x in 0..30 {+ assert_eq!(layer_rgba(&s, l, x, y), layer_rgba(&plain, l, x, y), "{angle} layer {l} ({x}, {y})");+ }+ }+ }+ }+ }++ /// Bad angles fail cleanly, before anything changes.+ #[test]+ fn crop_angle_rejects_bad_values_without_changing_the_document() {+ let bad = [+ json!({"x": 0, "y": 0, "width": 10, "height": 10, "angle": "NaN"}),+ json!({"x": 0, "y": 0, "width": 10, "height": 10, "angle": "12"}),+ json!({"x": 0, "y": 0, "width": 10, "height": 10, "angle": [1]}),+ json!({"x": 0, "y": 0, "width": 10, "height": 10, "angle": true}),+ json!({"x": 0, "y": 0, "width": 10, "height": 10, "angle": 1e308}),+ json!({"x": 0, "y": 0, "width": 10, "height": 10, "angle": -3601}),+ json!({"x": 0, "y": 0, "width": 10, "height": 10, "angle": f64::MAX}),+ // An angle needs the frame: a selection crop has none.+ json!({"angle": 10}),+ json!({"x": 0, "y": 0, "width": 0, "height": 10, "angle": 10}),+ json!({"x": 0, "y": 0, "width": 300_001, "height": 10, "angle": 10}),+ json!({"x": i32::MAX - 5, "y": 0, "width": 10, "height": 10, "angle": 10}),+ ];+ for p in bad {+ let mut s = marked("rgb", 8);+ s.execute("select.all", json!({})).unwrap();+ let before = doc(&s).clone();+ let past = s.active().unwrap().history.past_len();+ assert!(s.execute("image.crop", p.clone()).is_err(), "{p}");+ assert_eq!(doc(&s).size, before.size, "{p}");+ assert_eq!(s.active().unwrap().history.past_len(), past, "{p}");+ }+ // Far-off but representable frames turn and crop without panicking.+ for (x, y) in [(-1_000_000, 0), (0, 1_000_000), (i32::MIN / 4, i32::MAX / 4)] {+ let mut s = marked("rgb", 8);+ s.execute("image.crop", json!({"x": x, "y": y, "width": 4, "height": 3, "angle": 33.3})).unwrap();+ assert_eq!(doc(&s).size, Size::new(4, 3));+ }+ }+#[test]fn crop_refuses_a_canvas_side_past_the_new_document_limit() {// #960: an unbounded explicit crop left a canvas that a later Trim or Duplicate Mergeddiff --git a/crates/engine/src/mode_cmds.rs b/crates/engine/src/mode_cmds.rsindex ad8ca0179..f5e9c37f5 100644--- a/crates/engine/src/mode_cmds.rs+++ b/crates/engine/src/mode_cmds.rs@@ -53,7 +53,7 @@ pub fn rotated_size(size: Size, deg: f64) -> Size {Size::new(nw as u32, nh as u32)}-fn rotate_arbitrary(s: &mut Session, p: &Value) -> Result<Value> {+pub(crate) fn rotate_arbitrary(s: &mut Session, p: &Value) -> Result<Value> {const CMD: &str = "image.rotation.arbitrary";let angle = f64::from(num(p, "angle", 0.0));if !angle.is_finite() || angle.abs() > 3600.0 {diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rsindex 789391cf1..97ce2f650 100644--- a/crates/ui-egui/src/canvas.rs+++ b/crates/ui-egui/src/canvas.rs@@ -224,14 +224,14 @@ fn draw_marquee_readout(ctx: &egui::Context, cursor: Pos2, values: [String; 2])draw_readout(ctx, "marquee-readout", cursor, ["W:", "H:"], values);}-/// A two-row readout beside the pointer (labels left, values right-aligned), above everything.-pub(crate) fn draw_readout(ctx: &egui::Context, id: &str, cursor: Pos2, labels: [&str; 2], values: [String; 2]) {+/// A readout of `N` rows beside the pointer (labels left, values right-aligned), above everything.+pub(crate) fn draw_readout<const N: usize>(ctx: &egui::Context, id: &str, cursor: Pos2, labels: [&str; N], values: [String; N]) {let t = crate::theme::Tokens::get(ctx);let font = egui::FontId::proportional(11.5);let width = |text: &str| ctx.fonts_mut(|f| f.layout_no_wrap(text.to_owned(), font.clone(), t.text).size().x);let labels = labels.map(|label| tl!(label));- let (lw, vw) = (labels.map(width), [width(&values[0]), width(&values[1])]);- let (label_col, value_col) = (lw[0].max(lw[1]), vw[0].max(vw[1]));+ let (lw, vw) = (labels.map(width), values.each_ref().map(|v| width(v)));+ let (label_col, value_col) = (lw.iter().fold(0.0f32, |a, &b| a.max(b)), vw.iter().fold(0.0f32, |a, &b| a.max(b)));egui::Area::new(egui::Id::new(id)).order(egui::Order::Tooltip).fixed_pos(cursor + vec2(16.0, 18.0)).interactable(false).constrain(true).show(ctx, |ui| {egui::Frame::new().fill(t.card).stroke(Stroke::new(1.0, t.card_border)).corner_radius(t.radius_sm).inner_margin(egui::Margin::symmetric(7, 4)).show(ui,@@ -2612,6 +2612,10 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect:if app.ui.transform.is_some() && response.double_clicked() {crate::transform_tool::commit(app);}+ // Crop: a double-click inside the frame commits it, as ↵ does (#1792).+ if tool == Tool::Crop && response.double_clicked() && response.interact_pointer_pos().is_some_and(|p| crate::crop_ui::commits_at(app, xf.to_doc(p))) {+ commit_crop(app);+ }if tool.is_type() && response.double_clicked() && !crate::type_transform::visible(app, crate::workspace_ui::sticky_mods(app, mods)) {crate::type_tool::select_word(app);}@@ -2654,8 +2658,13 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect:crate::type_transform::cursor(app, &ctx, &xf, p, mods)}) {ui.ctx().set_cursor_icon(c);- } else if let Some(c) = response.hover_pos().filter(|_| tool == Tool::Crop).and_then(|p| crate::crop_ui::cursor(app, xf.to_doc(p))) {+ } else if let Some((p, c)) = response.hover_pos().filter(|_| tool == Tool::Crop).and_then(|p| Some((p, crate::crop_ui::cursor(app, xf.to_doc(p))?))) {ui.ctx().set_cursor_icon(c);+ let d = xf.to_doc(p);+ if let Some(k) = crate::crop_ui::turn_cursor_dir(app, d) {+ let toward = xf.to_screen((d[0] + k[0] * 16.0) as f32, (d[1] + k[1] * 16.0) as f32) - p;+ crate::crop_ui::draw_turn_cursor(&ctx, p, toward);+ }} else if app.drag.as_ref().is_some_and(|d| d.sel_move.is_some())|| response.hover_pos().is_some_and(|p| app.drag.is_none() && selection_drag_kind(app, tool, xf.to_doc(p), ui.input(|i| i.modifiers)).is_some()){@@ -2921,6 +2930,52 @@ 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]) {+ 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 {+ return;+ }+ let at = |a: f32, b: f32| q[0] + u * a + v * b;+ // The shield: four trapezoids from the frame out to the frame grown past the whole view.+ let clip = painter.clip_rect();+ let reach = clip.size().length() + (clip.center() - at(0.5, 0.5)).length();+ let (eu, ev) = (reach / lu, reach / lv);+ let outer = [at(-eu, -ev), at(1.0 + eu, -ev), at(1.0 + eu, 1.0 + ev), at(-eu, 1.0 + ev)];+ let dim = Color32::from_black_alpha(130);+ let mut mesh = egui::Mesh::default();+ for p in q.iter().chain(outer.iter()) {+ mesh.colored_vertex(*p, dim);+ }+ for i in 0..4u32 {+ let j = (i + 1) % 4;+ mesh.add_triangle(i, j, 4 + j);+ mesh.add_triangle(i, 4 + j, 4 + i);+ }+ 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);+ }+ 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);+ for (c, su, sv) in [(q[0], 1.0, 1.0), (q[1], -1.0, 1.0), (q[3], 1.0, -1.0), (q[2], -1.0, -1.0)] {+ painter.line_segment([c, c + du * (l * su)], h);+ painter.line_segment([c, c + dv * (l * sv)], h);+ }+ // Edge handles: short bars at the middle of each side, along it.+ let (lx, ly) = (l.min(lu / 4.0) / 2.0, l.min(lv / 4.0) / 2.0);+ for (c, e) in [(at(0.5, 0.0), du * lx), (at(0.5, 1.0), du * lx), (at(0.0, 0.5), dv * ly), (at(1.0, 0.5), dv * ly)] {+ painter.line_segment([c - e, c + e], h);+ }+}+/// What the Crop tool shows past the canvas, cached per document state ([`draw_beyond_canvas`]).#[derive(Clone)]struct BeyondCanvas {@@ -3023,6 +3078,8 @@ fn draw_beyond_canvas(app: &mut PhotocraftApp, painter: &egui::Painter, xf: &Vie};// Transparency out to the frame, in phase with the canvas's own checkerboard.let canvas = xf.doc_rect(doc.bounds());+ // A turned frame reaches as far as its corners.+ let f = crate::crop_ui::turned_bounds(f, crate::crop_ui::angle(app));let fr = DRect::new(f[0].floor() as i32, f[1].floor() as i32, f[2].ceil() as i32, f[3].ceil() as i32);let square = app.session.prefs().transparency_and_gamut.square();let checker_id = square.map(|_| checker(app, &ctx));@@ -3066,8 +3123,17 @@ fn draw_tool_state(app: &PhotocraftApp, painter: &egui::Painter, xf: &ViewXform,crate::tool_feedback::draw_ants(painter, &pts, false);}if let Some(c) = app.ui.crop_rect {- 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);+ 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);+ } else {+ crop_overlay_turned(painter, crate::crop_ui::corners(c, deg).map(|p| xf.to_screen(p[0] as f32, p[1] as f32)));+ }+ // The frame's angle beside the pointer while it turns (#1792).+ if let (Some(a), Some(h)) = (crate::crop_ui::turning(app), hover) {+ draw_readout(painter.ctx(), "crop-angle-readout", h, ["Angle:"], [format!("{a:.1}°")]);+ }}}@@ -3877,7 +3943,15 @@ pub fn commit_crop(app: &mut PhotocraftApp) {let (x, y) = (r[0].round(), r[1].round());let (w, h) = ((r[2] - r[0]).round().max(1.0), (r[3] - r[1]).round().max(1.0));let delete = app.ui.tool_options.crop_delete;- if app.run("image.crop", json!({"x": x, "y": y, "width": w, "height": h, "deleteCroppedPixels": delete})).is_ok()+ let mut p = json!({"x": x, "y": y, "width": w, "height": h, "deleteCroppedPixels": delete});+ // A turned frame (#1792): the document turns with it, then is cropped to it. (The untouched+ // default frame above is never turned: turning it makes it a real frame.)+ let angle = crate::crop_ui::angle(app);+ app.ui.crop_angle = 0.0;+ if angle != 0.0 {+ p["angle"] = json!(angle);+ }+ if app.run("image.crop", p).is_ok()&& let Some(i) = app.session.active_index(){app.ui.views[i].fit_pending = true;diff --git a/crates/ui-egui/src/crop_ui.rs b/crates/ui-egui/src/crop_ui.rsindex 438ab6bf5..1757a44aa 100644--- a/crates/ui-egui/src/crop_ui.rs+++ b/crates/ui-egui/src/crop_ui.rs@@ -1,14 +1,23 @@-//! Crop tool gestures, Photoshop "Classic Mode" style (the frame moves over a fixed image):+//! Crop tool gestures, Photoshop "Classic Mode" style (the frame moves and turns over a fixed+//! image)://!-//! - outside the frame (or with no frame), a drag draws a new frame; ⇧ makes it square, ⌥ draws-//! it from the centre, and holding Space while drawing repositions the frame being drawn;+//! - with no frame, or inside the untouched default frame, a drag draws a new frame; ⇧ makes it+//! square, ⌥ draws it from the centre, and holding Space while drawing repositions the frame+//! being drawn;//! - inside the frame, a drag moves it;-//! - on an edge or corner, a drag resizes it; ⇧ keeps the frame's aspect ratio, ⌥ resizes about-//! the centre, and an options-bar ratio preset always holds.+//! - on an edge or corner, a drag resizes it along the frame's own (possibly turned) axes; ⇧ keeps+//! the frame's aspect ratio, ⌥ resizes about the centre, and an options-bar ratio preset always+//! holds;+//! - outside the frame (off its handles) the pointer is the rotate cursor and a drag turns the+//! frame about its centre, ⇧ in 15° steps, with the angle beside the pointer (#1792). As in+//! Photoshop, a new frame is drawn after the pending one is committed or cancelled.//!-//! ↵ commits (`image.crop`, see `canvas::commit_crop`) and Esc cancels. The pending frame lives in-//! `UiState::crop_rect`, so the control channel reads it. `image.crop` has no angle, so dragging-//! outside the frame draws a new one rather than rotating it.+//! ↵ commits (`image.crop`, see `canvas::commit_crop`, with the turn as its `angle`: the document+//! is rotated so the frame is upright, then cropped to it) and Esc cancels. The pending frame lives+//! in `UiState::crop_rect` (the frame before its turn) and `UiState::crop_angle` (degrees,+//! clockwise on screen), so the control channel reads both. Photoshop's default mode keeps the box+//! upright and turns the image behind it; the result is the same, but here the frame turns over+//! the image (its Classic Mode), which the canvas draws without rotating the view.//!//! As in Photoshop, from the first press until the crop is committed or cancelled the canvas also//! shows the layers' pixels past its edges (kept by a crop with Delete Cropped Pixels off, or moved@@ -50,6 +59,9 @@ pub enum CropDrag {Move { start: [f64; 2], rect: [f64; 4] },/// Dragging an edge or corner: `hx`/`hy` are -1 (left/top), 1 (right/bottom) or 0 (untouched).Resize { hx: i8, hy: i8, start: [f64; 2], rect: [f64; 4] },+ /// Turning the frame about `center`: the pointer's direction from it at the press (radians)+ /// and the frame's angle then (degrees).+ Rotate { center: [f64; 2], grab: f64, from: f64 },}/// What the pointer is over, relative to a crop frame.@@ -92,6 +104,72 @@ pub fn hit(r: [f64; 4], p: [f64; 2], tol: f64) -> Hit {}}+/// The centre of `[x0, y0, x1, y1]`.+pub fn center(r: [f64; 4]) -> [f64; 2] {+ [(r[0] + r[2]) / 2.0, (r[1] + r[3]) / 2.0]+}++/// `p` turned `deg` degrees clockwise on screen (y down) about `c`.+pub fn turn(p: [f64; 2], c: [f64; 2], deg: f64) -> [f64; 2] {+ let (s, k) = deg.to_radians().sin_cos();+ let (dx, dy) = (p[0] - c[0], p[1] - c[1]);+ [c[0] + k * dx - s * dy, c[1] + s * dx + k * dy]+}++/// The corners of frame `r` turned `deg` degrees about its centre: top-left, top-right,+/// bottom-right, bottom-left (of the upright frame).+pub fn corners(r: [f64; 4], deg: f64) -> [[f64; 2]; 4] {+ let c = center(r);+ [[r[0], r[1]], [r[2], r[1]], [r[2], r[3]], [r[0], r[3]]].map(|p| turn(p, c, deg))+}++/// The axis-aligned bounds `[x0, y0, x1, y1]` of frame `r` turned `deg` degrees.+pub fn turned_bounds(r: [f64; 4], deg: f64) -> [f64; 4] {+ if deg == 0.0 {+ return r;+ }+ corners(r, deg)+ .iter()+ .fold([f64::INFINITY, f64::INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY], |b, p| [b[0].min(p[0]), b[1].min(p[1]), b[2].max(p[0]), b[3].max(p[1])])+}++/// [`hit`] for frame `r` turned `deg` degrees about its centre: handles and inside are found in+/// the frame's own axes.+pub fn hit_turned(r: [f64; 4], deg: f64, p: [f64; 2], tol: f64) -> Hit {+ if deg == 0.0 { hit(r, p, tol) } else { hit(r, turn(p, center(r), -deg), tol) }+}++/// An angle in degrees brought into (-180, 180]; 0 for anything not finite.+pub fn normalized_angle(deg: f64) -> f64 {+ if !deg.is_finite() {+ return 0.0;+ }+ let a = deg.rem_euclid(360.0);+ if a > 180.0 { a - 360.0 } else { a }+}++/// The frame's angle after turning it from `from` degrees by the pointer's sweep about `c` from+/// direction `grab` (radians) to `p`; ⇧ snaps it to 15° steps, as in Photoshop.+pub fn turned_angle(c: [f64; 2], grab: f64, from: f64, p: [f64; 2], snap: bool) -> f64 {+ let now = (p[1] - c[1]).atan2(p[0] - c[0]);+ let a = from + (now - grab).to_degrees();+ normalized_angle(if snap { (a / 15.0).round() * 15.0 } else { a })+}++/// [`resized`] for frame `r` turned `deg` degrees: the handle moves along the frame's own axes by+/// the document-space drag `d`, and the edges opposite stay where they are on the page.+pub fn resized_turned(r: [f64; 4], deg: f64, hx: i8, hy: i8, d: [f64; 2], ratio: Option<f64>, alt: bool) -> [f64; 4] {+ if deg == 0.0 {+ return resized(r, hx, hy, d, ratio, alt);+ }+ let c = center(r);+ // In the frame's axes (about its old centre), then the new centre back on the page.+ let n = resized(r, hx, hy, turn(d, [0.0, 0.0], -deg), ratio, alt);+ let nc = turn(center(n), c, deg);+ let (hw, hh) = ((n[2] - n[0]) / 2.0, (n[3] - n[1]) / 2.0);+ [nc[0] - hw, nc[1] - hh, nc[0] + hw, nc[1] + hh]+}+/// `[x0, y0, x1, y1]` with x0 ≤ x1, y0 ≤ y1.fn normalized(a: [f64; 2], b: [f64; 2]) -> [f64; 4] {[a[0].min(b[0]), a[1].min(b[1]), a[0].max(b[0]), a[1].max(b[1])]@@ -170,8 +248,15 @@ pub fn ensure_frame(app: &mut PhotocraftApp) {app.ui.crop_rect = None;app.crop.default_frame = false;}+ if app.ui.crop_rect.is_none() {+ app.ui.crop_angle = 0.0;+ }return;}+ // No frame (cancelled or committed): the next one starts upright.+ if app.ui.crop_rect.is_none() && app.crop.drag.is_none() {+ app.ui.crop_angle = 0.0;+ }let key = app.session.active_index().zip(app.session.active()).map(|(i, st)| (i, st.doc.size.width, st.doc.size.height));// Another document (or a resized one) gets its own default frame.if app.crop.default_frame && app.crop.frame_for != key && app.crop.drag.is_none() {@@ -218,6 +303,31 @@ fn tolerance(app: &PhotocraftApp) -> f64 {HANDLE_PX / (app.current_zoom() as f64).max(0.01)}+/// The pending frame's angle (degrees), 0 when it isn't a finite number.+pub fn angle(app: &PhotocraftApp) -> f64 {+ normalized_angle(app.ui.crop_angle)+}++/// A press at document point `p` would turn the frame (Crop tool, outside the frame and its+/// handles) rather than draw, move or resize one.+pub fn turns_at(app: &PhotocraftApp, p: [f64; 2]) -> bool {+ app.ui.tool == Tool::Crop+ && app.ui.crop_rect.filter(|r| r.iter().all(|v| v.is_finite())).is_some_and(|r| hit_turned(r, angle(app), p, tolerance(app)) == Hit::Outside)+}++/// A double-click at document point `p` commits the crop (Photoshop: double-click inside the box,+/// like ↵): Crop tool, a pending frame, and `p` inside it (not on a handle, not outside).+pub fn commits_at(app: &PhotocraftApp, p: [f64; 2]) -> bool {+ app.ui.tool == Tool::Crop+ && app.crop.drag.is_none()+ && app.ui.crop_rect.filter(|r| r.iter().all(|v| v.is_finite())).is_some_and(|r| hit_turned(r, angle(app), p, tolerance(app)) == Hit::Inside)+}++/// The frame is being turned: its angle, for the readout beside the pointer.+pub fn turning(app: &PhotocraftApp) -> Option<f64> {+ matches!(app.crop.drag, Some(CropDrag::Rotate { .. })).then(|| angle(app))+}+/// Pointer input for the Crop tool. Returns true when the event was its.pub fn pointer(app: &mut PhotocraftApp, ev: ToolEvent, mods: Modifiers) -> bool {if app.ui.tool != Tool::Crop {@@ -234,10 +344,19 @@ pub fn pointer(app: &mut PhotocraftApp, ev: ToolEvent, mods: Modifiers) -> boolToolEvent::Down { .. } => {app.crop.editing = true;let frame = app.ui.crop_rect.filter(|r| r.iter().all(|v| v.is_finite()));- app.crop.drag = Some(match frame.map(|r| (r, hit(r, p, tolerance(app)))) {+ let deg = angle(app);+ app.crop.drag = Some(match frame.map(|r| (r, hit_turned(r, deg, p, tolerance(app)))) {Some((rect, Hit::Handle(hx, hy))) => CropDrag::Resize { hx, hy, start: p, rect },Some((rect, Hit::Inside)) if !app.crop.default_frame => CropDrag::Move { start: p, rect },- _ => CropDrag::Draw { anchor: p, cur: p, last: p, prev: app.ui.crop_rect },+ // Outside the frame a drag turns it, as in Photoshop (#1792).+ Some((rect, Hit::Outside)) => {+ let c = center(rect);+ CropDrag::Rotate { center: c, grab: (p[1] - c[1]).atan2(p[0] - c[0]), from: deg }+ }+ _ => {+ app.ui.crop_angle = 0.0;+ CropDrag::Draw { anchor: p, cur: p, last: p, prev: app.ui.crop_rect }+ }});}ToolEvent::Move { .. } => update(app, p, mods),@@ -245,7 +364,9 @@ pub fn pointer(app: &mut PhotocraftApp, ev: ToolEvent, mods: Modifiers) -> boolupdate(app, p, mods);let Some(drag) = app.crop.drag.take() else { return true };let ok = app.ui.crop_rect.is_some_and(size_ok);- if ok {+ // A click outside the untouched default frame (no turn) leaves it the default.+ let changed = !matches!(drag, CropDrag::Rotate { from, .. } if from == angle(app));+ if ok && changed {app.crop.default_frame = false;}match drag {@@ -262,6 +383,11 @@ pub fn pointer(app: &mut PhotocraftApp, ev: ToolEvent, mods: Modifiers) -> boolfn update(app: &mut PhotocraftApp, p: [f64; 2], mods: Modifiers) {let ratio = preset_ratio(app);let space = app.crop.space;+ let deg = angle(app);+ if let Some(CropDrag::Rotate { center, grab, from }) = app.crop.drag {+ app.ui.crop_angle = turned_angle(center, grab, from, p, mods.shift);+ return;+ }let Some(drag) = app.crop.drag.as_mut() else { return };let rect = match drag {CropDrag::Draw { anchor, cur, last, .. } => {@@ -289,8 +415,9 @@ fn update(app: &mut PhotocraftApp, p: [f64; 2], mods: Modifiers) {(w > 0.0 && h > 0.0).then(|| w / h)};let ratio = ratio.or_else(|| if mods.shift { keep() } else { None });- resized(*rect, *hx, *hy, [p[0] - start[0], p[1] - start[1]], ratio, mods.alt)+ resized_turned(*rect, deg, *hx, *hy, [p[0] - start[0], p[1] - start[1]], ratio, mods.alt)}+ CropDrag::Rotate { .. } => return,};app.ui.crop_rect = Some(rect);}@@ -300,22 +427,90 @@ pub fn cursor(app: &PhotocraftApp, p: [f64; 2]) -> Option<CursorIcon> {if app.ui.tool != Tool::Crop {return None;}+ let deg = angle(app);let h = match app.crop.drag {Some(CropDrag::Move { .. }) => Hit::Inside,Some(CropDrag::Resize { hx, hy, .. }) => Hit::Handle(hx, hy),- Some(CropDrag::Draw { .. }) => Hit::Outside,- None => hit(app.ui.crop_rect?, p, tolerance(app)),+ Some(CropDrag::Draw { .. }) => return Some(CursorIcon::Crosshair),+ Some(CropDrag::Rotate { .. }) => Hit::Outside,+ None => hit_turned(app.ui.crop_rect?, deg, p, tolerance(app)),};Some(match h {- Hit::Handle(-1, -1) | Hit::Handle(1, 1) => CursorIcon::ResizeNwSe,- Hit::Handle(-1, 1) | Hit::Handle(1, -1) => CursorIcon::ResizeNeSw,- Hit::Handle(_, 0) => CursorIcon::ResizeHorizontal,- Hit::Handle(..) => CursorIcon::ResizeVertical,+ Hit::Handle(hx, hy) => resize_icon(hx, hy, deg),Hit::Inside => CursorIcon::Move,- Hit::Outside => CursorIcon::Crosshair,+ // Photoshop's curved two-headed arrow (`draw_turn_cursor`, from `turn_cursor_dir`).+ Hit::Outside => CursorIcon::None,})}+/// Where the turn cursor's arc bends at document point `p` (pointer outside the frame, or turning+/// 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 {+ return None;+ }+ let r = app.ui.crop_rect.filter(|r| r.iter().all(|v| v.is_finite()))?;+ let deg = angle(app);+ let turning = match app.crop.drag {+ Some(CropDrag::Rotate { .. }) => true,+ Some(_) => false,+ None => hit_turned(r, deg, p, tolerance(app)) == Hit::Outside,+ };+ if !turning || !(p[0].is_finite() && p[1].is_finite()) {+ return None;+ }+ let c = center(r);+ let local = turn(p, c, -deg);+ let sx = if local[0] < c[0] { 1.0 } else { -1.0 };+ let sy = if local[1] < c[1] { 1.0 } else { -1.0 };+ Some(turn([sx * std::f64::consts::FRAC_1_SQRT_2, sy * std::f64::consts::FRAC_1_SQRT_2], [0.0, 0.0], deg))+}++/// Photoshop's crop turn cursor at screen point `p`: a short arc with an arrowhead at each end,+/// curving round the frame corner that lies in screen direction `toward` (an original drawing, no+/// proprietary cursor asset).+pub fn draw_turn_cursor(ctx: &egui::Context, p: egui::Pos2, toward: egui::Vec2) {+ let len = toward.length();+ if !len.is_finite() || len < 1e-6 {+ return;+ }+ let u = toward / len;+ let tokens = crate::theme::Tokens::get(ctx);+ let painter = ctx.layer_painter(egui::LayerId::new(egui::Order::Tooltip, egui::Id::new("crop-turn-cursor")));+ const R: f32 = 12.0;+ const HALF: f32 = 0.75;+ let c = p + u * R;+ let mid = (-u.y).atan2(-u.x);+ let at = |a: f32| c + egui::vec2(a.cos(), a.sin()) * R;+ let points: Vec<egui::Pos2> = (0..=16).map(|i| at(mid - HALF + 2.0 * HALF * i as f32 / 16.0)).collect();+ painter.add(egui::Shape::line(points.clone(), egui::Stroke::new(3.5, tokens.shadow)));+ painter.add(egui::Shape::line(points, egui::Stroke::new(1.5, tokens.accent_text)));+ for (a, sign) in [(mid - HALF, -1.0f32), (mid + HALF, 1.0)] {+ let tip = at(a) + egui::vec2(-a.sin(), a.cos()) * (sign * 2.0);+ let tangent = egui::vec2(-a.sin(), a.cos()) * sign;+ let normal = egui::vec2(a.cos(), a.sin());+ painter.add(egui::Shape::convex_polygon(+ vec![tip + tangent * 3.5, tip - tangent * 3.0 + normal * 3.5, tip - tangent * 3.0 - normal * 3.5],+ tokens.accent_text,+ egui::Stroke::new(1.0, tokens.shadow),+ ));+ }+}++/// The resize arrow for handle (`hx`, `hy`) of a frame turned `deg` degrees: the handle's outward+/// direction, turned with the frame, to the nearest of the four arrows.+fn resize_icon(hx: i8, hy: i8, deg: f64) -> CursorIcon {+ let d = turn([f64::from(hx), f64::from(hy)], [0.0, 0.0], deg);+ let a = d[1].atan2(d[0]).rem_euclid(std::f64::consts::PI);+ match ((a / std::f64::consts::FRAC_PI_4).round() as i64).rem_euclid(4) {+ 0 => CursorIcon::ResizeHorizontal,+ 1 => CursorIcon::ResizeNwSe,+ 2 => CursorIcon::ResizeVertical,+ _ => CursorIcon::ResizeNeSw,+ }+}+#[cfg(test)]mod tests {use super::*;@@ -448,12 +643,131 @@ mod tests {assert_eq!(app.ui.crop_rect, Some([20.0, 20.0, 80.0, 60.0]));drag(&mut app, &[[50.0, 40.0], [60.0, 45.0], [70.0, 50.0]], NONE);assert_eq!(app.ui.crop_rect, Some([40.0, 30.0, 100.0, 70.0]), "moved, not redrawn");- // Outside, a drag still draws a new frame.- drag(&mut app, &[[150.0, 10.0], [190.0, 90.0]], NONE);- assert_eq!(app.ui.crop_rect, Some([150.0, 10.0, 190.0, 90.0]));- // A click outside keeps the frame.+ // A click outside keeps the frame (and leaves it upright).drag(&mut app, &[[5.0, 5.0]], NONE);- assert_eq!(app.ui.crop_rect, Some([150.0, 10.0, 190.0, 90.0]));+ assert_eq!(app.ui.crop_rect, Some([40.0, 30.0, 100.0, 70.0]));+ assert_eq!(app.ui.crop_angle, 0.0);+ // Outside, a drag turns the frame rather than drawing a new one (#1792).+ drag(&mut app, &[[150.0, 50.0], [190.0, 90.0]], NONE);+ assert_eq!(app.ui.crop_rect, Some([40.0, 30.0, 100.0, 70.0]));+ assert!(app.ui.crop_angle > 10.0, "{}", app.ui.crop_angle);+ }++ #[test]+ fn dragging_outside_turns_the_frame_about_its_centre() {+ let mut app = app(SampleType::U8);+ app.ui.crop_rect = Some([40.0, 30.0, 100.0, 70.0]);+ // Centre (70, 50): from straight right to straight below is a quarter turn clockwise.+ drag(&mut app, &[[150.0, 50.0], [140.0, 70.0], [70.0, 95.0]], NONE);+ assert!((app.ui.crop_angle - 90.0).abs() < 1e-9, "{}", app.ui.crop_angle);+ assert_eq!(app.ui.crop_rect, Some([40.0, 30.0, 100.0, 70.0]), "turning keeps the frame");+ // Back the other way, past -180 (normalised).+ drag(&mut app, &[[70.0, 120.0], [-10.0, 50.0], [70.0, -20.0]], NONE);+ assert!((app.ui.crop_angle - -90.0).abs() < 1e-9, "{}", app.ui.crop_angle);+ // ⇧ snaps the angle to 15° steps.+ app.ui.crop_angle = 0.0;+ let a = 22.0f64.to_radians();+ drag(&mut app, &[[150.0, 50.0], [70.0 + 80.0 * a.cos(), 50.0 + 80.0 * a.sin()]], SHIFT);+ assert_eq!(app.ui.crop_angle, 15.0);+ assert_eq!(cursor(&app, [150.0, 50.0]), Some(CursorIcon::None), "outside: the drawn turn cursor");+ // Turning the untouched default frame makes it a real frame; a click outside it doesn't.+ let mut app = super::tests::app(SampleType::U8);+ ensure_frame(&mut app);+ drag(&mut app, &[[250.0, 50.0]], NONE);+ assert!(app.crop.default_frame, "a click outside keeps the default frame");+ drag(&mut app, &[[250.0, 50.0], [250.0, 80.0]], NONE);+ assert!(!app.crop.default_frame && app.ui.crop_angle > 0.0);+ // Esc (no frame) starts the next one upright.+ app.ui.crop_rect = None;+ ensure_frame(&mut app);+ assert_eq!((app.ui.crop_rect, app.ui.crop_angle), (Some([0.0, 0.0, 200.0, 100.0]), 0.0));+ }++ #[test]+ fn hit_testing_a_turned_frame_uses_its_own_axes() {+ let r = [40.0, 30.0, 100.0, 70.0];+ // A quarter turn: the frame covers x 50..90, y 20..80 on the page.+ assert_eq!(hit_turned(r, 90.0, [70.0, 75.0], 2.0), Hit::Inside, "inside the turned frame only");+ assert_eq!(hit(r, [70.0, 75.0], 2.0), Hit::Outside);+ assert_eq!(hit_turned(r, 90.0, [45.0, 50.0], 2.0), Hit::Outside, "inside the upright frame only: the rotate zone");+ // The upright frame's top-left corner turns to the top-right of the page.+ assert_eq!(hit_turned(r, 90.0, [90.0, 20.0], 2.0), Hit::Handle(-1, -1));+ // Its right edge's middle is now at the bottom.+ assert_eq!(hit_turned(r, 90.0, [70.0, 80.0], 2.0), Hit::Handle(1, 0));+ let c = corners(r, 90.0);+ for (a, b) in c.iter().zip([[90.0, 20.0], [90.0, 80.0], [50.0, 80.0], [50.0, 20.0]]) {+ assert!((a[0] - b[0]).abs() < 1e-9 && (a[1] - b[1]).abs() < 1e-9, "{c:?}");+ }+ let b = turned_bounds(r, 90.0);+ assert!((b[0] - 50.0).abs() < 1e-9 && (b[3] - 80.0).abs() < 1e-9, "{b:?}");+ // Handle arrows turn with the frame.+ assert_eq!(resize_icon(1, 0, 0.0), CursorIcon::ResizeHorizontal);+ assert_eq!(resize_icon(1, 0, 90.0), CursorIcon::ResizeVertical);+ assert_eq!(resize_icon(1, 0, 45.0), CursorIcon::ResizeNwSe);+ assert_eq!(resize_icon(-1, -1, 90.0), CursorIcon::ResizeNeSw);+ assert_eq!(normalized_angle(540.0), 180.0);+ assert_eq!(normalized_angle(-190.0), 170.0);+ assert_eq!(normalized_angle(f64::NAN), 0.0);+ }++ #[test]+ fn resizing_a_turned_frame_moves_along_its_axes_and_keeps_the_opposite_edge() {+ let r = [40.0, 30.0, 100.0, 70.0];+ // At 90°, the right edge (local +x) faces down the page: dragging down 10 grows the width.+ let n = resized_turned(r, 90.0, 1, 0, [0.0, 10.0], None, false);+ assert!(((n[2] - n[0]) - 70.0).abs() < 1e-9 && ((n[3] - n[1]) - 40.0).abs() < 1e-9, "{n:?}");+ // The opposite (left) edge stays put on the page: at y = 20 with x 50..90.+ let (old, new) = (corners(r, 90.0), corners(n, 90.0));+ for (i, (a, b)) in [(0, 0), (3, 3)].map(|(i, j)| (old[i], new[j])).iter().enumerate() {+ assert!((a[0] - b[0]).abs() < 1e-9 && (a[1] - b[1]).abs() < 1e-9, "corner {i}: {a:?} vs {b:?}");+ }+ // A sideways drag does nothing to that handle.+ let same = resized_turned(r, 90.0, 1, 0, [25.0, 0.0], None, false);+ assert!(same.iter().zip(r).all(|(a, b)| (a - b).abs() < 1e-9), "{same:?}");+ // At 0° it is the plain resize.+ assert_eq!(resized_turned(r, 0.0, 1, 1, [5.0, 6.0], None, false), resized(r, 1, 1, [5.0, 6.0], None, false));+ // Through the pointer: grabbing the turned right-edge handle and dragging down 10.+ let mut app = app(SampleType::U8);+ app.ui.crop_rect = Some(r);+ app.ui.crop_angle = 90.0;+ drag(&mut app, &[[70.0, 80.0], [70.0, 90.0]], NONE);+ let got = app.ui.crop_rect.unwrap();+ assert!(got.iter().zip(n).all(|(a, b)| (a - b).abs() < 1e-9), "{got:?} vs {n:?}");+ // Moving a turned frame is a plain translation, angle kept.+ drag(&mut app, &[[70.0, 50.0], [80.0, 55.0]], NONE);+ let moved = app.ui.crop_rect.unwrap();+ assert!(moved.iter().zip([n[0] + 10.0, n[1] + 5.0, n[2] + 10.0, n[3] + 5.0]).all(|(a, b)| (a - b).abs() < 1e-9), "{moved:?}");+ assert_eq!(app.ui.crop_angle, 90.0);+ }++ /// ↵ on a turned frame crops the turned document (one step), at 8, 16 and 32 bits.+ #[test]+ fn commit_crops_to_the_turned_frame() {+ for depth in [SampleType::U8, SampleType::U16, SampleType::F32] {+ let mut app = app(depth);+ app.run("select.rect", json!({"x": 60, "y": 40, "width": 1, "height": 1})).unwrap();+ app.run("edit.fill", json!({"color": "#ff0000"})).unwrap();+ app.run("select.deselect", json!({})).unwrap();+ let past = app.session.active().unwrap().history.past_len();+ // A 40 × 20 frame centred on (60, 40), turned 90° by a drag outside it.+ app.ui.crop_rect = Some([40.0, 30.0, 80.0, 50.0]);+ app.crop.default_frame = false;+ drag(&mut app, &[[120.0, 40.0], [60.0, 100.0]], NONE);+ assert!((app.ui.crop_angle - 90.0).abs() < 1e-6, "{depth:?}: {}", app.ui.crop_angle);+ crate::canvas::commit_crop(&mut app);+ assert!(app.ui.crop_rect.is_none());+ assert_eq!(app.ui.crop_angle, 0.0, "the next frame starts upright");+ let st = app.session.active().unwrap();+ assert_eq!(st.history.past_len(), past + 1, "{depth:?}: one undo step");+ assert_eq!((st.doc.size.width, st.doc.size.height), (40, 20), "{depth:?}");+ assert_eq!(st.doc.depth, depth);+ // The red pixel was at the frame's centre: it is at the cropped image's centre.+ let surf = st.doc.layers[0].surface().unwrap();+ let red = (19..=21).flat_map(|x| (9..=11).map(move |y| (x, y))).map(|(x, y)| surf.rgba(x, y)).find(|px| px[0] > 0.6 && px[1] < 0.4);+ assert!(red.is_some(), "{depth:?}: no red at the centre");+ app.run("edit.undo", json!({})).unwrap();+ assert_eq!(app.session.active().unwrap().doc.size, Size::new(200, 100), "{depth:?}");+ }}#[test]@@ -597,6 +911,18 @@ mod tests {app.ui.crop_rect = Some(r);}}+ // Odd angles (the control channel can set any) turn, resize and commit without panicking.+ for a in [f64::NAN, f64::INFINITY, -1e300, 1e-300, 720.0] {+ app.ui.crop_rect = Some([10.0, 10.0, 50.0, 40.0]);+ app.ui.crop_angle = a;+ for pts in [[[30.0, 25.0], [f64::NAN, 1.0]], [[30.0, 25.0], [1e300, 2.0]], [[50.0, 40.0], [60.0, 45.0]], [[90.0, 90.0], [-1e300, 1e300]]] {+ drag(&mut app, &pts, SHIFT);+ let _ = cursor(&app, [5.0, 5.0]);+ }+ assert!(app.ui.crop_angle.is_finite() || !a.is_finite());+ crate::canvas::commit_crop(&mut app);+ app.run("edit.undo", json!({})).ok();+ }app.ui.tool_options.crop_ratio = "0:0".into();app.ui.crop_rect = Some([0.0, 0.0, 10.0, 10.0]);drag(&mut app, &[[10.0, 10.0], [30.0, 30.0]], SHIFT);@@ -608,6 +934,51 @@ mod tests {assert!(empty.ui.crop_rect.is_none());}+ /// #1792: outside the frame the turn cursor bends towards the corner of the pointer's quadrant+ /// (four variants, as in Photoshop) and turns with the frame; no turn cursor inside or on a handle.+ #[test]+ fn turn_cursor_points_at_the_quadrant_corner() {+ let mut app = app(SampleType::U8);+ app.ui.crop_rect = Some([20.0, 20.0, 100.0, 60.0]);+ let h = std::f64::consts::FRAC_1_SQRT_2;+ let near = |d: Option<[f64; 2]>, want: [f64; 2]| d.is_some_and(|d| (d[0] - want[0]).abs() < 1e-9 && (d[1] - want[1]).abs() < 1e-9);+ assert!(near(turn_cursor_dir(&app, [0.0, 0.0]), [h, h]), "top-left: towards the top-left corner");+ assert!(near(turn_cursor_dir(&app, [130.0, 5.0]), [-h, h]), "top-right");+ assert!(near(turn_cursor_dir(&app, [130.0, 90.0]), [-h, -h]), "bottom-right");+ assert!(near(turn_cursor_dir(&app, [5.0, 90.0]), [h, -h]), "bottom-left");+ assert!(near(turn_cursor_dir(&app, [150.0, 30.0]), [-h, h]), "beside the right edge, upper half");+ assert_eq!(turn_cursor_dir(&app, [60.0, 40.0]), None, "inside");+ assert_eq!(turn_cursor_dir(&app, [20.0, 20.0]), None, "on a handle");+ // A frame turned 45° turns the cursor with it: the diagonal becomes horizontal.+ app.ui.crop_angle = 45.0;+ assert!(near(turn_cursor_dir(&app, [0.0, 0.0]), [1.0, 0.0]), "{:?}", turn_cursor_dir(&app, [0.0, 0.0]));+ app.ui.crop_angle = f64::NAN;+ assert!(turn_cursor_dir(&app, [f64::NAN, 0.0]).is_none());+ app.ui.tool = Tool::Brush;+ assert_eq!(turn_cursor_dir(&app, [0.0, 0.0]), None);+ }++ /// A double-click inside the frame commits it, as ↵ does; on a handle or outside it doesn't.+ #[test]+ fn double_click_inside_the_frame_commits() {+ let mut app = app(SampleType::U8);+ app.ui.crop_rect = Some([20.0, 20.0, 100.0, 60.0]);+ assert!(commits_at(&app, [60.0, 40.0]));+ assert!(!commits_at(&app, [20.0, 20.0]), "on a handle");+ assert!(!commits_at(&app, [150.0, 40.0]), "outside: that turns the frame");+ app.ui.crop_angle = 30.0;+ assert!(commits_at(&app, [60.0, 40.0]), "inside a turned frame");+ assert!(!commits_at(&app, [25.0, 22.0]), "inside the upright frame but outside the turned one");+ app.ui.crop_angle = 0.0;+ app.ui.crop_rect = None;+ assert!(!commits_at(&app, [60.0, 40.0]), "no frame");+ app.ui.crop_rect = Some([f64::NAN, 0.0, 1.0, 1.0]);+ assert!(!commits_at(&app, [0.5, 0.5]));+ app.ui.crop_rect = Some([20.0, 20.0, 100.0, 60.0]);+ app.ui.tool = Tool::Brush;+ assert!(!commits_at(&app, [60.0, 40.0]));+ }+#[test]fn cursor_follows_the_frame() {let mut app = app(SampleType::U8);@@ -617,7 +988,7 @@ mod tests {assert_eq!(cursor(&app, [100.0, 20.0]), Some(CursorIcon::ResizeNeSw));assert_eq!(cursor(&app, [60.0, 60.0]), Some(CursorIcon::ResizeVertical));assert_eq!(cursor(&app, [60.0, 40.0]), Some(CursorIcon::Move));- assert_eq!(cursor(&app, [150.0, 40.0]), Some(CursorIcon::Crosshair));+ assert_eq!(cursor(&app, [150.0, 40.0]), Some(CursorIcon::None), "outside: the drawn turn cursor");app.ui.tool = Tool::Brush;assert_eq!(cursor(&app, [60.0, 40.0]), None);}diff --git a/crates/ui-egui/src/panels.rs b/crates/ui-egui/src/panels.rsindex e8a6eab5f..b0db717e1 100644--- a/crates/ui-egui/src/panels.rs+++ b/crates/ui-egui/src/panels.rs@@ -1004,6 +1004,7 @@ pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui) {}if icons::button(ui, "ban", 26.0, false, tl!("Cancel current crop operation (Esc)")).clicked() {app.ui.crop_rect = None;+ app.ui.crop_angle = 0.0;}});}diff --git a/crates/ui-egui/src/shortcuts.rs b/crates/ui-egui/src/shortcuts.rsindex f01b85121..0c77677b0 100644--- a/crates/ui-egui/src/shortcuts.rs+++ b/crates/ui-egui/src/shortcuts.rs@@ -389,6 +389,7 @@ pub fn handle(app: &mut PhotocraftApp, ctx: &egui::Context) {app.ui.polygon.clear();app.ui.polygon_mode.clear();app.ui.crop_rect = None;+ app.ui.crop_angle = 0.0;app.crop.drag = None;return;}diff --git a/crates/ui-egui/src/snap_ui.rs b/crates/ui-egui/src/snap_ui.rsindex 97502dd40..d33a5e063 100644--- a/crates/ui-egui/src/snap_ui.rs+++ b/crates/ui-egui/src/snap_ui.rs@@ -165,10 +165,17 @@ fn begin(app: &mut PhotocraftApp, p: [f64; 2]) {let exclude = app.session.active().map(|s| s.selected_layers()).unwrap_or_default();moving_rect(app).map(|rect| (Gesture::Move { rect }, exclude))} else if tool == Tool::Crop- && let Some(rect) = app.ui.crop_rect.filter(|r| crate::crop_ui::hit(*r, p, tol) == crate::crop_ui::Hit::Inside)+ && let Some(rect) = app.ui.crop_rect.filter(|r| crate::crop_ui::angle(app) == 0.0 && crate::crop_ui::hit(*r, p, tol) == crate::crop_ui::Hit::Inside){// Moving the crop frame snaps its edges, like the Move tool's layer bounds.Some((Gesture::Move { rect }, Vec::new()))+ } else if tool == Tool::Crop+ && (crate::crop_ui::turns_at(app, p)+ || app.ui.crop_rect.is_some_and(|r| crate::crop_ui::hit_turned(r, crate::crop_ui::angle(app), p, tol) == crate::crop_ui::Hit::Inside))+ {+ // Turning the frame, or moving a turned one (its edges don't line up with anything): no+ // snapping.+ None} else if is_point_tool(tool) {Some((Gesture::Point, Vec::new()))} else {diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rsindex e1c1b5528..6814cac83 100644--- a/crates/ui-egui/src/state.rs+++ b/crates/ui-egui/src/state.rs@@ -929,6 +929,10 @@ pub struct UiState {/// Crop tool rectangle being edited [x0, y0, x1, y1] (document coordinates).#[serde(default)]pub crop_rect: Option<[f64; 4]>,+ /// The crop frame's turn in degrees, clockwise on screen about its centre (`crop_rect` is the+ /// frame before the turn); 0 when upright. Committing passes it as `image.crop`'s `angle`.+ #[serde(default)]+ pub crop_angle: f64,pub next_id: u64,/// Last status message (errors from commands, hints).pub status: String,@@ -1006,6 +1010,7 @@ impl Default for UiState {polygon_mode: String::new(),magnetic: Default::default(),crop_rect: None,+ crop_angle: 0.0,next_id: 1,status: String::new(),status_error: false,diff --git a/docs/roadmap.md b/docs/roadmap.mdindex 8cae1974d..fc5612c09 100644--- a/docs/roadmap.md+++ b/docs/roadmap.md@@ -81,7 +81,7 @@ Confidence: moderate — the next users of 0.2.x will move these numbers either| Smart filters / text / effect shapes in PSDs | Measured on our Photoshop-authored set (https://github.com/storytold/photocraft-corpus, `corpus/photoshop`, 258 files): see the per-group floors in `crates/io/tests/corpus.rs` and `crates/engine/tests/photoshop_oracles.rs`. Smart objects and smart filters now survive PSD save and open (41 corpus files, 206 smart objects, round trip strict; Photoshop opens our exports with live filters); re-rendering Photoshop's smart filters with ours matches 5/30 (was 1/30) | low–medium | Remaining re-render gaps are filter maths (Gaussian/Motion Blur, Unsharp Mask, Emboss, Add Noise RNG) and bicubic placement. || Core editing (layers, masks, selections, adjustments, filters, transforms) | Broad engine coverage; many interaction bugs fixed after 0.2.0 (adjustment dialogs, Curves, crop, Move/Transform modifiers, gesture origin) | medium | Fixes not yet user-validated. || UI / UX polish | Shortcut audit 214 → 0 failures; dock, Layers rows and menus reworked; first visual-QA sweep found 14 defects (#147–#157). 2026-10-07: the keyboard-only shortcuts with no menu item (⌥[ ⌥] ⌥, ⌥. layer navigation, ⇧⌥[ ⇧⌥] to extend the selection, 1–0 for opacity and ⇧ for flow or fill, ⇧[ ⇧] hardness, ⌥⌘T to transform a copy and ⌥⇧⌘T to step and repeat), ⌥-click colour sampling with painting tools, double-click a Layers row for Layer Style, File › New from Clipboard, a centred main window and remembered Liquify settings (#352, #417, #350, #368, #419, #418) | low–medium | Needs recurring visual QA with realistic documents. |-| Tools | 2026-10-09: Pencil, Mixer Brush, Patch, Content-Aware Move, Vertical Type, Pattern Stamp and Rotate View are toolbar tools. Remaining missing tools include Red Eye, Art History Brush, Freeform/Curvature Pen, Add/Delete Anchor Point tools, single row/column marquee, Color Sampler, Perspective Crop, type masks and Frame | low–medium | Patch has a live healing preview. Content-Aware Move is partial: Move/Extend, Structure/Color and Sample All Layers exist; Transform On Drop and a live result preview remain missing (`TOOL-213-4` in the scorecard). Magic/Background Eraser added; live gradients in progress (#180). Magnetic Lasso added 2026-10-08 (live-wire edge tracing, Width/Contrast/Frequency, `select.magneticLasso`). Pattern Stamp added 2026-10-08 (S flyout, `paint.patternStamp`, Aligned / Impressionist). Rotate View (2026-10-09) turns the canvas camera around its centre without rewriting pixels; Reset View and Match Rotation copy the angle. |+| Tools | 2026-10-09: Pencil, Mixer Brush, Patch, Content-Aware Move, Vertical Type, Pattern Stamp and Rotate View are toolbar tools. Remaining missing tools include Red Eye, Art History Brush, Freeform/Curvature Pen, Add/Delete Anchor Point tools, single row/column marquee, Color Sampler, Perspective Crop, type masks and Frame | low–medium | Patch has a live healing preview. Content-Aware Move is partial: Move/Extend, Structure/Color and Sample All Layers exist; Transform On Drop and a live result preview remain missing (`TOOL-213-4` in the scorecard). Magic/Background Eraser added; live gradients in progress (#180). Magnetic Lasso added 2026-10-08 (live-wire edge tracing, Width/Contrast/Frequency, `select.magneticLasso`). Pattern Stamp added 2026-10-08 (S flyout, `paint.patternStamp`, Aligned / Impressionist). Rotate View (2026-10-09) turns the canvas camera around its centre without rewriting pixels; Reset View and Match Rotation copy the angle. Crop rotation (2026-10-09, #1792): dragging outside the crop frame turns it (⇧ 15° steps, angle readout), and ↵ rotates the document and crops in one undo step (`image.crop` `angle`); the frame turns over the image as in Photoshop's Classic Mode, and the options-bar Straighten is still missing. || Painting | Brush model and Brush Settings panel near Photoshop; .abr/.grd import; persistent presets; pen pressure/tilt on Windows, web, macOS and X11 | medium | Native Wayland pen input open (#79; a pen opens the window through Xwayland meanwhile); X11 pressure confirmed by a user, macOS not yet verified on tablet hardware. || Text / typography | Engine works; caret placement and size editing fixed; OpenType features, text-on-path editing, composer parity partial | medium-low | Measure with the Photoshop-authored set. || Colour management | Colour-managed canvas (document → monitor), embedded CMYK profiles, linear EXR/HDR, 16-bit float canvas | medium-high | Monitor profile follows only at launch. |diff --git a/docs/scorecard.md b/docs/scorecard.mdindex 10d41ba2c..9d43c31e4 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) | 12 | 14 | 8 | |+| [Tools](#tools) | 13 | 14 | 8 | || [Workspace and UI](#workspace-and-ui) | 4 | 7 | 12 | settings that do nothing: 55 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-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 |## Workspace and UIdiff --git a/scorecard/tools.toml b/scorecard/tools.tomlindex 745040b64..0e43cb37a 100644--- a/scorecard/tools.toml+++ b/scorecard/tools.toml@@ -242,3 +242,10 @@ target = "Eyedropper Sample Size (Point, 3×3 … 101×101 Average), Sample layestatus = "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-18"+target = "Crop: drag outside the frame to rotate it (Shift 15 deg steps, angle readout); Enter rotates and crops in one step"+status = "done"+issue = 1792+note = "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"