diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index a91ee3a9fe..e5353ffe06 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -21,9 +21,9 @@ mod linux_window_state; mod logging; #[cfg(target_os = "macos")] mod macos; -mod menu; #[cfg(target_os = "macos")] -mod page_swipe; +mod macos_webview_input; +mod menu; mod plugin_web; #[cfg(target_os = "macos")] mod relaunch; @@ -315,7 +315,7 @@ pub fn run() { window_zoom::forget(window.label()); #[cfg(target_os = "macos")] { - page_swipe::forget(window.label()); + macos_webview_input::forget(window.label()); titlebar::forget(window); } if windows::auxiliary_parent(window.label()).is_none() { @@ -409,12 +409,14 @@ fn window_state_flags() -> tauri_plugin_window_state::StateFlags { /// Routes IDE menu items to the focused window's frontend (`executeAction`). fn on_menu_event(app: &tauri::AppHandle, event: tauri::menu::MenuEvent) { let id = event.id().as_ref(); + #[cfg(target_os = "macos")] + if macos_webview_input::perform_native_history_if_needed(id) { + return; + } menu::restore_check(app, &app.state::(), id); // A keymap accelerator only draws the shortcut: its key reached the menu because the keymap declined it. #[cfg(target_os = "macos")] - if !menu::fires_natively(&menu::spec(menu::Os::Mac), id) - && (macos::handling_key_press() || macos::native_modal_open()) - { + if !menu::macos_native_action(id) && (macos::handling_key_press() || macos::native_modal_open()) { return; } dispatch_menu_action(app, id); diff --git a/src-tauri/src/page_swipe.rs b/src-tauri/src/macos_webview_input.rs similarity index 51% rename from src-tauri/src/page_swipe.rs rename to src-tauri/src/macos_webview_input.rs index f5d0232591..44e993ffc7 100644 --- a/src-tauri/src/page_swipe.rs +++ b/src-tauri/src/macos_webview_input.rs @@ -1,11 +1,15 @@ -//! System page gestures belong to the IDE keymap, not the webview's history. -use objc2::{MainThreadMarker, Message, rc::Retained, runtime::AnyObject}; -use objc2_app_kit::{NSEvent, NSEventMask, NSEventPhase, NSEventSwipeTrackingOptions, NSEventType, NSView}; +//! AppKit input routed to the workbench webview: Command shortcuts and page gestures. +use objc2::{ClassType, MainThreadMarker, Message, msg_send, rc::Retained, runtime::AnyObject}; +use objc2_app_kit::{ + NSEvent, NSEventMask, NSEventModifierFlags, NSEventPhase, NSEventSwipeTrackingOptions, NSEventType, NSWindow, +}; +use objc2_web_kit::WKWebView; use std::{cell::RefCell, collections::HashMap, ptr::NonNull}; -use tauri::{Listener, WebviewWindow}; +use tauri::{Listener, Manager, WebviewWindow}; struct Gestures { monitor: Retained, + view: Retained, listener: tauri::EventId, window: WebviewWindow, generation: u64, @@ -34,16 +38,31 @@ fn stroke(window: &WebviewWindow, right: bool) { pub fn install(window: &WebviewWindow) { let target = window.clone(); let _ = window.with_webview(move |webview| { - let view = unsafe { Retained::retain(webview.inner().cast::()).unwrap() }; + let view = unsafe { Retained::retain(webview.inner().cast::()).unwrap() }; + let primary_view = view.clone(); let native = webview.ns_window() as usize; let window = target.clone(); let block = block2::RcBlock::new(move |event: NonNull| { let event = unsafe { event.as_ref() }; - if event - .window(MainThreadMarker::new().expect("event monitor on main thread")) - .is_none_or(|w| Retained::as_ptr(&w) as usize != native) - { - return event as *const NSEvent as *mut NSEvent; + let pass = std::ptr::from_ref(event).cast_mut(); + let key_down = event.r#type() == NSEventType::KeyDown; + if key_down && !event.modifierFlags().contains(NSEventModifierFlags::Command) { + return pass; + } + let Some(owner) = event.window(MainThreadMarker::new().expect("event monitor on main thread")) else { + return pass; + }; + if Retained::as_ptr(&owner) as usize != native { + return pass; + } + if key_down { + return if window.state::().routes_key(event) + && workbench_key_equivalent(&view, &owner, event) + { + std::ptr::null_mut() + } else { + pass + }; } if event.r#type() == NSEventType::Swipe { if event.deltaX() != 0.0 && event.deltaY() == 0.0 { @@ -91,10 +110,13 @@ pub fn install(window: &WebviewWindow) { notify(&window, "ide:page-swipe-candidate", candidate); } } - event as *const NSEvent as *mut NSEvent + pass }); let monitor = unsafe { - NSEvent::addLocalMonitorForEventsMatchingMask_handler(NSEventMask::Swipe | NSEventMask::ScrollWheel, &block) + NSEvent::addLocalMonitorForEventsMatchingMask_handler( + NSEventMask::KeyDown | NSEventMask::Swipe | NSEventMask::ScrollWheel, + &block, + ) }; let Some(monitor) = monitor else { return; @@ -110,12 +132,111 @@ pub fn install(window: &WebviewWindow) { WINDOWS.with_borrow_mut(|windows| { windows.insert( target.label().into(), - Gestures { monitor, listener, window: target, generation: 0, pending: None, decided: false }, + Gestures { + monitor, + view: primary_view, + listener, + window: target, + generation: 0, + pending: None, + decided: false, + }, ) }); }); } +/// Printable Command equivalents displayed by the native menu. Named keys such as arrows use AppKit. +#[derive(Clone, Copy, PartialEq, Eq, Hash)] +pub(crate) struct CommandKey { + modifiers: NSEventModifierFlags, + key: u8, +} + +impl CommandKey { + pub(crate) fn from_binding(binding: &str) -> Option { + let (mods, name) = binding.rsplit_once('+')?; + let [key] = *name.as_bytes() else { return None }; + let mut modifiers = NSEventModifierFlags::empty(); + for modifier in mods.split('+') { + modifiers |= match modifier { + "Meta" | "Cmd" | "CmdOrCtrl" => NSEventModifierFlags::Command, + "Alt" => NSEventModifierFlags::Option, + "Ctrl" => NSEventModifierFlags::Control, + "Shift" => NSEventModifierFlags::Shift, + _ => return None, + }; + } + (key.is_ascii_graphic() && modifiers.contains(NSEventModifierFlags::Command)) + .then_some(Self { modifiers, key: key.to_ascii_uppercase() }) + } + + pub(crate) fn from_event(event: &NSEvent) -> Option { + let modifiers = event.modifierFlags() + & (NSEventModifierFlags::Command + | NSEventModifierFlags::Shift + | NSEventModifierFlags::Control + | NSEventModifierFlags::Option + | NSEventModifierFlags::Function + | NSEventModifierFlags::NumericPad); + // Use the active layout's Command layer, including layouts that switch to QWERTY under Command. + let chars = if modifiers == NSEventModifierFlags::Command { + event.characters()? + } else { + event.charactersByApplyingModifiers(NSEventModifierFlags::Command)? + }; + if chars.length() != 1 { + return None; + } + let key = u8::try_from(chars.characterAtIndex(0)).ok()?.to_ascii_uppercase(); + Some(Self { modifiers, key }) + } +} + +/// A sheet or guest view can take focus before the renderer has updated the Edit menu. +pub(crate) fn perform_native_history_if_needed(id: &str) -> bool { + let selector = match id { + crate::menu::EDITOR_UNDO => objc2::sel!(undo:), + crate::menu::EDITOR_REDO => objc2::sel!(redo:), + _ => return false, + }; + let Some(mtm) = MainThreadMarker::new() else { return false }; + let app = objc2_app_kit::NSApplication::sharedApplication(mtm); + if app.modalWindow().is_none() + && let Some(window) = app.keyWindow() + && window.attachedSheet().is_none() + && let Some(responder) = window.firstResponder() + && WINDOWS.with_borrow(|windows| { + windows.values().any(|w| { + std::ptr::eq(Retained::as_ptr(&w.view), Retained::as_ptr(&responder).cast()) + && !matches!( + crate::windows::auxiliary(w.window.label()), + Some((crate::windows::AuxKind::Settings, _)) + ) + }) + }) + { + return false; + } + // SAFETY: these standard NSResponder actions take one object argument. AppKit locates the target. + unsafe { app.sendAction_to_from(selector, None, None) }; + true +} + +fn workbench_key_equivalent(view: &WKWebView, owner: &NSWindow, event: &NSEvent) -> bool { + if !owner.isKeyWindow() || owner.attachedSheet().is_some() { + return false; + } + let Some(responder) = owner.firstResponder() else { return false }; + if !std::ptr::eq(Retained::as_ptr(&responder).cast::(), view) { + return false; + } + // Wry's child view declines every key equivalent. Restore WebKit's page-first dispatch + // for the focused workbench; WebKit declines a resent event so AppKit can try its menu. + // SAFETY: Tauri supplied a WKWebView subclass and the monitor runs on the AppKit thread. + unsafe { msg_send![super(view, WKWebView::class()), performKeyEquivalent: event] } +} + fn track(window: &WebviewWindow, id: u64) { let event = WINDOWS.with_borrow_mut(|windows| { let state = windows.get_mut(window.label())?; diff --git a/src-tauri/src/menu.rs b/src-tauri/src/menu.rs index 6e4711d486..6f866fa4fc 100644 --- a/src-tauri/src/menu.rs +++ b/src-tauri/src/menu.rs @@ -12,7 +12,7 @@ //! handle the key. IDE items therefore carry the native accelerator of their first //! keymap binding ([`MenuConfig::accelerators`]) so the menu draws the shortcut in //! its own column, and a menu event that such a key equivalent fires is dropped -//! ([`fires_natively`]): the keymap has already declined that key. Bindings with no +//! (`macos_native_action`): the keymap has already declined that key. Bindings with no //! native form (chords, double modifiers) show no shortcut, as in IDEA. Items with //! a spec accelerator fire natively for keys the keymap never binds: Quit and //! window cycling, next to the macOS clipboard/undo roles that text inputs need. @@ -33,6 +33,8 @@ const RECENT_PREFIX: &str = "recent:"; const DYNAMIC_PREFIX: &str = "dyn:"; /// Action run for an Open Recent entry (argument: the project path). pub const OPEN_RECENT_ACTION: &str = "file.openRecentProject"; +pub(crate) const EDITOR_UNDO: &str = "dyn:edit.undo|editorHistory"; +pub(crate) const EDITOR_REDO: &str = "dyn:edit.redo|editorHistory"; const MAX_RECENT: usize = 15; #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -110,7 +112,6 @@ impl Native { } /// Accelerator the OS attaches implicitly (macOS), in keymap syntax. - #[cfg(test)] fn implicit_accelerator(self) -> Option<&'static str> { match self { Native::Undo => Some("Meta+Z"), @@ -138,7 +139,7 @@ pub enum Entry { Action { id: &'static str, label: &'static str, - /// Native accelerator (Tauri syntax) that fires natively ([`fires_natively`]) and wins + /// Native accelerator (Tauri syntax) that fires natively (`macos_native_action`) and wins /// over the keymap's. Only for keys the webview never handles. accel: Option<&'static str>, /// Shortcut text after the label, for the Windows/Linux edit items without a keymap binding. @@ -998,6 +999,9 @@ pub struct MenuConfig { /// Ids of the toggle actions currently on. #[serde(default)] pub checked: Vec, + /// Whether the focused editor owns its undo history. + #[serde(default)] + pub editor_owns_history: bool, } /// An item of a frontend-listed menu slot. @@ -1117,6 +1121,16 @@ pub struct MenuState { /// Visible menu last installed. Accelerators of actions that are not on the menu /// are not part of this, so they must not redraw the macOS menu bar. rendered: Mutex>>, + #[cfg(target_os = "macos")] + command_keys: Mutex>, +} + +#[cfg(target_os = "macos")] +impl MenuState { + pub(crate) fn routes_key(&self, event: &objc2_app_kit::NSEvent) -> bool { + crate::macos_webview_input::CommandKey::from_event(event) + .is_some_and(|key| self.command_keys.lock().contains(&key)) + } } /// Stores `next` when it differs from the config last used to build the menu. @@ -1130,16 +1144,32 @@ pub fn store_config(state: &MenuState, next: MenuConfig) -> bool { true } -/// Whether the item `id` performs its own key equivalent: only items with a spec accelerator. -/// A keymap accelerator is drawn for display, and its key reached the menu because the -/// keymap declined it, so an event it fires is dropped. #[cfg(any(target_os = "macos", test))] -pub fn fires_natively(spec: &[Entry], id: &str) -> bool { - spec.iter().any(|entry| match entry { - Entry::Submenu { children, .. } => fires_natively(children, id), - Entry::Action { id: action, accel, .. } => *action == id && accel.is_some(), - _ => false, - }) +fn ids_with_accel(entries: &[Entry], out: &mut Vec<(&'static str, &'static str)>) { + for e in entries { + match e { + Entry::Submenu { children, .. } => ids_with_accel(children, out), + Entry::Action { id, accel: Some(a), .. } => out.push((id, a)), + _ => {} + } + } +} + +/// Fixed menu shortcuts must still run when the focused webview declines the key. +#[cfg(any(target_os = "macos", test))] +pub(crate) fn macos_native_action(id: &str) -> bool { + matches!(id, EDITOR_UNDO | EDITOR_REDO) || has_spec_accelerator(id) +} + +#[cfg(any(target_os = "macos", test))] +fn has_spec_accelerator(id: &str) -> bool { + static ACTIONS: std::sync::OnceLock> = std::sync::OnceLock::new(); + let actions = ACTIONS.get_or_init(|| { + let mut actions = Vec::new(); + ids_with_accel(&spec(Os::Mac), &mut actions); + actions + }); + actions.iter().any(|(action, _)| *action == id) } /// The action an item id stands for, if it is an IDE action item. @@ -1313,7 +1343,16 @@ fn render_items(entries: &[Entry], config: &MenuConfig, recent: &[RecentItem]) - } Entry::Dynamic(slot) => out.extend(config.dynamic_items(slot).iter().map(|item| item.render(config))), Entry::Native(kind) => { - out.push(RenderedItem::Native { kind: *kind, text: config.label(kind.key(), kind.default_label()) }) + let text = config.label(kind.key(), kind.default_label()); + match (kind, config.editor_owns_history) { + (Native::Undo | Native::Redo, true) => out.push(RenderedItem::Action { + id: if *kind == Native::Undo { EDITOR_UNDO } else { EDITOR_REDO }.into(), + text, + accel: kind.implicit_accelerator().map(Into::into), + checked: None, + }), + _ => out.push(RenderedItem::Native { kind: *kind, text }), + } } Entry::Separator => out.push(RenderedItem::Separator), Entry::RecentProjects if recent.is_empty() => out.push(RenderedItem::Placeholder { @@ -1735,6 +1774,41 @@ pub fn restore_check(app: &AppHandle, menu_state: &MenuState, id: } } +/// Workbench accelerators that AppKit could claim before Wry's child webview sees the key. +/// A native role wins collisions, including Copy/Cut/Paste shared with the project tree. +/// Editor history needs the page first for CodeMirror edits and a menu fallback if it declines. +#[cfg(target_os = "macos")] +fn workbench_command_keys(rendered: &[RenderedMenu]) -> HashSet { + use crate::macos_webview_input::CommandKey; + fn collect(items: &[RenderedItem], keys: &mut HashSet, native: &mut HashSet) { + for item in items { + let (binding, reserved) = match item { + RenderedItem::Submenu { items, .. } => { + collect(items, keys, native); + continue; + } + RenderedItem::Native { kind, .. } => (kind.implicit_accelerator(), true), + RenderedItem::Action { id, accel: Some(accel), .. } => (Some(accel.as_str()), has_spec_accelerator(id)), + _ => continue, + }; + if let Some(key) = binding.and_then(CommandKey::from_binding) { + if reserved { + native.insert(key); + } else { + keys.insert(key); + } + } + } + } + let mut keys = HashSet::new(); + let mut native = HashSet::new(); + for menu in rendered { + collect(&menu.items, &mut keys, &mut native); + } + keys.retain(|key| !native.contains(key)); + keys +} + /// Installs the app menu from the current config and recent list. /// /// The first install, and a change of the top-level menu ids, calls `set_menu`. @@ -1760,22 +1834,19 @@ pub fn install(app: &AppHandle, menu_state: &MenuState, recent: & } _ => false, }; - if patched { - *slot = Some(rendered); + if !patched + && let Err(e) = build(app, Os::current(), &config, &items, &disabled).and_then(|menu| app.set_menu(menu)) + { + tracing::warn!("failed to build the app menu: {e}"); return; } - let installed = match build(app, Os::current(), &config, &items, &disabled).and_then(|menu| app.set_menu(menu)) { - Ok(_) => { - *slot = Some(rendered); - true - } - Err(e) => { - tracing::warn!("failed to build the app menu: {e}"); - false - } - }; + #[cfg(target_os = "macos")] + { + *menu_state.command_keys.lock() = workbench_command_keys(&rendered); + } + *slot = Some(rendered); drop(slot); - if installed { + if !patched { // After the menu bar is installed. Holding `rendered` across this would deadlock a menu // click on the main thread, which also takes that lock. #[cfg(target_os = "macos")] @@ -1811,16 +1882,6 @@ mod tests { const ALL_OS: [Os; 3] = [Os::Mac, Os::Windows, Os::Linux]; - fn ids_with_accel(entries: &[Entry], out: &mut Vec<(&'static str, &'static str)>) { - for e in entries { - match e { - Entry::Submenu { children, .. } => ids_with_accel(children, out), - Entry::Action { id, accel: Some(a), .. } => out.push((id, a)), - _ => {} - } - } - } - fn natives(entries: &[Entry], out: &mut Vec) { for e in entries { match e { @@ -2113,13 +2174,46 @@ mod tests { assert!(accelerator_patchable(None, None)); } + #[cfg(target_os = "macos")] #[test] - fn only_spec_accelerators_fire_natively() { + fn workbench_keys_follow_menu_remaps_and_yield_to_native_roles() { + use crate::macos_webview_input::CommandKey; + let mut config = MenuConfig::default(); + config.accelerators.insert("find.inFile".into(), "Meta+F".into()); + config.accelerators.insert("find.replaceInFile".into(), "Meta+R".into()); + config.accelerators.insert("toolwindow.project".into(), "Meta+1".into()); + config.dynamic.insert(DYNAMIC_TOOL_WINDOWS.into(), vec![dynamic_item("toolwindow.project", None, "Project")]); let spec = spec(Os::Mac); - assert!(fires_natively(&spec, "app.quit")); - assert!(fires_natively(&spec, "window.next")); - assert!(!fires_natively(&spec, "file.save")); - assert!(!fires_natively(&spec, "dyn:toolwindow.project")); + let keys = workbench_command_keys(&render_bar(&spec, &config, &[])); + let key = |binding| CommandKey::from_binding(binding).unwrap(); + for b in ["Meta+F", "Meta+R", "Meta+1"] { + assert!(keys.contains(&key(b))); + } + config.editor_owns_history = true; + let editor_keys = workbench_command_keys(&render_bar(&spec, &config, &[])); + for b in ["Meta+Z", "Shift+Meta+Z"] { + assert!(editor_keys.contains(&key(b))); + } + assert_eq!(route(&spec, EDITOR_UNDO).unwrap().arg.as_deref(), Some("editorHistory")); + config.editor_owns_history = false; + config.accelerators.insert("find.inFile".into(), "Alt+Meta+J".into()); + for native in ["Meta+C", "Meta+V", "Meta+X", "Meta+Z", "Shift+Meta+Z", "Meta+A", "Meta+Q"] { + config.accelerators.insert("find.replaceInFile".into(), native.into()); + let keys = workbench_command_keys(&render_bar(&spec, &config, &[])); + assert!(keys.contains(&key("Alt+Meta+J"))); + assert!(!keys.contains(&key("Meta+F"))); + assert!(!keys.contains(&key(native))); + } + } + + #[test] + fn native_menu_accelerators_fire_when_the_keymap_declines() { + assert!(macos_native_action(EDITOR_UNDO)); + assert!(macos_native_action(EDITOR_REDO)); + assert!(macos_native_action("app.quit")); + assert!(macos_native_action("window.next")); + assert!(!macos_native_action("file.save")); + assert!(!macos_native_action("dyn:toolwindow.project")); } #[test] @@ -2631,7 +2725,9 @@ mod tests { ], "{os:?}" ); - assert!(!fires_natively(&entries, "build.compileFile")); + let mut fixed = Vec::new(); + ids_with_accel(children, &mut fixed); + assert!(!fixed.iter().any(|(id, _)| *id == "build.compileFile")); } let entries = spec(Os::Mac); let mut base = MenuConfig::default(); diff --git a/src-tauri/src/windows.rs b/src-tauri/src/windows.rs index 5d8103c1d1..b6790632b2 100644 --- a/src-tauri/src/windows.rs +++ b/src-tauri/src/windows.rs @@ -1118,7 +1118,7 @@ fn build_project_window(app: &AppHandle, mut config: WindowConfig) -> IdeResult< #[cfg(target_os = "linux")] decorate_csd(&window); #[cfg(target_os = "macos")] - crate::page_swipe::install(&window); + crate::macos_webview_input::install(&window); apply_zoom(app, &window); #[cfg(target_os = "macos")] align_titlebar(app, &window, app.try_state::().is_some_and(|w| w.opens_project(window.label()))); @@ -1959,7 +1959,7 @@ pub fn open_auxiliary_window(app: &AppHandle, caller: &WebviewWindow, aux: AuxWi #[cfg(target_os = "linux")] decorate_csd(&window); #[cfg(target_os = "macos")] - crate::page_swipe::install(&window); + crate::macos_webview_input::install(&window); apply_zoom(app, &window); #[cfg(target_os = "macos")] align_titlebar(app, &window, false); diff --git a/src/bindings.ts b/src/bindings.ts index 8f398e1834..7eea65fc3a 100644 --- a/src/bindings.ts +++ b/src/bindings.ts @@ -10124,6 +10124,8 @@ export type MenuConfig = { dynamic?: { [key in string]: DynamicItem[] }, /** Ids of the toggle actions currently on. */ checked?: string[], + /** Whether the focused editor owns its undo history. */ + editorOwnsHistory?: boolean, }; /** diff --git a/src/features/app/__tests__/menuBridge.test.ts b/src/features/app/__tests__/menuBridge.test.ts index dfe20dab1b..eb371df60d 100644 --- a/src/features/app/__tests__/menuBridge.test.ts +++ b/src/features/app/__tests__/menuBridge.test.ts @@ -1,3 +1,5 @@ +import { history } from "@codemirror/commands"; +import { EditorView } from "@codemirror/view"; import { afterEach, describe, expect, it, vi } from "vitest"; import { registerAction } from "@/platform/actions"; import { _resetI18nForTests, setLocale } from "@/platform/i18n"; @@ -8,6 +10,7 @@ import { registerStatusItem, registerToolWindow } from "@/workbench/contribution import { useProject } from "@/platform/project"; import { _reloadLayouts, saveLayout } from "@/workbench/toolwindows/layouts"; import { clearContext, setContext } from "@/platform/context"; +import * as host from "../host"; import { buildMenuConfig, disabledMenuActions, @@ -24,6 +27,57 @@ vi.mock("@tauri-apps/api/webviewWindow", () => ({ })); describe("menu state from the frontend", () => { + it("updates macOS history ownership as focus leaves and returns to CodeMirror", async () => { + vi.useFakeTimers(); + vi.spyOn(host, "hostOs").mockResolvedValue("macos"); + vi.spyOn(ipc, "isTauri").mockReturnValue(true); + const hasFocus = vi.spyOn(document, "hasFocus").mockReturnValue(true); + const configure = vi.spyOn(ipc.commands, "menuConfigure").mockResolvedValue(); + vi.spyOn(ipc.commands, "menuModel").mockResolvedValue([]); + vi.spyOn(ipc.commands, "menuSetDisabled").mockResolvedValue(); + const view = new EditorView({ doc: "source", extensions: history(), parent: document.body }); + const find = document.createElement("input"); + document.body.appendChild(find); + const dispose = installMenuBridge(); + const lastConfig = () => configure.mock.calls.at(-1)?.[0]; + + try { + await vi.advanceTimersByTimeAsync(120); + expect(lastConfig()).toHaveProperty("editorOwnsHistory", false); + + view.contentDOM.focus(); + await vi.advanceTimersByTimeAsync(0); + expect(lastConfig()).toHaveProperty("editorOwnsHistory", true); + + find.focus(); + await vi.advanceTimersByTimeAsync(0); + expect(lastConfig()).toHaveProperty("editorOwnsHistory", false); + + view.contentDOM.focus(); + await vi.advanceTimersByTimeAsync(0); + expect(lastConfig()).toHaveProperty("editorOwnsHistory", true); + + setContext("popupOpen", true); + await vi.advanceTimersByTimeAsync(0); + expect(lastConfig()).toHaveProperty("editorOwnsHistory", false); + clearContext("popupOpen"); + await vi.advanceTimersByTimeAsync(0); + expect(lastConfig()).toHaveProperty("editorOwnsHistory", true); + + hasFocus.mockReturnValue(false); + window.dispatchEvent(new Event("blur")); + await vi.advanceTimersByTimeAsync(0); + expect(lastConfig()).toHaveProperty("editorOwnsHistory", false); + } finally { + dispose(); + view.destroy(); + find.remove(); + clearContext("popupOpen"); + vi.useRealTimers(); + vi.restoreAllMocks(); + } + }); + it("refreshes the focused window's enablement even if context changes during the debounce", async () => { vi.useFakeTimers(); vi.spyOn(ipc, "isTauri").mockReturnValue(true); @@ -232,6 +286,37 @@ afterEach(() => { }); describe("menu event routing", () => { + it("routes native macOS Undo and Redo through the editor history only while it is focused", async () => { + const view = new EditorView({ doc: "source", extensions: history(), parent: document.body }); + const find = document.createElement("input"); + document.body.appendChild(find); + try { + view.contentDOM.focus(); + view.dispatch({ changes: { from: 0, to: 6 }, userEvent: "delete.cut" }); + view.dispatch({ changes: { from: 0, insert: "paste" }, userEvent: "input.paste" }); + const run = vi.fn(async () => true); + const undo = () => routeMenuEvent({ action: "edit.undo", arg: "editorHistory" }, run); + const redo = () => routeMenuEvent({ action: "edit.redo", arg: "editorHistory" }, run); + await expect(undo()).resolves.toBe(true); + expect(view.state.doc.toString()).toBe(""); + await expect(undo()).resolves.toBe(true); + expect(view.state.doc.toString()).toBe("source"); + await expect(redo()).resolves.toBe(true); + expect(view.state.doc.toString()).toBe(""); + await expect(redo()).resolves.toBe(true); + expect(view.state.doc.toString()).toBe("paste"); + + find.focus(); + await expect(undo()).resolves.toBe(false); + await expect(redo()).resolves.toBe(false); + expect(run).not.toHaveBeenCalled(); + expect(view.state.doc.toString()).toBe("paste"); + } finally { + view.destroy(); + find.remove(); + } + }); + it("runs the action named by the event, passing the argument", async () => { const run = vi.fn(); const off = registerAction({ id: "test.menuRoute", title: "Test", run }); diff --git a/src/features/app/menuBridge.ts b/src/features/app/menuBridge.ts index 10315b30cc..6e9372e417 100644 --- a/src/features/app/menuBridge.ts +++ b/src/features/app/menuBridge.ts @@ -5,8 +5,10 @@ * an IDE menu item is clicked; we run `executeAction(action, arg)`. In the * other direction we push localised labels (`menu.*` catalog keys) and the * native accelerator of every keymap binding, which the macOS menu shows as a key - * equivalent while the JS keymap stays the only dispatcher (see src-tauri/src/menu.rs). + * equivalent (see src-tauri/src/menu.rs), and whether the focused editor owns Undo and Redo. */ +import { historyField } from "@codemirror/commands"; +import { EditorView } from "@codemirror/view"; import { executeActionFrom, getAction, isActionEnabled, useActions } from "@/platform/actions"; import { getContext, useContextKeys } from "@/platform/context"; import { keysWithPrefix, t, tx, useI18n } from "@/platform/i18n"; @@ -42,12 +44,35 @@ export function isMenuRoute(v: unknown): v is MenuRoute { return typeof v === "object" && v !== null && typeof (v as MenuRoute).action === "string"; } +function focusedHistoryView(): EditorView | null { + if (!document.hasFocus() || getContext().popupOpen) return null; + const focused = document.activeElement; + if (!(focused instanceof HTMLElement)) return null; + const view = EditorView.findFromDOM(focused); + return view?.contentDOM === focused && + !view.state.readOnly && + view.state.facet(EditorView.editable) && + view.state.field(historyField, false) + ? view + : null; +} + /** Runs the action a menu item stands for. Returns whether it ran. */ export function routeMenuEvent( payload: unknown, run = (id: string, arg?: unknown) => executeActionFrom("menu", id, arg), ): Promise { if (!isMenuRoute(payload) || !payload.action) return Promise.resolve(false); + if (payload.arg === "editorHistory" && (payload.action === "edit.undo" || payload.action === "edit.redo")) { + const view = focusedHistoryView(); + // Focus may have moved while the event was queued. WebKit's undo stack can target a background editor. + if (!view) return Promise.resolve(false); + // Use the same history hooks as WebKit, including shared document and workspace history. + const inputType = payload.action === "edit.undo" ? "historyUndo" : "historyRedo"; + return Promise.resolve( + !view.contentDOM.dispatchEvent(new InputEvent("beforeinput", { inputType, bubbles: true, cancelable: true })), + ); + } return run(payload.action, payload.arg ?? undefined); } @@ -124,6 +149,7 @@ export function buildMenuConfig(os: HostOs): MenuConfig { accelerators, dynamic: dynamicMenuItems(), checked: toggledActions(), + editorOwnsHistory: os === "macos" && !!focusedHistoryView(), }; } @@ -199,13 +225,24 @@ export function installMenuBridge(): () => void { let unlisten: (() => void) | undefined; let timer: ReturnType | undefined; + let editorOwnsHistory: boolean | undefined; + const sendConfig = (os: HostOs) => { + if (disposed) return; + const config = buildMenuConfig(os); + editorOwnsHistory = config.editorOwnsHistory; + void commands.menuConfigure(config); + }; const push = () => { clearTimeout(timer); - timer = setTimeout(() => { - void hostOs().then((os) => { - if (!disposed) void commands.menuConfigure(buildMenuConfig(os)); - }); - }, 50); + timer = setTimeout(() => void hostOs().then(sendConfig), 50); + }; + // The next key uses these roles, so focus changes cannot wait for the general menu debounce. + const syncHistoryOwner = (force = false) => { + void hostOs().then((os) => { + if (disposed || os !== "macos" || (!force && editorOwnsHistory === !!focusedHistoryView())) return; + clearTimeout(timer); + sendConfig(os); + }); }; void import("@tauri-apps/api/webviewWindow").then(async ({ getCurrentWebviewWindow }) => { @@ -260,14 +297,24 @@ export function installMenuBridge(): () => void { push(); const onFocus = () => { push(); + syncHistoryOwner(true); pushEnablement(true); }; // The menu bar is shared. A focused window re-pushes labels that can differ per window. // The backend edits only submenus whose visible items changed, so switching project // tabs does not redraw the macOS menu bar. window.addEventListener("focus", onFocus); - const onBlur = () => pushEnablement(true, true); + const onBlur = () => { + syncHistoryOwner(); + pushEnablement(true, true); + }; window.addEventListener("blur", onBlur); + const onFocusIn = () => syncHistoryOwner(); + const onFocusOut = (event: FocusEvent) => { + if (!event.relatedTarget) syncHistoryOwner(); + }; + document.addEventListener("focusin", onFocusIn); + document.addEventListener("focusout", onFocusOut); const unsubs = [ useI18n.subscribe((s, prev) => { if (s.messages !== prev.messages) push(); @@ -287,6 +334,12 @@ export function installMenuBridge(): () => void { useMenuSlotItems.subscribe(push), useContextKeys.subscribe((s, prev) => { pushEnablement(); + if ( + s.popupOpen !== prev.popupOpen || + s.editorTextFocus !== prev.editorTextFocus || + s.editorReadOnly !== prev.editorReadOnly + ) + syncHistoryOwner(); if (javaFileNameOf(s.editorPath) !== javaFileNameOf(prev.editorPath)) push(); }), useActions.subscribe(() => pushEnablement()), @@ -304,6 +357,8 @@ export function installMenuBridge(): () => void { clearTimeout(enableTimer); window.removeEventListener("focus", onFocus); window.removeEventListener("blur", onBlur); + document.removeEventListener("focusin", onFocusIn); + document.removeEventListener("focusout", onFocusOut); unlisten?.(); unsubs.forEach((u) => u()); };