Skip to main content

mitsuami_appkit/
services.rs

1//! Clipboard, dialogs, the trash, launching and the menu bar on macOS.
2
3use mitsuami_core::l10n::{ToArg, tr};
4use std::cell::{Cell, RefCell};
5use std::collections::HashMap;
6use std::path::{Path, PathBuf};
7use std::rc::{Rc, Weak};
8
9use block2::RcBlock;
10use dispatch2::{DispatchQoS, DispatchQueue, GlobalQueueIdentifier};
11use mitsuami_core::services::{
12    Alert, AlertStyle, FileFilter, Launch, MenuBarData, MenuCheck, MenuData, MenuEntry, MenuItemData, MenuRole,
13    OpenFile, Reply, SaveFile, ServiceError, Services, Shortcut, existing_folder, menu_item_by_id,
14};
15use mitsuami_core::{Key, NodeId};
16use objc2::rc::Retained;
17use objc2::runtime::{AnyObject, NSObject, NSObjectProtocol, Sel};
18use objc2::{DefinedClass, MainThreadMarker, MainThreadOnly, Message, define_class, msg_send, sel};
19use objc2_app_kit::{
20    NSAlert, NSAlertFirstButtonReturn, NSAlertStyle, NSApplication, NSControlStateValueOff, NSControlStateValueOn,
21    NSEventModifierFlags, NSMenu, NSMenuItem, NSModalResponse, NSModalResponseCancel, NSModalResponseOK, NSOpenPanel,
22    NSPasteboard, NSPasteboardTypeString, NSRunningApplication, NSSavePanel, NSWindow,
23    NSWindowDidBecomeMainNotification, NSWindowDidResignMainNotification, NSWorkspace, NSWorkspaceOpenConfiguration,
24};
25use objc2_core_foundation::{CFRunLoop, kCFRunLoopCommonModes};
26use objc2_foundation::{
27    NSArray, NSCocoaErrorDomain, NSError, NSFeatureUnsupportedError, NSFileManager, NSNotification,
28    NSNotificationCenter, NSOSStatusErrorDomain, NSString, NSURL, NSUserCancelledError,
29};
30use objc2_uniform_type_identifiers::UTType;
31
32use crate::backend::AppKitHandle;
33
34/// The menus the bar shows: the app's, and the main window's own.
35struct Menus {
36    mtm: MainThreadMarker,
37    backend: AppKitHandle,
38    app: MenuBarData,
39    windows: HashMap<NodeId, MenuBarData>,
40    /// The main window, the one the menus act on.
41    main: Option<NodeId>,
42    activate: Option<Rc<dyn Fn(u32)>>,
43}
44
45impl Menus {
46    fn shown(&self) -> MenuBarData {
47        match self.main.and_then(|main| self.windows.get(&main)) {
48            Some(window) => self.app.merged(window),
49            None => self.app.clone(),
50        }
51    }
52}
53
54pub(crate) struct MenuIvars {
55    menus: Weak<RefCell<Menus>>,
56}
57
58define_class!(
59    /// Target of the app's own menu items (the item's tag is its id), and
60    /// observer of which window is main.
61    #[unsafe(super(NSObject))]
62    #[thread_kind = MainThreadOnly]
63    #[ivars = MenuIvars]
64    struct MenuTarget;
65
66    impl MenuTarget {
67        #[unsafe(method(choose:))]
68        fn choose(&self, sender: &NSMenuItem) {
69            let activate = self.ivars().menus.upgrade().and_then(|menus| menus.borrow().activate.clone());
70            if let Some(activate) = activate {
71                activate(sender.tag() as u32);
72            }
73        }
74
75        #[unsafe(method(windowDidBecomeMain:))]
76        fn window_did_become_main(&self, notification: &NSNotification) {
77            self.main_changed(notification, true);
78        }
79
80        #[unsafe(method(windowDidResignMain:))]
81        fn window_did_resign_main(&self, notification: &NSNotification) {
82            self.main_changed(notification, false);
83        }
84    }
85
86    unsafe impl NSObjectProtocol for MenuTarget {}
87);
88
89impl MenuTarget {
90    fn new(mtm: MainThreadMarker, menus: Weak<RefCell<Menus>>) -> Retained<MenuTarget> {
91        let this = MenuTarget::alloc(mtm).set_ivars(MenuIvars { menus });
92        unsafe { msg_send![super(this), init] }
93    }
94
95    /// A window's menus are in the bar while it's main. AppKit posts
96    /// these while a window closes, which the backend does while it applies
97    /// commands, its state borrowed: look the window up once that's over.
98    fn main_changed(&self, notification: &NSNotification, became: bool) {
99        let Some(window) = notification.object().and_then(|o| o.downcast::<NSWindow>().ok()) else { return };
100        let target = self.retain();
101        later(move || target.main_changed_now(&window, became));
102    }
103
104    fn main_changed_now(&self, window: &NSWindow, became: bool) {
105        let Some(menus) = self.ivars().menus.upgrade() else { return };
106        let node = menus.borrow().backend.window_node(window);
107        let changed = {
108            let mut menus = menus.borrow_mut();
109            let before = menus.main;
110            if became {
111                menus.main = node;
112            } else if node.is_some() && before == node {
113                menus.main = None;
114            }
115            let has_menus = |id: Option<NodeId>| id.is_some_and(|id| menus.windows.contains_key(&id));
116            before != menus.main && (has_menus(before) || has_menus(menus.main))
117        };
118        if changed {
119            self.install(&menus.borrow());
120        }
121    }
122
123    fn install(&self, menus: &Menus) {
124        let bar = menu_bar(menus.mtm, menus.shown(), &menus.backend.app_name(), self);
125        NSApplication::sharedApplication(menus.mtm).setMainMenu(Some(&bar));
126    }
127}
128
129pub struct AppKitServices {
130    mtm: MainThreadMarker,
131    backend: AppKitHandle,
132    pasteboard: Retained<NSPasteboard>,
133    menus: Rc<RefCell<Menus>>,
134    /// Menu items only hold weak references to their target.
135    menu_target: Retained<MenuTarget>,
136    sheets: Rc<RefCell<Sheets>>,
137}
138
139/// Alerts and panels shown as sheets, until they answer: the window each is
140/// on, and the response that cancels it.
141#[derive(Default)]
142struct Sheets {
143    next: u64,
144    open: Vec<Sheet>,
145}
146
147struct Sheet {
148    ticket: u64,
149    window: NodeId,
150    parent: Retained<NSWindow>,
151    sheet: Retained<NSWindow>,
152    cancel: NSModalResponse,
153}
154
155impl Drop for AppKitServices {
156    fn drop(&mut self) {
157        unsafe { NSNotificationCenter::defaultCenter().removeObserver(&self.menu_target) };
158    }
159}
160
161fn ns(s: &str) -> Retained<NSString> {
162    NSString::from_str(s)
163}
164
165/// The panel's start folder: its `directoryURL`, if the folder is there.
166fn start_in(panel: &NSSavePanel, folder: &Option<PathBuf>) {
167    if let Some(folder) = existing_folder(folder) {
168        panel.setDirectoryURL(Some(&NSURL::fileURLWithPath_isDirectory(&ns(&folder.to_string_lossy()), true)));
169    }
170}
171
172fn path(url: &NSURL) -> Option<PathBuf> {
173    url.path().map(|p| PathBuf::from(p.to_string()))
174}
175
176/// The types a panel allows: every filter's at once, since AppKit's panels
177/// have no filter menu. Every file when a filter lets every file through,
178/// so a file the types miss can still be chosen, as on the platforms where
179/// the user picks that filter.
180fn content_types(filters: &[FileFilter]) -> Option<Retained<NSArray<UTType>>> {
181    if filters.iter().any(FileFilter::is_all) {
182        return None;
183    }
184    let types: Vec<Retained<UTType>> = filters
185        .iter()
186        .flat_map(|f| &f.extensions)
187        .filter_map(|ext| UTType::typeWithFilenameExtension(&ns(ext.trim_start_matches('.'))))
188        .collect();
189    (!types.is_empty()).then(|| NSArray::from_retained_slice(&types))
190}
191
192/// Moves an item to its disk's trash, where Finder's Put Back finds it.
193fn trash_item(path: &Path) -> Result<(), ServiceError> {
194    let url = NSURL::fileURLWithPath(&ns(&path.to_string_lossy()));
195    NSFileManager::defaultManager().trashItemAtURL_resultingItemURL_error(&url, None).map_err(|error| {
196        if error.code() == NSFeatureUnsupportedError && error.domain().isEqualToString(unsafe { NSCocoaErrorDomain }) {
197            ServiceError::Unavailable
198        } else {
199            ServiceError::Failed(error.localizedDescription().to_string())
200        }
201    })
202}
203
204thread_local! {
205    /// Replies waiting for work done on another thread (`NSWorkspace`'s
206    /// completion handlers, the trash), by ticket.
207    static WAITING: RefCell<HashMap<u64, Reply<Result<(), ServiceError>>>> = RefCell::new(HashMap::new());
208    static NEXT_TICKET: Cell<u64> = const { Cell::new(0) };
209}
210
211/// Keeps a reply, which stays on the main thread, until [`answer`].
212fn wait(reply: Reply<Result<(), ServiceError>>) -> u64 {
213    let ticket = NEXT_TICKET.replace(NEXT_TICKET.get() + 1);
214    WAITING.with(|w| w.borrow_mut().insert(ticket, reply));
215    ticket
216}
217
218/// Answers a kept reply from any thread, on the main one.
219fn answer(ticket: u64, result: Result<(), ServiceError>) {
220    DispatchQueue::main().exec_async(move || {
221        if let Some(reply) = WAITING.with(|w| w.borrow_mut().remove(&ticket)) {
222            reply(result);
223        }
224    });
225}
226
227/// Launch Services' "no application" and "the user cancelled".
228const APPLICATION_NOT_FOUND: isize = -10814;
229const USER_CANCELED: isize = -128;
230
231fn launch_error(error: &NSError) -> ServiceError {
232    let (domain, code) = (error.domain(), error.code());
233    let cocoa = domain.isEqualToString(unsafe { NSCocoaErrorDomain });
234    let status = domain.isEqualToString(unsafe { NSOSStatusErrorDomain });
235    match code {
236        APPLICATION_NOT_FOUND if status => ServiceError::Unavailable,
237        USER_CANCELED if status => ServiceError::Cancelled,
238        code if cocoa && code == NSUserCancelledError => ServiceError::Cancelled,
239        _ => ServiceError::Failed(error.localizedDescription().to_string()),
240    }
241}
242
243/// Runs `f` on the main run loop soon, outside whatever is calling us now.
244fn later(f: impl Fn() + 'static) {
245    let block = RcBlock::new(f);
246    if let Some(run_loop) = CFRunLoop::main() {
247        unsafe { run_loop.perform_block(kCFRunLoopCommonModes.map(|m| &**m), Some(&block)) };
248        run_loop.wake_up();
249    }
250}
251
252/// Wraps a one-shot reply for AppKit's (reusable) completion blocks.
253fn once<T>(reply: Reply<T>) -> impl Fn(T) {
254    let reply = Cell::new(Some(reply));
255    move |value| {
256        if let Some(reply) = reply.take() {
257            reply(value);
258        }
259    }
260}
261
262impl AppKitServices {
263    pub(crate) fn new(mtm: MainThreadMarker, backend: AppKitHandle, private_clipboard: bool) -> AppKitServices {
264        let pasteboard = if private_clipboard {
265            NSPasteboard::pasteboardWithUniqueName()
266        } else {
267            NSPasteboard::generalPasteboard()
268        };
269        let menus = Rc::new(RefCell::new(Menus {
270            mtm,
271            backend: backend.clone(),
272            app: MenuBarData::default(),
273            windows: HashMap::new(),
274            main: None,
275            activate: None,
276        }));
277        let menu_target = MenuTarget::new(mtm, Rc::downgrade(&menus));
278        let center = NSNotificationCenter::defaultCenter();
279        // SAFETY: the target is removed as an observer when the services go.
280        unsafe {
281            center.addObserver_selector_name_object(
282                &menu_target,
283                sel!(windowDidBecomeMain:),
284                Some(NSWindowDidBecomeMainNotification),
285                None,
286            );
287            center.addObserver_selector_name_object(
288                &menu_target,
289                sel!(windowDidResignMain:),
290                Some(NSWindowDidResignMainNotification),
291                None,
292            );
293        }
294        AppKitServices { mtm, backend, pasteboard, menus, menu_target, sheets: Rc::default() }
295    }
296
297    /// Remembers a sheet on `parent` until it answers, so it ends with its
298    /// window; returns what forgets it.
299    fn track_sheet(&self, parent: &NSWindow, sheet: &NSWindow, cancel: NSModalResponse) -> impl Fn() + 'static {
300        let ticket = self.backend.window_node(parent).map(|window| {
301            let mut sheets = self.sheets.borrow_mut();
302            sheets.next += 1;
303            let ticket = sheets.next;
304            sheets.open.push(Sheet { ticket, window, parent: parent.retain(), sheet: sheet.retain(), cancel });
305            ticket
306        });
307        let sheets = Rc::downgrade(&self.sheets);
308        move || {
309            if let (Some(ticket), Some(sheets)) = (ticket, sheets.upgrade()) {
310                sheets.borrow_mut().open.retain(|s| s.ticket != ticket);
311            }
312        }
313    }
314
315    /// The window a dialog belongs to: the requested one, or the active one.
316    fn parent(&self, parent: Option<NodeId>) -> Option<Retained<NSWindow>> {
317        let app = NSApplication::sharedApplication(self.mtm);
318        parent.and_then(|id| self.backend.ns_window(id)).or_else(|| app.keyWindow()).or_else(|| app.mainWindow())
319    }
320}
321
322impl Services for AppKitServices {
323    fn clipboard_text(&mut self, reply: Reply<Option<String>>) {
324        // NSPasteboard reads synchronously: answer right away.
325        reply(self.pasteboard.stringForType(unsafe { NSPasteboardTypeString }).map(|s| s.to_string()));
326    }
327
328    fn set_clipboard_text(&mut self, text: &str, reply: Reply<Result<(), ServiceError>>) {
329        self.pasteboard.clearContents();
330        let written = self.pasteboard.setString_forType(&ns(text), unsafe { NSPasteboardTypeString });
331        reply(if written { Ok(()) } else { Err(ServiceError::Failed("the pasteboard refused the text".into())) });
332    }
333
334    fn alert(&mut self, parent: Option<NodeId>, alert: &Alert, reply: Reply<usize>) {
335        let ns_alert = NSAlert::new(self.mtm);
336        ns_alert.setMessageText(&ns(&alert.title));
337        if let Some(message) = &alert.message {
338            ns_alert.setInformativeText(&ns(message));
339        }
340        ns_alert.setAlertStyle(match alert.style {
341            AlertStyle::Info => NSAlertStyle::Informational,
342            AlertStyle::Warning => NSAlertStyle::Warning,
343            AlertStyle::Critical => NSAlertStyle::Critical,
344        });
345        let buttons = alert.effective_buttons();
346        for button in &buttons {
347            ns_alert.addButtonWithTitle(&ns(button));
348        }
349        let reply = once(reply);
350        let answer = move |response: NSModalResponse| reply((response - NSAlertFirstButtonReturn).max(0) as usize);
351        match self.parent(parent) {
352            // A sheet on the window it belongs to.
353            Some(window) => {
354                // The last button is the cancel one, as Escape chooses.
355                let cancel = NSAlertFirstButtonReturn + buttons.len() as NSModalResponse - 1;
356                let forget = self.track_sheet(&window, &ns_alert.window(), cancel);
357                let done = RcBlock::new(move |response| {
358                    forget();
359                    answer(response)
360                });
361                ns_alert.beginSheetModalForWindow_completionHandler(&window, Some(&done));
362            }
363            // No window: an app-modal alert, run once the caller has returned.
364            None => later(move || answer(ns_alert.runModal())),
365        }
366    }
367
368    fn open_file(&mut self, parent: Option<NodeId>, request: &OpenFile, reply: Reply<Option<Vec<PathBuf>>>) {
369        let panel = NSOpenPanel::openPanel(self.mtm);
370        panel.setCanChooseFiles(!request.directories);
371        panel.setCanChooseDirectories(request.directories);
372        // A folder can be made where one is chosen, as GTK's, Qt's and
373        // Windows' folder dialogs offer and Mac apps' folder panels do;
374        // AppKit's open panel leaves New Folder off (§14.9).
375        panel.setCanCreateDirectories(request.directories);
376        panel.setAllowsMultipleSelection(request.multiple);
377        if let Some(title) = &request.title {
378            panel.setMessage(Some(&ns(title)));
379        }
380        if let Some(types) = content_types(&request.filters) {
381            panel.setAllowedContentTypes(&types);
382        }
383        start_in(&panel, &request.start_folder);
384        let reply = once(reply);
385        let chosen = panel.clone();
386        let answer = move |response: NSModalResponse| {
387            reply((response == NSModalResponseOK).then(|| chosen.URLs().iter().filter_map(|u| path(&u)).collect()));
388        };
389        match self.parent(parent) {
390            Some(window) => {
391                let forget = self.track_sheet(&window, &panel, NSModalResponseCancel);
392                let done = RcBlock::new(move |response| {
393                    forget();
394                    answer(response)
395                });
396                panel.beginSheetModalForWindow_completionHandler(&window, &done)
397            }
398            None => panel.beginWithCompletionHandler(&RcBlock::new(answer)),
399        }
400    }
401
402    fn save_file(&mut self, parent: Option<NodeId>, request: &SaveFile, reply: Reply<Option<PathBuf>>) {
403        let panel = NSSavePanel::savePanel(self.mtm);
404        if let Some(title) = &request.title {
405            panel.setMessage(Some(&ns(title)));
406        }
407        if let Some(name) = &request.default_name {
408            panel.setNameFieldStringValue(&ns(name));
409        }
410        if let Some(types) = content_types(&request.filters) {
411            panel.setAllowedContentTypes(&types);
412        }
413        start_in(&panel, &request.start_folder);
414        let reply = once(reply);
415        let chosen = panel.clone();
416        let answer = move |response: NSModalResponse| {
417            reply(if response == NSModalResponseOK { chosen.URL().and_then(|u| path(&u)) } else { None });
418        };
419        match self.parent(parent) {
420            Some(window) => {
421                let forget = self.track_sheet(&window, &panel, NSModalResponseCancel);
422                let done = RcBlock::new(move |response| {
423                    forget();
424                    answer(response)
425                });
426                panel.beginSheetModalForWindow_completionHandler(&window, &done)
427            }
428            None => panel.beginWithCompletionHandler(&RcBlock::new(answer)),
429        }
430    }
431
432    /// `NSFileManager` trashes synchronously, so on a queue of its own, as
433    /// Finder does: within a disk it's a move, but each item on a network
434    /// disk is a round trip to the server, which would stall the window.
435    fn trash(&mut self, _parent: Option<NodeId>, paths: &[PathBuf], reply: Reply<Result<(), ServiceError>>) {
436        let (ticket, paths) = (wait(reply), paths.to_vec());
437        let queue = GlobalQueueIdentifier::QualityOfService(DispatchQoS::UserInitiated);
438        // The shared file manager is safe to use from any thread.
439        DispatchQueue::global_queue(queue)
440            .exec_async(move || answer(ticket, paths.iter().try_for_each(|path| trash_item(path))));
441    }
442
443    /// `NSWorkspace` opens it as Finder would, asking which app (or
444    /// saying there's none) itself when no app is set.
445    fn launch(&mut self, _parent: Option<NodeId>, target: &Launch, reply: Reply<Result<(), ServiceError>>) {
446        let url = match target {
447            Launch::Path(path) => NSURL::fileURLWithPath(&ns(&path.to_string_lossy())),
448            Launch::Url(url) => match NSURL::URLWithString(&ns(url)) {
449                Some(url) => url,
450                None => return reply(Err(ServiceError::Failed(format!("\u{201C}{url}\u{201D} isn't a URL")))),
451            },
452        };
453        let ticket = wait(reply);
454        let done = RcBlock::new(move |_app: *mut NSRunningApplication, error: *mut NSError| {
455            // SAFETY: AppKit passes a valid error or null.
456            answer(ticket, unsafe { error.as_ref() }.map_or(Ok(()), |error| Err(launch_error(error))));
457        });
458        let configuration = NSWorkspaceOpenConfiguration::configuration();
459        NSWorkspace::sharedWorkspace().openURL_configuration_completionHandler(&url, &configuration, Some(&done));
460    }
461
462    /// Each sheet on the window ends with its cancel response, as Escape
463    /// would end it, while the window is still there to end it on.
464    fn window_destroyed(&mut self, window: NodeId) {
465        let gone: Vec<(Retained<NSWindow>, Retained<NSWindow>, NSModalResponse)> = {
466            let sheets = self.sheets.borrow();
467            let on = sheets.open.iter().filter(|s| s.window == window);
468            on.map(|s| (s.parent.clone(), s.sheet.clone(), s.cancel)).collect()
469        };
470        for (parent, sheet, cancel) in gone {
471            parent.endSheet_returnCode(&sheet, cancel);
472        }
473    }
474
475    fn set_menu(&mut self, window: Option<NodeId>, menu: &MenuBarData, activate: Rc<dyn Fn(u32)>) {
476        {
477            let mut menus = self.menus.borrow_mut();
478            menus.activate = Some(activate);
479            match window {
480                None => menus.app = menu.clone(),
481                Some(window) if menu.menus.is_empty() => _ = menus.windows.remove(&window),
482                Some(window) => _ = menus.windows.insert(window, menu.clone()),
483            }
484            if menus.main.is_none() {
485                let main = NSApplication::sharedApplication(self.mtm).mainWindow();
486                menus.main = main.and_then(|w| self.backend.window_node(&w));
487            }
488            // Another window's menus aren't in the bar.
489            if window.is_some() && window != menus.main {
490                return;
491            }
492        }
493        self.menu_target.install(&self.menus.borrow());
494    }
495}
496
497fn item(mtm: MainThreadMarker, title: &str, action: Option<Sel>, key: &str) -> Retained<NSMenuItem> {
498    unsafe { NSMenuItem::initWithTitle_action_keyEquivalent(NSMenuItem::alloc(mtm), &ns(title), action, &ns(key)) }
499}
500
501/// `auto_enable`: let AppKit enable items by responder chain (standard
502/// menus); otherwise the app's `enabled` state decides.
503fn menu_of(
504    mtm: MainThreadMarker,
505    title: &str,
506    items: Vec<Retained<NSMenuItem>>,
507    auto_enable: bool,
508) -> Retained<NSMenuItem> {
509    let menu = NSMenu::initWithTitle(NSMenu::alloc(mtm), &ns(title));
510    menu.setAutoenablesItems(auto_enable);
511    for item in items {
512        menu.addItem(&item);
513    }
514    let holder = item(mtm, title, None, "");
515    holder.setSubmenu(Some(&menu));
516    holder
517}
518
519/// The character AppKit names a key by, in key equivalents and key
520/// events: the key's own for those that type one, a function key's
521/// (`NSUpArrowFunctionKey`) for the others.
522pub(crate) fn key_character(key: Key) -> char {
523    match key {
524        Key::Char(c) => c,
525        Key::Enter => '\r',
526        Key::Escape => '\u{1b}',
527        Key::Tab => '\t',
528        // `NSBackspaceCharacter`, as Finder's Move to Trash has it.
529        Key::Backspace => '\u{8}',
530        Key::Delete => '\u{f728}',
531        Key::Up => '\u{f700}',
532        Key::Down => '\u{f701}',
533        Key::Left => '\u{f702}',
534        Key::Right => '\u{f703}',
535        Key::Home => '\u{f729}',
536        Key::End => '\u{f72b}',
537        Key::PageUp => '\u{f72c}',
538        Key::PageDown => '\u{f72d}',
539        Key::F(n) => char::from_u32(0xf703 + u32::from(n)).unwrap_or('\u{f704}'),
540    }
541}
542
543/// The character a key event of this key carries, as the keyboard sends
544/// it: the Delete (⌫) key's is `NSDeleteCharacter`.
545pub(crate) fn event_character(key: Key) -> char {
546    match key {
547        Key::Backspace => '\u{7f}',
548        key => key_character(key),
549    }
550}
551
552/// The key AppKit names by this character (see [`key_character`]).
553/// `NSDeleteCharacter` is the Delete (⌫) key's own.
554pub(crate) fn key_of(c: char) -> Key {
555    match c {
556        '\r' | '\u{3}' => Key::Enter,
557        '\u{1b}' => Key::Escape,
558        '\t' => Key::Tab,
559        '\u{8}' | '\u{7f}' => Key::Backspace,
560        '\u{f728}' => Key::Delete,
561        '\u{f700}' => Key::Up,
562        '\u{f701}' => Key::Down,
563        '\u{f702}' => Key::Left,
564        '\u{f703}' => Key::Right,
565        '\u{f729}' => Key::Home,
566        '\u{f72b}' => Key::End,
567        '\u{f72c}' => Key::PageUp,
568        '\u{f72d}' => Key::PageDown,
569        '\u{f704}'..='\u{f726}' => Key::F((c as u32 - 0xf703) as u8),
570        c => Key::Char(c),
571    }
572}
573
574pub(crate) fn modifiers(shortcut: &Shortcut) -> NSEventModifierFlags {
575    let mut mask = NSEventModifierFlags::empty();
576    if shortcut.primary {
577        mask |= NSEventModifierFlags::Command;
578    }
579    if shortcut.shift {
580        mask |= NSEventModifierFlags::Shift;
581    }
582    if shortcut.alt {
583        mask |= NSEventModifierFlags::Option;
584    }
585    mask
586}
587
588/// Where menu items send their action: the item's tag is its id.
589#[derive(Clone, Copy)]
590pub(crate) struct ItemTarget<'a> {
591    pub(crate) object: &'a AnyObject,
592    pub(crate) action: Sel,
593}
594
595impl<'a> From<&'a MenuTarget> for ItemTarget<'a> {
596    fn from(target: &'a MenuTarget) -> ItemTarget<'a> {
597        ItemTarget { object: target as &AnyObject, action: sel!(choose:) }
598    }
599}
600
601/// One of the app's items. The check mark is AppKit's for radio items
602/// too: its menus show a group's choice with one.
603fn app_item(
604    mtm: MainThreadMarker,
605    data: &MenuItemData,
606    title: &str,
607    shortcut: Option<Shortcut>,
608    target: ItemTarget,
609) -> Retained<NSMenuItem> {
610    let key = shortcut.map(|s| key_character(s.key).to_string()).unwrap_or_default();
611    let item = item(mtm, title, Some(target.action), &key);
612    unsafe { item.setTarget(Some(target.object)) };
613    item.setTag(data.id as isize);
614    item.setEnabled(data.enabled);
615    if let Some(shortcut) = shortcut {
616        item.setKeyEquivalentModifierMask(modifiers(&shortcut));
617    }
618    if let MenuCheck::Check(on) | MenuCheck::Radio(on) = data.check {
619        item.setState(if on { NSControlStateValueOn } else { NSControlStateValueOff });
620    }
621    item
622}
623
624pub(crate) fn app_items(mtm: MainThreadMarker, entries: &[MenuEntry], target: ItemTarget) -> Vec<Retained<NSMenuItem>> {
625    entries
626        .iter()
627        .map(|entry| match entry {
628            MenuEntry::Separator => NSMenuItem::separatorItem(mtm),
629            MenuEntry::Item(data) => app_item(mtm, data, &data.title, data.shortcut, target),
630            MenuEntry::Submenu(menu) => menu_of(mtm, &menu.title, app_items(mtm, &menu.entries, target), false),
631        })
632        .collect()
633}
634
635/// A context menu: the app's entries, enabled as the app says.
636pub(crate) fn context_menu(mtm: MainThreadMarker, entries: &[MenuEntry], target: ItemTarget) -> Retained<NSMenu> {
637    let menu = NSMenu::new(mtm);
638    menu.setAutoenablesItems(false);
639    for item in app_items(mtm, entries, target) {
640        menu.addItem(&item);
641    }
642    menu
643}
644
645/// What a context menu shows, read back from AppKit. It can't tell a
646/// radio item from a check item, nor keep a role: those come from `sent`.
647pub(crate) fn context_menu_entries(menu: &NSMenu, sent: &[MenuEntry]) -> Vec<MenuEntry> {
648    fn read(menu: &NSMenu, sent: &[MenuEntry]) -> Vec<MenuEntry> {
649        menu.itemArray()
650            .iter()
651            .map(|item| {
652                if item.isSeparatorItem() {
653                    return MenuEntry::Separator;
654                }
655                if let Some(submenu) = item.submenu() {
656                    return MenuEntry::Submenu(MenuData {
657                        title: item.title().to_string(),
658                        entries: read(&submenu, sent),
659                    });
660                }
661                let id = item.tag() as u32;
662                let original = menu_item_by_id(sent, id);
663                let on = item.state() == NSControlStateValueOn;
664                let key = item.keyEquivalent().to_string();
665                let mask = item.keyEquivalentModifierMask();
666                MenuEntry::Item(MenuItemData {
667                    id,
668                    title: item.title().to_string(),
669                    shortcut: key.chars().next().map(|key| Shortcut {
670                        key: key_of(key),
671                        primary: mask.contains(NSEventModifierFlags::Command),
672                        shift: mask.contains(NSEventModifierFlags::Shift),
673                        alt: mask.contains(NSEventModifierFlags::Option),
674                    }),
675                    enabled: item.isEnabled(),
676                    check: match original.map(|s| s.check) {
677                        Some(MenuCheck::Radio(_)) => MenuCheck::Radio(on),
678                        Some(MenuCheck::Check(_)) => MenuCheck::Check(on),
679                        _ if on => MenuCheck::Check(true),
680                        _ => MenuCheck::None,
681                    },
682                    role: original.map(|s| s.role).unwrap_or_default(),
683                })
684            })
685            .collect()
686    }
687    read(menu, sent)
688}
689
690/// The item of a context menu with this id, submenus' included, and the
691/// menu holding it.
692pub(crate) fn find_tagged(menu: &NSMenu, id: u32) -> Option<(Retained<NSMenuItem>, Retained<NSMenu>)> {
693    menu.itemArray().iter().find_map(|item| match item.submenu() {
694        Some(submenu) => find_tagged(&submenu, id),
695        None if !item.isSeparatorItem() && item.tag() as u32 == id => Some((item, menu.retain())),
696        None => None,
697    })
698}
699
700/// The app menu, the app's File menu (if any), Edit (what makes ⌘C/⌘V/⌘Z
701/// work in text fields), then the app's other menus. Items with a role go
702/// to the app menu, with AppKit's titles and shortcuts, as Qt puts them.
703/// Titles of our own are in the app's language (`mitsuami.ftl`), and so
704/// is the File menu's, which the app's File menu is known by.
705fn menu_bar(mtm: MainThreadMarker, mut menus: MenuBarData, name: &str, target: &MenuTarget) -> Retained<NSMenu> {
706    let target = ItemTarget::from(target);
707    let bar = NSMenu::new(mtm);
708    let command = |key| Some(Shortcut::primary(key));
709    let app = |id: &str| tr(id, &[("app", name.to_arg())]);
710    let mut app_menu = Vec::new();
711    if let Some(about) = menus.take_role(MenuRole::About) {
712        app_menu.push(app_item(mtm, &about, &app("mitsuami-menu-about"), None, target));
713        app_menu.push(NSMenuItem::separatorItem(mtm));
714    }
715    if let Some(settings) = menus.take_role(MenuRole::Settings) {
716        app_menu.push(app_item(mtm, &settings, &tr("mitsuami-menu-settings", &[]), command(','), target));
717        app_menu.push(NSMenuItem::separatorItem(mtm));
718    }
719    app_menu.push(item(mtm, &app("mitsuami-menu-hide"), Some(sel!(hide:)), "h"));
720    app_menu.push(NSMenuItem::separatorItem(mtm));
721    let quit = app("mitsuami-menu-quit-app");
722    app_menu.push(match menus.take_role(MenuRole::Quit) {
723        Some(item) => app_item(mtm, &item, &quit, command('q'), target),
724        None => item(mtm, &quit, Some(sel!(terminate:)), "q"),
725    });
726    bar.addItem(&menu_of(mtm, name, app_menu, true));
727    let file_title = tr("mitsuami-menu-file", &[]);
728    let (file, others): (Vec<_>, Vec<_>) = menus.menus.iter().partition(|m| m.title == file_title);
729    for menu in file {
730        bar.addItem(&menu_of(mtm, &menu.title, app_items(mtm, &menu.entries, target), false));
731    }
732    bar.addItem(&menu_of(
733        mtm,
734        &tr("mitsuami-menu-edit", &[]),
735        vec![
736            item(mtm, &tr("mitsuami-menu-undo", &[]), Some(sel!(undo:)), "z"),
737            item(mtm, &tr("mitsuami-menu-redo", &[]), Some(sel!(redo:)), "Z"),
738            NSMenuItem::separatorItem(mtm),
739            item(mtm, &tr("mitsuami-menu-cut", &[]), Some(sel!(cut:)), "x"),
740            item(mtm, &tr("mitsuami-menu-copy", &[]), Some(sel!(copy:)), "c"),
741            item(mtm, &tr("mitsuami-menu-paste", &[]), Some(sel!(paste:)), "v"),
742            item(mtm, &tr("mitsuami-menu-select-all", &[]), Some(sel!(selectAll:)), "a"),
743        ],
744        true,
745    ));
746    for menu in others {
747        bar.addItem(&menu_of(mtm, &menu.title, app_items(mtm, &menu.entries, target), false));
748    }
749    bar
750}