From 3a0536eafca863331ae97feb1105f5e08029f688 Mon Sep 17 00:00:00 2001 From: LU XIANGRUI <1078666705@qq.com> Date: Mon, 16 Nov 2026 13:07:09 +0900 Subject: [PATCH] fix(menu): keep the menu usable while a Settings window is in front (#3657) On macOS the backend treated the Settings window as modal and dropped every menu item except Quit, Settings, Project Structure and New Projects Settings, while still showing them enabled. Items chosen with Settings in front now run in its project window, which is brought forward; once what the action opened closes (or right away if it opened nothing) Settings comes back to the front. The project window pushes its menu enablement once on blur, so editor-only items grey out, and enablement pushed by other windows no longer overrides the front window's. Closes #3625 Co-authored-by: wildcatDownstairs <26499420+wildcatDownstairs@users.noreply.github.com> --- src-tauri/src/commands/window.rs | 8 +- src-tauri/src/lib.rs | 27 +++---- src-tauri/src/menu.rs | 11 +++ src-tauri/src/windows.rs | 53 ++++++++++++- src/features/app/__tests__/menuBridge.test.ts | 79 +++++++++++++++++++ src/features/app/menuBridge.ts | 57 ++++++++++++- 6 files changed, 214 insertions(+), 21 deletions(-) diff --git a/src-tauri/src/commands/window.rs b/src-tauri/src/commands/window.rs index d4569f98e..73f3d0be3 100644 --- a/src-tauri/src/commands/window.rs +++ b/src-tauri/src/commands/window.rs @@ -330,7 +330,13 @@ pub fn menu_model(app: AppHandle, state: State<'_, AppState>, menu_state: State< /// disabled in place (no rebuild). #[tauri::command] #[specta::specta] -pub fn menu_set_disabled(app: AppHandle, menu_state: State<'_, MenuState>, ids: Vec) { +pub fn menu_set_disabled(window: WebviewWindow, app: AppHandle, menu_state: State<'_, MenuState>, ids: Vec) { + // The window whose menu runs: a project window also while its Settings window is focused. + if menu::native_menu_bar() + && windows::target_window(&app).is_some_and(|target| !owns_menu_config(window.label(), target.label())) + { + return; + } let disabled: std::collections::HashSet = ids.into_iter().collect(); if *menu_state.disabled.lock() == disabled { return; diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index 5cc37e24d..dcf2cf451 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -373,25 +373,24 @@ pub(crate) fn dispatch_menu_action(app: &tauri::AppHandle, id: &str) { let Some(route) = menu::route(&menu::spec(menu::Os::current()), id) else { return }; match windows::target_window(app) { Some(w) => { - // App-level items of an auxiliary window go to its project window. Settings is modal for it: - // nothing else gets through. Others handle their own items; Close Tab closes the window. - let label = match windows::auxiliary(w.label()) { - Some((_, parent)) - if matches!( - route.action.as_str(), - "app.quit" | "file.settings" | "file.projectStructure" | "file.newProjectsSettings" - ) => - { - parent + // The window to bring back to the front once what the action shows is closed (Settings). + let mut return_to = None; + let label = match windows::menu_destination(w.label(), &route.action) { + windows::MenuDestination::Own => w.label(), + windows::MenuDestination::Parent { label, raise } => { + if raise && let Some(parent) = app.get_webview_window(label) { + windows::focus(&parent); + return_to = Some(w.label()); + } + label } - Some((kind, _)) if kind.modal() => return, - Some(_) if route.action == "editor.closeTab" => { + windows::MenuDestination::Close => { let _ = w.close(); return; } - _ => w.label(), }; - if let Err(e) = app.emit_to(label, menu::MENU_EVENT, &route) { + let event = menu::MenuEvent { route: &route, return_to }; + if let Err(e) = app.emit_to(label, menu::MENU_EVENT, &event) { tracing::warn!("failed to deliver menu event {id}: {e}"); } } diff --git a/src-tauri/src/menu.rs b/src-tauri/src/menu.rs index 5b36ee213..2b121364e 100644 --- a/src-tauri/src/menu.rs +++ b/src-tauri/src/menu.rs @@ -904,6 +904,17 @@ pub struct MenuRoute { pub arg: Option, } +/// Payload of [`MENU_EVENT`]: the route, and the window that was in front when the item was +/// chosen if the action runs in another one (a Settings window's project window). +#[derive(Serialize)] +#[serde(rename_all = "camelCase")] +pub struct MenuEvent<'a> { + #[serde(flatten)] + pub route: &'a MenuRoute, + #[serde(skip_serializing_if = "Option::is_none")] + pub return_to: Option<&'a str>, +} + /// Maps a clicked item id to the action to run. `None` for ids that are not /// IDE items (native roles, placeholders). pub fn route(spec: &[Entry], id: &str) -> Option { diff --git a/src-tauri/src/windows.rs b/src-tauri/src/windows.rs index e89d9a796..34ab1482c 100644 --- a/src-tauri/src/windows.rs +++ b/src-tauri/src/windows.rs @@ -360,8 +360,8 @@ impl AuxKind { self != AuxKind::Settings } - /// Modal for its parent: menu items other than app-level ones are dropped. - pub fn modal(self) -> bool { + /// Has no actions of its own: menu items run in its project window. + fn runs_menu_in_parent(self) -> bool { self == AuxKind::Settings } @@ -386,6 +386,34 @@ pub fn auxiliary(label: &str) -> Option<(AuxKind, &str)> { }) } +/// Where a menu item chosen while window `label` is focused runs. +#[derive(Debug, PartialEq, Eq)] +pub enum MenuDestination<'a> { + /// The window's own frontend. + Own, + /// The project window `label`; `raise` brings it to the front so what the action shows is seen. + Parent { label: &'a str, raise: bool }, + /// The window itself is the tab: Close Tab closes it. + Close, +} + +/// Actions an auxiliary window always leaves to its project window. +const PARENT_ACTIONS: [&str; 4] = ["app.quit", "file.settings", "file.projectStructure", "file.newProjectsSettings"]; + +/// Where menu item `action` runs while window `label` is focused. As in IDEA, the menu stays usable +/// with Settings open: it runs in the project window, whose enablement (no focused editor) the menu shows. +pub fn menu_destination<'a>(label: &'a str, action: &str) -> MenuDestination<'a> { + match auxiliary(label) { + None => MenuDestination::Own, + Some((_, parent)) if PARENT_ACTIONS.contains(&action) => { + MenuDestination::Parent { label: parent, raise: false } + } + Some((kind, parent)) if kind.runs_menu_in_parent() => MenuDestination::Parent { label: parent, raise: true }, + Some(_) if action == "editor.closeTab" => MenuDestination::Close, + Some(_) => MenuDestination::Own, + } +} + /// The project window an auxiliary window belongs to (`settings-main` → `main`). pub fn auxiliary_parent(label: &str) -> Option<&str> { auxiliary(label).map(|(_, parent)| parent) @@ -2349,6 +2377,27 @@ mod tests { assert_eq!(sorted_labels(labels.into_iter().filter(|l| auxiliary_parent(l).is_none())), ["main", "project-2"]); } + #[test] + fn menu_items_chosen_in_settings_run_in_its_project_window() { + use MenuDestination::*; + for (label, action, expected) in [ + ("main", "app.about", Own), + ("main", "editor.closeTab", Own), + // #3625: Settings has no actions of its own; the rest of the menu runs in the project window. + ("settings-main", "app.checkForUpdates", Parent { label: "main", raise: true }), + ("settings-project-2", "file.newFile", Parent { label: "project-2", raise: true }), + ("settings-main", "editor.closeTab", Parent { label: "main", raise: true }), + ("settings-main", "file.settings", Parent { label: "main", raise: false }), + ("settings-main", "app.quit", Parent { label: "main", raise: false }), + ("comparison-main-0", "app.quit", Parent { label: "main", raise: false }), + ("comparison-main-0", "editor.closeTab", Close), + ("diff-main-1", "vcs.diff.next", Own), + ("deployment-main", "app.about", Own), + ] { + assert_eq!(menu_destination(label, action), expected, "{label} {action}"); + } + } + #[test] fn settings_bounds_fit_current_work_area() { for (parent, size, work, expected) in [ diff --git a/src/features/app/__tests__/menuBridge.test.ts b/src/features/app/__tests__/menuBridge.test.ts index a1eeb6989..228d62504 100644 --- a/src/features/app/__tests__/menuBridge.test.ts +++ b/src/features/app/__tests__/menuBridge.test.ts @@ -15,6 +15,7 @@ import { installMenuBridge, menuAccelerator, menuActionIds, + returnFocusAfterMenu, routeMenuEvent, } from "../menuBridge"; @@ -54,6 +55,84 @@ describe("menu state from the frontend", () => { } }); + it("pushes enablement once when the window loses focus, for its Settings window (#3625)", async () => { + vi.useFakeTimers(); + vi.spyOn(ipc, "isTauri").mockReturnValue(true); + const hasFocus = vi.spyOn(document, "hasFocus").mockReturnValue(true); + vi.spyOn(ipc.commands, "appBuildInfo").mockRejectedValue(new Error("No build info in tests")); + vi.spyOn(ipc.commands, "menuConfigure").mockResolvedValue(); + vi.spyOn(ipc.commands, "menuModel").mockResolvedValue([ + { kind: "action", id: "test.menuBlur", label: "Test", hint: null, arg: null, checked: null }, + ]); + const pushDisabled = vi.spyOn(ipc.commands, "menuSetDisabled").mockResolvedValue(); + const offAction = registerAction({ id: "test.menuBlur", title: "Test", when: "testMenuBlurEditor", run: () => {} }); + setContext("testMenuBlurEditor", true); + const dispose = installMenuBridge(); + try { + await vi.advanceTimersByTimeAsync(120); + expect(pushDisabled).toHaveBeenCalledExactlyOnceWith([]); + pushDisabled.mockClear(); + + // Focus moves to the Settings window: the editor loses focus, then the window blurs. + hasFocus.mockReturnValue(false); + setContext("testMenuBlurEditor", false); + window.dispatchEvent(new Event("blur")); + await vi.advanceTimersByTimeAsync(120); + expect(pushDisabled).toHaveBeenCalledExactlyOnceWith(["test.menuBlur"]); + pushDisabled.mockClear(); + + // Later changes in a background window are not pushed. + setContext("testMenuBlurEditor", true); + await vi.advanceTimersByTimeAsync(120); + expect(pushDisabled).not.toHaveBeenCalled(); + } finally { + dispose(); + offAction(); + clearContext("testMenuBlurEditor"); + vi.useRealTimers(); + vi.restoreAllMocks(); + } + }); + + it("brings Settings back once the dialog opened from its menu closes (#3625)", async () => { + vi.useFakeTimers(); + vi.spyOn(document, "hasFocus").mockReturnValue(true); + const focusSettings = vi.fn(async () => {}); + try { + // About opens a dialog: Settings waits under it. + const about = returnFocusAfterMenu( + Promise.resolve(true) + .then(() => setContext("popupOpen", true)) + .then(() => true), + focusSettings, + ); + await vi.advanceTimersByTimeAsync(1000); + expect(focusSettings).not.toHaveBeenCalled(); + setContext("popupOpen", false); + await about; + expect(focusSettings).toHaveBeenCalledOnce(); + + // An action that opens nothing: Settings comes back right away. + focusSettings.mockClear(); + const saveAll = returnFocusAfterMenu(Promise.resolve(true), focusSettings); + await vi.advanceTimersByTimeAsync(300); + await saveAll; + expect(focusSettings).toHaveBeenCalledOnce(); + + // Focus moved on (a new window or a native dialog): Settings stays where it is. + focusSettings.mockClear(); + vi.mocked(document.hasFocus).mockReturnValue(false); + const open = returnFocusAfterMenu(Promise.resolve(true), focusSettings); + await vi.advanceTimersByTimeAsync(300); + await open; + expect(focusSettings).not.toHaveBeenCalled(); + } finally { + clearContext("popupOpen"); + vi.useRealTimers(); + vi.restoreAllMocks(); + } + }); + it("lists registered tool windows by title and saved layouts", () => { localStorage.clear(); _reloadLayouts(); diff --git a/src/features/app/menuBridge.ts b/src/features/app/menuBridge.ts index da7fc668f..5d0f6ceea 100644 --- a/src/features/app/menuBridge.ts +++ b/src/features/app/menuBridge.ts @@ -8,7 +8,7 @@ * equivalent while the JS keymap stays the only dispatcher (see src-tauri/src/menu.rs). */ import { executeActionFrom, getAction, isActionEnabled, useActions } from "@/platform/actions"; -import { useContextKeys } from "@/platform/context"; +import { getContext, useContextKeys } from "@/platform/context"; import { keysWithPrefix, t, tx, useI18n } from "@/platform/i18n"; import { commands, isTauri, type DynamicItem, type MenuConfig, type MenuNode } from "@/platform/ipc"; import { @@ -32,6 +32,8 @@ export const MENU_EVENT = "openidea://menu"; export interface MenuRoute { action: string; arg?: string | null; + /** The window in front when the item was chosen, if it is not this one (this window's Settings). */ + returnTo?: string; } export function isMenuRoute(v: unknown): v is MenuRoute { @@ -47,6 +49,36 @@ export function routeMenuEvent( return run(payload.action, payload.arg ?? undefined); } +/** How long an action chosen from the menu may take to open its dialog or popup. */ +const OPEN_DELAY_MS = 300; + +const layersClosed = () => + new Promise((resolve) => { + if (!getContext().popupOpen) return resolve(); + const off = useContextKeys.subscribe((ctx) => { + if (ctx.popupOpen) return; + off(); + resolve(); + }); + }); + +/** + * After an item chosen in this window's Settings window ran here (the backend brought this window + * forward): once the dialog or popup it opened closes, or right away if it opened none, Settings comes + * back to the front, as IDEA's Settings dialog stays under the dialogs opened from the menu. Not when + * focus has moved on (a new window, a native dialog). + */ +export async function returnFocusAfterMenu( + ran: Promise, + focusWindow: () => Promise, + delay = OPEN_DELAY_MS, +): Promise { + await ran; + await new Promise((r) => setTimeout(r, delay)); + await layersClosed(); + if (document.hasFocus()) await focusWindow(); +} + /** * Keymap key names a macOS key equivalent can show. Mirrors the names muda's accelerator * parser accepts: Tauri drops an accelerator it cannot parse, and the item shows no shortcut. @@ -167,22 +199,36 @@ export function installMenuBridge(): () => void { void import("@tauri-apps/api/webviewWindow").then(async ({ getCurrentWebviewWindow }) => { // Window-scoped: a global `listen` would also receive other windows' menu events. - const off = await getCurrentWebviewWindow().listen(MENU_EVENT, ({ payload }) => void routeMenuEvent(payload)); + const off = await getCurrentWebviewWindow().listen(MENU_EVENT, ({ payload }) => { + const ran = routeMenuEvent(payload); + const returnTo = isMenuRoute(payload) ? payload.returnTo : undefined; + if (returnTo) + void returnFocusAfterMenu(ran, async () => { + const { Window } = await import("@tauri-apps/api/window"); + await (await Window.getByLabel(returnTo))?.setFocus(); + }).catch(() => {}); + }); if (disposed) off(); else unlisten = off; }); // Enablement of the native items follows this window's context (IDEA greys out // what cannot run). Recomputed shortly after context changes, sent only when it changed. + // Also once on blur: the menu still runs here while this window's Settings window is focused, + // with nothing focused here (editor actions disabled). The backend ignores it for other windows. let ids: Set | null = null; let lastDisabled = ""; let forceEnablement = false; + let afterBlur = false; let enableTimer: ReturnType | undefined; - const pushEnablement = (force = false) => { + const pushEnablement = (force = false, blurred = false) => { forceEnablement ||= force; + afterBlur ||= blurred; clearTimeout(enableTimer); enableTimer = setTimeout(() => { - if (!ids || disposed || !document.hasFocus()) return; + const unfocused = !document.hasFocus(); + if (!ids || disposed || (unfocused && !afterBlur)) return; + afterBlur = false; const dynamic = Object.values(dynamicMenuItems()).flatMap((items) => items.map((d) => d.action)); const disabled = disabledMenuActions(new Set([...ids, ...dynamic])); const key = disabled.join(","); @@ -209,6 +255,8 @@ export function installMenuBridge(): () => void { // 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); + window.addEventListener("blur", onBlur); const unsubs = [ useI18n.subscribe((s, prev) => { if (s.messages !== prev.messages) push(); @@ -237,6 +285,7 @@ export function installMenuBridge(): () => void { clearTimeout(timer); clearTimeout(enableTimer); window.removeEventListener("focus", onFocus); + window.removeEventListener("blur", onBlur); unlisten?.(); unsubs.forEach((u) => u()); };