Skip to main content

mitsuami_appkit/
services.rs

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