diff --git a/crates/ui-egui/src/shortcuts.rs b/crates/ui-egui/src/shortcuts.rs index 3d2f1799db..fc09069ba0 100644 --- a/crates/ui-egui/src/shortcuts.rs +++ b/crates/ui-egui/src/shortcuts.rs @@ -48,8 +48,119 @@ pub fn pretty(s: &str) -> String { .join(if mac { "" } else { "+" }) } +/// With ⇧ held the OS reports the shifted character as the logical key (US layout): ⇧; is `:`. +fn shifted(k: Key) -> Option { + Some(match k { + Key::Equals => Key::Plus, + Key::Semicolon => Key::Colon, + Key::OpenBracket => Key::OpenCurlyBracket, + Key::CloseBracket => Key::CloseCurlyBracket, + Key::Slash => Key::Questionmark, + Key::Backslash => Key::Pipe, + Key::Num1 => Key::Exclamationmark, + _ => return None, + }) +} + +/// Does a key press match a shortcut, the way Photoshop matches them? +/// +/// - Modifiers match exactly (⌘⌥I is not ⌘I), with ⌘ = Ctrl off the Mac. +/// - `=` also matches `+` (⌘+ with ⇧ on a US layout, the numpad `+`, the `+` key of Nordic and +/// German layouts): Photoshop zooms in on both. +/// - Delete also matches Backspace (the Mac's "delete" key). +/// - A ⇧ shortcut on a punctuation key matches the shifted character (⌘⇧; arrives as ⌘`:`). +pub fn key_matches(sc: &KeyboardShortcut, key: Key, mods: Modifiers) -> bool { + let k = sc.logical_key; + let direct = key == k || (k == Key::Delete && key == Key::Backspace); + let plus = k == Key::Equals && key == Key::Plus; + let via_shift = sc.modifiers.shift && shifted(k) == Some(key); + if !(direct || plus || via_shift) { + return false; + } + // Typing `+` (or another shifted symbol) may need ⇧ on this layout: don't require it absent. + let shifted_symbol = + matches!(key, Key::Plus | Key::Colon | Key::OpenCurlyBracket | Key::CloseCurlyBracket | Key::Questionmark | Key::Pipe | Key::Exclamationmark); + let shift_ok = mods.shift == sc.modifiers.shift || (shifted_symbol && !sc.modifiers.shift); + mods.alt == sc.modifiers.alt && shift_ok && mods.cmd_ctrl_matches(sc.modifiers) +} + +/// Consume a press of `sc` (see [`key_matches`]); true when one was found. +pub fn consume(ctx: &egui::Context, sc: &KeyboardShortcut) -> bool { + ctx.input_mut(|i| { + let before = i.events.len(); + i.events.retain(|e| !matches!(e, egui::Event::Key { key, pressed: true, modifiers, .. } if key_matches(sc, *key, *modifiers))); + i.events.len() != before + }) +} + +/// View navigation that Photoshop keeps live while a dialog is open (so the image can be judged +/// at any zoom): Zoom In / Out, Fit on Screen, 100%. +pub const NAV_COMMANDS: [&str; 4] = ["view.zoomIn", "view.zoomOut", "view.fitOnScreen", "view.actualPixels"]; + +/// ⌘+ / ⌘- / ⌘0 / ⌘1 (or their Edit › Keyboard Shortcuts overrides). Returns true when one ran. +fn nav_keys(app: &mut PhotocraftApp, ctx: &egui::Context) -> bool { + for id in NAV_COMMANDS { + let sc = crate::menus::UI_COMMANDS.iter().find(|c| c.0 == id).and_then(|c| parse(app.session.prefs().shortcut(id, c.3)?)); + if let Some(sc) = sc + && consume(ctx, &sc) + { + if crate::menus::is_enabled(app, id) { + let _ = crate::menus::invoke(app, ctx, id, json!({})); + } + return true; + } + } + false +} + +/// egui-winit turns ⌘C / ⌘X / ⌘V into `Event::Copy` / `Cut` / `Paste` and drops the key press, and +/// drops ⌘V entirely when the clipboard holds no text (an image). Outside text fields, give the +/// pixel commands their key presses back: Copy/Cut/Paste become ⌘C/⌘X/⌘V presses (with ⇧/⌥ as +/// held, so ⇧⌘C is Copy Merged), and a ⌘V release without a paste event becomes a ⌘V press. +pub fn clipboard_keys(ctx: &egui::Context, typing: bool, raw: &mut egui::RawInput) { + if typing { + return; + } + let seen = egui::Id::new("pc-paste-key-seen"); + // The modifiers held at each event: last frame's, updated as the events report changes. + let mut mods = ctx.input(|i| i.modifiers); + let press = |key, modifiers| egui::Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers }; + let mut out = Vec::with_capacity(raw.events.len()); + for e in raw.events.drain(..) { + if let egui::Event::ModifiersChanged(m) | egui::Event::Key { modifiers: m, .. } = &e { + mods = *m; + } + let held = if mods.command { mods } else { Modifiers::COMMAND }; + let key = match &e { + egui::Event::Copy => Some(Key::C), + egui::Event::Cut => Some(Key::X), + egui::Event::Paste(_) => Some(Key::V), + _ => None, + }; + if let Some(key) = key { + if key == Key::V { + ctx.data_mut(|d| d.insert_temp(seen, true)); + } + out.push(press(key, held)); + continue; + } + if let egui::Event::Key { key: Key::V, pressed: false, modifiers, .. } = &e + && modifiers.command + && !ctx.data_mut(|d| d.remove_temp::(seen)).unwrap_or(false) + { + out.push(press(Key::V, *modifiers)); + } + out.push(e); + } + raw.events = out; +} + pub fn handle(app: &mut PhotocraftApp, ctx: &egui::Context) { if ctx.egui_wants_keyboard_input() || !app.ui.dialogs.is_empty() || app.discard.is_some() { + // Dialogs and focused sliders keep canvas zoom; a focused text field keeps its keys. + if !ctx.text_edit_focused() { + nav_keys(app, ctx); + } return; } // Liquify / Puppet Warp / Perspective Warp: ↩ commits, Esc cancels. @@ -104,7 +215,7 @@ pub fn handle(app: &mut PhotocraftApp, ctx: &egui::Context) { if editing && matches!(id.as_str(), "edit.copy" | "edit.cut" | "edit.paste" | "edit.copyMerged" | "select.all" | "edit.pasteSpecial.pasteInPlace") { continue; } - if ctx.input_mut(|i| i.consume_shortcut(&sc)) { + if consume(ctx, &sc) { if crate::menus::is_enabled(app, &id) { let r = if id.starts_with("image.adjustments.") && !crate::panels::adjustment_sliders(id.rsplit('.').next().unwrap_or("")).is_empty() { let label = photocraft_engine::commands::find(&id).map(|c| c.label).unwrap_or(""); @@ -188,6 +299,67 @@ mod tests { assert!(parse("Cmd+Nonsense").is_none()); } + #[test] + fn keys_match_like_photoshop() { + let cmd = Modifiers::COMMAND; + let zoom_in = parse("Cmd+=").unwrap(); + // ⌘= , ⌘+ typed with ⇧ (US), ⌘+ from the numpad or a Nordic/German `+` key. + assert!(key_matches(&zoom_in, Key::Equals, cmd)); + assert!(key_matches(&zoom_in, Key::Plus, cmd | Modifiers::SHIFT)); + assert!(key_matches(&zoom_in, Key::Plus, cmd)); + assert!(!key_matches(&zoom_in, Key::Plus, Modifiers::NONE)); + assert!(!key_matches(&zoom_in, Key::Equals, cmd | Modifiers::ALT)); + assert!(key_matches(&parse("Cmd+-").unwrap(), Key::Minus, cmd)); + assert!(key_matches(&parse("Cmd+0").unwrap(), Key::Num0, cmd)); + // Ctrl (Windows) is ⌘. + assert!(key_matches(&zoom_in, Key::Plus, Modifiers::CTRL | Modifiers { command: true, ..Default::default() })); + // Exact modifiers: ⌘⌥I is Image Size, never Invert (⌘I); ⇧⌘Z is not ⌘Z. + let invert = parse("Cmd+I").unwrap(); + assert!(key_matches(&invert, Key::I, cmd)); + assert!(!key_matches(&invert, Key::I, cmd | Modifiers::ALT)); + assert!(!key_matches(&parse("Cmd+Z").unwrap(), Key::Z, cmd | Modifiers::SHIFT)); + // ⇧ shortcuts on punctuation arrive as the shifted character. + assert!(key_matches(&parse("Cmd+Shift+;").unwrap(), Key::Colon, cmd | Modifiers::SHIFT)); + assert!(key_matches(&parse("Cmd+Shift+]").unwrap(), Key::CloseCurlyBracket, cmd | Modifiers::SHIFT)); + assert!(!key_matches(&parse("Cmd+;").unwrap(), Key::Colon, cmd | Modifiers::SHIFT)); + // Delete and the Mac's delete (Backspace) both clear. + let clear = parse("Delete").unwrap(); + assert!(key_matches(&clear, Key::Delete, Modifiers::NONE) && key_matches(&clear, Key::Backspace, Modifiers::NONE)); + assert!(!key_matches(&clear, Key::Backspace, cmd)); + } + + #[test] + fn clipboard_events_become_pixel_shortcuts_outside_text() { + let ctx = egui::Context::default(); + let raw = |mut events: Vec, modifiers| { + events.insert(0, egui::Event::ModifiersChanged(modifiers)); + egui::RawInput { events, ..Default::default() } + }; + let keys = |r: &egui::RawInput| -> Vec<(Key, bool, bool)> { + r.events + .iter() + .filter_map(|e| if let egui::Event::Key { key, pressed, modifiers, .. } = e { Some((*key, *pressed, modifiers.shift)) } else { None }) + .collect() + }; + let cmd_shift = Modifiers::COMMAND | Modifiers::SHIFT; + let mut r = raw(vec![egui::Event::Copy, egui::Event::Cut], cmd_shift); + clipboard_keys(&ctx, false, &mut r); + assert_eq!(keys(&r), vec![(Key::C, true, true), (Key::X, true, true)]); + // A text paste becomes ⌘V; its key release then adds nothing. + let up = egui::Event::Key { key: Key::V, physical_key: None, pressed: false, repeat: false, modifiers: Modifiers::COMMAND }; + let mut r = raw(vec![egui::Event::Paste("x".into()), up.clone()], Modifiers::COMMAND); + clipboard_keys(&ctx, false, &mut r); + assert_eq!(keys(&r), vec![(Key::V, true, false), (Key::V, false, false)]); + // An image on the clipboard: egui-winit sends only the release. It still pastes. + let mut r = raw(vec![up.clone()], Modifiers::COMMAND); + clipboard_keys(&ctx, false, &mut r); + assert_eq!(keys(&r), vec![(Key::V, true, false), (Key::V, false, false)]); + // In a text field the events stay text clipboard events. + let mut r = raw(vec![egui::Event::Paste("x".into())], Modifiers::COMMAND); + clipboard_keys(&ctx, true, &mut r); + assert!(matches!(r.events.as_slice(), [_, egui::Event::Paste(_)])); + } + #[test] fn every_registered_shortcut_parses() { for c in photocraft_engine::command_specs() { diff --git a/crates/ui-egui/src/snap_ui.rs b/crates/ui-egui/src/snap_ui.rs index 14da92a31e..b3649a3634 100644 --- a/crates/ui-egui/src/snap_ui.rs +++ b/crates/ui-egui/src/snap_ui.rs @@ -124,8 +124,15 @@ fn near_handle(q: &[[f64; 2]; 4], p: [f64; 2], tol: f64) -> bool { }) } +/// Photoshop: holding Ctrl (Windows) / Control (macOS) *during* a drag temporarily turns snapping +/// off. Only the held state while dragging counts: Ctrl at the press belongs to the tool (Ctrl-click +/// auto-selects with the Move tool), and ⌘ on the Mac never overrides snapping. +fn override_held(mods: egui::Modifiers) -> bool { + mods.ctrl && !mods.mac_cmd +} + /// Start snapping for a drag beginning at `p` (called on pointer down). -fn begin(app: &mut PhotocraftApp, p: [f64; 2], mods: egui::Modifiers) { +fn begin(app: &mut PhotocraftApp, p: [f64; 2]) { app.prefs_rt.snap = None; app.prefs_rt.snap_lines.clear(); if app.session.active().is_none() { @@ -158,7 +165,7 @@ fn begin(app: &mut PhotocraftApp, p: [f64; 2], mods: egui::Modifiers) { targets = targets.filtered(|k| k != SnapKind::Guide); } let smart = if matches!(gesture, Gesture::Move { .. }) && smart_on(app) { build(app, &exclude, true) } else { SnapTargets::default() }; - app.prefs_rt.snap = Some(ActiveSnap { gesture, start: p, targets, smart, disabled: mods.ctrl && !mods.mac_cmd }); + app.prefs_rt.snap = Some(ActiveSnap { gesture, start: p, targets, smart, disabled: false }); } /// Round to whole pixels when Preferences › Tools asks vector tools and transforms to snap to @@ -199,7 +206,7 @@ fn apply(app: &mut PhotocraftApp, p: [f64; 2]) -> [f64; 2] { pub fn filter_event(app: &mut PhotocraftApp, ev: ToolEvent, mods: egui::Modifiers) -> ToolEvent { match ev { ToolEvent::Down { x, y, pressure } => { - begin(app, [x, y], mods); + begin(app, [x, y]); // Moves snap their delta, which is zero at the start: keep the press point. let p = match app.prefs_rt.snap.as_ref().map(|s| &s.gesture) { Some(Gesture::Point) => { @@ -215,7 +222,7 @@ pub fn filter_event(app: &mut PhotocraftApp, ev: ToolEvent, mods: egui::Modifier return ev; } if let Some(s) = app.prefs_rt.snap.as_mut() { - s.disabled = mods.ctrl && !mods.mac_cmd; + s.disabled = override_held(mods); } let q = apply(app, [x, y]); let p = pixel_round(app, q); @@ -225,6 +232,9 @@ pub fn filter_event(app: &mut PhotocraftApp, ev: ToolEvent, mods: egui::Modifier if app.prefs_rt.snap.is_none() { return ev; } + if let Some(s) = app.prefs_rt.snap.as_mut() { + s.disabled = override_held(mods); + } let q = apply(app, [x, y]); let p = pixel_round(app, q); app.prefs_rt.snap = None; @@ -341,9 +351,17 @@ mod tests { assert_eq!(mover_bounds(&app).x0, 303); app.ui.extras.snap = true; let ctrl = egui::Modifiers { ctrl: true, ..Default::default() }; - crate::canvas::tool_event(&mut app, ToolEvent::Down { x: 60.0, y: 60.0, pressure: 1.0 }, ctrl); + crate::canvas::tool_event(&mut app, ToolEvent::Down { x: 60.0, y: 60.0, pressure: 1.0 }, m); crate::canvas::tool_event(&mut app, ToolEvent::Up { x: 62.0, y: 60.0 }, ctrl); assert_eq!(mover_bounds(&app).x0, 305, "no snap to the target's right edge at 350? (moved freely)"); + // Ctrl only at the press (Ctrl-click auto-select) doesn't turn snapping off for the drag. + crate::canvas::tool_event(&mut app, ToolEvent::Down { x: 60.0, y: 60.0, pressure: 1.0 }, ctrl); + crate::canvas::tool_event(&mut app, ToolEvent::Move { x: 61.0, y: 60.0, pressure: 1.0 }, m); + assert!(!app.prefs_rt.snap.as_ref().is_some_and(|s| s.disabled)); + crate::canvas::tool_event(&mut app, ToolEvent::Up { x: 61.0, y: 60.0 }, m); + // ⌘ on the Mac is not the override. + let cmd = egui::Modifiers { mac_cmd: true, command: true, ..Default::default() }; + assert!(!override_held(cmd) && override_held(ctrl)); } #[test]