Skip to content

Visual Studio Code, rebuilt in Rust

Rust
26.5 KB
Raw Blame
//! The native macOS menu bar: `MenuId.MenubarMainMenu` as menubarControl.ts (electron-browser) sends it, built
//! into the application menu as platform/menubar/electron-main/menubar.ts does, with its app and Window menus.

#[cfg(test)]
mod tests;

use std::collections::BTreeMap;

use std::cell::Cell;
use std::rc::Rc;

use gpui::{
    Action, AnyWindowHandle, App, Bounds, Context, Div, InteractiveElement, KeyBinding, KeyBindingContextPredicate, Menu, MenuItem, MouseButton, OsAction, ParentElement, Pixels, Rgba, SharedString, Styled, SystemMenuType, Window, WindowControlArea, actions, div, px,
};
#[cfg(target_os = "macos")]
use objc2::{MainThreadMarker, sel};
#[cfg(target_os = "macos")]
use objc2_app_kit::{NSApplication, NSMenuItem};
#[cfg(target_os = "macos")]
use objc2_foundation::NSString;
use serde_json::{Value, json};

use super::{Workbench, output_view};
use super::auxiliary_windows::{AuxiliaryWindow, window_workbench};
use crate::keybindings::Chord;
use super::workspace_actions::recent_openable;
use crate::menus::{MenuAction, MenuId, menu_actions, mnemonic_menu_label};
use crate::recently_opened;
use crate::update::State;

actions!(menubar, [Hide, HideOthers, ShowAll]);

/// A menu item that runs a command.
#[derive(Clone, Debug, PartialEq, gpui::Action)]
#[action(namespace = menubar, no_json)]
pub struct RunMenuCommand {
    pub id: String,
}

/// An Open Recent entry of the menu bar, by its index in `Menubar::recent`.
#[derive(Clone, Debug, PartialEq, gpui::Action)]
#[action(namespace = menubar, no_json)]
pub struct OpenRecentMenuEntry {
    pub index: usize,
}

/// A disabled item. AppKit enables an item only when GPUI has a listener for its action, and this one has none.
#[derive(Clone, Debug, PartialEq, gpui::Action)]
#[action(namespace = menubar, no_json)]
pub struct DisabledMenuCommand {
    pub id: String,
}

/// The key context of the bindings that give menu items their key equivalents. No element sets it, so the keys
/// still go through the workbench's own resolver first.
const MENU_KEY_EQUIVALENT: &str = "menubar_key_equivalent";

/// What the menu bar shows: the top-level menus with mnemonics dropped, and each command's primary keybinding.
#[derive(Debug, PartialEq)]
pub struct Menubar {
    pub menus: Vec<(String, Vec<MenuAction>)>,
    pub keybindings: BTreeMap<String, Vec<Chord>>,
    /// `getOpenRecentActions`: the labels and entries of the recent folders and workspaces, then of the files.
    pub recent: Vec<(String, Value)>,
    pub recent_workspaces: usize,
    /// The Window menu's Always on Top check.
    pub always_on_top: bool,
    /// `getUpdateMenuItems`: the app menu's update item after About, its title, command and enablement.
    pub update_item: Option<(String, &'static str, bool)>,
}

/// menubarControl.ts `MAX_MENU_RECENT_ENTRIES` and `MAX_MENU_RECENT_LABEL_LENGTH`.
const MAX_MENU_RECENT_ENTRIES: usize = 10;
const MAX_MENU_RECENT_LABEL_LENGTH: usize = 120;

/// Runs the menu actions in the window `menu_window` picks.
pub fn install(cx: &mut App) {
    cx.on_action(move |action: &RunMenuCommand, cx| {
        // With the window active, GPUI calls this inside its `window.update`, where a nested update fails.
        let id = action.id.clone();
        cx.defer(move |cx| {
            // menubar.ts `runActionInRenderer`: the focused window runs it; with no window Quit quits, New Window
            // opens one and the others open an empty window first.
            match menu_window(cx) {
                Some(window) => update_menu_window(window, cx, |workbench, window, cx| workbench.run_menu_command(&id, window, cx)),
                None if id == "workbench.action.quit" => cx.quit(),
                None if id == "workbench.action.newWindow" => crate::open_window_or_log(crate::WindowRequest::default(), cx),
                None => {
                    let Ok(window) = crate::open_window(crate::WindowRequest::default(), cx) else { return };
                    let _ = window.update(cx, |workbench, window, cx| workbench.run_menu_command(&id, window, cx));
                }
            }
        });
    });
    cx.on_action(move |action: &OpenRecentMenuEntry, cx| {
        let index = action.index;
        cx.defer(move |cx| {
            let Some(window) = menu_window(cx) else { return };
            update_menu_window(window, cx, |workbench, window, cx| workbench.open_recent_menu_entry(index, window, cx));
        });
    });
    cx.on_action(|_: &Hide, cx| cx.hide());
    cx.on_action(|_: &HideOthers, cx| cx.hide_other_apps());
    cx.on_action(|_: &ShowAll, cx| cx.unhide_other_apps());
    #[cfg(target_os = "macos")]
    cx.set_dock_menu(dock_menu());
}

/// menubar.ts `install`: the Dock menu's one item, New Window, opens an empty window.
#[cfg(target_os = "macos")]
fn dock_menu() -> Vec<MenuItem> {
    vec![MenuItem::action(native_label(&main_label("miNewWindow", "New &&Window")), RunMenuCommand { id: "workbench.action.newWindow".into() })]
}

/// The window menu actions go to: the active workbench or editor window, else the frontmost workbench window, else
/// any (a platform without a window stack).
fn menu_window(cx: &App) -> Option<AnyWindowHandle> {
    let ours = |window: &AnyWindowHandle| window.downcast::<Workbench>().is_some() || window.downcast::<AuxiliaryWindow>().is_some();
    let frontmost = || cx.window_stack().unwrap_or_else(|| cx.windows()).into_iter().find(|window| window.downcast::<Workbench>().is_some());
    cx.active_window().filter(ours).or_else(frontmost)
}

/// Runs `run` on the workbench of `window` with that window.
fn update_menu_window(window: AnyWindowHandle, cx: &mut App, run: impl FnOnce(&mut Workbench, &mut Window, &mut Context<Workbench>)) {
    let _ = window.update(cx, |_, window, cx| {
        let Some(workbench) = window_workbench(window, cx) else { return };
        workbench.update(cx, |workbench, cx| run(workbench, window, cx));
    });
}

impl Workbench {
    /// `MenubarControl.getMenubarMenus` with the keybindings of `getMenubarKeybinding` and `getAdditionalKeybindings`.
    pub fn menubar(&self, window: &Window) -> Menubar {
        let context = self.key_context(window);
        let mut menus = Vec::new();
        for action in menu_actions(&self.menus, MenuId::MenubarMainMenu, &context) {
            if let MenuAction::Submenu { title, actions, .. } = action {
                menus.push((mnemonic_menu_label(&title), actions));
            }
        }
        let mut ids = vec!["workbench.action.quit".to_string()];
        for (_, actions) in &menus {
            collect_command_ids(actions, &mut ids);
        }
        let mut keybindings = BTreeMap::new();
        for id in ids {
            if let Some(item) = self.keybindings.resolver.lookup_primary_keybinding(&id, &context) {
                keybindings.insert(id, item.keybinding.clone());
            }
        }
        // Entries of other schemes (remote) are left out: the port opens `file` paths only.
        let menu_entries = |entries: &[Value]| -> Vec<(String, Value)> {
            let entries = entries.iter().filter(|entry| recently_opened::path(entry).is_some()).take(MAX_MENU_RECENT_ENTRIES);
            // menubarControl.ts escapes `&` (`unmnemonicLabel`) so Electron shows it; GPUI shows the label as is.
            entries.map(|entry| (truncate_middle(&recently_opened::label(entry), MAX_MENU_RECENT_LABEL_LENGTH), entry.clone())).collect()
        };
        let mut recent = menu_entries(&self.recently_opened.workspaces);
        let recent_workspaces = recent.len();
        recent.extend(menu_entries(&self.recently_opened.files));
        let always_on_top = context.get("isWindowAlwaysOnTop") == Some(&Value::Bool(true));
        let update_item = match self.update_state {
            State::Idle { .. } => Some((main_label("miCheckForUpdates", "Check for &&Updates..."), "update.checkForUpdate", true)),
            State::CheckingForUpdates { .. } => Some((main_label("miCheckingForUpdates", "Checking for Updates..."), "update.checking", false)),
            State::AvailableForDownload { .. } => Some((main_label("miDownloadUpdate", "D&&ownload Available Update"), "update.downloadNow", true)),
            State::Downloading { .. } => Some((main_label("miDownloadingUpdate", "Downloading Update..."), "update.downloading", false)),
            State::Ready { .. } => Some((main_label("miRestartToUpdate", "Restart to &&Update"), "update.restartToUpdate", true)),
            State::Uninitialized | State::Disabled(_) | State::Downloaded { .. } | State::Restarting { .. } => None,
        };
        Menubar { menus, keybindings, recent, recent_workspaces, always_on_top, update_item }
    }

    /// `updateMenubar`: `menuUpdater` updates the menu 200 ms later. Every render asks, so a frame does not build the
    /// menus again; the first menu, and the menu of a window come to the front, install at once.
    pub(super) fn schedule_menubar_update(&mut self, window: &Window, cx: &mut Context<Self>) {
        if self.installed_menubar.is_none() {
            return self.update_menubar(window, cx);
        }
        if self.menubar_update.is_some() {
            return;
        }
        self.menubar_update = Some(cx.spawn_in(window, async move |workbench, cx| {
            cx.background_executor().timer(std::time::Duration::from_millis(200)).await;
            let _ = workbench.update_in(cx, |workbench, window, cx| {
                workbench.menubar_update = None;
                workbench.update_menubar(window, cx);
            });
        }));
    }

    /// Sets the application menu when what it shows changed, as `updateMenubar` does on menu changes.
    pub(super) fn update_menubar(&mut self, window: &Window, cx: &mut Context<Self>) {
        // The application menu is the focused window's (menubar.ts `onDidChangeWindowFocus`); a window in the
        // background installs its menu again once it comes to the front.
        if !window.is_window_active() && cx.windows().len() > 1 {
            self.installed_menubar = None;
            return;
        }
        let menubar = self.menubar(window);
        if self.installed_menubar.as_ref() == Some(&menubar) {
            return;
        }
        let (menus, key_equivalents) = native_menus(&menubar, cx);
        cx.clear_key_bindings();
        cx.bind_keys(key_equivalents);
        cx.set_menus(menus);
        // AppKit retitles the app menu's first "Preferences" item to "Settings…" on a later main-queue turn.
        #[cfg(target_os = "macos")]
        cx.spawn(async |_, _| fix_up_app_kit_menus()).detach();
        self.installed_menubar = Some(menubar);
    }

    /// menubar.ts `createOpenRecentMenuItem`: an entry that fails to open leaves the list.
    fn open_recent_menu_entry(&mut self, index: usize, window: &mut Window, cx: &mut Context<Self>) {
        let Some((_, entry)) = self.installed_menubar.as_ref().and_then(|menubar| menubar.recent.get(index)).cloned() else { return };
        if !self.open_window(vec![recent_openable(&entry)], None, false, window, cx) {
            let uri = recently_opened::location(&entry).to_string();
            recently_opened::remove(&mut self.shared_storage.lock().unwrap(), &[&uri]);
            self.recently_opened_changed(window, cx);
        }
    }

    /// `runActionInRenderer` of a menu click: the command gets `{ from: 'menu' }` (window.ts `vscode:runAction`).
    fn run_menu_command(&mut self, id: &str, window: &mut Window, cx: &mut Context<Self>) {
        let outcome = self.execute_command(id, vec![json!({ "from": "menu" })], window, cx);
        super::keyboard::report_failure(outcome, cx);
    }

    /// menubarControl.ts `CustomMenubarControl`, the menu bar titlebarPart.ts puts after the app icon on Windows:
    /// a title per top-level menu, or one `menu` button under `compact`.
    pub(super) fn custom_menubar(&self, foreground: Rgba, window: &Window, cx: &mut Context<Self>) -> Option<Div> {
        // shortcut: `toggle` stays hidden, the bar does not show on Alt; upgrade with the menu bar's keyboard focus.
        let setting = self.setting("window.menuBarVisibility");
        let visibility = menubar_visibility(&setting);
        if matches!(visibility, "hidden" | "toggle") {
            return None;
        }
        let selection = self.color("menubar.selectionBackground");
        let button = |id: SharedString, index: Option<usize>, cx: &mut Context<Self>| {
            let bounds = Rc::new(Cell::new(Bounds::default()));
            div()
                .id(id)
                .h_full()
                .flex()
                .items_center()
                .occlude()
                .child(output_view::bounds_tracker(bounds.clone()))
                .on_mouse_down(MouseButton::Left, cx.listener(move |workbench, _, window, cx| workbench.show_custom_menu(index, bounds.get(), window, cx)))
        };
        let context = self.key_context(window);
        let menubar = div().h_full().flex().text_size(px(13.)).text_color(foreground);
        if visibility == "compact" {
            let menu = button("menubar-compact".into(), None, cx).w(px(35.)).justify_center().hover(|menu| menu.bg(selection)).child(self.icon("menu", 16., 16., foreground));
            return Some(menubar.child(menu));
        }
        let mut titles = Vec::new();
        for (index, action) in menu_actions(&self.menus, MenuId::MenubarMainMenu, &context).into_iter().enumerate() {
            let MenuAction::Submenu { title, .. } = action else { continue };
            let group: SharedString = format!("menubar-{index}").into();
            let label = div().px(px(8.)).rounded(px(5.)).line_height(px(22.)).group_hover(group.clone(), move |label| label.bg(selection)).child(mnemonic_menu_label(&title));
            titles.push(button(group.clone(), Some(index), cx).group(group).child(label));
        }
        Some(menubar.children(titles))
    }

    /// Opens the menu bar's menu `index` below `anchor`, or under `compact` (`None`) a menu of the menus.
    fn show_custom_menu(&mut self, index: Option<usize>, anchor: Bounds<Pixels>, window: &mut Window, cx: &mut Context<Self>) {
        let menubar = self.menubar(window);
        let actions = match index {
            Some(index) => custom_menu_actions(&menubar, &menubar.menus[index].1),
            None => menubar.menus.iter().map(|(title, actions)| MenuAction::Submenu { title: title.clone(), actions: custom_menu_actions(&menubar, actions), checked: false }).collect(),
        };
        let context = self.key_context(window);
        self.show_context_menu_actions(actions, &context, anchor, Vec::new(), window, cx);
    }

    /// The window controls titlebarPart.ts leaves room for on Windows, as Electron's title bar overlay draws them
    /// (titlebarpart.css `.window-icon`): minimize, maximize or restore and close, 46px each. Windows runs them
    /// from their hit test areas.
    pub(super) fn window_controls(&self, foreground: Rgba, window: &Window) -> Div {
        let hover = if self.theme.kind.is_light() { gpui::rgba(0x0000001a) } else { gpui::rgba(0xffffff1a) };
        let control = |id: &'static str, icon: &str, area: WindowControlArea, hover: Rgba| {
            div().id(id).h_full().w(px(46.)).flex().items_center().justify_center().occlude().window_control_area(area).hover(move |control| control.bg(hover)).child(self.icon(icon, 16., 16., foreground))
        };
        let maximize = if window.is_maximized() { "chrome-restore" } else { "chrome-maximize" };
        div()
            .h_full()
            .flex()
            .child(control("window-minimize", "chrome-minimize", WindowControlArea::Min, hover))
            .child(control("window-maximize", maximize, WindowControlArea::Max, hover))
            .child(control("window-close", "chrome-close", WindowControlArea::Close, gpui::rgba(0xe81123e6)))
    }
}

/// window.ts `getMenuBarVisibility` under the custom title bar: `default` and unknown values are `classic`.
pub fn menubar_visibility(setting: &Value) -> &str {
    match setting.as_str() {
        Some(visibility @ ("classic" | "visible" | "toggle" | "hidden" | "compact")) => visibility,
        _ => "classic",
    }
}

/// menubarControl.ts `insertActionsBefore` off macOS: the update item and a separator come before About.
pub fn custom_menu_actions(menubar: &Menubar, actions: &[MenuAction]) -> Vec<MenuAction> {
    let mut items = Vec::new();
    for action in actions {
        if let MenuAction::Command { id, .. } = action
            && id == "workbench.action.showAboutDialog"
            && let Some((title, id, enabled)) = &menubar.update_item
        {
            items.push(MenuAction::Command { id: id.to_string(), title: mnemonic_menu_label(title), enabled: *enabled, checked: false, alt: None });
            items.push(MenuAction::Separator);
        }
        items.push(action.clone());
    }
    items
}

fn collect_command_ids(actions: &[MenuAction], ids: &mut Vec<String>) {
    for action in actions {
        match action {
            MenuAction::Command { id, .. } => ids.push(id.clone()),
            MenuAction::Submenu { actions, .. } => collect_command_ids(actions, ids),
            MenuAction::Separator => {}
        }
    }
}

/// `Menubar.install`: the app menu, the workbench's menus, then the Window menu before Help.
fn native_menus(menubar: &Menubar, cx: &App) -> (Vec<Menu>, Vec<KeyBinding>) {
    let mut key_equivalents = vec![
        KeyBinding::new("cmd-h", Hide, Some(MENU_KEY_EQUIVALENT)),
        KeyBinding::new("alt-cmd-h", HideOthers, Some(MENU_KEY_EQUIVALENT)),
    ];
    let name = crate::product::name_long();
    let mut app_items = vec![native_command("workbench.action.showAboutDialog", &main_label("mAbout", "About {0}").replace("{0}", name), true, false, menubar, &mut key_equivalents, cx)];
    if let Some((title, id, enabled)) = &menubar.update_item {
        app_items.push(native_command(id, title, *enabled, false, menubar, &mut key_equivalents, cx));
    }
    if let Some((_, preferences)) = menubar.menus.iter().find(|(title, _)| title == "Preferences") {
        app_items.push(MenuItem::separator());
        app_items.push(MenuItem::submenu(Menu::new(native_label(&main_label("miPreferences", "&&Preferences"))).items(native_items(preferences, menubar, &mut key_equivalents, cx))));
        app_items.push(MenuItem::separator());
    }
    app_items.extend([
        MenuItem::os_submenu(main_label("mServices", "Services"), SystemMenuType::Services),
        MenuItem::separator(),
        MenuItem::action(main_label("mHide", "Hide {0}").replace("{0}", name), Hide),
        MenuItem::action(main_label("mHideOthers", "Hide Others"), HideOthers),
        MenuItem::action(main_label("mShowAll", "Show All"), ShowAll),
        MenuItem::separator(),
        native_command("workbench.action.quit", &main_label("miQuit", "Quit {0}").replace("{0}", name), true, false, menubar, &mut key_equivalents, cx),
    ]);
    let mut menus = vec![Menu::new(name).items(app_items)];
    // menubar.ts `setMacWindowMenu`: fix_up_app_kit_menus makes it the windows menu and adds the AppKit role items.
    let window_menu = |key_equivalents: &mut Vec<KeyBinding>| {
        Menu::new(main_label("mWindow", "Window")).items([
            native_command("workbench.action.toggleWindowAlwaysOnTop", &main_label("mAlwaysOnTop", "Always on Top"), true, menubar.always_on_top, menubar, key_equivalents, cx),
            MenuItem::separator(),
            native_command("workbench.action.switchWindow", &main_label("miSwitchWindow", "Switch &&Window..."), true, false, menubar, key_equivalents, cx),
        ])
    };
    for (title, actions) in &menubar.menus {
        match title.as_str() {
            "Preferences" => continue,
            "Help" => menus.push(window_menu(&mut key_equivalents)),
            _ => {}
        }
        menus.push(Menu::new(top_level_label(title)).items(native_items(actions, menubar, &mut key_equivalents, cx)));
    }
    if !menubar.menus.iter().any(|(title, _)| title == "Help") {
        menus.push(window_menu(&mut key_equivalents));
    }
    (menus, key_equivalents)
}

fn native_items(actions: &[MenuAction], menubar: &Menubar, key_equivalents: &mut Vec<KeyBinding>, cx: &App) -> Vec<MenuItem> {
    let mut items = Vec::new();
    for action in actions {
        // menubarControl.ts `insertActionsBefore`: the recent entries come before Open Recent's "More...".
        if matches!(action, MenuAction::Command { id, .. } if id == "workbench.action.openRecent") {
            for (index, (label, _)) in menubar.recent.iter().enumerate() {
                if index == menubar.recent_workspaces && index > 0 {
                    items.push(MenuItem::separator());
                }
                items.push(MenuItem::action(label.clone(), OpenRecentMenuEntry { index }));
            }
            if !menubar.recent.is_empty() {
                items.push(MenuItem::separator());
            }
        }
        items.push(match action {
            MenuAction::Command { id, title, enabled, checked, .. } => native_command(id, title, *enabled, *checked, menubar, key_equivalents, cx),
            MenuAction::Submenu { title, actions, .. } => MenuItem::submenu(Menu::new(native_label(title)).items(native_items(actions, menubar, key_equivalents, cx))),
            MenuAction::Separator => MenuItem::separator(),
        });
    }
    items
}

/// menubar.ts `createMenuItem` with `withKeybinding`: a keybinding of one chord is the item's key equivalent; one
/// AppKit cannot show, such as a chord sequence, is appended to the label in brackets.
fn native_command(id: &str, title: &str, enabled: bool, checked: bool, menubar: &Menubar, key_equivalents: &mut Vec<KeyBinding>, cx: &App) -> MenuItem {
    let mut label = native_label(title);
    let chords = menubar.keybindings.get(id);
    let key_equivalent = match chords.map(Vec::as_slice) {
        Some([chord]) => chord.gpui_keystroke(),
        _ => None,
    };
    if let (None, Some(chords)) = (&key_equivalent, chords) {
        let labels: Vec<String> = chords.iter().map(Chord::label).collect();
        label = format!("{label} [{}]", labels.join(" "));
    }
    // menubar.ts gives the clipboard items their roles, so they also reach native text fields.
    let os_action = match id {
        "editor.action.clipboardCutAction" => Some(OsAction::Cut),
        "editor.action.clipboardCopyAction" => Some(OsAction::Copy),
        "editor.action.clipboardPasteAction" => Some(OsAction::Paste),
        _ => None,
    };
    let item = match enabled {
        true => action_item(label, RunMenuCommand { id: id.to_string() }, os_action, key_equivalent, key_equivalents, cx),
        false => action_item(label, DisabledMenuCommand { id: id.to_string() }, os_action, key_equivalent, key_equivalents, cx),
    };
    item.checked(checked)
}

/// strings.ts `truncateMiddle` with its one-character ellipsis.
fn truncate_middle(value: &str, max_length: usize) -> String {
    let chars: Vec<char> = value.chars().collect();
    if chars.len() <= max_length {
        return value.to_string();
    }
    let prefix: String = chars[..max_length.div_ceil(2) - 1].iter().collect();
    let suffix: String = chars[chars.len() - max_length / 2..].iter().collect();
    format!("{prefix}…{suffix}")
}

/// The label Electron's Cocoa menu shows: mnemonics dropped and "..." drawn as "…".
fn native_label(title: &str) -> String {
    mnemonic_menu_label(title).replace("...", "…")
}

/// The label electron-main/menubar.ts gives a top-level menu, by the menu's English title.
fn top_level_label(title: &str) -> String {
    let key = match title {
        "File" => "mFile",
        "Edit" => "mEdit",
        "Selection" => "mSelection",
        "View" => "mView",
        "Go" => "mGoto",
        "Run" => "mRun",
        "Terminal" => "mTerminal",
        "Help" => "mHelp",
        _ => return title.to_string(),
    };
    native_label(&main_label(key, &format!("&&{title}")))
}

/// A label of electron-main/menubar.ts's own `localize` call `key`.
fn main_label(key: &str, english: &str) -> String {
    crate::nls::localize_key(Some(&format!("vs/platform/menubar/electron-main/menubar#{key}")), english).into_owned()
}

fn action_item<A: Action + Clone>(label: String, action: A, os_action: Option<OsAction>, key_equivalent: Option<String>, key_equivalents: &mut Vec<KeyBinding>, cx: &App) -> MenuItem {
    if let Some(keystroke) = key_equivalent {
        let context = KeyBindingContextPredicate::parse(MENU_KEY_EQUIVALENT).unwrap();
        key_equivalents.push(KeyBinding::load(&keystroke, Box::new(action.clone()), Some(context.into()), false, None, cx).unwrap());
    }
    match os_action {
        Some(os_action) => MenuItem::os_action(label, action, os_action),
        None => MenuItem::action(label, action),
    }
}

/// What GPUI's menus cannot express, set on the AppKit menus gpui_macos `create_menu_bar` built.
#[cfg(target_os = "macos")]
fn fix_up_app_kit_menus() {
    // Test threads have no AppKit menus.
    let Some(mtm) = MainThreadMarker::new() else { return };
    let app = NSApplication::sharedApplication(mtm);
    let preferences = app.mainMenu().and_then(|menu| menu.itemAtIndex(0)).and_then(|item| item.submenu()).and_then(|menu| menu.itemAtIndex(0));
    if let Some(item) = preferences
        && item.submenu().is_some()
    {
        item.setTitle(&NSString::from_str(&native_label(&main_label("miPreferences", "&&Preferences"))));
    }
    // Electron's `role: 'window'`; gpui_macos makes only a menu titled "Window" the windows menu.
    let title = NSString::from_str(&main_label("mWindow", "Window"));
    let Some(window_menu) = app.mainMenu().and_then(|menu| menu.itemWithTitle(&title)).and_then(|item| item.submenu()) else { return };
    if app.windowsMenu().as_ref() != Some(&window_menu) {
        app.setWindowsMenu(Some(&window_menu));
        // Set once the menu is in the menu bar, AppKit lists only the windows ordered in after it.
        for window in app.windows() {
            if window.isVisible() && !window.isExcludedFromWindowsMenu() {
                app.addWindowsItem_title_filename(&window, &window.title(), false);
            }
        }
    }
    // menubar.ts `setMacWindowMenu` roles. AppKit adds its Move & Resize and tiling items after `performZoom:`.
    // SAFETY: each `action` is a selector NSWindow or NSApplication answers; `mtm` proves the main thread.
    let item = |title: &str, action, key: &str| unsafe {
        NSMenuItem::initWithTitle_action_keyEquivalent(mtm.alloc(), &NSString::from_str(title), Some(action), &NSString::from_str(key))
    };
    window_menu.insertItem_atIndex(&item(&main_label("mMinimize", "Minimize"), sel!(performMiniaturize:), "m"), 0);
    window_menu.insertItem_atIndex(&item(&main_label("mZoom", "Zoom"), sel!(performZoom:), ""), 1);
    window_menu.addItem(&NSMenuItem::separatorItem(mtm));
    window_menu.addItem(&item(&main_label("mBringToFront", "Bring All to Front"), sel!(arrangeInFront:), ""));
}