From 225ccc0db131fb35ac89fbaeb3552caf2a2dc688 Mon Sep 17 00:00:00 2001 From: David Mann Date: Sat, 10 Oct 2026 20:14:19 +0200 Subject: [PATCH] Crop tool: Photoshop's default mode turns the image behind an upright box; Use Classic Mode (P), Auto Center Preview (#1919) (#2545) * Crop tool: Photoshop's default mode turns the image behind an upright box; Use Classic Mode (P), Auto Center Preview (#1919) The Crop tool's gear menu gets Use Classic Mode (P toggles it while the tool shows a box; off by default, as in Photoshop) and Auto Center Preview (on by default). In the default mode the box stays upright on screen: a drag outside it turns the image about the box's centre (Shift 15 deg steps, angle readout), a drag inside moves the image under the box, the arrow keys nudge the image, Straighten turns the image so the line is level, and with Auto Center Preview a drawn or resized box is re-centred in the canvas. Classic Mode is the previous behaviour. The crop model and the commit are shared: crop_rect + crop_angle and one image.crop {angle}. crop_mode.rs only drives the view: while a frame is edited the view's rotation is -crop_angle, pivoting so the box (or the pressed point) stays put, and the user's view (a Rotate View turn, its centre) is put back on commit, cancel, leaving the tool or switching to Classic Mode. The untouched default frame leaves an R turn alone. The options live in ToolOptions.crop_shield (classic_mode, auto_center_preview; ui.set cropShield). ui.pointer reads a default-mode drag's points in the view at its press, so an up where the last move was is idempotent. Co-Authored-By: Claude Opus 5.5 (1M context) * Crop default mode: match Photoshop (view upright on tool pick, live Auto Center, image-turn readout, gear menu order) (#1919) Checked by hand against Photoshop in its default (non-classic) mode: - Picking the Crop tool turns a Rotate View (R) turn upright at once (about the view centre), and the view stays upright after Enter or Esc: the save/restore of the user's view is gone. Classic Mode still leaves the view alone (not checked against Photoshop). - The angle beside the pointer while the image turns is the image's turn, clockwise positive. - Auto Center Preview keeps a box being resized centred live: the handle follows the pointer, the box grows on both sides, and on the image the opposite edge (with Alt the centre) stays put. Computed from the press, so the view following the frame can't feed back into the drag. - Gear menu order as Photoshop's: Use Classic Mode (P), Show Cropped Area (H), Auto Center Preview, no separator; Classic Mode greys out the other two. Show Cropped Area then acts as on and H does nothing (the stored choice is kept). German: Classic-Modus verwenden, Automatische zentrierte Vorschau. - Crop preview past the canvas in a turned view: each band is drawn as its turned quad (the screen bounding box stretched band textures and spread the checkerboard). The white corners in the earlier offscreen snapshot were egui_kittest clamping the repeating checker texture; the real app shows the checkerboard in both modes. Co-Authored-By: Claude Opus 5.5 (1M context) * docs: regenerate scorecard for the crop default-mode row (#1919) Co-Authored-By: Claude Opus 5.5 (1M context) * Crop default mode: the canvas keeps the view the Crop tool moves; a move starts from a centred box (#1919) Tried by hand in the app: with Auto Center Preview on, a drag inside the box made the box wander instead of moving the image, and a handle drag didn't keep the box's centre in place (after a Space pan, too). Root cause: canvas_view works on a copy of the view for the frame and writes it back at the end, so every camera change the Crop tool made during the frame (the image moving with the pointer, the live-centred resize, Auto Center on release, the pivot while turning) was undone, while the frame itself moved in the document. Tests driving tool_event never saw it. - canvas_view notes the camera before the frame's input and, before writing its copy back, keeps a centre or rotation a tool changed meanwhile. - With Auto Center Preview a move inside an off-centre box (after a pan) centres the box first, then grabs the image point now under the pointer. - New tests/crop_default_mode.rs drives the full app UI with egui pointer and key events over several frames (offscreen wgpu): the box stays put while the image follows the pointer, and a resize after a Space pan keeps the box's centre fixed while the handle follows the pointer. Both failed before the fix. Co-Authored-By: Claude Opus 5.5 (1M context) * Crop default mode: a moved or resized box stays where it is on screen (#1919) Checked in Photoshop: after a Space (Hand) pan the box isn't snapped back to the middle of the canvas. A drag inside moves only the image, the box staying wherever it is; a resize keeps the box's centre where it was at the press (also after a pan), and its release no longer pans the box to the middle. Auto Center Preview still centres a newly drawn box on release and X still re-centres. Classic Mode is unchanged. Co-Authored-By: Claude Opus 5.5 (1M context) * Crop tool: Classic Mode turns a Rotate View turn upright too (#1919) Checked in Photoshop: with Classic Mode on and the view turned with Rotate View (R), picking the Crop tool also turns the view upright, and the crop frame stays on the same image area. So the Crop tool now drives the camera in both modes: default mode keeps it at -crop_angle (the box upright), Classic Mode at 0 with the frame drawn with its own turn. Picking the tool pivots about the view centre; commit and cancel leave the view upright in both modes, and P switching modes never brings the R turn back. Auto Center Preview stays default-mode only. Co-Authored-By: Claude Opus 5.5 (1M context) * Regenerate the scorecard; update the crop test's header Co-Authored-By: Claude Opus 5.5 * Crop: snap a new box's corner inside the untouched default frame in both modes (#2549 with #2545) Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 (1M context) Co-authored-by: Brandon Thomas --- crates/automation/src/server.rs | 4 +- crates/ui-egui/src/canvas.rs | 61 +- crates/ui-egui/src/control.rs | 13 + crates/ui-egui/src/crop_mode.rs | 772 +++++++++++++++++++++ crates/ui-egui/src/crop_shield.rs | 66 +- crates/ui-egui/src/crop_straighten.rs | 9 +- crates/ui-egui/src/crop_ui.rs | 147 +++- crates/ui-egui/src/i18n/cs.tsv | 2 + crates/ui-egui/src/i18n/de.tsv | 2 + crates/ui-egui/src/i18n/el.tsv | 2 + crates/ui-egui/src/i18n/es.tsv | 2 + crates/ui-egui/src/i18n/fr.tsv | 2 + crates/ui-egui/src/i18n/id.tsv | 2 + crates/ui-egui/src/i18n/it.tsv | 2 + crates/ui-egui/src/i18n/ja.tsv | 2 + crates/ui-egui/src/i18n/ko.tsv | 2 + crates/ui-egui/src/i18n/nl.tsv | 2 + crates/ui-egui/src/i18n/pl.tsv | 2 + crates/ui-egui/src/i18n/pt-br.tsv | 2 + crates/ui-egui/src/i18n/ru.tsv | 2 + crates/ui-egui/src/i18n/uk.tsv | 2 + crates/ui-egui/src/i18n/zh-hans.tsv | 2 + crates/ui-egui/src/i18n/zh-hant.tsv | 2 + crates/ui-egui/src/lib.rs | 1 + crates/ui-egui/src/snap_ui.rs | 22 +- crates/ui-egui/tests/crop_beyond_canvas.rs | 4 +- crates/ui-egui/tests/crop_default_mode.rs | 161 +++++ docs/control-protocol.md | 4 +- docs/scorecard.md | 7 +- scorecard/tools.toml | 11 +- 30 files changed, 1259 insertions(+), 55 deletions(-) create mode 100644 crates/ui-egui/src/crop_mode.rs create mode 100644 crates/ui-egui/tests/crop_default_mode.rs diff --git a/crates/automation/src/server.rs b/crates/automation/src/server.rs index 634b645ead..191de20b5e 100644 --- a/crates/automation/src/server.rs +++ b/crates/automation/src/server.rs @@ -239,8 +239,8 @@ pub struct UiSetParams { /// allNoAdjustments, currentAndBelowNoAdjustments), eyedropperRing (bool), cropOverlay (thirds, /// grid, diagonal, triangle, goldenRatio, goldenSpiral), cropOverlayShow (auto, always, never), /// cropOverlayOrientation (0..3), cropShield (an object patching show_cropped_area, enabled, - /// color ("matchCanvas" or "custom"), custom_color ([r, g, b]), opacity (0..100) and - /// auto_adjust), shapeStroke (an object patching width, align, cap, join, miterLimit, + /// color ("matchCanvas" or "custom"), custom_color ([r, g, b]), opacity (0..100), + /// auto_adjust, classic_mode and auto_center_preview), shapeStroke (an object patching width, align, cap, join, miterLimit, /// dashes, dashOffset and opacity; null disables the stroke). Shape stroke fields use /// `shape.edit` names and units; colour comes from `tools.setColors`. Other fields are an error. pub fields: Value, diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index a18d847178..ea212ef22b 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -2183,6 +2183,11 @@ fn hdr_preview(app: &PhotocraftApp, doc: &photocraft_doc::Document) -> Option<[f /// Draw one canvas view and handle its input. `primary` = main window (tools active). pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect: Rect, mut view: View, primary: bool) -> View { let ctx = ui.ctx().clone(); + // The camera as the app holds it before this frame's input. The canvas works on its own copy + // (`view`) and writes it back at the end; a tool that moves the camera itself meanwhile (the + // Crop tool's default mode pans and turns the view with the image, `crop_mode`) must not be + // undone by that write-back. + let camera = if primary { app.ui.views.get(idx).map(|v| (v.center, v.rotation)) } else { None }; // `View::zoom` is device pixels per document pixel; this canvas's geometry is in its own // viewport's egui points. A document window can sit on another display with a different // scale, so only the primary canvas records `app.ppp` for the frame's shared helpers @@ -3054,6 +3059,17 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect: } crate::rotate_view::overlay(app, &ctx, &painter, &xf, &mut view, &response); if primary { + // The camera the tools set this frame wins over the copy's. + if let (Some((center, rotation)), Some(now)) = (camera, app.ui.views.get(idx)) { + if now.center != center { + view.center = now.center; + ctx.request_repaint(); + } + if now.rotation != rotation { + view.rotation = now.rotation; + ctx.request_repaint(); + } + } app.ui.views[idx] = view.clone(); } view @@ -3341,11 +3357,26 @@ fn draw_beyond_canvas(app: &mut PhotocraftApp, painter: &egui::Painter, xf: &Vie let square = app.session.prefs().transparency_and_gamut.square(); let checker_id = square.map(|_| checker(app, &ctx)); let around = ring(c.extent.union(&fr), doc.bounds()); + // A turned view (Rotate View, or the Crop tool's default mode turning the image behind its + // box) draws each band as its turned quad: its screen bounding box would stretch the band's + // texture and spread the checkerboard past the band. + let turned = xf.rotation != 0.0; + let checker_uv = |p: Pos2, sq: f32| ((p - canvas.min) / (2.0 * sq)).to_pos2(); for &b in &around { + if turned { + let q = doc_quad(xf, b); + match square.zip(checker_id) { + Some((sq, id)) => textured_quad(painter, id, q, q.map(|p| checker_uv(p, sq))), + None => { + painter.add(egui::Shape::convex_polygon(q.to_vec(), Color32::WHITE, Stroke::NONE)); + } + } + continue; + } let r = under_canvas(xf.doc_rect(b), canvas); match square.zip(checker_id) { Some((sq, id)) => { - let uv = Rect::from_min_max(((r.min - canvas.min) / (2.0 * sq)).to_pos2(), ((r.max - canvas.min) / (2.0 * sq)).to_pos2()); + let uv = Rect::from_min_max(checker_uv(r.min, sq), checker_uv(r.max, sq)); painter.image(id, r, uv, Color32::WHITE); } None => { @@ -3356,6 +3387,12 @@ fn draw_beyond_canvas(app: &mut PhotocraftApp, painter: &egui::Painter, xf: &Vie for (b, t, tex) in &c.bands { let part = |a: i32, o: i32, len: u32| (i64::from(a) - i64::from(o)) as f32 / len.max(1) as f32; let (mut u0, mut u1) = (part(b.x0, t.x0, t.width()), part(b.x1, t.x0, t.width())); + if turned { + // The quad's corners are the band's own (flip included), so no swap. + let (v0, v1) = (part(b.y0, t.y0, t.height()), part(b.y1, t.y0, t.height())); + textured_quad(painter, tex.id(), doc_quad(xf, *b), [pos2(u0, v0), pos2(u1, v0), pos2(u1, v1), pos2(u0, v1)]); + continue; + } if xf.flip { (u0, u1) = (u1, u0); } @@ -3368,6 +3405,26 @@ fn draw_beyond_canvas(app: &mut PhotocraftApp, painter: &egui::Painter, xf: &Vie !around.is_empty() } +/// Document rect `b`'s corners on screen, clockwise from its top-left (a parallelogram in a turned +/// view). +fn doc_quad(xf: &ViewXform, b: DRect) -> [Pos2; 4] { + [(b.x0, b.y0), (b.x1, b.y0), (b.x1, b.y1), (b.x0, b.y1)].map(|(x, y)| xf.to_screen(x as f32, y as f32)) +} + +/// Texture `tex` drawn over the quad `q`, `uv` at its corners. +fn textured_quad(painter: &egui::Painter, tex: egui::TextureId, q: [Pos2; 4], uv: [Pos2; 4]) { + if !q.iter().chain(uv.iter()).all(|p| p.x.is_finite() && p.y.is_finite()) { + return; + } + let mut mesh = egui::Mesh::with_texture(tex); + for (pos, uv) in q.into_iter().zip(uv) { + mesh.vertices.push(egui::epaint::Vertex { pos, uv, color: Color32::WHITE }); + } + mesh.add_triangle(0, 1, 2); + mesh.add_triangle(0, 2, 3); + painter.add(egui::Shape::mesh(mesh)); +} + /// Overlays that persist between gestures: polygonal or magnetic lasso in progress, pending crop box. fn draw_tool_state(app: &PhotocraftApp, painter: &egui::Painter, xf: &ViewXform, hover: Option) { crate::magnetic_lasso_ui::draw(app, painter, xf, hover); @@ -4346,6 +4403,8 @@ pub fn commit_crop(app: &mut PhotocraftApp) { // Never another document's frame (#1918). crate::crop_ui::cancel_stale(app); let Some(r) = app.ui.crop_rect.take() else { return }; + // The crop's default mode leaves the view upright (`crop_mode`). + crate::crop_mode::upright(app); // The untouched default frame around the whole canvas crops nothing (Photoshop's ↵ on it does // nothing); one framing the selection's bounds crops to them (#1789). if std::mem::take(&mut app.crop.default_frame) { diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs index 889426960d..357e99cd38 100644 --- a/crates/ui-egui/src/control.rs +++ b/crates/ui-egui/src/control.rs @@ -846,6 +846,19 @@ fn dispatch(app: &mut PhotocraftApp, ctx: &egui::Context, req: &ControlRequest) if let Some(d) = app.drag.as_mut().filter(|d| crate::hold_keys::repositions(d.tool)) { d.reposition = space; } + // A Crop drag in the default mode turns and pans the view with the image: its + // points are read as the view showed them at the press (`crop_mode`). + let ev = match ev { + ToolEvent::Move { x, y, pressure } => { + let [x, y] = crate::crop_mode::control_point(app, [x, y]); + ToolEvent::Move { x, y, pressure } + } + ToolEvent::Up { x, y } => { + let [x, y] = crate::crop_mode::control_point(app, [x, y]); + ToolEvent::Up { x, y } + } + down => down, + }; tool_event(app, ev, mods); } app.stylus.feed.set(None); diff --git a/crates/ui-egui/src/crop_mode.rs b/crates/ui-egui/src/crop_mode.rs new file mode 100644 index 0000000000..bf14dbcbe2 --- /dev/null +++ b/crates/ui-egui/src/crop_mode.rs @@ -0,0 +1,772 @@ +//! The Crop tool's two modes (Photoshop's gear menu, "Set additional Crop options", #1919). +//! +//! - **Default mode** (Photoshop's default, Use Classic Mode off): the crop box stays upright on +//! screen and the image turns behind it. A drag outside the box turns the image about the box's +//! centre (⇧ in 15° steps; the readout beside the pointer is the image's turn, clockwise +//! positive), a drag inside moves the image under the box (the box stays put), the arrow keys +//! nudge the image, and the handles resize the box on screen as usual. With **Auto Center +//! Preview** on (the default), a box being resized keeps its centre where it is on screen (also +//! after a Space pan) while the handle follows the pointer, a drawn box moves to the middle of +//! the canvas on release, and X re-centres it. A drag inside never re-centres the box +//! (Photoshop 25.1). +//! - **Classic Mode** (P toggles it while the Crop tool shows a box): the box moves and turns over +//! a fixed image (`crop_ui`). Show Cropped Area and Auto Center Preview are greyed out in it, and +//! the area outside the box shows whatever Show Cropped Area says (Photoshop 25.1). +//! +//! The crop model is the same in both: `UiState::crop_rect` is the frame in document px and +//! `UiState::crop_angle` its turn, so ↵ commits the same `image.crop {…, angle}` (one undo step) +//! whichever mode drew it. Default mode only changes the view: while the Crop tool shows a frame, +//! the view's camera rotation is the frame's turn undone (`View::rotation = -crop_angle`), so the +//! box shows upright. In Classic Mode the camera is upright (rotation 0) and the frame shows with +//! its own turn on the image. As in Photoshop 25.1, picking the tool in either mode turns a Rotate +//! View (R) turn upright at once, about the view's centre (the frame stays on the same image +//! area), and the view stays upright after ↵ or Esc and when P switches modes (the R turn isn't +//! restored). +//! +//! Both options live in `ToolOptions::crop_shield` (`classic_mode`, `auto_center_preview`), which +//! `ui.inspect` reports and `ui.set {cropShield: {...}}` patches. + +use egui::{Rect, vec2}; + +use crate::PhotocraftApp; +use crate::canvas::ViewXform; +use crate::state::Tool; + +/// Use Classic Mode is on: the box turns and moves over the image. +pub fn classic(app: &PhotocraftApp) -> bool { + app.ui.tool_options.crop_shield.classic_mode +} + +fn finite_frame(app: &PhotocraftApp) -> Option<[f64; 4]> { + app.ui.crop_rect.filter(|r| r.iter().all(|v| v.is_finite())) +} + +/// The Crop tool drives the view: it shows a frame (either mode; [`sync`]). +pub fn turns_view(app: &PhotocraftApp) -> bool { + app.ui.tool == Tool::Crop && finite_frame(app).is_some() && app.session.active().is_some() +} + +/// Gestures move and turn the image rather than the box (default mode with the Crop tool). +pub fn moves_image(app: &PhotocraftApp) -> bool { + app.ui.tool == Tool::Crop && !classic(app) +} + +/// The view centre that keeps document point `c` where it is on screen when the camera rotation +/// goes from `from` to `to` degrees (zoom and flip unchanged). `center` itself when anything isn't +/// finite. +pub fn pivot_center(center: [f32; 2], c: [f64; 2], from: f32, to: f32, flip: bool) -> [f32; 2] { + let a = ViewXform { rect: Rect::ZERO, zoom: 1.0, center, flip, rotation: from }; + // c's offset from the view centre on screen (at zoom 1), then the same offset in the new view. + let off = a.to_screen(c[0] as f32, c[1] as f32).to_vec2(); + let u = ViewXform { rotation: to, ..a }.unmap_vec(off); + let n = [c[0] as f32 - u.x, c[1] as f32 - u.y]; + if n.iter().all(|v| v.is_finite()) { n } else { center } +} + +/// The active document's view rotation in degrees (0 without a view). +pub fn view_rotation(app: &PhotocraftApp) -> f32 { + app.session.active_index().and_then(|i| app.ui.views.get(i)).map_or(0.0, |v| v.rotation) +} + +/// Turns the active view so the frame shows upright while default mode drives it, pivoting about +/// document point `pivot` so that point stays put on screen (the view's own centre when `None`: +/// picking the tool, a commit or a cancel only straighten the view). +pub fn sync(app: &mut PhotocraftApp, pivot: Option<[f64; 2]>) { + if !turns_view(app) { + return; + } + let Some(i) = app.session.active_index() else { return }; + // Classic Mode: an upright camera, the frame turned on it. Default mode: the frame upright. + let want = if classic(app) { 0.0 } else { crate::rotate_view::wrap_deg(-crate::crop_ui::angle(app) as f32) }; + let flip = app.ui.view.flip_horizontal; + let Some(v) = app.ui.views.get_mut(i) else { return }; + if v.rotation != want { + if let Some(p) = pivot.filter(|p| p.iter().all(|v| v.is_finite())) { + v.center = pivot_center(v.center, p, v.rotation, want, flip); + } + v.rotation = want; + } +} + +/// [`sync`] about the frame's centre: the box stays put on screen while the image turns. +pub fn sync_frame(app: &mut PhotocraftApp) { + let c = finite_frame(app).map(crate::crop_ui::center); + sync(app, c); +} + +/// A commit or cancel in default mode: the view is left upright (Photoshop 25.1 doesn't bring +/// back a Rotate View turn). +pub fn upright(app: &mut PhotocraftApp) { + if app.ui.tool != Tool::Crop { + return; + } + if let Some(v) = app.session.active_index().and_then(|i| app.ui.views.get_mut(i)) { + v.rotation = 0.0; + } +} + +/// The image's turn the default mode shows beside the pointer: clockwise on screen is positive, +/// the frame's angle on the image undone. +pub fn image_turn(frame_angle: f64) -> f64 { + let a = crate::crop_ui::normalized_angle(-frame_angle); + // Never "-0.0°". + if a == 0.0 { 0.0 } else { a } +} + +/// A live-centred resize ([`live_resize`]): the frame `rect` and handle (`hx`, `hy`) at the press, +/// grabbed at document point `start`; the pointer now at `q` (in the press view); the frame's turn +/// `deg`, the aspect `ratio` to hold and ⌥ (resize about the centre). +#[derive(Clone, Copy, Debug)] +pub struct LiveResize { + pub rect: [f64; 4], + pub deg: f64, + pub hx: i8, + pub hy: i8, + pub start: [f64; 2], + pub q: [f64; 2], + pub ratio: Option, + pub alt: bool, +} + +/// Auto Center Preview during a handle drag: the box stays centred on screen where it was at the +/// press and grows or shrinks symmetrically there, so the handle stays under the pointer, while on +/// the image the opposite edge stays put (the centre with ⌥), as in a plain resize. Everything is +/// computed from the press, so the view following the frame can't feed back into the drag. +pub fn live_resize(app: &mut PhotocraftApp, g: LiveResize, press: PressView) { + let LiveResize { rect, deg, hx, hy, start, q, ratio, alt } = g; + let c0 = crate::crop_ui::center(rect); + let (w0, h0) = (rect[2] - rect[0], rect[3] - rect[1]); + // The pointer's offset from where it grabbed the handle, in the frame's own axes; the handle + // moves by it on screen, so each half extent grows by it. + let d = crate::crop_ui::turn([q[0] - start[0], q[1] - start[1]], [0.0, 0.0], -deg); + let local = [-w0 / 2.0, -h0 / 2.0, w0 / 2.0, h0 / 2.0]; + let n = crate::crop_ui::resized(local, hx, hy, d, ratio, true); + let (w1, h1) = (n[2] - n[0], n[3] - n[1]); + // On the image the opposite edge stays put (with ⌥ the centre), so the centre moves. + let shift = if alt { [0.0, 0.0] } else { [f64::from(hx) * (w1 - w0) / 2.0, f64::from(hy) * (h1 - h0) / 2.0] }; + let s = crate::crop_ui::turn(shift, [0.0, 0.0], deg); + let c1 = [c0[0] + s[0], c0[1] + s[1]]; + let f = [c1[0] - w1 / 2.0, c1[1] - h1 / 2.0, c1[0] + w1 / 2.0, c1[1] + h1 / 2.0]; + if !f.iter().all(|v| v.is_finite()) { + return; + } + app.ui.crop_rect = Some(f); + // The view follows the centre, so the box stays where it was on screen. + if let Some(v) = app.session.active_index().and_then(|i| app.ui.views.get_mut(i)) { + let c = [press.center[0] + s[0] as f32, press.center[1] + s[1] as f32]; + if c.iter().all(|x| x.is_finite()) { + v.center = c; + } + } +} + +/// Auto Center Preview while a handle is dragged in default mode. +pub fn live_center(app: &PhotocraftApp) -> bool { + moves_image(app) && app.ui.tool_options.crop_shield.auto_center_preview +} + +/// Moves the image under the box by document vector `d` as the view shows it: the frame moves by +/// `-d` in the document and the view with it, so the box stays put on screen. +pub fn shift_image(app: &mut PhotocraftApp, d: [f64; 2]) { + let Some(r) = finite_frame(app) else { return }; + if !(d[0].is_finite() && d[1].is_finite()) { + return; + } + let n = [r[0] - d[0], r[1] - d[1], r[2] - d[0], r[3] - d[1]]; + if !n.iter().all(|v| v.is_finite()) { + return; + } + app.ui.crop_rect = Some(n); + if let Some(v) = app.session.active_index().and_then(|i| app.ui.views.get_mut(i)) { + let c = [v.center[0] - d[0] as f32, v.center[1] - d[1] as f32]; + if c.iter().all(|x| x.is_finite()) { + v.center = c; + } + } +} + +/// The active view's camera (rotation and centre) when a default-mode drag began: the drag reads +/// its points in it, so it doesn't matter that the view turns and pans with the image meanwhile. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct PressView { + rotation: f32, + center: [f32; 2], +} + +/// The active view's camera now. +pub fn press_view(app: &PhotocraftApp) -> Option { + app.session.active_index().and_then(|i| app.ui.views.get(i)).map(|v| PressView { rotation: v.rotation, center: v.center }) +} + +/// Document point `p` as seen through camera `from` re-read through camera `to`: the point that +/// `to` shows at the screen position where `from` shows `p` (zoom and flip are the same). `p` +/// itself when anything isn't finite. +fn remap(p: [f64; 2], from: PressView, to: PressView, flip: bool) -> [f64; 2] { + let at = |v: PressView| ViewXform { rect: Rect::ZERO, zoom: 1.0, center: v.center, flip, rotation: v.rotation }; + let q = at(to).to_doc(at(from).to_screen(p[0] as f32, p[1] as f32)); + if q.iter().all(|v| v.is_finite()) { q } else { p } +} + +/// A pointer point `p` the canvas mapped through the view as it is now, read in the press-time +/// view `press` (unchanged without one). +pub fn to_press(app: &PhotocraftApp, press: Option, p: [f64; 2]) -> [f64; 2] { + match (press, press_view(app)) { + (Some(press), Some(now)) => remap(p, now, press, app.ui.view.flip_horizontal), + _ => p, + } +} + +/// The control channel's `ui.pointer` gives document points as the view showed them at the press +/// (it can't know how the view turns and pans with the image): during a default-mode drag, the +/// point the canvas would report for the same screen position now. +pub fn control_point(app: &PhotocraftApp, p: [f64; 2]) -> [f64; 2] { + let press = match app.crop.drag { + Some( + crate::crop_ui::CropDrag::MoveImage { view, .. } | crate::crop_ui::CropDrag::TurnImage { view, .. } | crate::crop_ui::CropDrag::Resize { view, .. }, + ) => view, + _ => None, + }; + match (press, press_view(app)) { + (Some(press), Some(now)) if app.ui.tool == Tool::Crop => remap(p, press, now, app.ui.view.flip_horizontal), + _ => p, + } +} + +/// A default-mode drag inside the box: the image has moved by document vector `d` (in the press +/// view) since the press, when the frame was `rect` and the view `press`. The frame moves by `-d` +/// on the image and the view's centre with it, so the box stays put on screen. +pub fn offset_image(app: &mut PhotocraftApp, rect: [f64; 4], press: Option, d: [f64; 2]) { + let n = [rect[0] - d[0], rect[1] - d[1], rect[2] - d[0], rect[3] - d[1]]; + if !n.iter().all(|v| v.is_finite()) { + return; + } + app.ui.crop_rect = Some(n); + let (Some(press), Some(v)) = (press, app.session.active_index().and_then(|i| app.ui.views.get_mut(i))) else { return }; + let c = [press.center[0] - d[0] as f32, press.center[1] - d[1] as f32]; + if c.iter().all(|x| x.is_finite()) { + v.center = c; + } +} + +/// A screen vector `s` (points, at the current zoom ignored) as a document vector of the same +/// length: undoes the view's flip and rotation. +pub fn screen_to_doc_vec(app: &PhotocraftApp, s: [f64; 2]) -> [f64; 2] { + let xf = ViewXform { rect: Rect::ZERO, zoom: 1.0, center: [0.0, 0.0], flip: app.ui.view.flip_horizontal, rotation: view_rotation(app) }; + let u = xf.unmap_vec(vec2(s[0] as f32, s[1] as f32)); + [f64::from(u.x), f64::from(u.y)] +} + +/// Auto Center Preview: in default mode, pans the view so the box sits in the middle of the canvas +/// (the view turns about its centre, so the box stays upright). +pub fn auto_center(app: &mut PhotocraftApp) { + if !turns_view(app) || classic(app) || !app.ui.tool_options.crop_shield.auto_center_preview { + return; + } + let Some(c) = finite_frame(app).map(crate::crop_ui::center) else { return }; + let c = [c[0] as f32, c[1] as f32]; + if let (Some(v), true) = (app.session.active_index().and_then(|i| app.ui.views.get_mut(i)), c.iter().all(|x| x.is_finite())) { + v.center = c; + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::canvas::{ToolEvent, tool_event}; + use crate::crop_ui::{CropDrag, corners}; + use egui::{Modifiers, Pos2, pos2}; + use photocraft_doc::{Color, ColorMode, Document, SampleType, Size}; + use serde_json::json; + + const NONE: Modifiers = Modifiers::NONE; + + /// A 200 × 100 document in a 800 × 600 canvas at 100 %, centred, the Crop tool in default mode. + fn app() -> PhotocraftApp { + let doc = Document::with_background("crop", Size::new(200, 100), ColorMode::Rgb, SampleType::U8, Color::WHITE); + let mut s = photocraft_engine::Session::new(); + s.add_document(doc, None); + let mut app = PhotocraftApp::new(s, crate::Services::default()); + app.sync_views(); + app.ui.tool = Tool::Crop; + app.ui.extras.snap = false; + app.ui.extras.rulers = false; + app.ui.view.show.smart_guides = false; + app.last_canvas_rect = Rect::from_min_size(Pos2::ZERO, vec2(800.0, 600.0)); + let v = &mut app.ui.views[0]; + (v.zoom, v.center, v.fit_pending, v.rotation) = (1.0, [100.0, 50.0], false, 0.0); + assert!(!classic(&app), "Photoshop's default mode is the default"); + app + } + + fn xf(app: &PhotocraftApp) -> ViewXform { + ViewXform::active(app).unwrap() + } + + /// A drag through screen points, each mapped through the view as it is at that moment (as the + /// canvas does every frame). + fn screen_drag(app: &mut PhotocraftApp, pts: &[Pos2], mods: Modifiers) { + let at = |app: &PhotocraftApp, p: Pos2| xf(app).to_doc(p); + let d = at(app, pts[0]); + tool_event(app, ToolEvent::Down { x: d[0], y: d[1], pressure: 1.0 }, mods); + for p in &pts[1..] { + let d = at(app, *p); + tool_event(app, ToolEvent::Move { x: d[0], y: d[1], pressure: 1.0 }, mods); + } + let d = at(app, pts[pts.len() - 1]); + tool_event(app, ToolEvent::Up { x: d[0], y: d[1] }, mods); + } + + fn screen_box(app: &PhotocraftApp) -> [Pos2; 4] { + let x = xf(app); + corners(app.ui.crop_rect.unwrap(), crate::crop_ui::angle(app)).map(|p| x.to_screen(p[0] as f32, p[1] as f32)) + } + + fn assert_upright(q: [Pos2; 4]) { + let ok = (q[0].y - q[1].y).abs() < 0.01 && (q[2].y - q[3].y).abs() < 0.01 && (q[0].x - q[3].x).abs() < 0.01 && (q[1].x - q[2].x).abs() < 0.01; + assert!(ok && q[1].x > q[0].x && q[3].y > q[0].y, "not an upright box on screen: {q:?}"); + } + + fn close(a: [Pos2; 4], b: [Pos2; 4]) -> bool { + a.iter().zip(b).all(|(p, q)| p.distance(q) < 0.02) + } + + /// A real (not default) frame [40, 30, 100, 70], centred at (70, 50) = screen (370, 300). + fn with_frame(app: &mut PhotocraftApp) { + crate::crop_ui::ensure_frame(app); + app.ui.crop_rect = Some([40.0, 30.0, 100.0, 70.0]); + app.crop.default_frame = false; + } + + #[test] + fn dragging_outside_turns_the_image_and_the_box_stays_upright() { + let mut app = app(); + with_frame(&mut app); + let before = screen_box(&app); + // From straight right of the box centre to straight below it: a quarter turn clockwise + // on screen, so the image turns clockwise and the frame turns -90° on it. + screen_drag(&mut app, &[pos2(450.0, 300.0), pos2(440.0, 320.0), pos2(370.0, 380.0)], NONE); + assert!((crate::crop_ui::angle(&app) - -90.0).abs() < 0.01, "{}", app.ui.crop_angle); + assert!((view_rotation(&app) - 90.0).abs() < 0.01, "the view turned with it"); + assert_upright(screen_box(&app)); + assert!(close(screen_box(&app), before), "the box doesn't move on screen: {:?} vs {before:?}", screen_box(&app)); + assert_eq!(app.ui.crop_rect, Some([40.0, 30.0, 100.0, 70.0]), "turning keeps the frame"); + // ⇧ steps of 15°, still upright. + let a = 22.0f32.to_radians(); + screen_drag(&mut app, &[pos2(450.0, 300.0), pos2(370.0 + 80.0 * a.cos(), 300.0 + 80.0 * a.sin())], Modifiers::SHIFT); + assert!((crate::crop_ui::angle(&app) - -105.0).abs() < 0.01, "{}", app.ui.crop_angle); + assert_upright(screen_box(&app)); + assert!(close(screen_box(&app), before)); + assert!(crate::crop_ui::turning(&app).is_none()); + } + + /// Even with Auto Center Preview, a drag inside an off-centre box (after a pan, say) leaves the + /// box where it is on screen: only the image moves (Photoshop 25.1). + #[test] + fn a_move_never_recentres_the_box() { + let mut app = app(); + assert!(app.ui.tool_options.crop_shield.auto_center_preview); + with_frame(&mut app); + assert!(mid_of(screen_box(&app)).distance(pos2(370.0, 300.0)) < 0.01); + screen_drag(&mut app, &[pos2(370.0, 300.0), pos2(380.0, 300.0), pos2(390.0, 300.0)], NONE); + assert!(mid_of(screen_box(&app)).distance(pos2(370.0, 300.0)) < 0.01, "{:?}", mid_of(screen_box(&app))); + let r = app.ui.crop_rect.unwrap(); + assert!(r.iter().zip([20.0, 30.0, 80.0, 70.0]).all(|(a, b)| (a - b).abs() < 1e-3), "{r:?}"); + } + + fn mid_of(q: [Pos2; 4]) -> Pos2 { + pos2((q[0].x + q[2].x) / 2.0, (q[0].y + q[2].y) / 2.0) + } + + #[test] + fn dragging_inside_moves_the_image_under_the_box() { + let mut app = app(); + with_frame(&mut app); + let before = screen_box(&app); + screen_drag(&mut app, &[pos2(370.0, 300.0), pos2(380.0, 305.0), pos2(390.0, 310.0)], NONE); + // The image followed the pointer 20, 10 to the right and down: the frame lies that much + // further up-left on it. + let r = app.ui.crop_rect.unwrap(); + assert!(r.iter().zip([20.0, 20.0, 80.0, 60.0]).all(|(a, b)| (a - b).abs() < 1e-3), "{r:?}"); + assert!(close(screen_box(&app), before), "the box stays put on screen"); + // Turned 30° first: the move follows the pointer on screen, along the turned image. + screen_drag(&mut app, &[pos2(450.0, 300.0), pos2(370.0 + 80.0 * 30f32.to_radians().cos(), 300.0 + 80.0 * 30f32.to_radians().sin())], NONE); + assert!((crate::crop_ui::angle(&app) - -30.0).abs() < 0.01); + let (before, c0) = (screen_box(&app), crate::crop_ui::center(app.ui.crop_rect.unwrap())); + let img = |app: &PhotocraftApp| xf(app).to_screen(0.0, 0.0); + let origin = img(&app); + screen_drag(&mut app, &[pos2(370.0, 300.0), pos2(400.0, 300.0)], NONE); + assert!(close(screen_box(&app), before), "box put"); + assert!((img(&app) - origin - vec2(30.0, 0.0)).length() < 0.05, "the image moved 30 right on screen"); + let c1 = crate::crop_ui::center(app.ui.crop_rect.unwrap()); + assert!(((c1[0] - c0[0]).hypot(c1[1] - c0[1]) - 30.0).abs() < 1e-3); + } + + #[test] + fn the_readout_is_the_images_turn_clockwise_positive() { + let mut app = app(); + with_frame(&mut app); + // A 30° clockwise sweep on screen, held mid-drag. + let d = |app: &PhotocraftApp, p: Pos2| xf(app).to_doc(p); + let a = 30f32.to_radians(); + let (p0, p1) = (pos2(450.0, 300.0), pos2(370.0 + 80.0 * a.cos(), 300.0 + 80.0 * a.sin())); + let s = d(&app, p0); + tool_event(&mut app, ToolEvent::Down { x: s[0], y: s[1], pressure: 1.0 }, NONE); + let m = d(&app, p1); + tool_event(&mut app, ToolEvent::Move { x: m[0], y: m[1], pressure: 1.0 }, NONE); + let shown = crate::crop_ui::turning(&app).unwrap(); + assert!((shown - 30.0).abs() < 0.01, "clockwise is positive: {shown}"); + assert!((crate::crop_ui::angle(&app) - -30.0).abs() < 0.01, "the frame turns the other way on the image"); + let m = d(&app, p1); + tool_event(&mut app, ToolEvent::Up { x: m[0], y: m[1] }, NONE); + assert_eq!(image_turn(0.0).to_string(), "0", "never -0"); + // Classic Mode shows the frame's own turn, clockwise positive as before. + let mut app = self::app(); + app.ui.tool_options.crop_shield.classic_mode = true; + with_frame(&mut app); + let s = d(&app, p0); + tool_event(&mut app, ToolEvent::Down { x: s[0], y: s[1], pressure: 1.0 }, NONE); + let m = d(&app, p1); + tool_event(&mut app, ToolEvent::Move { x: m[0], y: m[1], pressure: 1.0 }, NONE); + assert!((crate::crop_ui::turning(&app).unwrap() - 30.0).abs() < 0.01); + } + + #[test] + fn auto_center_keeps_the_box_centred_while_a_handle_is_dragged() { + for auto in [true, false] { + let mut app = app(); + app.ui.tool_options.crop_shield.auto_center_preview = auto; + with_frame(&mut app); + // Turn 90° clockwise on screen first: the frame is at -90° in the image. + screen_drag(&mut app, &[pos2(450.0, 300.0), pos2(370.0, 380.0)], NONE); + let q = screen_box(&app); + assert_upright(q); + let mid = |q: [Pos2; 4]| pos2((q[0].x + q[2].x) / 2.0, (q[0].y + q[2].y) / 2.0); + // The box's right edge on screen, dragged 10 then 20 further right. + let right = pos2(q[1].x, (q[1].y + q[2].y) / 2.0); + assert_eq!(crate::crop_ui::cursor(&app, xf(&app).to_doc(right)), Some(egui::CursorIcon::ResizeHorizontal), "screen-space arrow"); + let at = |app: &PhotocraftApp, p: Pos2| xf(app).to_doc(p); + let s = at(&app, right); + tool_event(&mut app, ToolEvent::Down { x: s[0], y: s[1], pressure: 1.0 }, NONE); + for dx in [10.0, 20.0] { + let m = at(&app, right + vec2(dx, 0.0)); + tool_event(&mut app, ToolEvent::Move { x: m[0], y: m[1], pressure: 1.0 }, NONE); + let n = screen_box(&app); + assert_upright(n); + assert!((n[1].x - (right.x + dx)).abs() < 0.02, "auto={auto} dx={dx}: the handle follows the pointer: {n:?}"); + if auto { + assert!(mid(n).distance(mid(q)) < 0.02, "dx={dx}: live, the box stays centred: {:?} vs {:?}", mid(n), mid(q)); + assert!(((n[1].x - n[0].x) - (q[1].x - q[0].x) - 2.0 * dx).abs() < 0.02, "it grows on both sides"); + } else { + assert!((n[0].x - q[0].x).abs() < 0.02, "the left edge stays put"); + } + assert!(((n[3].y - n[0].y) - (q[3].y - q[0].y)).abs() < 0.02); + } + let m = at(&app, right + vec2(20.0, 0.0)); + tool_event(&mut app, ToolEvent::Up { x: m[0], y: m[1] }, NONE); + let n = screen_box(&app); + if auto { + assert!(mid(n).distance(mid(q)) < 0.05, "on release it stays where its centre was: {:?} vs {:?}", mid(n), mid(q)); + // On the image, the opposite edge stayed put: the frame grew 40 px from it. + let r = app.ui.crop_rect.unwrap(); + assert!(((r[2] - r[0]) - 100.0).abs() < 1e-3 && ((r[3] - r[1]) - 40.0).abs() < 1e-3, "{r:?}"); + let left = corners(r, crate::crop_ui::angle(&app))[0]; + let was = corners([40.0, 30.0, 100.0, 70.0], -90.0)[0]; + assert!((left[0] - was[0]).abs() < 1e-3 && (left[1] - was[1]).abs() < 1e-3, "{left:?} vs {was:?}"); + } else { + assert!(mid(n).distance(pos2(380.0, 300.0)) < 0.05, "{:?}", mid(n)); + } + } + // ⌥: about the centre, and a collapsed drag puts frame and view back. + let mut app = app(); + with_frame(&mut app); + let q = screen_box(&app); + let center = app.ui.views[0].center; + let right = pos2(q[1].x, (q[1].y + q[2].y) / 2.0); + screen_drag(&mut app, &[right, right + vec2(10.0, 0.0)], Modifiers::ALT); + let r = app.ui.crop_rect.unwrap(); + assert!(((r[0] + r[2]) / 2.0 - 70.0).abs() < 1e-3 && ((r[2] - r[0]) - 80.0).abs() < 1e-3, "{r:?}"); + let mut app = self::app(); + with_frame(&mut app); + screen_drag(&mut app, &[right, pos2(370.0, 300.0)], NONE); + assert_eq!(app.ui.crop_rect, Some([40.0, 30.0, 100.0, 70.0]), "too small: the frame is back"); + assert_eq!(app.ui.views[0].center, center, "and the view"); + } + + /// The same frame and angle commit the same crop in both modes, and in both the view stays + /// upright after a commit or a cancel (Photoshop 25.1 doesn't restore a Rotate View turn). + #[test] + fn commit_is_the_same_in_both_modes_and_the_view_stays_upright() { + let mut out = Vec::new(); + for classic in [true, false] { + let mut app = app(); + app.run("select.rect", json!({"x": 70, "y": 50, "width": 2, "height": 2})).unwrap(); + app.run("edit.fill", json!({"color": "#ff0000"})).unwrap(); + app.run("select.deselect", json!({})).unwrap(); + app.ui.tool_options.crop_shield.classic_mode = classic; + app.ui.views[0].rotation = 20.0; + with_frame(&mut app); + app.ui.crop_angle = 30.0; + app.crop.editing = true; + crate::crop_ui::ensure_frame(&mut app); + let want = if classic { 0.0 } else { -30.0 }; + assert!((view_rotation(&app) - want).abs() < 1e-4, "classic={classic}: {}", view_rotation(&app)); + if !classic { + assert_upright(screen_box(&app)); + } + let past = app.session.active().unwrap().history.past_len(); + crate::canvas::commit_crop(&mut app); + assert_eq!(view_rotation(&app), 0.0, "classic={classic}: after ↵"); + crate::crop_ui::ensure_frame(&mut app); + assert_eq!(view_rotation(&app), 0.0, "classic={classic}: with the next frame"); + let st = app.session.active().unwrap(); + assert_eq!(st.history.past_len(), past + 1, "one undo step"); + let surf = st.doc.layers[0].surface().unwrap(); + let px: Vec<[f32; 4]> = + (0..st.doc.size.width as i32).flat_map(|x| (0..st.doc.size.height as i32).map(move |y| (x, y))).map(|(x, y)| surf.rgba(x, y)).collect(); + out.push((st.doc.size, px)); + // Esc. + let mut app = self::app(); + app.ui.tool_options.crop_shield.classic_mode = classic; + app.ui.views[0].rotation = -45.0; + with_frame(&mut app); + screen_drag(&mut app, &[pos2(500.0, 300.0), pos2(370.0, 420.0)], NONE); + crate::crop_ui::cancel(&mut app); + crate::crop_ui::ensure_frame(&mut app); + assert_eq!(view_rotation(&app), 0.0, "classic={classic}: Esc"); + } + assert_eq!(out[0].0, out[1].0, "same size"); + assert!(out[0].1 == out[1].1, "same pixels"); + } + + #[test] + fn picking_the_crop_tool_turns_a_rotated_view_upright() { + let mut app = app(); + app.ui.tool = Tool::Brush; + app.ui.views[0].rotation = 30.0; + let center = app.ui.views[0].center; + app.ui.tool = Tool::Crop; + crate::crop_ui::ensure_frame(&mut app); + assert!(app.crop.default_frame && !app.crop.editing, "no click needed"); + assert_eq!(view_rotation(&app), 0.0); + assert_eq!(app.ui.views[0].center, center, "about the view's centre"); + // Leaving the tool doesn't bring the turn back. + app.ui.tool = Tool::Brush; + crate::crop_ui::ensure_frame(&mut app); + assert_eq!(view_rotation(&app), 0.0); + // Classic Mode too (Photoshop 25.1): the camera goes upright about the view's centre and + // the frame stays on the same image area, keeping its own turn. + let mut app = self::app(); + app.ui.tool_options.crop_shield.classic_mode = true; + app.ui.tool = Tool::Brush; + app.ui.views[0].rotation = 30.0; + app.ui.crop_rect = Some([40.0, 30.0, 100.0, 70.0]); + app.ui.crop_angle = 12.0; + app.ui.tool = Tool::Crop; + crate::crop_ui::ensure_frame(&mut app); + assert_eq!(view_rotation(&app), 0.0); + assert_eq!(app.ui.views[0].center, center, "about the view's centre"); + assert_eq!((app.ui.crop_rect, app.ui.crop_angle), (Some([40.0, 30.0, 100.0, 70.0]), 12.0), "the frame is unchanged"); + // P switches modes without bringing the R turn back: default mode turns the view with the + // frame, Classic Mode puts the camera upright again. + let press_p = |app: &mut PhotocraftApp| { + let ctx = egui::Context::default(); + ctx.input_mut(|i| i.events.push(egui::Event::Key { key: egui::Key::P, physical_key: None, pressed: true, repeat: false, modifiers: NONE })); + assert!(crate::crop_shield::keys(app, &ctx)); + }; + press_p(&mut app); + assert!(!classic(&app)); + assert!((view_rotation(&app) - -12.0).abs() < 1e-4, "{}", view_rotation(&app)); + press_p(&mut app); + assert!(classic(&app)); + assert_eq!(view_rotation(&app), 0.0); + crate::crop_ui::cancel(&mut app); + crate::crop_ui::ensure_frame(&mut app); + assert_eq!(view_rotation(&app), 0.0, "Esc in Classic Mode: still upright"); + } + + fn key(app: &mut PhotocraftApp, key: egui::Key, modifiers: Modifiers) { + let ctx = egui::Context::default(); + ctx.input_mut(|i| i.events.push(egui::Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers })); + crate::shortcuts::handle(app, &ctx); + } + + #[test] + fn arrows_nudge_the_image_shift_by_ten_and_x_recentres() { + let mut app = app(); + with_frame(&mut app); + app.crop.editing = true; + app.ui.crop_angle = -90.0; + crate::crop_ui::ensure_frame(&mut app); + let before = screen_box(&app); + let img = |app: &PhotocraftApp| xf(app).to_screen(0.0, 0.0); + let origin = img(&app); + key(&mut app, egui::Key::ArrowRight, NONE); + assert!(close(screen_box(&app), before), "the box stays put"); + assert!((img(&app) - origin - vec2(1.0, 0.0)).length() < 0.02, "the image moved 1 px right on screen"); + key(&mut app, egui::Key::ArrowDown, Modifiers::SHIFT); + assert!((img(&app) - origin - vec2(1.0, 10.0)).length() < 0.02, "⇧: 10 px"); + assert!(close(screen_box(&app), before)); + assert!(crate::crop_ui::swap_orientation(&mut app)); + assert_upright(screen_box(&app)); + let q = screen_box(&app); + assert!(pos2((q[0].x + q[2].x) / 2.0, (q[0].y + q[2].y) / 2.0).distance(pos2(400.0, 300.0)) < 0.05, "Auto Center Preview"); + } + + /// Photoshop 25.1 greys out Show Cropped Area and Auto Center Preview in Classic Mode. Show + /// Cropped Area then acts as on (an assumption) and H does nothing; the stored choice stays. + #[test] + fn classic_mode_shows_the_cropped_area_and_h_does_nothing() { + let mut app = app(); + crate::crop_ui::ensure_frame(&mut app); + app.ui.tool_options.crop_shield.show_cropped_area = false; + assert!(crate::crop_shield::hides_outside(&app)); + app.ui.tool_options.crop_shield.classic_mode = true; + assert!(!crate::crop_shield::hides_outside(&app)); + let canvas = egui::Color32::from_rgb(40, 40, 40); + assert_ne!(crate::crop_shield::fill(&app.ui.tool_options.crop_shield, canvas, false), Some(canvas), "the shield, not the opaque canvas"); + key(&mut app, egui::Key::H, NONE); + assert_eq!(app.ui.tool, Tool::Crop, "H is taken, not the Hand tool"); + assert!(!app.ui.tool_options.crop_shield.show_cropped_area, "and changes nothing"); + app.ui.tool_options.crop_shield.classic_mode = false; + assert!(crate::crop_shield::hides_outside(&app), "the stored choice is back"); + key(&mut app, egui::Key::H, NONE); + assert!(app.ui.tool_options.crop_shield.show_cropped_area); + } + + #[test] + fn p_toggles_classic_mode_while_the_crop_tool_shows_a_box() { + let mut app = app(); + crate::crop_ui::ensure_frame(&mut app); + let press = |app: &mut PhotocraftApp| { + let ctx = egui::Context::default(); + ctx.input_mut(|i| i.events.push(egui::Event::Key { key: egui::Key::P, physical_key: None, pressed: true, repeat: false, modifiers: NONE })); + crate::shortcuts::handle(app, &ctx); + }; + press(&mut app); + assert!(classic(&app) && app.ui.tool == Tool::Crop, "P doesn't pick the Pen tool"); + press(&mut app); + assert!(!classic(&app)); + // Mid-drag P is left alone; without a box P is the Pen key. + app.crop.drag = Some(CropDrag::Move { start: [0.0, 0.0], rect: [0.0, 0.0, 10.0, 10.0] }); + let ctx = egui::Context::default(); + ctx.input_mut(|i| i.events.push(egui::Event::Key { key: egui::Key::P, physical_key: None, pressed: true, repeat: false, modifiers: NONE })); + assert!(!crate::crop_shield::keys(&mut app, &ctx)); + assert!(!classic(&app)); + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.ui.tool = Tool::Crop; + press(&mut app); + assert_ne!(app.ui.tool, Tool::Crop); + assert!(!classic(&app)); + } + + #[test] + fn straighten_turns_the_image_so_the_line_is_level_on_screen() { + let mut app = app(); + crate::crop_ui::ensure_frame(&mut app); + crate::crop_straighten::toggle(&mut app); + // A horizon falling to the right, drawn on screen. + let (a, b) = (pos2(320.0, 290.0), pos2(480.0, 310.0)); + let (da, db) = (xf(&app).to_doc(a), xf(&app).to_doc(b)); + screen_drag(&mut app, &[a, b], NONE); + assert!(crate::crop_ui::angle(&app) > 5.0, "{}", app.ui.crop_angle); + let (sa, sb) = (xf(&app).to_screen(da[0] as f32, da[1] as f32), xf(&app).to_screen(db[0] as f32, db[1] as f32)); + assert!((sa.y - sb.y).abs() < 0.01, "the line is level: {sa:?} {sb:?}"); + assert_upright(screen_box(&app)); + } + + /// `ui.pointer` points are read in the view at the press, so an `up` where the last `move` was + /// doesn't move or turn the image a second time. + #[test] + fn ui_pointer_drives_the_default_mode_in_press_coordinates() { + let mut app = app(); + app.ui.tool_options.crop_shield.auto_center_preview = false; + with_frame(&mut app); + let ctx = egui::Context::default(); + let pointer = |app: &mut PhotocraftApp, pts: [[f64; 2]; 2]| { + let ev = json!([ + {"kind": "down", "x": pts[0][0], "y": pts[0][1]}, + {"kind": "move", "x": pts[1][0], "y": pts[1][1]}, + {"kind": "up", "x": pts[1][0], "y": pts[1][1]}, + ]); + let (req, _rx) = crate::control::ControlRequest::new("ui.pointer", json!({"events": ev})); + let crate::control::Outcome::Done(v) = crate::control::handle(app, &ctx, &req) else { panic!("ui.pointer didn't finish") }; + assert_eq!(v["ok"], true, "{v}"); + }; + pointer(&mut app, [[70.0, 50.0], [80.0, 55.0]]); + let r = app.ui.crop_rect.unwrap(); + assert!(r.iter().zip([30.0, 25.0, 90.0, 65.0]).all(|(a, b)| (a - b).abs() < 1e-3), "{r:?}"); + assert!((app.ui.views[0].center[0] - 90.0).abs() < 1e-3 && (app.ui.views[0].center[1] - 45.0).abs() < 1e-3); + // Outside: from right of the centre (60, 45) to below it, a quarter turn of the image. + pointer(&mut app, [[140.0, 45.0], [60.0, 125.0]]); + assert!((crate::crop_ui::angle(&app) - -90.0).abs() < 0.01, "{}", app.ui.crop_angle); + assert_upright(screen_box(&app)); + } + + #[test] + fn degenerate_input_never_panics() { + let mut app = app(); + for frame in + [[0.0, 0.0, 0.0, 0.0], [5.0, 5.0, 5.0, 5.0], [f64::NAN, 0.0, 10.0, 10.0], [f64::INFINITY, 0.0, 1e300, 1e300], [-1e300, -1e300, 1e300, 1e300]] + { + for angle in [0.0, f64::NAN, f64::INFINITY, 1e300, -720.5] { + app.ui.crop_rect = Some(frame); + app.ui.crop_angle = angle; + app.crop.default_frame = false; + app.crop.editing = true; + crate::crop_ui::ensure_frame(&mut app); + for p in [pos2(400.0, 300.0), pos2(10.0, 10.0), pos2(f32::NAN, 3.0), pos2(1e30, -1e30)] { + screen_drag(&mut app, &[p, p + vec2(15.0, 7.0)], NONE); + screen_drag(&mut app, &[p, p + vec2(15.0, 7.0)], Modifiers::SHIFT | Modifiers::ALT); + } + crate::crop_ui::nudge(&mut app, f64::NAN, 1.0); + crate::crop_ui::nudge(&mut app, 1.0, 1.0); + crate::crop_ui::swap_orientation(&mut app); + auto_center(&mut app); + shift_image(&mut app, [f64::NAN, f64::INFINITY]); + let press = PressView { rotation: f32::NAN, center: [f32::INFINITY, 0.0] }; + let g = LiveResize { rect: frame, deg: angle, hx: 1, hy: -1, start: [0.0, f64::NAN], q: [1e300, -1e300], ratio: Some(f64::NAN), alt: false }; + live_resize(&mut app, g, press); + assert!(app.ui.crop_rect.is_none_or(|r| r.iter().all(|v| v.is_finite()) || r == frame), "{frame:?} {angle}"); + let v = &app.ui.views[0]; + assert!(v.rotation.is_finite() && v.center.iter().all(|c| c.is_finite()), "{frame:?} {angle}: {v:?}"); + crate::crop_ui::cancel(&mut app); + } + } + assert_eq!(pivot_center([1.0, 2.0], [f64::NAN, 0.0], 0.0, 90.0, false), [1.0, 2.0]); + assert_eq!(pivot_center([1.0, 2.0], [0.0, 0.0], f32::NAN, 90.0, true), [1.0, 2.0]); + // No view at all (no document). + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.ui.tool = Tool::Crop; + app.ui.crop_rect = Some([0.0, 0.0, 10.0, 10.0]); + app.crop.editing = true; + sync(&mut app, None); + auto_center(&mut app); + shift_image(&mut app, [1.0, 1.0]); + upright(&mut app); + } + + #[test] + fn the_options_default_to_photoshops_and_older_settings_load() { + let s = crate::crop_shield::CropShield::default(); + assert!(!s.classic_mode && s.auto_center_preview); + let s: crate::crop_shield::CropShield = serde_json::from_str(r#"{"enabled": false}"#).unwrap(); + assert!(!s.classic_mode && s.auto_center_preview); + let s: crate::crop_shield::CropShield = serde_json::from_str(r#"{"classic_mode": true, "auto_center_preview": false}"#).unwrap(); + assert!(s.classic_mode && !s.auto_center_preview); + } + + #[test] + fn pivoting_keeps_the_point_on_screen() { + for flip in [false, true] { + for (from, to) in [(0.0, 30.0), (45.0, -90.0), (170.0, -170.0)] { + let center = [100.0f32, 50.0]; + let c = [70.0, 20.0]; + let a = ViewXform { rect: Rect::from_min_size(Pos2::ZERO, vec2(800.0, 600.0)), zoom: 2.0, center, flip, rotation: from }; + let n = pivot_center(center, c, from, to, flip); + let b = ViewXform { center: n, rotation: to, ..a }; + let (p, q) = (a.to_screen(70.0, 20.0), b.to_screen(70.0, 20.0)); + assert!(p.distance(q) < 0.01, "{flip} {from} {to}: {p:?} vs {q:?}"); + } + } + } +} diff --git a/crates/ui-egui/src/crop_shield.rs b/crates/ui-egui/src/crop_shield.rs index e97bff2d10..aef70e5afb 100644 --- a/crates/ui-egui/src/crop_shield.rs +++ b/crates/ui-egui/src/crop_shield.rs @@ -2,8 +2,8 @@ //! options", #1919): whether the area outside the crop box shows at all (Show Cropped Area, H), //! and the shield dimming it (Enable Crop Shield: Match Canvas or a custom colour, an opacity, and //! Auto Adjust Opacity, which lightens it while the box is dragged). Photoshop's defaults: all on, -//! Match Canvas, 75 %. PhotoCraft always works like Photoshop's Classic Mode, so the menu has no -//! Use Classic Mode or Auto Center Preview. +//! Match Canvas, 75 %. The menu also holds the crop mode: Use Classic Mode (P; off by default) and +//! Auto Center Preview (on by default, default mode only), see `crop_mode`. //! //! The state lives in `ToolOptions::crop_shield` ([`CropShield`]), which `ui.inspect` reports and //! `ui.set {cropShield: {...}}` patches. [`fill`] resolves it to the colour the canvas paints over @@ -35,6 +35,12 @@ pub enum ShieldColor { #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] #[serde(default)] pub struct CropShield { + /// Use Classic Mode (P): the box turns and moves over the image instead of the image turning + /// and moving behind an upright box (`crop_mode`). Off by default, as in Photoshop. + pub classic_mode: bool, + /// Auto Center Preview: in default mode, drawing or resizing the box re-pans the view so the + /// box sits in the middle of the canvas. + pub auto_center_preview: bool, /// Show Cropped Area (H): off hides everything outside the box behind the canvas colour. pub show_cropped_area: bool, /// Enable Crop Shield: off shows the area outside the box undimmed. @@ -50,11 +56,26 @@ pub struct CropShield { impl Default for CropShield { fn default() -> Self { - Self { show_cropped_area: true, enabled: true, color: ShieldColor::MatchCanvas, custom_color: [0, 0, 0], opacity: DEFAULT_OPACITY, auto_adjust: true } + Self { + classic_mode: false, + auto_center_preview: true, + show_cropped_area: true, + enabled: true, + color: ShieldColor::MatchCanvas, + custom_color: [0, 0, 0], + opacity: DEFAULT_OPACITY, + auto_adjust: true, + } } } impl CropShield { + /// Show Cropped Area as it acts: always on in Classic Mode, where Photoshop greys the option + /// out (the stored choice is kept for the default mode). + pub fn shows_cropped_area(&self) -> bool { + self.classic_mode || self.show_cropped_area + } + /// The opacity as a fraction in 0..=1: a non-finite value (a hand-edited settings file) is /// the default, an out-of-range one is clamped. pub fn opacity(&self) -> f32 { @@ -68,7 +89,7 @@ impl CropShield { /// shield when it is disabled (or fully transparent), otherwise its colour at its opacity. pub fn fill(s: &CropShield, canvas: Color32, editing: bool) -> Option { let [r, g, b, _] = canvas.to_srgba_unmultiplied(); - if !s.show_cropped_area { + if !s.shows_cropped_area() { return Some(Color32::from_rgb(r, g, b)); } if !s.enabled { @@ -95,18 +116,29 @@ pub fn current(app: &PhotocraftApp, ctx: &egui::Context) -> Option { /// Show Cropped Area is off with the Crop tool showing a box: nothing outside it shows. pub fn hides_outside(app: &PhotocraftApp) -> bool { - app.ui.tool == Tool::Crop && app.ui.crop_rect.is_some() && !app.ui.tool_options.crop_shield.show_cropped_area + app.ui.tool == Tool::Crop && app.ui.crop_rect.is_some() && !app.ui.tool_options.crop_shield.shows_cropped_area() } -/// H with the Crop tool showing a box and no drag in progress toggles Show Cropped Area. Returns -/// true when the key was used; otherwise H stays the Hand tool key. +/// H with the Crop tool showing a box and no drag in progress toggles Show Cropped Area (in +/// Classic Mode, where the option is greyed out, H is taken and does nothing), and P Use Classic +/// Mode. Returns true when a key was used; otherwise H stays the Hand tool key and P the Pen's. pub fn keys(app: &mut PhotocraftApp, ctx: &egui::Context) -> bool { if app.ui.tool != Tool::Crop || app.ui.crop_rect.is_none() || app.crop.drag.is_some() { return false; } if ctx.input_mut(|i| i.consume_key(Modifiers::NONE, Key::H)) { let s = &mut app.ui.tool_options.crop_shield; - s.show_cropped_area = !s.show_cropped_area; + if !s.classic_mode { + s.show_cropped_area = !s.show_cropped_area; + } + return true; + } + if ctx.input_mut(|i| i.consume_key(Modifiers::NONE, Key::P)) { + let s = &mut app.ui.tool_options.crop_shield; + s.classic_mode = !s.classic_mode; + // The view follows at once, about its own centre: default mode turns it with the frame, + // Classic Mode puts the camera upright (never back to a Rotate View turn). + crate::crop_mode::sync(app, None); return true; } false @@ -120,9 +152,23 @@ pub fn options_button(s: &mut CropShield, ui: &mut egui::Ui) -> bool { egui::Popup::menu(&r).close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside).show(|ui| { ui.set_min_width(240.0); ui.set_max_width(300.0); + // Photoshop 25.1's order; Classic Mode greys out the other two (Show Cropped Area then + // shows as on, which is how it acts there). ui.horizontal(|ui| { - crate::widgets::checkbox(ui, &mut s.show_cropped_area, tl!("Show Cropped Area")); - ui.weak(crate::shortcuts::pretty("H")); + crate::widgets::checkbox(ui, &mut s.classic_mode, tl!("Use Classic Mode")); + ui.weak(crate::shortcuts::pretty("P")); + }); + let classic = s.classic_mode; + ui.add_enabled_ui(!classic, |ui| { + ui.horizontal(|ui| { + if classic { + crate::widgets::checkbox(ui, &mut true, tl!("Show Cropped Area")); + } else { + crate::widgets::checkbox(ui, &mut s.show_cropped_area, tl!("Show Cropped Area")); + } + ui.weak(crate::shortcuts::pretty("H")); + }); + crate::widgets::checkbox(ui, &mut s.auto_center_preview, tl!("Auto Center Preview")); }); ui.separator(); crate::widgets::checkbox(ui, &mut s.enabled, tl!("Enable Crop Shield")); diff --git a/crates/ui-egui/src/crop_straighten.rs b/crates/ui-egui/src/crop_straighten.rs index 286f04253a..fc9ac3ab3b 100644 --- a/crates/ui-egui/src/crop_straighten.rs +++ b/crates/ui-egui/src/crop_straighten.rs @@ -8,9 +8,9 @@ //! - 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: +//! While the line is drawn its angle shows beside the pointer. Straighten sets the frame's angle +//! and fits the frame to the image ([`fitted`]); in Classic Mode the frame then shows turned over +//! the image, in the default mode the image turns behind the upright box (`crop_mode`). 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. @@ -183,6 +183,9 @@ mod tests { s.add_document(doc, None); let mut app = PhotocraftApp::new(s, crate::Services::default()); app.ui.tool = Tool::Crop; + // Classic Mode: the frame turns over the image (the default mode's Straighten is tested in + // `crop_mode`). + app.ui.tool_options.crop_shield.classic_mode = true; app.ui.extras.snap = false; app.ui.view.show.smart_guides = false; ensure_frame(&mut app); diff --git a/crates/ui-egui/src/crop_ui.rs b/crates/ui-egui/src/crop_ui.rs index 5115867c89..b2ab235711 100644 --- a/crates/ui-egui/src/crop_ui.rs +++ b/crates/ui-egui/src/crop_ui.rs @@ -1,5 +1,7 @@ -//! Crop tool gestures, Photoshop "Classic Mode" style (the frame moves and turns over a fixed -//! image): +//! Crop tool gestures. In Photoshop's "Classic Mode" (Use Classic Mode, P) the frame moves and +//! turns over a fixed image, as described below; in its default mode (`crop_mode`) the box stays +//! upright on screen and the same gestures inside and outside it move and turn the image behind +//! it instead (the view turns with the frame, so hit-testing in document space is unchanged): //! //! - 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 @@ -16,15 +18,12 @@ //! - with a pending frame and no gesture, the arrow keys nudge it 1 document px (⇧ 10 px) instead //! of the selection or layer, and X swaps it between portrait and landscape about its centre //! (keeping its angle, and swapping an options-bar ratio with it) instead of the colours -//! ([`keys`], #1919). These are Photoshop's Classic Mode keys: in its default mode the arrows -//! move the image under the box. +//! ([`keys`], #1919). In the default mode the arrows move the image under the box instead. //! //! ↵ 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. +//! clockwise on screen), so the control channel reads both. Both modes commit the same crop. //! //! 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 @@ -69,10 +68,20 @@ pub enum CropDrag { /// Moving the frame `rect` grabbed at `start`. 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] }, + /// `view` is the view at the press when Auto Center Preview keeps the box's centre in place + /// while it is resized (default mode, `crop_mode::live_resize`), else `None`. + Resize { hx: i8, hy: i8, start: [f64; 2], rect: [f64; 4], view: Option }, /// 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 }, + /// Default mode, inside the box: the image moves under it, so the document point grabbed at + /// `start` stays under the pointer. `rect` is the frame and `view` the view at the press; + /// pointer points are read in that view (`crop_mode::to_press`). + MoveImage { start: [f64; 2], rect: [f64; 4], view: Option }, + /// Default mode, outside the box: the image turns about the frame's `center` (which stays put + /// on screen). `grab` is the pointer's direction from it at the press (radians, in the press + /// `view`), `from` the frame's angle then (degrees). + TurnImage { center: [f64; 2], grab: f64, from: f64, view: Option }, } /// What the pointer is over, relative to a crop frame. @@ -254,8 +263,14 @@ pub fn set_space(app: &mut PhotocraftApp, down: bool) { } /// As in Photoshop, the Crop tool always shows a frame: on picking the tool, and after a crop is -/// cancelled or committed, it frames the selection's bounds, or the whole canvas. +/// cancelled or committed, it frames the selection's bounds, or the whole canvas. In default mode +/// the view then follows the frame being edited (`crop_mode::sync`). pub fn ensure_frame(app: &mut PhotocraftApp) { + frame(app); + crate::crop_mode::sync(app, None); +} + +fn frame(app: &mut PhotocraftApp) { if app.ui.tool != Tool::Crop { app.crop.editing = false; crate::crop_straighten::reset(app); @@ -303,6 +318,7 @@ pub fn active(app: &PhotocraftApp) -> bool { /// Cancel the pending crop: the frame, any gesture on it and the default-frame state. With the /// Crop tool still picked, [`ensure_frame`] then makes the active document a new default frame. pub fn cancel(app: &mut PhotocraftApp) { + crate::crop_mode::upright(app); app.ui.crop_rect = None; app.ui.crop_angle = 0.0; app.crop.drag = None; @@ -416,9 +432,14 @@ pub fn commits_at(app: &PhotocraftApp, p: [f64; 2]) -> bool { && 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. +/// The frame is being turned: the angle for the readout beside the pointer. Classic Mode shows +/// the frame's turn; the default mode the image's (clockwise positive, as Photoshop 25.1 does). pub fn turning(app: &PhotocraftApp) -> Option { - matches!(app.crop.drag, Some(CropDrag::Rotate { .. })).then(|| angle(app)) + match app.crop.drag { + Some(CropDrag::Rotate { .. }) => Some(angle(app)), + Some(CropDrag::TurnImage { .. }) => Some(crate::crop_mode::image_turn(angle(app))), + _ => None, + } } /// The size ↵ would crop frame `r` to: its own width and height (before any turn) in whole @@ -455,9 +476,20 @@ fn keyed(app: &mut PhotocraftApp, r: [f64; 4]) { } /// Moves the pending frame by (`dx`, `dy`) document px (a turned frame moves on the page, keeping -/// its angle). Returns false when the Crop tool doesn't take the keys ([`takes_keys`]). +/// its angle); in default mode the image moves that way on screen under the box instead. Returns +/// false when the Crop tool doesn't take the keys ([`takes_keys`]). pub fn nudge(app: &mut PhotocraftApp, dx: f64, dy: f64) -> bool { let Some(r) = app.ui.crop_rect.filter(|_| takes_keys(app)) else { return false }; + if crate::crop_mode::moves_image(app) { + if dx.is_finite() && dy.is_finite() { + app.crop.default_frame = false; + app.crop.editing = true; + crate::crop_mode::sync_frame(app); + let d = crate::crop_mode::screen_to_doc_vec(app, [dx, dy]); + crate::crop_mode::shift_image(app, d); + } + return true; + } if dx.is_finite() && dy.is_finite() { keyed(app, [r[0] + dx, r[1] + dy, r[2] + dx, r[3] + dy]); } @@ -491,6 +523,8 @@ pub fn swap_orientation(app: &mut PhotocraftApp) -> bool { app.ui.tool_options.crop_ratio = k; } keyed(app, swapped(r)); + crate::crop_mode::sync_frame(app); + crate::crop_mode::auto_center(app); true } @@ -529,17 +563,39 @@ pub fn pointer(app: &mut PhotocraftApp, ev: ToolEvent, mods: Modifiers) -> bool // 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); + // Default mode: the image turns so the line ends up level (the press keeps its point). + match ev { + ToolEvent::Down { .. } => crate::crop_mode::sync(app, Some(p)), + _ => crate::crop_mode::sync_frame(app), + } return true; } match ev { ToolEvent::Down { .. } => { claim(app); app.crop.editing = true; + // Default mode: the view is upright for the frame (picking the tool already made it so; + // this catches a frame set over the control channel), about the pressed point. + crate::crop_mode::sync(app, Some(p)); let frame = app.ui.crop_rect.filter(|r| r.iter().all(|v| v.is_finite())); let deg = angle(app); + let image = crate::crop_mode::moves_image(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::Handle(hx, hy))) => { + let view = if crate::crop_mode::live_center(app) { crate::crop_mode::press_view(app) } else { None }; + CropDrag::Resize { hx, hy, start: p, rect, view } + } + // Default mode: inside the box the image moves, the box staying where it is on + // screen (Photoshop doesn't re-centre it). Inside the untouched frame a drag still + // draws a new box. + Some((rect, Hit::Inside)) if !app.crop.default_frame && image => { + CropDrag::MoveImage { start: p, rect, view: crate::crop_mode::press_view(app) } + } Some((rect, Hit::Inside)) if !app.crop.default_frame => CropDrag::Move { start: p, rect }, + Some((rect, Hit::Outside)) if image => { + let c = center(rect); + CropDrag::TurnImage { center: c, grab: (p[1] - c[1]).atan2(p[0] - c[0]), from: deg, view: crate::crop_mode::press_view(app) } + } // Outside the frame a drag turns it, as in Photoshop (#1792). Some((rect, Hit::Outside)) => { let c = center(rect); @@ -557,17 +613,27 @@ pub fn pointer(app: &mut PhotocraftApp, ev: ToolEvent, mods: Modifiers) -> bool let Some(drag) = app.crop.drag.take() else { return true }; let ok = app.ui.crop_rect.is_some_and(size_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)); + let changed = !matches!(drag, CropDrag::Rotate { from, .. } | CropDrag::TurnImage { from, .. } if from == angle(app)) + && !matches!(drag, CropDrag::MoveImage { rect, .. } if app.ui.crop_rect == Some(rect)); if ok && changed { app.crop.default_frame = false; } match drag { CropDrag::Draw { prev, .. } if !ok => app.ui.crop_rect = prev, - CropDrag::Move { rect, .. } | CropDrag::Resize { rect, .. } if !ok => app.ui.crop_rect = Some(rect), + CropDrag::Move { rect, .. } | CropDrag::Resize { rect, view: None, .. } if !ok => app.ui.crop_rect = Some(rect), + // A live-centred resize collapsed: the frame and the view it moved go back. + CropDrag::Resize { rect, view: Some(view), .. } if !ok => crate::crop_mode::offset_image(app, rect, Some(view), [0.0, 0.0]), + // Auto Center Preview: a box drawn in default mode moves to the middle. (A resized + // one stays where its centre was: `crop_mode::live_resize`.) + CropDrag::Draw { .. } if ok => { + crate::crop_mode::sync_frame(app); + crate::crop_mode::auto_center(app); + } _ => {} } } } + crate::crop_mode::sync_frame(app); true } @@ -576,9 +642,38 @@ fn 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; + match app.crop.drag { + Some(CropDrag::Rotate { center, grab, from }) => { + app.ui.crop_angle = turned_angle(center, grab, from, p, mods.shift); + return; + } + Some(CropDrag::TurnImage { center, grab, from, view }) => { + // The image turns with the pointer's sweep on screen, so the frame turns against it. + let q = crate::crop_mode::to_press(app, view, p); + let a = from - ((q[1] - center[1]).atan2(q[0] - center[0]) - grab).to_degrees(); + if a.is_finite() { + app.ui.crop_angle = normalized_angle(if mods.shift { (a / 15.0).round() * 15.0 } else { a }); + crate::crop_mode::sync_frame(app); + } + return; + } + Some(CropDrag::MoveImage { start, rect, view }) => { + // The image follows the pointer: the frame moves the other way on it, and the view + // with the frame, so the box stays put. + let q = crate::crop_mode::to_press(app, view, p); + crate::crop_mode::offset_image(app, rect, view, [q[0] - start[0], q[1] - start[1]]); + return; + } + Some(CropDrag::Resize { hx, hy, start, rect, view: Some(view) }) => { + // Auto Center Preview: the box stays centred where it was while the handle follows + // the pointer. + let q = crate::crop_mode::to_press(app, Some(view), p); + let keep = (rect[2] - rect[0] > 0.0 && rect[3] - rect[1] > 0.0).then(|| (rect[2] - rect[0]) / (rect[3] - rect[1])); + let ratio = ratio.or(if mods.shift { keep } else { None }); + crate::crop_mode::live_resize(app, crate::crop_mode::LiveResize { rect, deg, hx, hy, start, q, ratio, alt: mods.alt }, view); + return; + } + _ => {} } let Some(drag) = app.crop.drag.as_mut() else { return }; let rect = match drag { @@ -601,7 +696,7 @@ fn update(app: &mut PhotocraftApp, p: [f64; 2], mods: Modifiers) { let (dx, dy) = (p[0] - start[0], p[1] - start[1]); [rect[0] + dx, rect[1] + dy, rect[2] + dx, rect[3] + dy] } - CropDrag::Resize { hx, hy, start, rect } => { + CropDrag::Resize { hx, hy, start, rect, .. } => { let keep = || { let (w, h) = (rect[2] - rect[0], rect[3] - rect[1]); (w > 0.0 && h > 0.0).then(|| w / h) @@ -609,7 +704,7 @@ fn update(app: &mut PhotocraftApp, p: [f64; 2], mods: Modifiers) { let ratio = ratio.or_else(|| if mods.shift { keep() } else { None }); resized_turned(*rect, deg, *hx, *hy, [p[0] - start[0], p[1] - start[1]], ratio, mods.alt) } - CropDrag::Rotate { .. } => return, + CropDrag::Rotate { .. } | CropDrag::TurnImage { .. } | CropDrag::MoveImage { .. } => return, }; app.ui.crop_rect = Some(rect); } @@ -624,14 +719,15 @@ pub fn cursor(app: &PhotocraftApp, p: [f64; 2]) -> Option { } let deg = angle(app); let h = match app.crop.drag { - Some(CropDrag::Move { .. }) => Hit::Inside, + Some(CropDrag::Move { .. } | CropDrag::MoveImage { .. }) => Hit::Inside, Some(CropDrag::Resize { hx, hy, .. }) => Hit::Handle(hx, hy), Some(CropDrag::Draw { .. }) => return Some(CursorIcon::Crosshair), - Some(CropDrag::Rotate { .. }) => Hit::Outside, + Some(CropDrag::Rotate { .. } | CropDrag::TurnImage { .. }) => Hit::Outside, None => hit_turned(app.ui.crop_rect?, deg, p, tolerance(app)), }; Some(match h { - Hit::Handle(hx, hy) => resize_icon(hx, hy, deg), + // The arrow as the handle faces on screen: the frame's turn plus the view's. + Hit::Handle(hx, hy) => resize_icon(hx, hy, deg + f64::from(crate::crop_mode::view_rotation(app))), Hit::Inside => CursorIcon::Move, // Photoshop's curved two-headed arrow (`draw_turn_cursor`, from `turn_cursor_dir`). Hit::Outside => CursorIcon::None, @@ -648,7 +744,7 @@ pub fn turn_cursor_dir(app: &PhotocraftApp, p: [f64; 2]) -> Option<[f64; 2]> { 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(CropDrag::Rotate { .. } | CropDrag::TurnImage { .. }) => true, Some(_) => false, None => hit_turned(r, deg, p, tolerance(app)) == Hit::Outside, }; @@ -722,6 +818,9 @@ mod tests { s.add_document(doc, None); let mut app = PhotocraftApp::new(s, crate::Services::default()); app.ui.tool = Tool::Crop; + // These tests pin Classic Mode (the frame moves and turns over the image); the default + // mode's are in `crop_mode`. + app.ui.tool_options.crop_shield.classic_mode = true; app.ui.extras.snap = false; app.ui.view.show.smart_guides = false; app diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 695c143273..61c26a0c1e 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -2412,6 +2412,8 @@ fontWeight Italic Kurzíva Quick Selection found nothing there Rychlý výběr zde nic nenašel Object Selection found nothing there — try a tighter rectangle Výběr objektu zde nic nenašel — zkuste těsnější obdélník No subject found — try a rectangle around the object Nebyl nalezen žádný objekt — zkuste obdélník kolem objektu + Use Classic Mode Použít klasický režim + Auto Center Preview Automaticky vystředit náhled Next Document Další dokument Previous Document Předchozí dokument W x H x Resolution Š x V x Rozlišení diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 1079eefefc..9c5284cbf0 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -2451,6 +2451,8 @@ fontWeight Italic Kursiv Quick Selection found nothing there Die Schnellauswahl hat dort nichts gefunden Object Selection found nothing there — try a tighter rectangle Die Objektauswahl hat dort nichts gefunden — versuchen Sie ein engeres Rechteck No subject found — try a rectangle around the object Kein Motiv gefunden — versuchen Sie ein Rechteck um das Objekt + Use Classic Mode Classic-Modus verwenden + Auto Center Preview Automatische zentrierte Vorschau Next Document Nächstes Dokument Previous Document Vorheriges Dokument W x H x Resolution B x H x Auflösung diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 1ee4957f7d..33ac5903be 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -3520,6 +3520,8 @@ fontWeight Thin Πολύ λεπτά Quick Selection found nothing there Η Γρήγορη επιλογή δεν βρήκε τίποτα εκεί Object Selection found nothing there — try a tighter rectangle Η Επιλογή αντικειμένου δεν βρήκε τίποτα εκεί — δοκιμάστε ένα πιο στενό ορθογώνιο No subject found — try a rectangle around the object Δεν βρέθηκε θέμα — δοκιμάστε ένα ορθογώνιο γύρω από το αντικείμενο + Use Classic Mode Χρήση κλασικής λειτουργίας + Auto Center Preview Αυτόματο κεντράρισμα προεπισκόπησης Next Document Επόμενο έγγραφο Previous Document Προηγούμενο έγγραφο W x H x Resolution Π x Υ x Ανάλυση diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index b85a2c5ca8..9927431dc9 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -2480,6 +2480,8 @@ fontWeight Italic Cursiva Quick Selection found nothing there Selección rápida no encontró nada ahí Object Selection found nothing there — try a tighter rectangle Selección de objeto no encontró nada ahí — pruebe un rectángulo más ajustado No subject found — try a rectangle around the object No se encontró ningún sujeto — pruebe un rectángulo alrededor del objeto + Use Classic Mode Usar modo clásico + Auto Center Preview Centrar previsualización automáticamente Next Document Documento siguiente Previous Document Documento anterior W x H x Resolution An. x Al. x Resolución diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 88088270ab..bd563985a4 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -2831,6 +2831,8 @@ fontWeight Italic Italique Quick Selection found nothing there La Sélection rapide n'a rien trouvé à cet endroit Object Selection found nothing there — try a tighter rectangle La Sélection d'objet n'a rien trouvé à cet endroit — essayez un rectangle plus serré No subject found — try a rectangle around the object Aucun sujet trouvé — essayez un rectangle autour de l'objet + Use Classic Mode Utiliser le mode classique + Auto Center Preview Centrer automatiquement l'aperçu Next Document Document suivant Previous Document Document précédent W x H x Resolution L x H x Résolution diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 421c68c16e..d07f9a0977 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -2818,6 +2818,8 @@ fontWeight Italic Miring Quick Selection found nothing there Seleksi Cepat tidak menemukan apa pun di sana Object Selection found nothing there — try a tighter rectangle Seleksi Objek tidak menemukan apa pun di sana — coba persegi panjang yang lebih rapat No subject found — try a rectangle around the object Subjek tidak ditemukan — coba persegi panjang di sekitar objek + Use Classic Mode Gunakan Mode Klasik + Auto Center Preview Pusatkan Pratinjau Otomatis Next Document Dokumen Berikutnya Previous Document Dokumen Sebelumnya W x H x Resolution L x T x Resolusi diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 1fd70c9fc3..dfef795cf2 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -2482,6 +2482,8 @@ fontWeight Italic Corsivo Quick Selection found nothing there Selezione rapida non ha trovato nulla lì Object Selection found nothing there — try a tighter rectangle Selezione oggetto non ha trovato nulla lì — prova un rettangolo più stretto No subject found — try a rectangle around the object Nessun soggetto trovato — prova un rettangolo attorno all'oggetto + Use Classic Mode Usa modalità classica + Auto Center Preview Centra anteprima automaticamente Next Document Documento successivo Previous Document Documento precedente W x H x Resolution L x A x Risoluzione diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 08ddf09927..b216a10844 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -3432,6 +3432,8 @@ fontWeight Italic 斜体 Quick Selection found nothing there クイック選択ではそこに何も見つかりませんでした Object Selection found nothing there — try a tighter rectangle オブジェクト選択ではそこに何も見つかりませんでした — より狭い長方形で試してください No subject found — try a rectangle around the object 被写体が見つかりません — オブジェクトを囲む長方形を試してください + Use Classic Mode クラシックモードを使用 + Auto Center Preview プレビューを自動的に中央に配置 Next Document 次のドキュメント Previous Document 前のドキュメント W x H x Resolution 幅 x 高さ x 解像度 diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 2b32c878d3..6e66c634a8 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -2990,6 +2990,8 @@ fontWeight Italic 기울임 Quick Selection found nothing there 빠른 선택으로 해당 위치에서 아무것도 찾지 못했습니다 Object Selection found nothing there — try a tighter rectangle 개체 선택으로 해당 위치에서 아무것도 찾지 못했습니다 — 더 좁은 사각형을 사용해 보세요 No subject found — try a rectangle around the object 피사체를 찾을 수 없습니다 — 개체 주위에 사각형을 그려 보세요 + Use Classic Mode 클래식 모드 사용 + Auto Center Preview 미리 보기 자동 가운데 맞춤 Next Document 다음 문서 Previous Document 이전 문서 W x H x Resolution 폭 x 높이 x 해상도 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 0c6db6b9f3..062280f223 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -3591,6 +3591,8 @@ cameraRaw Whites Witten Quick Selection found nothing there Snelle selectie heeft daar niets gevonden Object Selection found nothing there — try a tighter rectangle Objectselectie heeft daar niets gevonden — probeer een krappere rechthoek No subject found — try a rectangle around the object Geen onderwerp gevonden — probeer een rechthoek rond het object + Use Classic Mode Klassieke modus gebruiken + Auto Center Preview Voorvertoning automatisch centreren Next Document Volgend document Previous Document Vorig document W x H x Resolution B x H x Resolutie diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index f00cfc5b54..237f52408a 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -3432,6 +3432,8 @@ cameraRaw Roughness Chropowatość Quick Selection found nothing there Szybkie zaznaczanie nic tam nie znalazło Object Selection found nothing there — try a tighter rectangle Zaznaczanie obiektu nic tam nie znalazło — spróbuj ciaśniejszego prostokąta No subject found — try a rectangle around the object Nie znaleziono obiektu — spróbuj prostokąta wokół obiektu + Use Classic Mode Użyj trybu klasycznego + Auto Center Preview Automatycznie wyśrodkuj podgląd Next Document Następny dokument Previous Document Poprzedni dokument W x H x Resolution Szer. x Wys. x Rozdzielczość diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 2559bb158c..513b7df19c 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -2839,6 +2839,8 @@ fontWeight Italic Itálico Quick Selection found nothing there A Seleção rápida não encontrou nada ali Object Selection found nothing there — try a tighter rectangle A Seleção de objeto não encontrou nada ali — tente um retângulo mais justo No subject found — try a rectangle around the object Nenhum assunto encontrado — tente um retângulo ao redor do objeto + Use Classic Mode Usar modo clássico + Auto Center Preview Centralizar visualização automaticamente Next Document Próximo documento Previous Document Documento anterior W x H x Resolution L x A x Resolução diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 97865b52cc..816a4504bd 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -2696,6 +2696,8 @@ fontWeight Italic Курсив Missing delete command Отсутствует команда удаления Invalid delete command Недопустимая команда удаления Layer deleted, but confirmation preference could not be saved: {error} Слой удалён, но не удалось сохранить настройку подтверждения: {error} + Use Classic Mode Использовать классический режим + Auto Center Preview Автоматически центрировать просмотр Next Document Следующий документ Previous Document Предыдущий документ W x H x Resolution Ш x В x Разрешение diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 8642ca2f05..a5e4fcbede 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -3519,6 +3519,8 @@ cameraRaw Masking Маскування Quick Selection found nothing there Швидке виділення нічого тут не знайшло Object Selection found nothing there — try a tighter rectangle Виділення об'єктів нічого тут не знайшло — спробуйте вужчий прямокутник No subject found — try a rectangle around the object Об'єкт не знайдено — спробуйте прямокутник навколо об'єкта + Use Classic Mode Використовувати класичний режим + Auto Center Preview Автоматично центрувати перегляд Next Document Наступний документ Previous Document Попередній документ W x H x Resolution Ш x В x Роздільна здатність diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 120656243f..98b4cb2653 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -2420,6 +2420,8 @@ fontWeight Italic 斜体 Quick Selection found nothing there 快速选择在该处未找到任何内容 Object Selection found nothing there — try a tighter rectangle 对象选择在该处未找到任何内容 — 请尝试更紧凑的矩形 No subject found — try a rectangle around the object 未找到主体 — 请尝试在对象周围绘制矩形 + Use Classic Mode 使用经典模式 + Auto Center Preview 自动居中预览 Next Document 下一个文档 Previous Document 上一个文档 W x H x Resolution 宽 x 高 x 分辨率 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 18b7da8824..098400245e 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -2389,6 +2389,8 @@ fontWeight Italic 斜體 Quick Selection found nothing there 快速選取在該處找不到任何內容 Object Selection found nothing there — try a tighter rectangle 物件選取在該處找不到任何內容 — 請嘗試更緊密的矩形 No subject found — try a rectangle around the object 找不到主體 — 請嘗試在物件周圍繪製矩形 + Use Classic Mode 使用傳統模式 + Auto Center Preview 自動置中預視 Next Document 下一個文件 Previous Document 上一個文件 W x H x Resolution 寬 x 高 x 解析度 diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 036fc0b689..a94d8a76ba 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -46,6 +46,7 @@ pub mod color_range_ui; pub mod comps_ui; pub mod control; pub mod credits; +pub mod crop_mode; pub mod crop_overlay; pub mod crop_shield; pub mod crop_size; diff --git a/crates/ui-egui/src/snap_ui.rs b/crates/ui-egui/src/snap_ui.rs index b28a2d2b92..7e9875d245 100644 --- a/crates/ui-egui/src/snap_ui.rs +++ b/crates/ui-egui/src/snap_ui.rs @@ -167,18 +167,20 @@ 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 + && (crate::crop_mode::classic(app) || app.crop.default_frame) && 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) { - // Inside the untouched default frame draws a new crop: snap its corner, not the old - // canvas-sized frame's bounds. An edited frame still moves and snaps its edges. + // Inside the untouched default frame draws a new crop (in both modes): snap its corner, not + // the old canvas-sized frame's bounds. An edited Classic Mode frame still moves and snaps + // its edges. let gesture = if app.crop.default_frame { Gesture::Point } else { Gesture::Move { rect } }; Some((gesture, 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. + // Turning the frame, moving a turned one (its edges don't line up with anything), or in + // the default mode moving or turning the image under the box: no snapping. None } else if is_point_tool(tool) { Some((Gesture::Point, Vec::new())) @@ -354,7 +356,9 @@ mod tests { #[test] fn drawing_a_new_crop_snaps_its_corner_not_the_default_frame() { - for (snap, end) in [(false, [300.0, 220.0]), (true, [294.0, 217.0])] { + // In both crop modes: the default mode draws a new box inside the untouched frame too. + for (classic, snap, end) in [(true, false, [300.0, 220.0]), (true, true, [294.0, 217.0]), (false, false, [300.0, 220.0]), (false, true, [294.0, 217.0])] + { let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); app.run("file.new", json!({"width": 640, "height": 480, "background": "white"})).unwrap(); app.run("shape.create", json!({"kind": "rect", "rect": [100, 80, 200, 140], "fill": "#d59b40"})).unwrap(); @@ -363,6 +367,7 @@ mod tests { app.ui.views[0].zoom = 1.0; app.ui.views[0].fit_pending = false; app.ui.tool = Tool::Crop; + app.ui.tool_options.crop_shield.classic_mode = classic; app.ui.extras.snap = snap; app.ui.view.show.smart_guides = true; crate::crop_ui::ensure_frame(&mut app); @@ -374,8 +379,11 @@ mod tests { crate::canvas::tool_event(&mut app, ToolEvent::Up { x: end[0], y: end[1] }, m); // Smart Guides must not snap the old canvas-sized frame as if it were moving. // With View Snap on, the new corner still snaps to the nearby shape's edges. - assert_eq!(app.ui.crop_rect, Some([100.0, 80.0, 300.0, 220.0]), "View Snap: {snap}"); - assert_eq!(app.ui.views[0], view); + assert_eq!(app.ui.crop_rect, Some([100.0, 80.0, 300.0, 220.0]), "Classic Mode: {classic}, View Snap: {snap}"); + // The default mode's Auto Center Preview re-centres the drawn box; Classic Mode keeps the view. + if classic { + assert_eq!(app.ui.views[0], view); + } assert_eq!(app.session.active().unwrap().history.past_len(), history); } } diff --git a/crates/ui-egui/tests/crop_beyond_canvas.rs b/crates/ui-egui/tests/crop_beyond_canvas.rs index e4d4e8fb35..c9b0a50727 100644 --- a/crates/ui-egui/tests/crop_beyond_canvas.rs +++ b/crates/ui-egui/tests/crop_beyond_canvas.rs @@ -121,7 +121,9 @@ fn editing_a_crop_frame_shows_the_pixels_past_the_canvas() { app.ui.extras.rulers = false; app.ui.extras.snap = false; } - control(&mut h, "ui.set", json!({"tool": "crop", "zoom": 1.0, "center": [100, 50]})); + // Classic Mode: the edge drag below moves only that edge (Auto Center Preview in the default + // mode would keep the box centred, growing it on both sides). + control(&mut h, "ui.set", json!({"tool": "crop", "zoom": 1.0, "center": [100, 50], "cropShield": {"classic_mode": true}})); h.run_steps(3); assert_eq!(h.state().ui.crop_rect, Some([0.0, 0.0, 200.0, 100.0]), "the default frame"); let (red, blue, white, beyond) = ([-25.0, 50.0], [225.0, 50.0], [100.0, 110.0], [-80.0, 50.0]); diff --git a/crates/ui-egui/tests/crop_default_mode.rs b/crates/ui-egui/tests/crop_default_mode.rs new file mode 100644 index 0000000000..7792c68b7c --- /dev/null +++ b/crates/ui-egui/tests/crop_default_mode.rs @@ -0,0 +1,161 @@ +//! Crop tool, Photoshop's default mode (#1919), through the real canvas: egui pointer and key +//! events on the full app UI, frames in between, as a user's drag arrives. +//! +//! In the default mode the view moves and turns with the image while the box stays put on +//! screen. The canvas works on a copy of the view for the frame and writes it back at the end, so +//! a view change made by the Crop tool during the frame used to be lost: a drag inside the box +//! made the box wander instead of moving the image, and a resize with Auto Center Preview didn't +//! keep the box's centre in place. Tests driving `tool_event` directly never saw that. +//! +//! Skips when no GPU +//! adapter exists (like `crop_beyond_canvas.rs`). + +use egui::{Key, Modifiers, PointerButton, Pos2, pos2, vec2}; +use photocraft_ui_egui::PhotocraftApp; +use photocraft_ui_egui::canvas::ViewXform; +use photocraft_ui_egui::control::{ControlRequest, handle}; +use serde_json::{Value, json}; + +type Harness = egui_kittest::Harness<'static, PhotocraftApp>; + +fn harness() -> Option { + let built = std::panic::catch_unwind(|| { + egui_kittest::Harness::builder().with_size(egui::vec2(900.0, 640.0)).with_max_steps(64).wgpu().build_eframe(|cc| { + PhotocraftApp::setup_context(&cc.egui_ctx, Default::default()); + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + if let Some(rs) = cc.wgpu_render_state.as_ref() { + app.set_wgpu(rs.clone()); + } + app + }) + }); + match built { + Ok(h) => Some(h), + Err(_) => { + eprintln!("skipping: no GPU adapter"); + None + } + } +} + +fn control(h: &mut Harness, method: &str, params: Value) { + let ctx = h.ctx.clone(); + let (req, _rx) = ControlRequest::new(method, params); + handle(h.state_mut(), &ctx, &req); + h.run_steps(3); +} + +fn xf(h: &Harness) -> ViewXform { + ViewXform::active(h.state()).expect("a view") +} + +/// The crop box's corners on screen. +fn screen_box(h: &Harness) -> [Pos2; 4] { + let app = h.state(); + let r = app.ui.crop_rect.expect("a frame"); + let x = xf(h); + photocraft_ui_egui::crop_ui::corners(r, photocraft_ui_egui::crop_ui::angle(app)).map(|p| x.to_screen(p[0] as f32, p[1] as f32)) +} + +fn mid(q: [Pos2; 4]) -> Pos2 { + pos2((q[0].x + q[2].x) / 2.0, (q[0].y + q[2].y) / 2.0) +} + +fn press(h: &mut Harness, p: Pos2, pressed: bool) { + h.event(egui::Event::PointerMoved(p)); + h.event(egui::Event::PointerButton { pos: p, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE }); + h.step(); +} + +/// A drag in screen points, `steps` frames of moves; `each` runs after every move frame. +fn drag(h: &mut Harness, from: Pos2, to: Pos2, steps: usize, mut each: impl FnMut(&mut Harness, usize)) { + press(h, from, true); + for i in 1..=steps { + let t = i as f32 / steps as f32; + h.event(egui::Event::PointerMoved(from + (to - from) * t)); + h.step(); + each(h, i); + } + press(h, to, false); + h.run_steps(2); +} + +fn setup() -> Option { + let mut h = harness()?; + h.run_steps(4); + { + let app = h.state_mut(); + app.run("file.new", json!({"width": 300, "height": 200, "background": "white"})).expect("new"); + app.run("select.rect", json!({"x": 100, "y": 50, "width": 60, "height": 60})).expect("select"); + app.run("edit.fill", json!({"color": "#ff0000"})).expect("fill"); + app.run("select.deselect", json!({})).expect("deselect"); + app.sync_views(); + app.ui.extras.rulers = false; + app.ui.extras.snap = false; + app.ui.view.show.smart_guides = false; + } + control(&mut h, "ui.set", json!({"tool": "crop", "zoom": 1.0, "center": [150, 100]})); + h.run_steps(3); + let s = &h.state().ui.tool_options.crop_shield; + assert!(!s.classic_mode && s.auto_center_preview, "Photoshop's defaults"); + Some(h) +} + +#[test] +fn dragging_inside_moves_the_image_and_the_box_stays_centred() { + let Some(mut h) = setup() else { return }; + assert!(!photocraft_ui_egui::crop_ui::pending(h.state()), "the untouched frame"); + let c = h.state().last_canvas_rect.center(); + // Inside the untouched frame a drag draws a new box; Auto Center Preview centres it. + drag(&mut h, c + vec2(-100.0, -60.0), c + vec2(60.0, 40.0), 6, |_, _| {}); + assert!(photocraft_ui_egui::crop_ui::pending(h.state()), "a real frame now"); + let box0 = screen_box(&h); + assert!(mid(box0).distance(c) < 1.0, "the drawn box is centred: {:?} vs {c:?}", mid(box0)); + let r0 = h.state().ui.crop_rect.expect("frame"); + let red0 = xf(&h).to_screen(130.0, 80.0); + // Inside the box: the image moves with the pointer, the box stays put. + let (from, to) = (mid(box0) + vec2(-20.0, -10.0), mid(box0) + vec2(40.0, 30.0)); + drag(&mut h, from, to, 8, |h, i| { + let b = screen_box(h); + assert!(mid(b).distance(mid(box0)) < 0.5, "frame {i}: the box stays put: {:?} vs {:?}", mid(b), mid(box0)); + // The image follows the pointer. + let t = i as f32 / 8.0; + let want = red0 + (to - from) * t; + let red = xf(h).to_screen(130.0, 80.0); + assert!(red.distance(want) < 0.5, "frame {i}: the image under the pointer: {red:?} vs {want:?}"); + }); + let b = screen_box(&h); + assert!(mid(b).distance(mid(box0)) < 0.5, "after the release: {:?} vs {:?}", mid(b), mid(box0)); + let r = h.state().ui.crop_rect.expect("frame"); + assert!((r[0] - (r0[0] - 60.0)).abs() < 0.5 && (r[1] - (r0[1] - 40.0)).abs() < 0.5, "the frame lies 60, 40 up-left on the image: {r:?} (was {r0:?})"); + assert_eq!((r[2] - r[0], r[3] - r[1]), (r0[2] - r0[0], r0[3] - r0[1]), "same size"); +} + +#[test] +fn a_resize_keeps_the_box_centre_after_a_space_pan() { + let Some(mut h) = setup() else { return }; + // Space held: the temporary Hand pans the view 80, 40. + let c = h.state().last_canvas_rect.center(); + h.event(egui::Event::Key { key: Key::Space, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::NONE }); + h.step(); + drag(&mut h, c + vec2(0.0, 200.0), c + vec2(80.0, 240.0), 4, |_, _| {}); + h.event(egui::Event::Key { key: Key::Space, physical_key: None, pressed: false, repeat: false, modifiers: Modifiers::NONE }); + h.run_steps(3); + let box0 = screen_box(&h); + assert!(mid(box0).distance(c + vec2(80.0, 40.0)) < 1.0, "panned: {:?}", mid(box0)); + // The right edge, dragged 48 out over several frames (8 a frame: past egui's drag threshold). + let right = pos2(box0[1].x, (box0[1].y + box0[2].y) / 2.0); + drag(&mut h, right, right + vec2(48.0, 0.0), 6, |h, i| { + let b = screen_box(h); + assert!(mid(b).distance(mid(box0)) < 0.5, "frame {i}: the centre stays put: {:?} vs {:?}", mid(b), mid(box0)); + let want = right.x + 48.0 * i as f32 / 6.0; + assert!((b[1].x - want).abs() < 0.5, "frame {i}: the handle follows the pointer: {} vs {want}", b[1].x); + }); + // On the image the left edge stayed put: the frame grew 96 to the right. + let r = h.state().ui.crop_rect.expect("frame"); + assert!((r[0] - 0.0).abs() < 0.5 && (r[2] - 396.0).abs() < 0.5, "{r:?}"); + // On release the box stays at the panned position (Photoshop doesn't snap it back to the + // middle). + let b = screen_box(&h); + assert!(mid(b).distance(mid(box0)) < 0.5, "still where it was: {:?} vs {:?}", mid(b), mid(box0)); +} diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 18d2f64563..1443d7b81d 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -51,7 +51,7 @@ The transport is `apps/photocraft/src/control_server.rs`, and the handlers are i - `ui.set` also accepts the Eyedropper options bar (#1649): `eyedropperSampleSize` (`"point"` or 1, 3, 5, 11, 31, 51, 101: the side of the averaged square, shared by the Eyedropper, a painting tool's Alt-click eyedropper, the Curves/Color Picker eyedroppers and the Info panel), `eyedropperSample` (`current`, `currentAndBelow`, `all`, `allNoAdjustments`, `currentAndBelowNoAdjustments`) and `eyedropperRing` (boolean, Show Sampling Ring). `ui.inspect` reports them under `toolOptions` (`eyedropper_size`, `eyedropper_sample`, `eyedropper_ring`). The engine command `document.sampleColor {x, y, size, sampleLayer}` returns the colour such a sample picks. - `ui.set` also accepts the Crop tool's overlay menu (#1919): `cropOverlay` (`thirds`, `grid`, `diagonal`, `triangle`, `goldenRatio`, `goldenSpiral`), `cropOverlayShow` (`auto`: only while the crop box is dragged, Photoshop's default; `always`; `never`) and `cropOverlayOrientation` (0..3; Triangle has two orientations and Golden Spiral four, the others ignore it). `ui.inspect` reports them under `toolOptions` (`crop_overlay`, `crop_overlay_show`, `crop_overlay_orientation`). In the app, O cycles the overlay and ⇧O its orientation while the Crop tool shows a box. Both gradient modes use the current preset, including its opacity stops. Select `Foreground to Transparent` through `gradient.presets.select`, or pass custom `stops` and `transparency: [[0,100],[1,0]]` (location 0..1, opacity 0..100). Use `applyToLayer: false` to edit only the tool preset. Classic gradient drags dispatch `paint.gradient` without overriding them. -- `ui.set` also accepts the Crop tool's gear menu (#1919) as `cropShield`, an object patching any of `show_cropped_area` (Show Cropped Area; off hides everything outside the box behind the canvas colour, H in the app), `enabled` (Enable Crop Shield), `color` (`matchCanvas`, the pasteboard colour, or `custom`), `custom_color` (`[r, g, b]`, 0..255), `opacity` (0..100, default 75) and `auto_adjust` (Auto Adjust Opacity: half the opacity while the box is dragged). `ui.inspect` reports it as `toolOptions.crop_shield`. +- `ui.set` also accepts the Crop tool's gear menu (#1919) as `cropShield`, an object patching any of `show_cropped_area` (Show Cropped Area; off hides everything outside the box behind the canvas colour, H in the app), `enabled` (Enable Crop Shield), `color` (`matchCanvas`, the pasteboard colour, or `custom`), `custom_color` (`[r, g, b]`, 0..255), `opacity` (0..100, default 75), `auto_adjust` (Auto Adjust Opacity: half the opacity while the box is dragged), `classic_mode` (Use Classic Mode, default off: the box turns and moves over the image; off is Photoshop's default mode, where the box stays upright and the view turns and pans the image behind it while the Crop tool shows a frame, P in the app; in both modes picking the tool turns a rotated view upright about its centre, Classic Mode keeping the camera upright with the frame drawn turned, and the view stays upright after a commit or cancel; Classic Mode greys out Show Cropped Area, which then acts as on, and Auto Center Preview) and `auto_center_preview` (default on: in default mode a box being resized keeps its centre where it is on screen, also after a pan, a drawn one moves to the middle of the canvas, and X re-centres it; a move never re-centres the box). `ui.inspect` reports it as `toolOptions.crop_shield`. The pending frame (`crop_rect`, `crop_angle`: its turn on the image) and the `image.crop` a commit runs are the same in both modes. - `ui.dialog.open {kind, fields?}` (kinds `newDocument`, `about`, `layerStyle {effect?}`, `colorPicker {target: foreground|background}`, `command {command}`) / `ui.dialog.set {dialog, field, value}` / `ui.dialog.confirm {dialog, wait?}` / `ui.dialog.cancel {dialog}`. Like `ui.menu.invoke`, `ui.dialog.confirm` waits for a background job its command starts (a filter dialog's OK) and replies with the result; `"wait": false` replies `{job, pending: true}` at once - A Layer Style color field opens the shared picker with `ui.dialog.open {"kind":"colorPicker","parent":12,"effect":"fx2","field":"color"}`. `parent` is the Layer Style dialog id; `effect` is its effect instance id. `field` must be one of that instance's color parameters (`color`, or `from`/`to` for Gradient Overlay). The picker previews over the pending style without changing the document. Picker OK changes only the parent parameter; Cancel discards the preview. Confirm the parent afterwards to apply the style. Parent confirmation is refused while its picker is open; parent cancellation closes both. The binding is exposed in `ui.inspect` as `__layerStyleColor`; changed/closed targets or a document switch invalidate it. - `ui.dialog.open {kind:"colorPicker", textStyle:{kind:"character"|"paragraph", id:u32}}` opens the shared Color Picker for an explicitly enabled Color attribute in Style Options. It opens the matching style panel/editor after validation; inherited colors must first be enabled through the existing style command. The picker reports its bound document/revision/style under `__textStyleColor` in `ui.inspect`. Changes preview in an isolated document; OK runs the existing style `set` command once, Cancel changes nothing. Document edits/switches or closed/changed Style Options discard the picker. `textStyle` cannot be combined with `parent`, `effect`, `field` or `target`. @@ -61,7 +61,7 @@ The transport is `apps/photocraft/src/control_server.rs`, and the handlers are i - Edit › Fill… (`ui.menu.invoke {id: "edit.fill"}`, Shift+F5, Shift+Backspace) opens the Fill dialog; its fields are `edit.fill`'s params (`contents`, `color`, `pattern`, `colorAdaptation`, `mode`, `opacity`, `preserveTransparency`), and OK remembers them in the preferences (`dialogs["edit.fill"]`). - A pixel tool pressed on a type, shape, Smart Object or fill layer (e.g. through `ui.pointer`) opens the "Rasterize?" prompt instead of painting: a dialog with `__rasterize` (`type|shape|smartObject|fill`), `message`, `layer`, `tool` and `at`. `ui.dialog.confirm` runs the `layer.rasterize.*` command and then paints at `at` (two history states, `{"rasterized", "painted"}`); `ui.dialog.cancel` does nothing. - `ui.window.open {document?}` / `ui.window.close {window}`: extra document windows -- `ui.pointer {events: [{kind: down|move|up, x, y, pressure?, tiltX?, tiltY?, rotation?}], tool?, modifiers?, button?}`: drive the active tool in document coordinates (pressure 0..1, tilt in degrees -90..90, barrel rotation 0..360: a simulated pen). Modifier flags (`shift`, `alt`, `command`, `ctrl`, `space`) go either at the top level or grouped under `modifiers`; when `modifiers` is present, top-level flags are ignored. `space: true` holds Space (the Crop frame, marquee, lasso or shape being drawn then moves instead of growing). `command: true` with a painting, retouching, eraser, gradient, eyedropper or other non-selection tool makes the gesture the Move tool's, as holding ⌘ (Ctrl off the Mac) does in the app: a drag moves the active layer (the selected pixels when there is a selection), with `alt: true` as well it duplicates the layer first, and a click picks the layer under the point; the tool is unchanged afterwards. The Hand, Rotate View, Zoom, Crop, Slice, Path Selection, Pen, shape, Type and selection tools keep `command` for themselves. `ctrl: true` with `alt: true` and a brush tool is the on-canvas brush resize instead (in the app, Ctrl+Alt-drag off the Mac). `button: "right"` (or `"secondary"`) is the right button: with the Move tool (or `command: true` with any tool) it opens the canvas layer menu (`layerMenu` in `ui.inspect` lists the layers there, topmost first; select one with `layer.select`); with Marquee, Lasso, Magic Wand, Object Selection, or Pen it opens a tool context menu (`canvasToolMenu` in `ui.inspect`, with ordered command ids, separators, and enabled states); with a painting tool it opens the Brush Preset picker, or erases with Preferences › Tools › Right-click with painting tools = erase. The menus open at the screen position of the pressed document point. Use `ui.context.choose {id}` for enabled tool-context actions. The Pen menu is documented in `docs/context-menu-parity.md`. With a Color Picker as the top dialog, `down` and `move` sample the image into its new colour instead (its eyedropper, like a click on the canvas) and the tool is not driven. A `down`/`up` at the same point with the Rectangle, Ellipse, Triangle or Polygon tool opens Create Rectangle / Ellipse / Triangle / Polygon (Photoshop's click-to-size dialog); set its `width` and `height` (document pixels), `fromCenter`, `radii` [tl, tr, br, bl] (Rectangle) or `sides` and `starRatio` (percent, Polygon) with `ui.dialog.set`, then `ui.dialog.confirm` runs `shape.create` at the clicked point. +- `ui.pointer {events: [{kind: down|move|up, x, y, pressure?, tiltX?, tiltY?, rotation?}], tool?, modifiers?, button?}`: drive the active tool in document coordinates (pressure 0..1, tilt in degrees -90..90, barrel rotation 0..360: a simulated pen). Modifier flags (`shift`, `alt`, `command`, `ctrl`, `space`) go either at the top level or grouped under `modifiers`; when `modifiers` is present, top-level flags are ignored. `space: true` holds Space (the Crop frame, marquee, lasso or shape being drawn then moves instead of growing). With the Crop tool in its default mode (Use Classic Mode off) a drag inside the box moves the image and one outside turns it, the view panning and turning with it; a drag's `move`/`up` points are read as the view showed the document at its `down`, so an `up` where the last `move` was changes nothing more. `command: true` with a painting, retouching, eraser, gradient, eyedropper or other non-selection tool makes the gesture the Move tool's, as holding ⌘ (Ctrl off the Mac) does in the app: a drag moves the active layer (the selected pixels when there is a selection), with `alt: true` as well it duplicates the layer first, and a click picks the layer under the point; the tool is unchanged afterwards. The Hand, Rotate View, Zoom, Crop, Slice, Path Selection, Pen, shape, Type and selection tools keep `command` for themselves. `ctrl: true` with `alt: true` and a brush tool is the on-canvas brush resize instead (in the app, Ctrl+Alt-drag off the Mac). `button: "right"` (or `"secondary"`) is the right button: with the Move tool (or `command: true` with any tool) it opens the canvas layer menu (`layerMenu` in `ui.inspect` lists the layers there, topmost first; select one with `layer.select`); with Marquee, Lasso, Magic Wand, Object Selection, or Pen it opens a tool context menu (`canvasToolMenu` in `ui.inspect`, with ordered command ids, separators, and enabled states); with a painting tool it opens the Brush Preset picker, or erases with Preferences › Tools › Right-click with painting tools = erase. The menus open at the screen position of the pressed document point. Use `ui.context.choose {id}` for enabled tool-context actions. The Pen menu is documented in `docs/context-menu-parity.md`. With a Color Picker as the top dialog, `down` and `move` sample the image into its new colour instead (its eyedropper, like a click on the canvas) and the tool is not driven. A `down`/`up` at the same point with the Rectangle, Ellipse, Triangle or Polygon tool opens Create Rectangle / Ellipse / Triangle / Polygon (Photoshop's click-to-size dialog); set its `width` and `height` (document pixels), `fromCenter`, `radii` [tl, tr, br, bl] (Rectangle) or `sides` and `starRatio` (percent, Polygon) with `ui.dialog.set`, then `ui.dialog.confirm` runs `shape.create` at the clicked point. - Magnetic Lasso (`tool: "magneticLasso"`): a `down`/`up` pair is a click. The first sets the first fastening point (its modifiers set the selection mode); later clicks fasten a point, or close the border on the first point. `move` events trace the border with or without a button held, fastening points by themselves; with `alt: true` a click draws a straight segment and a drag a freehand one. `ui.inspect` shows the border in progress under `magnetic` (`path`, `anchors`, `live`, `mode`). `ui.key` Enter closes it along the edges, Backspace removes the last fastening point, Escape cancels. To select along edges in one call instead, use the `select.magneticLasso` command with rough points around the shape. - `ui.click {x, y, button?, count?}` / `ui.move {x, y}`: synthetic pointer input in screen points (`button`: `left` (default), `right` or `middle`). `count` (default 1, `2` for a double-click) is at most 256; a larger one is an error and queues nothing - `ui.key {key, command?, shift?, alt?, ctrl?}` (flags may also be grouped under `modifiers`): press and release a key, e.g. `{"key": "ArrowLeft", "shift": true}` diff --git a/docs/scorecard.md b/docs/scorecard.md index 0967d73af3..1259424029 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 | 22 | 56 scenarios: 3 within budget, 22 over budget or failing, 9 tracked only, 15 not run, 7 not measurable yet (baseline 2026-10-05) | | [File compatibility](#file-compatibility) | 5 | 11 | 11 | io corpus: oracle ≥ 146/170, round trip ≥ 169/170; psd-tools corpus: oracle ≥ 236/309, round trip ≥ 308/309; photoshop oracles: oracle ≥ 133/256, round trip ≥ 258/256 | -| [Tools](#tools) | 20 | 15 | 6 | | +| [Tools](#tools) | 21 | 15 | 6 | | | [Workspace and UI](#workspace-and-ui) | 6 | 7 | 10 | settings that do nothing: 46 of 149 (target 0) | | [Type](#type) | 0 | 3 | 6 | | | [Automation](#automation) | 3 | 2 | 6 | 628 of 628 menu items live (100.0%) | @@ -165,10 +165,11 @@ Corpus floors (`crates/io/tests/corpus.rs`): the enforced minimums; the corpus t | TOOL-214-17 | Rotate View tool: drag to turn the view, Reset View, Match Rotation copies the angle | done | [#214](https://github.com/storytold/photocraft/issues/214) | Tool::RotateView in the Hand flyout; view.rotateView / view.resetView; Match Rotation copies views[].rotation; enhanced_controls.rotate_view_with_trackpad is read | | TOOL-1649-1 | Eyedropper Sample Size (Point, 3×3 … 101×101 Average), Sample layers, Show Sampling Ring | done | [#1649](https://github.com/storytold/photocraft/issues/1649) | document.sampleColor (sample_cmds.rs): average of the square clipped to the canvas, in the document's model and depth; eyedropper_ui.rs options bar; shared with Alt-click, dialog eyedroppers and the Info panel; ui.set eyedropperSampleSize/eyedropperSample/eyedropperRing. Color Sampler tool still missing | | TOOL-214-20 | Crop overlay options: Rule of Thirds, Grid, Diagonal, Triangle, Golden Ratio, Golden Spiral; Auto / Always / Never Show Overlay; O cycles the overlay, Shift+O its orientation | done | [#1919](https://github.com/storytold/photocraft/issues/1919) | crop_overlay.rs: unit-square guides shared by upright and turned frames (canvas.rs), options-bar menu, O / Shift+O ahead of the tool keys in shortcuts.rs; ToolOptions crop_overlay / crop_overlay_show / crop_overlay_orientation, ui.set cropOverlay / cropOverlayShow / cropOverlayOrientation | -| TOOL-214-18 | Crop: drag outside the frame to rotate it (Shift 15 deg steps, angle readout); Enter rotates and crops in one step | done | [#1792](https://github.com/storytold/photocraft/issues/1792) | image.crop angle param (image_cmds.rs: Image Rotation > Arbitrary + crop, one undo step); crop_ui.rs turns, moves and resizes the frame along its axes (Classic Mode visuals); UiState.crop_angle | +| TOOL-214-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; default mode turns the image instead, TOOL-214-23); 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 | -| TOOL-214-22 | Crop gear menu: Show Cropped Area (H), Enable Crop Shield with Match Canvas / custom colour, opacity and Auto Adjust Opacity | done | [#1919](https://github.com/storytold/photocraft/issues/1919) | crop_shield.rs: fill() resolves the shield (canvas.rs paints it around upright and turned frames), gear popup in the options bar, H ahead of the Hand key in shortcuts.rs, Custom… opens the Color Picker; ToolOptions crop_shield, ui.set cropShield. No Classic Mode / Auto Center Preview (PhotoCraft is always Classic Mode) | +| TOOL-214-22 | Crop gear menu: Show Cropped Area (H), Enable Crop Shield with Match Canvas / custom colour, opacity and Auto Adjust Opacity | done | [#1919](https://github.com/storytold/photocraft/issues/1919) | crop_shield.rs: fill() resolves the shield (canvas.rs paints it around upright and turned frames), gear popup in the options bar, H ahead of the Hand key in shortcuts.rs, Custom… opens the Color Picker; ToolOptions crop_shield, ui.set cropShield. Use Classic Mode / Auto Center Preview: TOOL-214-23 | +| TOOL-214-23 | Crop: Photoshop's default mode (the image turns and moves behind an upright box, Auto Center Preview keeps a resized box's centre in place and centres a drawn one) and Use Classic Mode (P) in the gear menu | done | [#1919](https://github.com/storytold/photocraft/issues/1919) | crop_mode.rs: the crop model (crop_rect + crop_angle) and image.crop are shared by both modes; default mode sets the view's rotation to -crop_angle while the tool shows a frame (picking the tool, in either mode, turns a Rotate View turn upright about the view centre, not restored after Enter/Esc or by P; Classic Mode keeps the camera upright with the frame drawn turned; as Photoshop 25.1), pivoting so the box stays put, moves view and frame together for drags inside and arrow keys, keeps a resized box's centre in place live (Auto Center Preview; a drawn box is centred on release, a moved one never), readout = the image's turn; gear menu order and Classic Mode greying as Photoshop 25.1; CropShield classic_mode / auto_center_preview (ui.set cropShield), P ahead of the Pen key | | TOOL-1053-1 | Shape stroke controls: solid/dashed/dotted, custom dash/gap/offset, caps, joins, alignment, miter limit and opacity | done | [#1053](https://github.com/storytold/photocraft/issues/1053) | shape_stroke_ui.rs: shared staged editor, renderer samples, cached Properties canvas preview; existing shape.create/edit/info; serde tool defaults, ui.set shapeStroke; pcraft and vstk style round trips. Gradient fill UI and saved stroke libraries remain open; Line retains filled-bar geometry | | TOOL-213-19 | Remove tool: paint over an object (or circle it) and it is filled from its surroundings | partial | [#213](https://github.com/storytold/photocraft/issues/213) | paint.remove (retouch_cmds/remove.rs, background job) + Tool::Remove in the J flyout; loops close over what they enclose; fill by non-local patch completion with texture features, onion-peel start, best-patch copy and gradient-domain seam hiding (algo/nonlocal.rs, Newson et al. IPOL 2017); sparse holes in tiles (algo/remove.rs). remove_quality on 20 holes in public-domain photos: the fill keeps 0.89 of the texture it replaces (0.54 with Content-Aware Fill's completion), edge gradient 1.03 of the original's; remove_bench 24 MP: 100 px ring 120 ms, 1000 px ring 2.5 s, 3000 px line 1.7 s. Missing: generative AI mode, Remove after each stroke off, live preview of the result | diff --git a/scorecard/tools.toml b/scorecard/tools.toml index ea6cee3afb..65464e1c43 100644 --- a/scorecard/tools.toml +++ b/scorecard/tools.toml @@ -255,7 +255,7 @@ 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" +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; default mode turns the image instead, TOOL-214-23); UiState.crop_angle" [[item]] id = "TOOL-214-19" @@ -276,7 +276,14 @@ id = "TOOL-214-22" target = "Crop gear menu: Show Cropped Area (H), Enable Crop Shield with Match Canvas / custom colour, opacity and Auto Adjust Opacity" status = "done" issue = 1919 -note = "crop_shield.rs: fill() resolves the shield (canvas.rs paints it around upright and turned frames), gear popup in the options bar, H ahead of the Hand key in shortcuts.rs, Custom… opens the Color Picker; ToolOptions crop_shield, ui.set cropShield. No Classic Mode / Auto Center Preview (PhotoCraft is always Classic Mode)" +note = "crop_shield.rs: fill() resolves the shield (canvas.rs paints it around upright and turned frames), gear popup in the options bar, H ahead of the Hand key in shortcuts.rs, Custom… opens the Color Picker; ToolOptions crop_shield, ui.set cropShield. Use Classic Mode / Auto Center Preview: TOOL-214-23" + +[[item]] +id = "TOOL-214-23" +target = "Crop: Photoshop's default mode (the image turns and moves behind an upright box, Auto Center Preview keeps a resized box's centre in place and centres a drawn one) and Use Classic Mode (P) in the gear menu" +status = "done" +issue = 1919 +note = "crop_mode.rs: the crop model (crop_rect + crop_angle) and image.crop are shared by both modes; default mode sets the view's rotation to -crop_angle while the tool shows a frame (picking the tool, in either mode, turns a Rotate View turn upright about the view centre, not restored after Enter/Esc or by P; Classic Mode keeps the camera upright with the frame drawn turned; as Photoshop 25.1), pivoting so the box stays put, moves view and frame together for drags inside and arrow keys, keeps a resized box's centre in place live (Auto Center Preview; a drawn box is centred on release, a moved one never), readout = the image's turn; gear menu order and Classic Mode greying as Photoshop 25.1; CropShield classic_mode / auto_center_preview (ui.set cropShield), P ahead of the Pen key" [[item]] id = "TOOL-1053-1"