diff --git a/src-tauri/src/commands/window.rs b/src-tauri/src/commands/window.rs index 44eff84a7e..2e743bd393 100644 --- a/src-tauri/src/commands/window.rs +++ b/src-tauri/src/commands/window.rs @@ -543,13 +543,13 @@ pub fn menu_set_remote_recent( #[tauri::command] #[specta::specta] 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(); + let source = window.label().to_owned(); + let focused = windows::target_window(&app).map(|w| w.label().to_owned()).unwrap_or_else(|| source.clone()); + let disabled = { + let mut by_window = menu_state.disabled_by_window.lock(); + by_window.insert(source, ids.into_iter().collect()); + windows::effective_menu_disabled(&focused, &by_window) + }; if *menu_state.disabled.lock() == disabled { return; } diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index 19d9c92e8a..ca90e8f57e 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -447,11 +447,21 @@ fn on_menu_event(app: &tauri::AppHandle, event: tauri::menu::MenuEvent) { let id = event.id().as_ref(); menu::restore_check(app, &app.state::(), id); // A keymap accelerator only draws the shortcut: its key reached the menu because the keymap declined it. + // Not for an item that never runs in the focused window's page (an application action chosen in a + // diff window), whose page has no action to decline it with. #[cfg(target_os = "macos")] - if !menu::fires_natively(&menu::spec(menu::Os::Mac), id) - && (macos::handling_key_press() || macos::native_modal_open()) { - return; + let spec = menu::spec(menu::Os::Mac); + let key_runs = || { + menu::route(&spec, id) + .zip(windows::target_window(app)) + .is_some_and(|(route, w)| windows::key_equivalent_runs(w.label(), &route.action)) + }; + if !menu::fires_natively(&spec, id) + && ((macos::handling_key_press() && !key_runs()) || macos::native_modal_open()) + { + return; + } } dispatch_menu_action(app, id); } diff --git a/src-tauri/src/menu.rs b/src-tauri/src/menu.rs index 366d5b016a..ebeffb189f 100644 --- a/src-tauri/src/menu.rs +++ b/src-tauri/src/menu.rs @@ -20,7 +20,7 @@ pub use ide_host::menu::*; use parking_lot::Mutex; use serde::Serialize; -use std::collections::HashSet; +use std::collections::{HashMap, HashSet}; use tauri::menu::{CheckMenuItem, IsMenuItem, Menu, MenuItem, MenuItemKind, NativeIcon, PredefinedMenuItem, Submenu}; use tauri::{AppHandle, Runtime}; @@ -50,8 +50,10 @@ fn render_dynamic(item: &DynamicItem, config: &MenuConfig) -> RenderedItem { #[derive(Default)] pub struct MenuState { pub config: Mutex, - /// Action ids the focused window reports as disabled (no context / not registered). + /// Action ids the focused window cannot run now, derived from `disabled_by_window` and menu routing. pub disabled: Mutex>, + /// Action ids each window reports as disabled (no context / not registered), cached per window. + pub disabled_by_window: Mutex>>, /// 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>>, diff --git a/src-tauri/src/windows.rs b/src-tauri/src/windows.rs index 496b7f1c49..6ab550618a 100644 --- a/src-tauri/src/windows.rs +++ b/src-tauri/src/windows.rs @@ -770,8 +770,51 @@ pub enum MenuDestination<'a> { CycleWindows { forward: bool }, } -/// Actions an auxiliary window always leaves to its project window. -const PARENT_ACTIONS: [&str; 4] = ["app.quit", "file.settings", "file.projectStructure", "file.newProjectsSettings"]; +/// Actions an auxiliary window always leaves to its project window, which stays where it is: they +/// open their own window or change every window. +const PARENT_ACTIONS: [&str; 6] = [ + "app.quit", + "file.settings", + "file.projectStructure", + "file.newProjectsSettings", + "view.toggleTheme", + "file.togglePowerSave", +]; + +/// Application actions no auxiliary window's page registers. Chosen there they run in the project +/// window, brought to the front to show what they open (About, a file chooser, a popup). +const APP_ACTIONS: [&str; 30] = [ + "app.about", + "app.checkForUpdates", + "app.installCli", + "app.uninstallCli", + "file.newProject", + "file.newUntitled", + "file.openProject", + "file.openFile", + "file.openInNewWindow", + crate::menu::OPEN_RECENT_ACTION, + "file.renameProject", + "file.exportSettings", + "file.importSettings", + "file.importJetBrainsSettings", + "file.importJetBrainsRecentProjects", + "file.syncSettings", + "file.invalidateCaches", + "help.keymapReference", + "help.showLog", + "project.attach", + "vcs.clone", + "vcs.cloneProject", + "view.quickSwitchScheme", + "view.notifications", + "welcome.recentProjects", + "window.new", + "window.mergeAllWindows", + "workspace.create", + "workspace.manage", + "workspace.open", +]; /// 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. @@ -781,14 +824,49 @@ pub fn menu_destination<'a>(label: &'a str, action: &str) -> MenuDestination<'a> Some((_, parent)) if PARENT_ACTIONS.contains(&action) => { MenuDestination::Parent { label: parent, raise: false } } + Some(_) if action == "window.toggleFullScreen" => MenuDestination::Own, Some(_) if action == "window.next" => MenuDestination::CycleWindows { forward: true }, Some(_) if action == "window.previous" => MenuDestination::CycleWindows { forward: false }, - Some((kind, parent)) if kind.runs_menu_in_parent() => MenuDestination::Parent { label: parent, raise: true }, + Some((kind, parent)) if kind.runs_menu_in_parent() || APP_ACTIONS.contains(&action) => { + MenuDestination::Parent { label: parent, raise: true } + } Some(_) if action == "editor.closeTab" => MenuDestination::Close, Some(_) => MenuDestination::Own, } } +/// The disabled action ids the shared menu should show while `label` is focused. Items routed to +/// a parent window follow that destination window's enablement, not the focused auxiliary page's. +pub fn effective_menu_disabled( + label: &str, + by_window: &std::collections::HashMap>, +) -> std::collections::HashSet { + let all: std::collections::HashSet = by_window.values().flatten().cloned().collect(); + all.into_iter() + .filter(|action| { + let source = match menu_destination(label, action) { + MenuDestination::Own => label, + MenuDestination::Parent { label: parent, .. } => parent, + MenuDestination::Close | MenuDestination::CycleWindows { .. } => return false, + }; + by_window.get(source).is_some_and(|disabled| disabled.contains(action)) + }) + .collect() +} + +/// Whether the key equivalent of menu item `action`, pressed in window `label`, runs the item. A +/// page declines the keys it has no action for, and for an item that runs in that page the keymap +/// has spoken; items that never run there (window cycling, application actions from an auxiliary +/// window) still need the key. Only the macOS menu fires key equivalents (`on_menu_event`). +#[cfg(any(target_os = "macos", test))] +pub fn key_equivalent_runs(label: &str, action: &str) -> bool { + match menu_destination(label, action) { + MenuDestination::CycleWindows { .. } => true, + MenuDestination::Parent { .. } => PARENT_ACTIONS.contains(&action) || APP_ACTIONS.contains(&action), + MenuDestination::Own | MenuDestination::Close => false, + } +} + /// The project window an auxiliary window belongs to (`settings-main` → `main`). pub fn auxiliary_parent(label: &str) -> Option<&str> { auxiliary(label).map(|(_, parent)| parent) @@ -3275,6 +3353,58 @@ mod tests { assert_eq!(next_label(["main", "project-1", "project-3"]), "project-2"); } + /// A routed action that the menu doesn't have (renamed, removed) would silently fall back to + /// the auxiliary window's page, where it does nothing. + #[test] + fn actions_routed_to_the_project_window_are_menu_items() { + let mac = crate::menu::action_ids(&crate::menu::spec(crate::menu::Os::Mac)); + for action in PARENT_ACTIONS.iter().chain(&APP_ACTIONS) { + assert!( + mac.contains(action) || *action == crate::menu::OPEN_RECENT_ACTION, + "{action} is not in the macOS menu" + ); + } + } + + #[test] + fn key_equivalents_run_only_items_outside_the_page() { + for (label, action, runs) in [ + // The diff window's page has no About: its key goes to the project window. + ("diff-main-1", "app.about", true), + ("diff-main-1", "file.settings", true), + ("settings-main", "help.showLog", true), + ("diff-main-1", "window.next", true), + ("main", "window.previous", false), + // The keymap already declined these: the page runs them, or nothing does. + ("main", "app.about", false), + ("diff-main-1", "window.toggleFullScreen", false), + ("diff-main-1", "find.inFile", false), + ("settings-main", "find.inFile", false), + ("comparison-main-0", "editor.closeTab", false), + ] { + assert_eq!(key_equivalent_runs(label, action), runs, "{label} {action}"); + } + } + + #[test] + fn menu_enablement_comes_from_the_destination_window() { + let mut by_window = std::collections::HashMap::new(); + by_window.insert("main".to_owned(), std::collections::HashSet::from(["workspace.manage".to_owned()])); + by_window.insert( + "diff-main-1".to_owned(), + std::collections::HashSet::from([ + "workspace.manage".to_owned(), + "app.about".to_owned(), + "window.next".to_owned(), + ]), + ); + assert!(effective_menu_disabled("diff-main-1", &by_window).contains("workspace.manage")); + by_window.get_mut("main").unwrap().remove("workspace.manage"); + let effective = effective_menu_disabled("diff-main-1", &by_window); + assert!(!effective.contains("workspace.manage")); + assert!(!effective.contains("window.next")); + } + #[test] fn window_cycling_reaches_auxiliary_windows() { let order = window_cycle_order(["project-1", "diff-main-42", "settings-main", "main", "editor-project-1-3"]); @@ -3881,19 +4011,34 @@ mod tests { ("settings-main", "editor.closeTab", Parent { label: "main", raise: true }), ("new-project-main", "file.newFile", Parent { label: "main", raise: true }), ("clone-main", "vcs.clone", Parent { label: "main", raise: true }), + ("clone-main", "vcs.cloneProject", Parent { label: "main", raise: true }), ("new-project-project-2", "editor.closeTab", Parent { label: "project-2", 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), + // Its page has no About: before, choosing it there did nothing. + ("deployment-main", "app.about", Parent { label: "main", raise: true }), + ("deployment-main", "vcs.diff.next", Own), // ⌘` from any window, its page's actions and a dialog's parent notwithstanding. ("main", "window.next", Own), ("diff-main-1", "window.next", CycleWindows { forward: true }), ("diff-main-1", "window.previous", CycleWindows { forward: false }), ("settings-main", "window.next", CycleWindows { forward: true }), ("editor-project-2-4", "window.previous", CycleWindows { forward: false }), + // Application actions no auxiliary page registers run in its project window. + ("diff-main-1", "app.about", Parent { label: "main", raise: true }), + ("editor-project-2-4", "file.openFile", Parent { label: "project-2", raise: true }), + ("deployment-main", "help.showLog", Parent { label: "main", raise: true }), + ("comparison-main-0", "file.openRecentProject", Parent { label: "main", raise: true }), + ("diff-main-1", "view.toggleTheme", Parent { label: "main", raise: false }), + ("main", "app.about", Own), + // Toggle Full Screen is the window's own: every auxiliary page registers it. + ("diff-main-1", "window.toggleFullScreen", Own), + ("settings-main", "window.toggleFullScreen", Own), + // What concerns the project itself stays with the window (greyed out where unregistered). + ("diff-main-1", "file.closeProject", Own), ] { assert_eq!(menu_destination(label, action), expected, "{label} {action}"); } diff --git a/src/auxiliaryBoot.ts b/src/auxiliaryBoot.ts index e9e5072340..b9b14ba561 100644 --- a/src/auxiliaryBoot.ts +++ b/src/auxiliaryBoot.ts @@ -1,13 +1,13 @@ import { registerLocalizedActions } from "./features/app/locale"; -import { windowCycleActions } from "./features/app/windowCycle"; +import { sharedWindowActions } from "./features/app/sharedWindowActions"; import type { AuxKind } from "./platform/auxWindow"; import { mountWindowRoot } from "./windowBoot"; import { activateSecondaryWindow } from "./workbench/activateSecondary"; export async function bootAuxiliaryWindow(aux: { kind: AuxKind; parent: string }): Promise { activateSecondaryWindow(); - // Every auxiliary window, whatever its kind, can reach the other windows with the keymap. - registerLocalizedActions(windowCycleActions); + // Every auxiliary window, whatever its kind, can reach the other windows and go full screen. + registerLocalizedActions(sharedWindowActions); switch (aux.kind) { case "settings": { const { bootSettingsWindow } = await import("./settingsWindowBoot"); diff --git a/src/deploymentWindowBoot.ts b/src/deploymentWindowBoot.ts index 375d1c209f..72731bf5e7 100644 --- a/src/deploymentWindowBoot.ts +++ b/src/deploymentWindowBoot.ts @@ -1,5 +1,6 @@ import type { ComponentType } from "react"; import { installLocaleSync } from "./features/app/locale"; +import { installMenuBridge } from "./features/app/menuBridge"; import { activateDeploymentWindow, DeploymentWindow } from "./features/deployment/window"; import { trackRuntimeSettings } from "./features/settings/runtime"; import { activateDiffViewer } from "./features/vcs/diffViewer"; @@ -13,6 +14,8 @@ export function bootDeploymentWindow(parent: string): ComponentType { activateList("deployment window", [ ["locale", installLocaleSync], ["settings", trackRuntimeSettings], + // Without it, menu items chosen here did nothing: they run in this window, as in the diff window. + ["menu", installMenuBridge], ["diff", activateDiffViewer], ["deployment", () => activateDeploymentWindow(parent)], ]); diff --git a/src/features/app/__tests__/menuBridge.test.ts b/src/features/app/__tests__/menuBridge.test.ts index 8ecfc7f75e..eab4907f56 100644 --- a/src/features/app/__tests__/menuBridge.test.ts +++ b/src/features/app/__tests__/menuBridge.test.ts @@ -179,6 +179,8 @@ describe("menu state from the frontend", () => { expect([...ids].sort()).toEqual(["not.registered", "test.menu.always", "test.menu.whenEditor"]); // Unregistered ids stay enabled: the action may register later (lazy features). expect(disabledMenuActions(ids)).toEqual(["test.menu.whenEditor"]); + // An auxiliary window (a diff window) greys them out: chosen there, they would do nothing. + expect(disabledMenuActions(ids, true)).toEqual(["not.registered", "test.menu.whenEditor"]); setContext("testMenuEditor", true); expect(disabledMenuActions(ids)).toEqual([]); setContext("testMenuEditor", false); diff --git a/src/features/app/menuBridge.ts b/src/features/app/menuBridge.ts index 28e2cde8f5..b98e5576eb 100644 --- a/src/features/app/menuBridge.ts +++ b/src/features/app/menuBridge.ts @@ -19,6 +19,7 @@ import { primaryKeyBinding, useKeymap, } from "@/platform/keymap"; +import { auxiliaryWindow } from "@/platform/auxWindow"; import { useProject } from "@/platform/project"; import { hiddenMenuEntries, onWorkflowSettingsChange } from "@/platform/workflowSettings"; import { useOtherVcsRoots } from "@/platform/gitEnabled"; @@ -188,12 +189,18 @@ export function menuActionIds(nodes: readonly MenuNode[], out = new Set( return out; } -/** The registered ones among `ids` that cannot run in the current context. */ -export function disabledMenuActions(ids: Iterable): string[] { +/** + * The ones among `ids` that cannot run in the current context: registered but disabled, and with + * `unregistered`, those this window never registered. A project window leaves those enabled (a + * feature may register them later); an auxiliary window boots a fixed set of features, so a menu + * item it has no action for would do nothing there. The backend keeps items it runs elsewhere + * (in the project window) enabled. + */ +export function disabledMenuActions(ids: Iterable, unregistered = false): string[] { const out: string[] = []; for (const id of ids) { const action = getAction(id); - if (action && !isActionEnabled(action)) out.push(id); + if (action ? !isActionEnabled(action) : unregistered) out.push(id); } return out.sort(); } @@ -231,8 +238,9 @@ export function installMenuBridge(): () => void { // 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. + // with nothing focused here (editor actions disabled). The backend caches it as this window's state. let ids: Set | null = null; + const auxiliary = auxiliaryWindow() !== null; let lastDisabled = ""; let forceEnablement = false; let afterBlur = false; @@ -246,7 +254,7 @@ export function installMenuBridge(): () => void { 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 disabled = disabledMenuActions(new Set([...ids, ...dynamic]), auxiliary); const key = disabled.join(","); if (!forceEnablement && key === lastDisabled) return; forceEnablement = false; diff --git a/src/features/app/sharedWindowActions.ts b/src/features/app/sharedWindowActions.ts new file mode 100644 index 0000000000..585a3d021e --- /dev/null +++ b/src/features/app/sharedWindowActions.ts @@ -0,0 +1,37 @@ +import type { Action } from "@/platform/actions"; +import { t } from "@/platform/i18n"; +import { commands, isTauri } from "@/platform/ipc"; + +/** + * Window actions every window registers: project windows and each auxiliary window (diff, + * comparison, editor, Settings, …), so their menu items and keymap bindings work wherever focus + * is. Next / Previous Window step through every open window; Toggle Full Screen acts on this one. + */ +export function sharedWindowActions(): Action[] { + return [ + { + id: "window.next", + title: t("app.action.nextWindow"), + category: t("app.category.window"), + run: () => (isTauri() ? commands.windowCycle(true) : undefined), + }, + { + id: "window.previous", + title: t("app.action.previousWindow"), + category: t("app.category.window"), + run: () => (isTauri() ? commands.windowCycle(false) : undefined), + }, + { + id: "window.toggleFullScreen", + title: t("app.action.toggleFullScreen"), + category: t("app.category.view"), + icon: "maximize", + keywords: ["full screen", "fullscreen"], + run: async () => { + if (isTauri()) await commands.windowToggleFullscreen(); + else if (document.fullscreenElement) await document.exitFullscreen(); + else await document.documentElement.requestFullscreen?.(); + }, + }, + ]; +} diff --git a/src/features/app/windowCycle.ts b/src/features/app/windowCycle.ts deleted file mode 100644 index 5f2205dab4..0000000000 --- a/src/features/app/windowCycle.ts +++ /dev/null @@ -1,25 +0,0 @@ -import type { Action } from "@/platform/actions"; -import { t } from "@/platform/i18n"; -import { commands, isTauri } from "@/platform/ipc"; - -/** - * Next / Previous Window, for every window: project windows and each auxiliary window (diff, - * comparison, editor, Settings, …), so the keymap's binding works wherever focus is. The backend - * steps through every open window. - */ -export function windowCycleActions(): Action[] { - return [ - { - id: "window.next", - title: t("app.action.nextWindow"), - category: t("app.category.window"), - run: () => (isTauri() ? commands.windowCycle(true) : undefined), - }, - { - id: "window.previous", - title: t("app.action.previousWindow"), - category: t("app.category.window"), - run: () => (isTauri() ? commands.windowCycle(false) : undefined), - }, - ]; -} diff --git a/src/features/app/windows.ts b/src/features/app/windows.ts index 8fa5884859..2fb141e5f6 100644 --- a/src/features/app/windows.ts +++ b/src/features/app/windows.ts @@ -32,7 +32,7 @@ import { openTabColorPicker } from "@/workbench/TabColorPicker"; import { cycleWindowTab, useWindowGroup } from "@/platform/windowGroups"; import { editorSwitching } from "@/editor/api"; import { showWorkspaceDialog } from "./WorkspaceDialog"; -import { windowCycleActions } from "./windowCycle"; +import { sharedWindowActions } from "./sharedWindowActions"; export const LAUNCH_EVENT = "openidea://launch"; @@ -705,19 +705,7 @@ export function windowActions(): Action[] { ); }, }, - ...windowCycleActions(), - { - id: "window.toggleFullScreen", - title: t("app.action.toggleFullScreen"), - category: t("app.category.view"), - icon: "maximize", - keywords: ["full screen", "fullscreen"], - run: async () => { - if (isTauri()) await commands.windowToggleFullscreen(); - else if (document.fullscreenElement) await document.exitFullscreen(); - else await document.documentElement.requestFullscreen?.(); - }, - }, + ...sharedWindowActions(), ]; }