diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index d2e535f3f64..4715613a872 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -3704,9 +3704,11 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect: && !crate::layer_pick_ui::is_gesture(tool, mods) && let Some(p) = response.interact_pointer_pos() { + // A pending crop: its menu, also outside the image, where the frame can reach (#6561). // Outside the image: the pasteboard colour menu (#2462), else the tool's own. The view // menu belongs to the selected Zoom or Hand, not to Space or a held zoom key. - if crate::canvas_tool_menu::pasteboard_at(app, tool, xf.to_doc(p)) { + if crate::canvas_tool_menu::open_crop(app, &ctx, tool, [p.x, p.y]) { + } else if crate::canvas_tool_menu::pasteboard_at(app, tool, xf.to_doc(p)) { crate::canvas_tool_menu::open_pasteboard(app, &ctx, tool, [p.x, p.y]); } else if crate::canvas_tool_menu::is_view_tool(tool) { if tool == app.ui.tool { diff --git a/crates/ui-egui/src/canvas_tool_menu.rs b/crates/ui-egui/src/canvas_tool_menu.rs index 43418d5ff9c..df77c709766 100644 --- a/crates/ui-egui/src/canvas_tool_menu.rs +++ b/crates/ui-egui/src/canvas_tool_menu.rs @@ -1,6 +1,6 @@ //! Canvas context menus for the selection tools, the Pen, the Zoom and Hand tools, an active Free //! Transform box, text being edited with a Type tool, committed type under a Type tool, the -//! pasteboard (outside the image) and a guide. +//! pasteboard (outside the image), a guide and a pending crop. use egui::Context; use photocraft_doc::LayerContent; @@ -42,6 +42,10 @@ pub struct CanvasToolMenu { /// the menu. #[serde(default)] pub spelling: Option, + /// Opened on a pending crop: the crop menu, listing the saved crop presets by the names they + /// had when it opened. + #[serde(default)] + pub crop: Option>, } /// A misspelled word in the type layer being edited (`edit.checkSpelling`'s `list` entry). @@ -63,7 +67,7 @@ const SPELLING_NONE: &str = "spelling.none"; const SPELLING_ADD: &str = "spelling.add"; /// One menu row: label and command id. `None` is a separator. -pub type Row = Option<(&'static str, &'static str)>; +pub type Row = Option<(S, S)>; /// Right-click while transforming, in Photoshop's order: what the box's handles do, then Rotate /// and Flip, which turn the open box without committing it (`transform_tool::intercept`). @@ -196,6 +200,146 @@ pub const GUIDE_MENU: &[Row] = &[ Some(("Clear Selected Artboard Guides", "view.clearSelectedArtboardGuides")), ]; +/// The crop menu's row ids. A ratio row is `crop.ratio.`, the options bar's preset dropdown +/// key (`crop_size::dropdown_options`); a saved preset is `crop.preset.`, the n-th name the menu +/// opened with; an overlay row is `crop.overlay.` or `crop.overlayShow.`. +const CROP_RATIO: &str = "crop.ratio."; +const CROP_PRESET: &str = "crop.preset."; +const CROP_OVERLAY: &str = "crop.overlay."; +const CROP_SHOW: &str = "crop.overlayShow."; +pub const CROP_CLEAR: &str = "crop.clear"; +pub const CROP_NEW: &str = "crop.newPreset"; +pub const CROP_DELETE: &str = "crop.deletePreset"; +pub const CROP_CANCEL: &str = "crop.cancel"; +pub const CROP_COMMIT: &str = "crop.commit"; + +/// The crop menu (right-click on a pending crop, #6561): the options bar's preset dropdown, in its +/// order, and its Clear; the overlay and when it shows; then Cancel and Crop, the bar's ⊘ and ✓. +/// Built from the bar's own lists, so the two cannot disagree. Empty for any other menu. +pub fn crop_rows(menu: &CanvasToolMenu) -> Vec> { + use crate::crop_overlay::{CropOverlay, OverlayShow}; + let Some(users) = menu.crop.as_ref() else { return Vec::new() }; + let ratio = |(k, l): &(String, &str)| Some((l.to_string(), format!("{CROP_RATIO}{k}"))); + let (before, after): (Vec<_>, Vec<_>) = crate::crop_size::dropdown_options().into_iter().partition(|(k, _)| k != crate::crop_size::FRONT); + let mut rows: Vec> = before.iter().map(ratio).collect(); + rows.extend(users.iter().enumerate().map(|(i, name)| Some((name.clone(), format!("{CROP_PRESET}{i}"))))); + rows.extend(after.iter().map(ratio)); + rows.push(Some(("Clear".into(), CROP_CLEAR.into()))); + rows.push(None); + rows.push(Some(("New Crop Preset…".into(), CROP_NEW.into()))); + rows.push(Some(("Delete Crop Preset…".into(), CROP_DELETE.into()))); + rows.push(None); + rows.extend(CropOverlay::ALL.iter().map(|k| Some((k.label().to_string(), format!("{CROP_OVERLAY}{}", k.id()))))); + rows.push(None); + rows.extend(OverlayShow::ALL.iter().map(|k| Some((k.label().to_string(), format!("{CROP_SHOW}{}", k.id()))))); + rows.push(None); + rows.push(Some(("Cancel".into(), CROP_CANCEL.into()))); + rows.push(Some(("Crop".into(), CROP_COMMIT.into()))); + rows +} + +/// Is a crop row's label UI text (translated), rather than a saved preset's name? +pub fn crop_label_is_ui(id: &str) -> bool { + !id.starts_with(CROP_PRESET) +} + +/// Is `command` one of the crop menu's rows? +fn is_crop(menu: &CanvasToolMenu, command: &str) -> bool { + crop_rows(menu).iter().flatten().any(|(_, id)| id == command) +} + +/// The saved crop preset a `crop.preset.` row picks. +fn crop_preset<'a>(menu: &'a CanvasToolMenu, command: &str) -> Option<&'a String> { + let n = command.strip_prefix(CROP_PRESET)?.parse::().ok()?; + menu.crop.as_ref()?.get(n) +} + +/// The crop menu's checkmarks, as the options bar shows them: the dropdown's entry (a saved +/// preset the fields hold, else the mode or ratio, so a size preset checks W x H x Resolution), +/// the overlay and when it shows. +fn crop_checked(app: &PhotocraftApp, menu: &CanvasToolMenu, command: &str) -> bool { + let o = &app.ui.tool_options; + let user = crate::crop_presets::current_user(app); + if let Some(k) = command.strip_prefix(CROP_RATIO) { + return user.is_none() && k == o.crop_ratio; + } + if command.starts_with(CROP_PRESET) { + return user.is_some() && crop_preset(menu, command) == user.as_ref(); + } + if let Some(k) = command.strip_prefix(CROP_OVERLAY) { + return k == o.crop_overlay.id(); + } + command.strip_prefix(CROP_SHOW).is_some_and(|k| k == o.crop_overlay_show.id()) +} + +fn crop_enabled(app: &PhotocraftApp, menu: &CanvasToolMenu, command: &str) -> bool { + match command { + CROP_NEW => crate::crop_presets::savable(&app.ui.tool_options).is_some(), + CROP_DELETE => menu.crop.as_ref().is_some_and(|u| !u.is_empty()), + c => is_crop(menu, c), + } +} + +/// Right-click with `tool` on a pending crop: the crop menu at screen point `pos`. Only the Crop +/// tool itself, not one held over it (Space's Hand). +pub fn open_crop(app: &mut PhotocraftApp, ctx: &Context, tool: Tool, pos: [f32; 2]) -> bool { + if tool != Tool::Crop || !crate::crop_ui::pending(app) || !pos.iter().all(|v| v.is_finite()) { + return false; + } + app.ui.brush_picker = None; + app.ui.layer_menu = None; + let users = crate::crop_presets::user_presets(app).into_iter().map(|(name, _)| name).collect(); + app.ui.canvas_tool_menu = Some(CanvasToolMenu { + pos, + tool, + has_selection: false, + has_path: false, + path_name: None, + transform: false, + pasteboard: false, + anchor: None, + text: false, + type_layer: false, + guide: false, + spelling: None, + crop: Some(users), + }); + crate::canvas_popup::mark_open(ctx, menu_id()); + true +} + +/// A crop row: each runs what its options-bar twin runs. +fn choose_crop(app: &mut PhotocraftApp, menu: &CanvasToolMenu, command: &str) -> Result<(), String> { + use crate::crop_overlay::{CropOverlay, OverlayShow}; + use crate::crop_presets::{Choice, apply_choice}; + match command { + CROP_CANCEL => crate::crop_ui::cancel(app), + CROP_COMMIT => crate::canvas::commit_crop(app), + CROP_NEW => apply_choice(app, Choice::New), + CROP_DELETE => apply_choice(app, Choice::Delete), + _ => { + let before = crate::crop_ui::preset_ratio(app); + if let Some(k) = command.strip_prefix(CROP_RATIO) { + apply_choice(app, Choice::Builtin(k.to_string())); + } else if let Some(name) = crop_preset(menu, command) { + apply_choice(app, Choice::User(name.clone())); + } else if command == CROP_CLEAR { + crate::crop_size::clear_ratio(&mut app.ui.tool_options); + } else if let Some(k) = command.strip_prefix(CROP_OVERLAY).and_then(CropOverlay::from_id) { + crate::crop_overlay::set_overlay(&mut app.ui.tool_options, k); + } else if let Some(k) = command.strip_prefix(CROP_SHOW).and_then(OverlayShow::from_id) { + app.ui.tool_options.crop_overlay_show = k; + } + // As the options bar does: a saved preset or Clear changes the ratio without refitting + // the frame, so refit it when the ratio (or W x H) the frame follows changed. + if crate::crop_ui::preset_ratio(app) != before { + crate::crop_ui::apply_ratio(app); + } + } + } + Ok(()) +} + /// The pasteboard colours in the menu's order, which Space+F steps through. const CANVAS_COLORS: [CanvasColor; 6] = [CanvasColor::Default, CanvasColor::Black, CanvasColor::DarkGray, CanvasColor::MediumGray, CanvasColor::LightGray, CanvasColor::Custom]; @@ -337,7 +481,10 @@ pub fn selection_rows(has_selection: bool) -> &'static [Row] { /// The rows of an open menu. pub fn rows(menu: &CanvasToolMenu) -> &'static [Row] { - if menu.guide { + if menu.crop.is_some() { + // Built per menu: [`crop_rows`]. + &[] + } else if menu.guide { GUIDE_MENU } else if menu.pasteboard { PASTEBOARD_MENU @@ -358,13 +505,16 @@ pub fn rows(menu: &CanvasToolMenu) -> &'static [Row] { /// Is `command` one of the open menu's rows, and enabled? pub fn available(app: &PhotocraftApp, menu: &CanvasToolMenu, command: &str) -> bool { - (rows(menu).iter().flatten().any(|(_, id)| *id == command) || is_spelling(menu, command)) && entry_enabled(app, menu, command) + (rows(menu).iter().flatten().any(|(_, id)| *id == command) || is_spelling(menu, command) || is_crop(menu, command)) && entry_enabled(app, menu, command) } /// Is `command` the transform box's current mode (checked in the transform menu)? /// Scale stays Free Transform's mode (only Free Transform is checked). Rotate is its own mode. /// Warp is not a box mode (it is its own session), and `for_command` would read it as Free. pub(crate) fn mode_checked(app: &PhotocraftApp, menu: &CanvasToolMenu, command: &str) -> bool { + if menu.crop.is_some() { + return crop_checked(app, menu, command); + } if menu.guide { return command == "view.lockGuides" && app.ui.extras.lock_guides; } @@ -486,6 +636,7 @@ pub fn open_transform(app: &mut PhotocraftApp, ctx: &Context, pos: [f32; 2]) -> type_layer: false, guide: false, spelling: None, + crop: None, }); crate::canvas_popup::mark_open(ctx, menu_id()); true @@ -500,6 +651,9 @@ fn pasteboard_choice(command: &str) -> Option { /// The engine command (and params) a pasteboard row runs, for the automation policy: every row /// changes a preference. pub fn engine_call(app: &PhotocraftApp, menu: &CanvasToolMenu, command: &str) -> (String, Value) { + if menu.crop.is_some() && command == CROP_COMMIT { + return ("image.crop".into(), json!({})); + } if menu.guide { let selected = crate::guide_select::selected(app); return match command { @@ -560,6 +714,7 @@ pub fn open_pasteboard(app: &mut PhotocraftApp, ctx: &Context, tool: Tool, pos: type_layer: false, guide: false, spelling: None, + crop: None, }); crate::canvas_popup::mark_open(ctx, menu_id()); true @@ -590,6 +745,7 @@ pub fn open_guide(app: &mut PhotocraftApp, ctx: &Context, tool: Tool, mods: egui type_layer: false, guide: true, spelling: None, + crop: None, }); crate::canvas_popup::mark_open(ctx, menu_id()); true @@ -617,6 +773,9 @@ fn choose_pasteboard(app: &mut PhotocraftApp, menu: &CanvasToolMenu, command: &s } pub fn entry_enabled(app: &PhotocraftApp, menu: &CanvasToolMenu, command: &str) -> bool { + if menu.crop.is_some() { + return crop_enabled(app, menu, command); + } if menu.guide { return match command { GUIDE_EDIT | GUIDE_CLEAR => crate::guide_select::selected(app).is_some(), @@ -717,6 +876,7 @@ pub fn open_at(app: &mut PhotocraftApp, ctx: &Context, tool: Tool, pos: [f32; 2] type_layer, guide: false, spelling, + crop: None, }); crate::canvas_popup::mark_open(ctx, menu_id()); true @@ -743,6 +903,7 @@ pub fn open_view(app: &mut PhotocraftApp, ctx: &Context, tool: Tool, pos: [f32; type_layer: false, guide: false, spelling: None, + crop: None, }); crate::canvas_popup::mark_open(ctx, menu_id()); true @@ -779,7 +940,9 @@ pub fn choose(app: &mut PhotocraftApp, ctx: &Context, command: &str) { if !available(app, &menu, command) { return; } - let result = if menu.guide { + let result = if menu.crop.is_some() { + choose_crop(app, &menu, command) + } else if menu.guide { choose_guide(app, ctx, command) } else if menu.pasteboard { choose_pasteboard(app, &menu, command) @@ -925,6 +1088,7 @@ pub fn show(app: &mut PhotocraftApp, ctx: &Context) { || (menu.transform && app.ui.transform.is_none()) || (menu.text && app.ui.text_edit.is_none()) || (menu.type_layer && app.ui.text_edit.is_some()) + || (menu.crop.is_some() && !crate::crop_ui::pending(app)) { app.ui.canvas_tool_menu = None; return; @@ -959,6 +1123,17 @@ pub fn show(app: &mut PhotocraftApp, ctx: &Context) { if !spelling.is_empty() { ui.separator(); } + for row in crop_rows(&menu) { + let Some((label, command)) = row else { + ui.separator(); + continue; + }; + let text = if crop_label_is_ui(&command) { tl!(&label).to_string() } else { label }; + let item = egui::Button::selectable(mode_checked(app, &menu, &command), text).min_size(egui::vec2(200.0, 20.0)); + if ui.add_enabled(entry_enabled(app, &menu, &command), item).clicked() { + selected = Some(command); + } + } for row in rows(&menu) { let Some((label, command)) = *row else { ui.separator(); @@ -1830,4 +2005,158 @@ mod tests { } assert!(entry_enabled(&app, menu, "path.toSelection")); } + + /// A 32 × 32 document with the Crop tool picked (Classic Mode, so the view stays put) and its + /// untouched default frame. + fn crop_app() -> PhotocraftApp { + let mut app = app(); + app.ui.tool = Tool::Crop; + app.ui.tool_options.crop_shield.classic_mode = true; + app.ui.extras.snap = false; + crate::crop_ui::ensure_frame(&mut app); + app + } + + /// Draws a crop frame from (4, 4) to (28, 28): a pending crop. Returns the frame. + fn draw_crop(app: &mut PhotocraftApp) -> [f64; 4] { + use crate::canvas::{ToolEvent, tool_event}; + tool_event(app, ToolEvent::Down { x: 4.0, y: 4.0, pressure: 1.0 }, Modifiers::NONE); + tool_event(app, ToolEvent::Move { x: 16.0, y: 16.0, pressure: 1.0 }, Modifiers::NONE); + tool_event(app, ToolEvent::Move { x: 28.0, y: 28.0, pressure: 1.0 }, Modifiers::NONE); + tool_event(app, ToolEvent::Up { x: 28.0, y: 28.0 }, Modifiers::NONE); + assert!(crate::crop_ui::pending(app), "the drag draws a pending frame"); + app.ui.crop_rect.unwrap() + } + + fn aspect(r: [f64; 4]) -> f64 { + (r[2] - r[0]) / (r[3] - r[1]) + } + + /// #6561: right-click on a pending crop opens its menu without touching the frame, and a ratio + /// row refits the frame as the options bar's dropdown does. + #[test] + fn right_click_on_a_pending_crop_opens_the_crop_menu_and_a_ratio_refits_the_frame() { + let mut app = crop_app(); + let frame = draw_crop(&mut app); + let mut h = harness(app); + let center = h.state().last_canvas_rect.center(); + right_click(&mut h, center, Modifiers::NONE); + let menu = h.state().ui.canvas_tool_menu.clone().expect("right-click on a pending crop opens a menu"); + assert_eq!(h.state().ui.crop_rect, Some(frame), "the right-click leaves the frame alone"); + assert!(available(h.state(), &menu, "crop.ratio.16:9"), "the menu lists the options bar's ratios"); + let ctx = h.ctx.clone(); + choose(h.state_mut(), &ctx, "crop.ratio.16:9"); + assert_eq!(h.state().ui.tool_options.crop_ratio, "16:9"); + let r = h.state().ui.crop_rect.unwrap(); + assert!((aspect(r) - 16.0 / 9.0).abs() < 1e-9, "the frame is 16 : 9 now: {r:?}"); + assert!(r[0] >= frame[0] && r[1] >= frame[1] && r[2] <= frame[2] && r[3] <= frame[3], "fitted inside the old frame: {r:?}"); + assert!(h.state().ui.canvas_tool_menu.is_none()); + } + + #[test] + fn untouched_crop_frame_has_no_menu_and_a_pending_one_wins_over_the_pasteboard() { + let mut h = harness(crop_app()); + let rect = h.state().last_canvas_rect; + let outside = rect.min + vec2(5.0, 5.0); + right_click(&mut h, rect.center(), Modifiers::NONE); + assert!(h.state().ui.canvas_tool_menu.is_none(), "the tool's untouched frame is no crop in progress"); + right_click(&mut h, outside, Modifiers::NONE); + assert!(h.state().ui.canvas_tool_menu.as_ref().is_some_and(|m| m.pasteboard), "outside: the pasteboard menu, as before"); + h.state_mut().ui.canvas_tool_menu = None; + draw_crop(h.state_mut()); + h.run_steps(2); + right_click(&mut h, outside, Modifiers::NONE); + let menu = h.state().ui.canvas_tool_menu.clone().unwrap(); + assert!(menu.crop.is_some() && !menu.pasteboard, "with a crop pending, its menu also outside the image"); + } + + #[test] + fn esc_closes_only_the_crop_menu() { + let mut app = crop_app(); + let frame = draw_crop(&mut app); + app.sync_views(); + let mut h = Harness::builder().with_size(vec2(1000.0, 700.0)).build_ui_state( + |ui, app: &mut PhotocraftApp| { + let ctx = ui.ctx().clone(); + if !ctx.fonts(|f| f.families().contains(&egui::FontFamily::Name("medium".into()))) { + return; + } + // The app's order: shortcuts (the crop's Esc among them), then the canvas. + crate::shortcuts::handle(app, &ctx); + egui::CentralPanel::default().show(ui, |ui| crate::canvas::document_area(app, ui)); + }, + app, + ); + PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::default()); + h.run_steps(4); + let center = h.state().last_canvas_rect.center(); + right_click(&mut h, center, Modifiers::NONE); + assert!(h.state().ui.canvas_tool_menu.as_ref().is_some_and(|m| m.crop.is_some())); + h.key_press(egui::Key::Escape); + h.run_steps(2); + assert!(h.state().ui.canvas_tool_menu.is_none(), "Esc closes the menu"); + assert_eq!(h.state().ui.crop_rect, Some(frame), "and only the menu: the crop is not cancelled"); + assert!(crate::crop_ui::pending(h.state())); + } + + #[test] + fn crop_menu_rows_act_like_the_options_bar() { + use crate::crop_overlay::{CropOverlay, OverlayShow}; + let ctx = Context::default(); + let mut app = crop_app(); + draw_crop(&mut app); + // Space's Hand held over the Crop tool keeps its own right-click. + assert!(!open_crop(&mut app, &ctx, Tool::Hand, [10.0, 10.0])); + let reopen = |app: &mut PhotocraftApp| { + assert!(open_crop(app, &Context::default(), Tool::Crop, [10.0, 10.0])); + app.ui.canvas_tool_menu.clone().unwrap() + }; + // Nothing to save with a free ratio, nothing to delete without saved presets. + let menu = reopen(&mut app); + assert!(!entry_enabled(&app, &menu, CROP_NEW) && !entry_enabled(&app, &menu, CROP_DELETE)); + assert!(mode_checked(&app, &menu, "crop.ratio."), "free Ratio is checked, as in the dropdown"); + // A size preset fills W x H x Resolution, which the menu checks, as the dropdown does. + choose(&mut app, &ctx, "crop.ratio.preset:4x5in"); + let menu = reopen(&mut app); + assert!(mode_checked(&app, &menu, "crop.ratio.whr") && !mode_checked(&app, &menu, "crop.ratio.preset:4x5in")); + assert!((aspect(app.ui.crop_rect.unwrap()) - 0.8).abs() < 1e-9); + assert!(entry_enabled(&app, &menu, CROP_NEW)); + // Clear empties W x H x Resolution, as the bar's Clear. + choose(&mut app, &ctx, CROP_CLEAR); + assert_eq!(app.ui.tool_options.crop_width, ""); + // Overlays: another overlay starts at its first orientation; when it shows. + app.ui.tool_options.crop_overlay = CropOverlay::GoldenSpiral; + app.ui.tool_options.crop_overlay_orientation = 2; + reopen(&mut app); + choose(&mut app, &ctx, "crop.overlay.triangle"); + assert_eq!((app.ui.tool_options.crop_overlay, app.ui.tool_options.crop_overlay_orientation), (CropOverlay::Triangle, 0)); + reopen(&mut app); + choose(&mut app, &ctx, "crop.overlayShow.never"); + assert_eq!(app.ui.tool_options.crop_overlay_show, OverlayShow::Never); + let menu = reopen(&mut app); + assert!(mode_checked(&app, &menu, "crop.overlay.triangle") && mode_checked(&app, &menu, "crop.overlayShow.never")); + // A saved preset is listed by name; picking it refits the frame to its W x H, though the + // ratio key is "whr" before and after. + app.ui.canvas_tool_menu = None; + app.ui.tool_options.crop_ratio = crate::crop_size::WHR.into(); + let saved = json!({"crop_ratio": "whr", "crop_width": "300 px", "crop_height": "100 px", "crop_resolution": "72", "crop_resolution_unit": "px/in"}); + app.run("tool.presets.new", json!({"name": "Banner", "tool": "crop", "options": {"toolOptions": saved}})).unwrap(); + let menu = reopen(&mut app); + let banner = crop_rows(&menu).into_iter().flatten().find(|(l, _)| l == "Banner").expect("the saved preset is a row").1; + assert!(entry_enabled(&app, &menu, CROP_DELETE)); + choose(&mut app, &ctx, &banner); + assert_eq!(app.ui.tool_options.crop_width, "300 px"); + assert!((aspect(app.ui.crop_rect.unwrap()) - 3.0).abs() < 1e-9, "the frame follows the preset: {:?}", app.ui.crop_rect); + let menu = reopen(&mut app); + assert!(mode_checked(&app, &menu, &banner)); + // Crop commits as ↵ does: the preset's size. + choose(&mut app, &ctx, CROP_COMMIT); + let size = app.session.active().unwrap().doc.size; + assert_eq!((size.width, size.height), (300, 100)); + // Cancel drops a pending crop. + draw_crop(&mut app); + reopen(&mut app); + choose(&mut app, &ctx, CROP_CANCEL); + assert!(!crate::crop_ui::pending(&app)); + } } diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs index 46f17357d15..14fd82c5226 100644 --- a/crates/ui-egui/src/control.rs +++ b/crates/ui-egui/src/control.rs @@ -372,12 +372,16 @@ pub fn handle(app: &mut PhotocraftApp, ctx: &egui::Context, req: &ControlRequest /// The open canvas context menu's rows for `ui.state`: the spelling suggestions first (type edit /// menu over a misspelled word), then the menu's own rows. fn context_entries(app: &PhotocraftApp, menu: &crate::canvas_tool_menu::CanvasToolMenu) -> Vec { - use crate::canvas_tool_menu::{entry_enabled, rows, spelling_rows}; + use crate::canvas_tool_menu::{crop_rows, entry_enabled, rows, spelling_rows}; let spelling = spelling_rows(menu); let mut entries: Vec = spelling.iter().map(|(label, id)| json!({"label": label, "id": id, "enabled": entry_enabled(app, menu, id)})).collect(); if !spelling.is_empty() { entries.push(json!({"separator": true})); } + entries.extend(crop_rows(menu).iter().map(|row| match row { + Some((label, id)) => json!({"label": label, "id": id, "enabled": entry_enabled(app, menu, id)}), + None => json!({"separator": true}), + })); entries.extend(rows(menu).iter().map(|row| match row { Some((label, id)) => json!({"label": label, "id": id, "enabled": entry_enabled(app, menu, id)}), None => json!({"separator": true}), @@ -1088,6 +1092,12 @@ fn dispatch(app: &mut PhotocraftApp, ctx: &egui::Context, req: &ControlRequest) } continue; } + if app.ui.tool == crate::state::Tool::Crop && crate::crop_ui::pending(app) { + if down { + crate::canvas_tool_menu::open_crop(app, ctx, app.ui.tool, screen_point(app, x, y)); + } + continue; + } if crate::canvas_tool_menu::pasteboard_at(app, app.ui.tool, [x, y]) { if down { crate::canvas_tool_menu::open_pasteboard(app, ctx, app.ui.tool, screen_point(app, x, y)); @@ -1339,6 +1349,7 @@ pub fn inspect(app: &PhotocraftApp, ctx: &egui::Context) -> Value { "tool": menu.tool, "pasteboard": menu.pasteboard, "guide": menu.guide, + "crop": menu.crop.is_some(), "entries": context_entries(app, menu) }) }), @@ -1871,6 +1882,39 @@ mod tests { assert!(app.ui.canvas_tool_menu.is_none()); } + /// #6561: an agent's right-click on a pending crop opens the crop menu, as on the canvas. + #[test] + fn agent_right_click_on_a_pending_crop_opens_and_runs_the_crop_menu() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + let ctx = egui::Context::default(); + app.run("file.new", json!({"width": 32, "height": 32})).unwrap(); + app.sync_views(); + app.ui.tool = crate::state::Tool::Crop; + app.ui.tool_options.crop_shield.classic_mode = true; + app.ui.extras.snap = false; + crate::crop_ui::ensure_frame(&mut app); + tool_event(&mut app, ToolEvent::Down { x: 4.0, y: 4.0, pressure: 1.0 }, egui::Modifiers::NONE); + tool_event(&mut app, ToolEvent::Move { x: 16.0, y: 12.0, pressure: 1.0 }, egui::Modifiers::NONE); + tool_event(&mut app, ToolEvent::Move { x: 28.0, y: 20.0, pressure: 1.0 }, egui::Modifiers::NONE); + tool_event(&mut app, ToolEvent::Up { x: 28.0, y: 20.0 }, egui::Modifiers::NONE); + let frame = app.ui.crop_rect.unwrap(); + let result = call( + &mut app, + &ctx, + "ui.pointer", + json!({"tool": "Crop", "button": "secondary", "events": [{"kind":"down","x":16,"y":12},{"kind":"up","x":16,"y":12}]}), + ); + assert_eq!(result["ok"], true); + let inspected = call(&mut app, &ctx, "ui.inspect", json!({})); + assert_eq!(inspected.pointer("/result/canvasToolMenu/crop"), Some(&json!(true))); + let entries = inspected.pointer("/result/canvasToolMenu/entries").and_then(Value::as_array).unwrap(); + assert!(entries.iter().any(|row| row.get("id") == Some(&json!("crop.commit")) && row.get("enabled") == Some(&json!(true)))); + assert_eq!(app.ui.crop_rect, Some(frame), "the right-click leaves the frame alone"); + assert_eq!(call(&mut app, &ctx, "ui.context.choose", json!({"id":"crop.commit"}))["ok"], true); + let size = app.session.active().unwrap().doc.size; + assert_eq!([f64::from(size.width), f64::from(size.height)], [frame[2] - frame[0], frame[3] - frame[1]], "cropped to the frame"); + } + #[test] fn agent_can_inspect_and_choose_pen_make_selection_from_full_context_menu() { let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); diff --git a/crates/ui-egui/src/crop_overlay.rs b/crates/ui-egui/src/crop_overlay.rs index b0be59f2b1e..c93f5e12e10 100644 --- a/crates/ui-egui/src/crop_overlay.rs +++ b/crates/ui-egui/src/crop_overlay.rs @@ -249,6 +249,14 @@ pub fn cycle(o: &mut ToolOptions) { o.crop_overlay_orientation = 0; } +/// Picks overlay `k`; another overlay starts at its first orientation. +pub fn set_overlay(o: &mut ToolOptions, k: CropOverlay) { + if o.crop_overlay != k { + o.crop_overlay_orientation = 0; + } + o.crop_overlay = k; +} + /// ⇧O: the overlay's next orientation (nothing for a symmetric one). pub fn cycle_orientation(o: &mut ToolOptions) { let n = o.crop_overlay.orientations().max(1); @@ -288,10 +296,7 @@ pub fn options_button(o: &mut ToolOptions, ui: &mut egui::Ui) { }; for k in CropOverlay::ALL { if item(ui, o.crop_overlay == k, tl!(k.label()), None) { - if o.crop_overlay != k { - o.crop_overlay_orientation = 0; - } - o.crop_overlay = k; + set_overlay(o, k); ui.close(); } } diff --git a/crates/ui-egui/src/crop_presets.rs b/crates/ui-egui/src/crop_presets.rs index e30b0d1cfc2..b0986f9e1eb 100644 --- a/crates/ui-egui/src/crop_presets.rs +++ b/crates/ui-egui/src/crop_presets.rs @@ -34,9 +34,9 @@ pub const MAX_NAME: usize = 255; /// The `ToolOptions` fields a crop preset saves. const KEYS: [&str; 5] = ["crop_ratio", "crop_width", "crop_height", "crop_resolution", "crop_resolution_unit"]; -/// One entry of the preset dropdown. +/// One entry of the preset dropdown (and of the Crop tool's canvas menu). #[derive(Clone, Debug, PartialEq)] -enum Choice { +pub(crate) enum Choice { /// A built-in key (`crop_ratio` value, size preset or Front Image), see [`crop_size::chosen`]. Builtin(String), /// A saved crop preset, by name. @@ -139,7 +139,7 @@ pub fn dropdown(app: &mut PhotocraftApp, ui: &mut egui::Ui) { let users = user_presets(app); let o = &app.ui.tool_options; let label = button_label(o, &builtin, &users); - let current_user = users.iter().rev().find(|(_, f)| matches(o, f)).map(|(n, _)| n.clone()); + let current_user = current_user(app); let can_new = savable(o).is_some(); let mut chosen: Option = None; egui::ComboBox::from_id_salt("crop-ratio").selected_text(label).width(140.0).height(420.0).icon(crate::widgets::chevron_icon).show_ui(ui, |ui| { @@ -167,27 +167,40 @@ pub fn dropdown(app: &mut PhotocraftApp, ui: &mut egui::Ui) { chosen = Some(Choice::Delete); } }); - match chosen { - Some(Choice::Builtin(k)) => { + if let Some(c) = chosen { + apply_choice(app, c); + } +} + +/// What picking a dropdown entry does; the Crop tool's canvas menu picks through it too. +pub(crate) fn apply_choice(app: &mut PhotocraftApp, choice: Choice) { + match choice { + Choice::Builtin(k) => { app.ui.tool_options.crop_ratio = k; // A size preset or Front Image fills W x H x Resolution (#2443). crop_size::chosen(app); sync_custom_ratio_fields(app); } - Some(Choice::User(name)) => { + Choice::User(name) => { select(app, &name); sync_custom_ratio_fields(app); } - Some(Choice::New) => { + Choice::New => { open_new(app); } - Some(Choice::Delete) => { + Choice::Delete => { open_delete(app); } - None => {} } } +/// The saved crop preset whose values the fields hold (the latest saved one first), as the +/// dropdown shows it. +pub(crate) fn current_user(app: &PhotocraftApp) -> Option { + let o = &app.ui.tool_options; + user_presets(app).into_iter().rev().find(|(_, f)| matches(o, f)).map(|(n, _)| n) +} + /// A newly chosen ratio fills the editable custom W/H fields (free Ratio clears them, #3188). fn sync_custom_ratio_fields(app: &mut PhotocraftApp) { if app.ui.tool_options.crop_ratio != crop_size::WHR { diff --git a/crates/ui-egui/src/crop_size.rs b/crates/ui-egui/src/crop_size.rs index b30cdd8c4a2..194760e6de9 100644 --- a/crates/ui-egui/src/crop_size.rs +++ b/crates/ui-egui/src/crop_size.rs @@ -223,6 +223,15 @@ pub fn clear(o: &mut ToolOptions) { o.crop_resolution.clear(); } +/// The options bar's Clear: W, H and the resolution in W x H x Resolution mode, else the ratio. +pub fn clear_ratio(o: &mut ToolOptions) { + if o.crop_ratio == WHR { + clear(o); + } else { + o.crop_ratio.clear(); + } +} + /// Swaps W and H (the ⇄ button, X). False outside W x H x Resolution mode. pub fn swap(o: &mut ToolOptions) -> bool { if o.crop_ratio != WHR { diff --git a/crates/ui-egui/src/panels.rs b/crates/ui-egui/src/panels.rs index 18cef34c980..d15914828c1 100644 --- a/crates/ui-egui/src/panels.rs +++ b/crates/ui-egui/src/panels.rs @@ -1350,11 +1350,7 @@ pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui) { } widgets::vline(ui, 22.0); if widgets::secondary_button(ui, tl!("Clear"), 0.0).clicked() { - if o.crop_ratio == crate::crop_size::WHR { - crate::crop_size::clear(o); - } else { - o.crop_ratio.clear(); - } + crate::crop_size::clear_ratio(o); } crate::crop_straighten::options_button(&mut app.crop.straighten, ui); crate::crop_overlay::options_button(o, ui); diff --git a/crates/ui-egui/src/shortcuts.rs b/crates/ui-egui/src/shortcuts.rs index 1ad8d6d92a8..94787c8193f 100644 --- a/crates/ui-egui/src/shortcuts.rs +++ b/crates/ui-egui/src/shortcuts.rs @@ -391,8 +391,9 @@ pub fn handle(app: &mut PhotocraftApp, ctx: &egui::Context) { return; } // So does the right-click menu of text being edited: Esc closes only it, and keys typed while - // it is open don't reach the text beneath. - if app.ui.canvas_tool_menu.as_ref().is_some_and(|m| m.text) { + // it is open don't reach the text beneath. The crop menu's likewise: Esc and ↵ don't cancel or + // commit the crop under it (#6561). + if app.ui.canvas_tool_menu.as_ref().is_some_and(|m| m.text || m.crop.is_some()) { return; } let symmetry_editing = app.ui.symmetry_transform.is_some(); diff --git a/crates/ui-egui/src/transform_type_tests.rs b/crates/ui-egui/src/transform_type_tests.rs index 457c03c1cbf..eeb91f44b9e 100644 --- a/crates/ui-egui/src/transform_type_tests.rs +++ b/crates/ui-egui/src/transform_type_tests.rs @@ -55,6 +55,7 @@ fn type_layers_offer_free_transform_but_not_distort_or_perspective() { type_layer: false, guide: false, spelling: None, + crop: None, }; assert!(crate::canvas_tool_menu::available(&app, &menu, "edit.freeTransform")); assert!(!crate::canvas_tool_menu::available(&app, &menu, "edit.transform.distort")); diff --git a/docs/context-menu-parity.md b/docs/context-menu-parity.md index 53b6d99bd9e..d6ec330909b 100644 --- a/docs/context-menu-parity.md +++ b/docs/context-menu-parity.md @@ -1,6 +1,6 @@ # Context-menu parity contract -> **Last reviewed:** 2026-10-18 · **Last updated:** 2026-10-18 · **Change:** minor (Type tool menu over committed type, #7324) · **Target:** Adobe Photoshop 2026 +> **Last reviewed:** 2026-10-18 · **Last updated:** 2026-10-21 · **Change:** minor (Crop tool menu on a pending crop, #6561; Type tool menu over committed type, #7324) · **Target:** Adobe Photoshop 2026 Status: implementation contract, updated 2026-10-09. Scope: canvas, document tabs, and panels. “Right-click” means a secondary pointer click; macOS Control-click should also open the same menu where the platform sends a context-menu gesture. Photoshop changes a context menu with the active tool, selection, and panel item. Adobe documents that principle but does not publish a complete current menu catalog. **Documented** means an Adobe source explicitly names the gesture or action. **Inferred** means a PhotoCraft design target or an item known from a main menu whose presence in a Photoshop context menu still needs a current-product capture. Do not present inferred rows as exact Photoshop menus. [Adobe: panels and menus](https://helpx.adobe.com/photoshop/using/panels-menus.html), [Adobe: shortcuts and context menus](https://helpx.adobe.com/sa_en/photoshop/using/customizing-keyboard-shortcuts.html). @@ -22,7 +22,7 @@ The “PhotoCraft at branch point” column records behavior before this PR. Pic |---|---|---|---| | Move | Choose a layer at the point; an auto-select choice also exists in the options bar | Layers | P0; [Adobe layer movement](https://helpx.adobe.com/photoshop/using/moving-stacking-locking-layers.html); exact pop-up layout requires capture | | Rectangular/Elliptical Marquee, Lasso, Polygonal Lasso, Magnetic Lasso, Magic Wand, Quick Selection, Object Selection | Active selection: the 2026 selection menu (see *Selection canvas reference* below); no selection: making a selection | Quick Selection: Picker (a brush tool, as in Photoshop); the other six: the selection menu below (#614, #738) | P1; no-selection variant still needs a dated capture | -| Crop | During crop: ratio/preset, overlay, clear/reset, commit/cancel **(inferred context placement)** | No tool menu | P1; pending crop target | +| Crop | During crop: ratio/preset, overlay, clear/reset, commit/cancel **(inferred context placement)** | On a pending crop (canvas_tool_menu.rs `crop_rows`, #6561): the options bar's preset dropdown in its order (Ratio, W x H x Resolution, the ratios, the size presets, saved crop presets, Front Image), Clear, New/Delete Crop Preset…, the six overlays and Auto/Always/Never Show Overlay (checked as in the bar), Cancel and Crop; also outside the image while a crop is pending. The untouched default frame has no menu. Esc closes only the menu. Reset remains open (no reset of frame, rotation and ratio yet, nor the options bar's ↺) | P1; pending crop target; item list still needs a dated Photoshop capture | | Eyedropper | Sample-size/source choices **(inferred)** | No tool menu | P2; [Adobe illustration uses Eyedropper](https://helpx.adobe.com/photoshop/using/panels-menus.html), but does not publish item text | | Ruler, Note, Count | Unit / measurement, note edit/delete, count-group operations **(inferred)** | No tool menu | P2 | | Brush, Pencil, Eraser, Background Eraser, Spot Healing, Healing, Clone Stamp, History Brush, Blur, Sharpen, Smudge, Dodge, Burn, Sponge | Brush preset, size and hardness where applicable | Picker | P0; [Adobe Brush Settings](https://helpx.adobe.com/photoshop/desktop/apply-painting-techniques/brushes-presets/create-brush-set-painting-options.html). Alt+secondary-drag on Windows and Control+Option-drag on macOS adjust size/hardness ([Adobe cursor shortcuts](https://helpx.adobe.com/in/photoshop/desktop/get-started/settings-and-preferences/change-tool-pointers.html)) | @@ -100,6 +100,7 @@ Each slice needs pure model tests (including every item dispatching a known comm | Date | Change | Summary | |---|---|---| +| 2026-10-21 | minor | Crop tool menu on a pending crop (#6561) | | 2026-10-18 | minor | Type tool menu over committed type (#7324) | | 2026-10-13 | minor | Layer-mask thumbnail menu (#4575) | | 2026-10-10 | trivial | Status line, revision history | diff --git a/docs/gaps.md b/docs/gaps.md index ab42d0f8ef8..894370c42fe 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -1,6 +1,6 @@ # Where PhotoCraft falls short of Photoshop -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-18 · **Change:** minor (G9: fill and adjustment layers copy and paste whole, #2344; G1: smart filter masks show on PSD open, Photoshop-oracle floor 188/258; G10: DPX read and write, #1049, Cineon read; G1: CMYK Hue/Saturation and Color Balance keep the black ink; G1: CMYK Posterize on the stored values, psd-tools oracle floor 242/309; G1: CMYK adjustment layers composite on the document's inks, Photoshop-oracle floor 165/258; G1: CMYK Brightness/Contrast on the inks, CMYK Threshold's luma; G1: modern Brightness/Contrast's brightness curve matches Photoshop, Photoshop-oracle floor 151/258; G1: Lab documents composite on their stored L, a, b, Photoshop-oracle floor 152/258; G1: Levels on whole levels at every step, Photoshop-oracle floor 146/258, psd-tools 238/309; G1: 32-bit Brightness/Contrast legacy, Channel Mixer, Photo Filter and Black & White tint unclipped as in Photoshop, Photoshop-oracle floor 149/258; G1: mask feathers blur with their exact variance, psd-tools oracle floor 240/309; G1: Threshold splits on Photoshop's luminosity, psd-tools oracle floor 241/309; G1: pass-through clipping base with an adjustment renders isolated, psd-tools oracle floor 240/309; G1: 16-bit Posterize as Photoshop bins it, psd-tools oracle floor 241/309; G1: Gradient Map driven by the W3C luminosity, Photoshop-oracle floor 147/258; G7: Field Blur's on-canvas pins, #3373; G4: Hue Jitter amount track, #3825 partial; G4: minimum field interaction, #3825 partial; G1: CMYK Invert, Posterize and Threshold on the inks, 16-bit Lab Invert; Photoshop-oracle floor 145/258; G11: `.atn` import maps 112 events: Select and Mask, Filter Gallery Spatter, Ripple, Crystallize, Pattern Fill layers, mask targeting, Step Backward, nudges in points, Bitmap mode; G5: Free Transform H/V skew fields; G9: toolbar tool shortcut editing; refreshed against main: G2, G5, G7, G9, G10, G13, G14, G17 items that landed; G10: DPX read and write, #1049; G4: checkbox-only Brush Settings rows; G11: Load/Save Actions `.atn` landed, AUTO-219-2 partial; G5: hold-a-key spring-loaded tools landed, #2672; G1: #2465 fixed; stale missing-tool rows corrected: Color Replacement, Red Eye and Add/Delete Anchor Point are live tools, so only Art History Brush is missing; no estimate changed) · **Target:** Adobe Photoshop 2026 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-21 · **Change:** minor (G9: Crop tool canvas menu, #6561; G9: fill and adjustment layers copy and paste whole, #2344; G1: smart filter masks show on PSD open, Photoshop-oracle floor 188/258; G10: DPX read and write, #1049, Cineon read; G1: CMYK Hue/Saturation and Color Balance keep the black ink; G1: CMYK Posterize on the stored values, psd-tools oracle floor 242/309; G1: CMYK adjustment layers composite on the document's inks, Photoshop-oracle floor 165/258; G1: CMYK Brightness/Contrast on the inks, CMYK Threshold's luma; G1: modern Brightness/Contrast's brightness curve matches Photoshop, Photoshop-oracle floor 151/258; G1: Lab documents composite on their stored L, a, b, Photoshop-oracle floor 152/258; G1: Levels on whole levels at every step, Photoshop-oracle floor 146/258, psd-tools 238/309; G1: 32-bit Brightness/Contrast legacy, Channel Mixer, Photo Filter and Black & White tint unclipped as in Photoshop, Photoshop-oracle floor 149/258; G1: mask feathers blur with their exact variance, psd-tools oracle floor 240/309; G1: Threshold splits on Photoshop's luminosity, psd-tools oracle floor 241/309; G1: pass-through clipping base with an adjustment renders isolated, psd-tools oracle floor 240/309; G1: 16-bit Posterize as Photoshop bins it, psd-tools oracle floor 241/309; G1: Gradient Map driven by the W3C luminosity, Photoshop-oracle floor 147/258; G7: Field Blur's on-canvas pins, #3373; G4: Hue Jitter amount track, #3825 partial; G4: minimum field interaction, #3825 partial; G1: CMYK Invert, Posterize and Threshold on the inks, 16-bit Lab Invert; Photoshop-oracle floor 145/258; G11: `.atn` import maps 112 events: Select and Mask, Filter Gallery Spatter, Ripple, Crystallize, Pattern Fill layers, mask targeting, Step Backward, nudges in points, Bitmap mode; G5: Free Transform H/V skew fields; G9: toolbar tool shortcut editing; refreshed against main: G2, G5, G7, G9, G10, G13, G14, G17 items that landed; G10: DPX read and write, #1049; G4: checkbox-only Brush Settings rows; G11: Load/Save Actions `.atn` landed, AUTO-219-2 partial; G5: hold-a-key spring-loaded tools landed, #2672; G1: #2465 fixed; stale missing-tool rows corrected: Color Replacement, Red Eye and Add/Delete Anchor Point are live tools, so only Art History Brush is missing; no estimate changed) · **Target:** Adobe Photoshop 2026 Every known shortfall against Photoshop 2026 (27.11.0), one entry each, ranked by user impact on the way to beta. This is the work list agents pick from: take the highest-ranked entry that @@ -204,7 +204,8 @@ what an agent can't finish alone. - **Missing:** 27 of 156 preferences do nothing (scorecard prefs audit); panel groups can't float or tear off into OS windows (UI-217-5, #1828, #1213, #2305); Color panel lacks wheel and slider modes (UI-217-17, #2569); more themes (UI-217-11, #2661); a single pixel layer - copies without its mask and styles (UI-217-23; fill and adjustment layers copy whole, #2344); tool-specific context menus beyond brushes, selections and Pen + copies without its mask and styles (UI-217-23; fill and adjustment layers copy whole, #2344); tool-specific context menus beyond brushes, selections, Pen and + Crop ([context-menu-parity.md](context-menu-parity.md)); Libraries, Comments, Contextual Task Bar panels. - **Estimate:** 150–250 h. @@ -274,6 +275,7 @@ what an agent can't finish alone. | Date | Change | Summary | |---|---|---| +| 2026-10-21 | minor | G9: right-click on a pending crop opens the Crop tool menu (presets, Clear, overlays, Cancel, Crop; #6561); Reset still open | | 2026-10-15 | minor | G1 / #5972 A1: render only provably constant-RGB `GdFl` noise fills; variable noise synthesis remains open | | 2026-10-18 | minor | G9: with no selection, Copy takes fill and adjustment layers whole and Paste recreates them (#2344); UI-217-23 stays partial (a single pixel layer copies its pixels only); estimate unchanged | | 2026-10-14 | minor | G1: a PSD smart object's filter mask shows when the file opens (Photoshop stores the filtered pixels unmasked); export stores them that way too; Photoshop-oracle floor 185 → 188 of 258 |