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::{ClassType, 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/// AppKit gives a sandboxed process no open or save panel without the
244/// user-selected files entitlement (a child that inherits its parent's
245/// sandbox never has it), and objc2-app-kit's bindings panic on that nil:
246/// the request is answered as a cancel instead, and the reason said here,
247/// since the user sees nothing happen.
248fn no_panel(kind: &str) {
249    eprintln!(
250        "mitsuami: AppKit gave no {kind} panel; in the App Sandbox, the app needs the \
251         com.apple.security.files.user-selected.read-only or .read-write entitlement"
252    );
253}
254
255/// Runs `f` on the main run loop soon, outside whatever is calling us now.
256fn later(f: impl Fn() + 'static) {
257    let block = RcBlock::new(f);
258    if let Some(run_loop) = CFRunLoop::main() {
259        unsafe { run_loop.perform_block(kCFRunLoopCommonModes.map(|m| &**m), Some(&block)) };
260        run_loop.wake_up();
261    }
262}
263
264/// Wraps a one-shot reply for AppKit's (reusable) completion blocks.
265fn once<T>(reply: Reply<T>) -> impl Fn(T) {
266    let reply = Cell::new(Some(reply));
267    move |value| {
268        if let Some(reply) = reply.take() {
269            reply(value);
270        }
271    }
272}
273
274impl AppKitServices {
275    pub(crate) fn new(mtm: MainThreadMarker, backend: AppKitHandle, private_clipboard: bool) -> AppKitServices {
276        let pasteboard = if private_clipboard {
277            NSPasteboard::pasteboardWithUniqueName()
278        } else {
279            NSPasteboard::generalPasteboard()
280        };
281        let menus = Rc::new(RefCell::new(Menus {
282            mtm,
283            backend: backend.clone(),
284            app: MenuBarData::default(),
285            windows: HashMap::new(),
286            main: None,
287            activate: None,
288        }));
289        let menu_target = MenuTarget::new(mtm, Rc::downgrade(&menus));
290        let center = NSNotificationCenter::defaultCenter();
291        // SAFETY: the target is removed as an observer when the services go.
292        unsafe {
293            center.addObserver_selector_name_object(
294                &menu_target,
295                sel!(windowDidBecomeMain:),
296                Some(NSWindowDidBecomeMainNotification),
297                None,
298            );
299            center.addObserver_selector_name_object(
300                &menu_target,
301                sel!(windowDidResignMain:),
302                Some(NSWindowDidResignMainNotification),
303                None,
304            );
305        }
306        AppKitServices { mtm, backend, pasteboard, menus, menu_target, sheets: Rc::default() }
307    }
308
309    /// What a dialog needs once it goes up, which may be after this call
310    /// (`AppKitHandle::when_shown`).
311    fn dialogs(&self) -> Dialogs {
312        Dialogs { mtm: self.mtm, backend: self.backend.clone(), sheets: self.sheets.clone() }
313    }
314}
315
316/// Puts dialogs up: on the window they belong to, as sheets.
317#[derive(Clone)]
318struct Dialogs {
319    mtm: MainThreadMarker,
320    backend: AppKitHandle,
321    sheets: Rc<RefCell<Sheets>>,
322}
323
324impl Dialogs {
325    /// Remembers a sheet on `parent` until it answers, so it ends with its
326    /// window; returns what forgets it.
327    fn track_sheet(&self, parent: &NSWindow, sheet: &NSWindow, cancel: NSModalResponse) -> impl Fn() + 'static {
328        let ticket = self.backend.window_node(parent).map(|window| {
329            let mut sheets = self.sheets.borrow_mut();
330            sheets.next += 1;
331            let ticket = sheets.next;
332            sheets.open.push(Sheet { ticket, window, parent: parent.retain(), sheet: sheet.retain(), cancel });
333            ticket
334        });
335        let sheets = Rc::downgrade(&self.sheets);
336        move || {
337            if let (Some(ticket), Some(sheets)) = (ticket, sheets.upgrade()) {
338                sheets.borrow_mut().open.retain(|s| s.ticket != ticket);
339            }
340        }
341    }
342
343    /// The window a dialog belongs to: the requested one, or the active one.
344    fn parent(&self, parent: Option<NodeId>) -> Option<Retained<NSWindow>> {
345        let app = NSApplication::sharedApplication(self.mtm);
346        parent.and_then(|id| self.backend.ns_window(id)).or_else(|| app.keyWindow()).or_else(|| app.mainWindow())
347    }
348
349    /// Runs `show` with the window the dialog belongs to, once that window
350    /// is on screen.
351    fn present(self, parent: Option<NodeId>, show: impl FnOnce(&Dialogs, Option<Retained<NSWindow>>) + 'static) {
352        let backend = self.backend.clone();
353        backend.when_shown(parent, move || show(&self, self.parent(parent)));
354    }
355}
356
357impl Services for AppKitServices {
358    fn clipboard_text(&mut self, reply: Reply<Option<String>>) {
359        // NSPasteboard reads synchronously: answer right away.
360        reply(self.pasteboard.stringForType(unsafe { NSPasteboardTypeString }).map(|s| s.to_string()));
361    }
362
363    fn set_clipboard_text(&mut self, text: &str, reply: Reply<Result<(), ServiceError>>) {
364        self.pasteboard.clearContents();
365        let written = self.pasteboard.setString_forType(&ns(text), unsafe { NSPasteboardTypeString });
366        reply(if written { Ok(()) } else { Err(ServiceError::Failed("the pasteboard refused the text".into())) });
367    }
368
369    fn alert(&mut self, parent: Option<NodeId>, alert: &Alert, reply: Reply<usize>) {
370        let ns_alert = NSAlert::new(self.mtm);
371        ns_alert.setMessageText(&ns(&alert.title));
372        if let Some(message) = &alert.message {
373            ns_alert.setInformativeText(&ns(message));
374        }
375        ns_alert.setAlertStyle(match alert.style {
376            AlertStyle::Info => NSAlertStyle::Informational,
377            AlertStyle::Warning => NSAlertStyle::Warning,
378            AlertStyle::Critical => NSAlertStyle::Critical,
379        });
380        let buttons = alert.effective_buttons();
381        for (i, button) in buttons.iter().enumerate() {
382            let button = ns_alert.addButtonWithTitle(&ns(button));
383            // An alert draws it red; a window's button doesn't.
384            button.setHasDestructiveAction(alert.destructive == Some(i));
385        }
386        let reply = once(reply);
387        let answer = move |response: NSModalResponse| reply((response - NSAlertFirstButtonReturn).max(0) as usize);
388        self.dialogs().present(parent, move |dialogs, window| match window {
389            // A sheet on the window it belongs to.
390            Some(window) => {
391                // The last button is the cancel one, as Escape chooses.
392                let cancel = NSAlertFirstButtonReturn + buttons.len() as NSModalResponse - 1;
393                let forget = dialogs.track_sheet(&window, &ns_alert.window(), cancel);
394                let done = RcBlock::new(move |response| {
395                    forget();
396                    answer(response)
397                });
398                ns_alert.beginSheetModalForWindow_completionHandler(&window, Some(&done));
399            }
400            // No window: an app-modal alert, run once the caller has returned.
401            None => later(move || answer(ns_alert.runModal())),
402        });
403    }
404
405    fn open_file(&mut self, parent: Option<NodeId>, request: &OpenFile, reply: Reply<Option<Vec<PathBuf>>>) {
406        let panel: Option<Retained<NSOpenPanel>> = unsafe { msg_send![NSOpenPanel::class(), openPanel] };
407        let Some(panel) = panel else {
408            no_panel("open");
409            return reply(None);
410        };
411        panel.setCanChooseFiles(!request.directories);
412        panel.setCanChooseDirectories(request.directories);
413        // A folder can be made where one is chosen, as GTK's, Qt's and
414        // Windows' folder dialogs offer and Mac apps' folder panels do;
415        // AppKit's open panel leaves New Folder off (§14.9).
416        panel.setCanCreateDirectories(request.directories);
417        panel.setAllowsMultipleSelection(request.multiple);
418        if let Some(title) = &request.title {
419            panel.setMessage(Some(&ns(title)));
420        }
421        if let Some(types) = content_types(&request.filters) {
422            panel.setAllowedContentTypes(&types);
423        }
424        start_in(&panel, &request.start_folder);
425        let reply = once(reply);
426        let chosen = panel.clone();
427        let answer = move |response: NSModalResponse| {
428            reply((response == NSModalResponseOK).then(|| chosen.URLs().iter().filter_map(|u| path(&u)).collect()));
429        };
430        self.dialogs().present(parent, move |dialogs, window| match window {
431            Some(window) => {
432                let forget = dialogs.track_sheet(&window, &panel, NSModalResponseCancel);
433                let done = RcBlock::new(move |response| {
434                    forget();
435                    answer(response)
436                });
437                panel.beginSheetModalForWindow_completionHandler(&window, &done)
438            }
439            None => panel.beginWithCompletionHandler(&RcBlock::new(answer)),
440        });
441    }
442
443    fn save_file(&mut self, parent: Option<NodeId>, request: &SaveFile, reply: Reply<Option<PathBuf>>) {
444        let panel: Option<Retained<NSSavePanel>> = unsafe { msg_send![NSSavePanel::class(), savePanel] };
445        let Some(panel) = panel else {
446            no_panel("save");
447            return reply(None);
448        };
449        if let Some(title) = &request.title {
450            panel.setMessage(Some(&ns(title)));
451        }
452        if let Some(name) = &request.default_name {
453            panel.setNameFieldStringValue(&ns(name));
454        }
455        if let Some(types) = content_types(&request.filters) {
456            panel.setAllowedContentTypes(&types);
457        }
458        start_in(&panel, &request.start_folder);
459        let reply = once(reply);
460        let chosen = panel.clone();
461        let answer = move |response: NSModalResponse| {
462            reply(if response == NSModalResponseOK { chosen.URL().and_then(|u| path(&u)) } else { None });
463        };
464        self.dialogs().present(parent, move |dialogs, window| match window {
465            Some(window) => {
466                let forget = dialogs.track_sheet(&window, &panel, NSModalResponseCancel);
467                let done = RcBlock::new(move |response| {
468                    forget();
469                    answer(response)
470                });
471                panel.beginSheetModalForWindow_completionHandler(&window, &done)
472            }
473            None => panel.beginWithCompletionHandler(&RcBlock::new(answer)),
474        });
475    }
476
477    /// `NSFileManager` trashes synchronously, so on a queue of its own, as
478    /// Finder does: within a disk it's a move, but each item on a network
479    /// disk is a round trip to the server, which would stall the window.
480    fn trash(&mut self, _parent: Option<NodeId>, paths: &[PathBuf], reply: Reply<Result<(), ServiceError>>) {
481        let (ticket, paths) = (wait(reply), paths.to_vec());
482        let queue = GlobalQueueIdentifier::QualityOfService(DispatchQoS::UserInitiated);
483        // The shared file manager is safe to use from any thread.
484        DispatchQueue::global_queue(queue)
485            .exec_async(move || answer(ticket, paths.iter().try_for_each(|path| trash_item(path))));
486    }
487
488    /// `NSWorkspace` opens it as Finder would, asking which app (or
489    /// saying there's none) itself when no app is set.
490    fn launch(&mut self, _parent: Option<NodeId>, target: &Launch, reply: Reply<Result<(), ServiceError>>) {
491        let url = match target {
492            Launch::Path(path) => NSURL::fileURLWithPath(&ns(&path.to_string_lossy())),
493            Launch::Url(url) => match NSURL::URLWithString(&ns(url)) {
494                Some(url) => url,
495                None => return reply(Err(ServiceError::Failed(format!("\u{201C}{url}\u{201D} isn't a URL")))),
496            },
497        };
498        let ticket = wait(reply);
499        let done = RcBlock::new(move |_app: *mut NSRunningApplication, error: *mut NSError| {
500            // SAFETY: AppKit passes a valid error or null.
501            answer(ticket, unsafe { error.as_ref() }.map_or(Ok(()), |error| Err(launch_error(error))));
502        });
503        let configuration = NSWorkspaceOpenConfiguration::configuration();
504        NSWorkspace::sharedWorkspace().openURL_configuration_completionHandler(&url, &configuration, Some(&done));
505    }
506
507    /// Each sheet on the window ends with its cancel response, as Escape
508    /// would end it, while the window is still there to end it on.
509    fn window_destroyed(&mut self, window: NodeId) {
510        let gone: Vec<(Retained<NSWindow>, Retained<NSWindow>, NSModalResponse)> = {
511            let sheets = self.sheets.borrow();
512            let on = sheets.open.iter().filter(|s| s.window == window);
513            on.map(|s| (s.parent.clone(), s.sheet.clone(), s.cancel)).collect()
514        };
515        for (parent, sheet, cancel) in gone {
516            parent.endSheet_returnCode(&sheet, cancel);
517        }
518    }
519
520    fn set_menu(&mut self, window: Option<NodeId>, menu: &MenuBarData, activate: Rc<dyn Fn(u32)>) {
521        {
522            let mut menus = self.menus.borrow_mut();
523            menus.activate = Some(activate);
524            match window {
525                None => menus.app = menu.clone(),
526                Some(window) if menu.menus.is_empty() => _ = menus.windows.remove(&window),
527                Some(window) => _ = menus.windows.insert(window, menu.clone()),
528            }
529            if menus.main.is_none() {
530                let main = NSApplication::sharedApplication(self.mtm).mainWindow();
531                menus.main = main.and_then(|w| self.backend.window_node(&w));
532            }
533            // Another window's menus aren't in the bar.
534            if window.is_some() && window != menus.main {
535                return;
536            }
537        }
538        self.menu_target.install(&self.menus.borrow());
539    }
540}
541
542fn item(mtm: MainThreadMarker, title: &str, action: Option<Sel>, key: &str) -> Retained<NSMenuItem> {
543    unsafe { NSMenuItem::initWithTitle_action_keyEquivalent(NSMenuItem::alloc(mtm), &ns(title), action, &ns(key)) }
544}
545
546/// `auto_enable`: let AppKit enable items by responder chain (standard
547/// menus); otherwise the app's `enabled` state decides.
548fn menu_of(
549    mtm: MainThreadMarker,
550    title: &str,
551    items: Vec<Retained<NSMenuItem>>,
552    auto_enable: bool,
553) -> Retained<NSMenuItem> {
554    let menu = NSMenu::initWithTitle(NSMenu::alloc(mtm), &ns(title));
555    menu.setAutoenablesItems(auto_enable);
556    for item in items {
557        menu.addItem(&item);
558    }
559    let holder = item(mtm, title, None, "");
560    holder.setSubmenu(Some(&menu));
561    holder
562}
563
564/// The character AppKit names a key by, in key equivalents and key
565/// events: the key's own for those that type one, a function key's
566/// (`NSUpArrowFunctionKey`) for the others.
567pub(crate) fn key_character(key: Key) -> char {
568    match key {
569        Key::Char(c) => c,
570        Key::Enter => '\r',
571        Key::Escape => '\u{1b}',
572        Key::Tab => '\t',
573        // `NSBackspaceCharacter`, as Finder's Move to Trash has it.
574        Key::Backspace => '\u{8}',
575        Key::Delete => '\u{f728}',
576        Key::Up => '\u{f700}',
577        Key::Down => '\u{f701}',
578        Key::Left => '\u{f702}',
579        Key::Right => '\u{f703}',
580        Key::Home => '\u{f729}',
581        Key::End => '\u{f72b}',
582        Key::PageUp => '\u{f72c}',
583        Key::PageDown => '\u{f72d}',
584        Key::F(n) => char::from_u32(0xf703 + u32::from(n)).unwrap_or('\u{f704}'),
585    }
586}
587
588/// The character a key event of this key carries, as the keyboard sends
589/// it: the Delete (⌫) key's is `NSDeleteCharacter`.
590pub(crate) fn event_character(key: Key) -> char {
591    match key {
592        Key::Backspace => '\u{7f}',
593        key => key_character(key),
594    }
595}
596
597/// The key AppKit names by this character (see [`key_character`]).
598/// `NSDeleteCharacter` is the Delete (⌫) key's own.
599pub(crate) fn key_of(c: char) -> Key {
600    match c {
601        '\r' | '\u{3}' => Key::Enter,
602        '\u{1b}' => Key::Escape,
603        '\t' => Key::Tab,
604        '\u{8}' | '\u{7f}' => Key::Backspace,
605        '\u{f728}' => Key::Delete,
606        '\u{f700}' => Key::Up,
607        '\u{f701}' => Key::Down,
608        '\u{f702}' => Key::Left,
609        '\u{f703}' => Key::Right,
610        '\u{f729}' => Key::Home,
611        '\u{f72b}' => Key::End,
612        '\u{f72c}' => Key::PageUp,
613        '\u{f72d}' => Key::PageDown,
614        '\u{f704}'..='\u{f726}' => Key::F((c as u32 - 0xf703) as u8),
615        c => Key::Char(c),
616    }
617}
618
619pub(crate) fn modifiers(shortcut: &Shortcut) -> NSEventModifierFlags {
620    let mut mask = NSEventModifierFlags::empty();
621    if shortcut.primary {
622        mask |= NSEventModifierFlags::Command;
623    }
624    if shortcut.shift {
625        mask |= NSEventModifierFlags::Shift;
626    }
627    if shortcut.alt {
628        mask |= NSEventModifierFlags::Option;
629    }
630    mask
631}
632
633/// Where menu items send their action: the item's tag is its id.
634#[derive(Clone, Copy)]
635pub(crate) struct ItemTarget<'a> {
636    pub(crate) object: &'a AnyObject,
637    pub(crate) action: Sel,
638}
639
640impl<'a> From<&'a MenuTarget> for ItemTarget<'a> {
641    fn from(target: &'a MenuTarget) -> ItemTarget<'a> {
642        ItemTarget { object: target as &AnyObject, action: sel!(choose:) }
643    }
644}
645
646/// One of the app's items. The check mark is AppKit's for radio items
647/// too: its menus show a group's choice with one.
648fn app_item(
649    mtm: MainThreadMarker,
650    data: &MenuItemData,
651    title: &str,
652    shortcut: Option<Shortcut>,
653    target: ItemTarget,
654) -> Retained<NSMenuItem> {
655    let key = shortcut.map(|s| key_character(s.key).to_string()).unwrap_or_default();
656    let item = item(mtm, title, Some(target.action), &key);
657    unsafe { item.setTarget(Some(target.object)) };
658    item.setTag(data.id as isize);
659    item.setEnabled(data.enabled);
660    if let Some(shortcut) = shortcut {
661        item.setKeyEquivalentModifierMask(modifiers(&shortcut));
662    }
663    if let MenuCheck::Check(on) | MenuCheck::Radio(on) = data.check {
664        item.setState(if on { NSControlStateValueOn } else { NSControlStateValueOff });
665    }
666    item
667}
668
669pub(crate) fn app_items(mtm: MainThreadMarker, entries: &[MenuEntry], target: ItemTarget) -> Vec<Retained<NSMenuItem>> {
670    entries
671        .iter()
672        .map(|entry| match entry {
673            MenuEntry::Separator => NSMenuItem::separatorItem(mtm),
674            MenuEntry::Item(data) => app_item(mtm, data, &data.title, data.shortcut, target),
675            MenuEntry::Submenu(menu) => menu_of(mtm, &menu.title, app_items(mtm, &menu.entries, target), false),
676        })
677        .collect()
678}
679
680/// A context menu: the app's entries, enabled as the app says.
681pub(crate) fn context_menu(mtm: MainThreadMarker, entries: &[MenuEntry], target: ItemTarget) -> Retained<NSMenu> {
682    let menu = NSMenu::new(mtm);
683    menu.setAutoenablesItems(false);
684    for item in app_items(mtm, entries, target) {
685        menu.addItem(&item);
686    }
687    menu
688}
689
690/// What a context menu shows, read back from AppKit. It can't tell a
691/// radio item from a check item, nor keep a role: those come from `sent`.
692pub(crate) fn context_menu_entries(menu: &NSMenu, sent: &[MenuEntry]) -> Vec<MenuEntry> {
693    fn read(menu: &NSMenu, sent: &[MenuEntry]) -> Vec<MenuEntry> {
694        menu.itemArray()
695            .iter()
696            .map(|item| {
697                if item.isSeparatorItem() {
698                    return MenuEntry::Separator;
699                }
700                if let Some(submenu) = item.submenu() {
701                    return MenuEntry::Submenu(MenuData {
702                        title: item.title().to_string(),
703                        entries: read(&submenu, sent),
704                    });
705                }
706                let id = item.tag() as u32;
707                let original = menu_item_by_id(sent, id);
708                let on = item.state() == NSControlStateValueOn;
709                let key = item.keyEquivalent().to_string();
710                let mask = item.keyEquivalentModifierMask();
711                MenuEntry::Item(MenuItemData {
712                    id,
713                    title: item.title().to_string(),
714                    shortcut: key.chars().next().map(|key| Shortcut {
715                        key: key_of(key),
716                        primary: mask.contains(NSEventModifierFlags::Command),
717                        shift: mask.contains(NSEventModifierFlags::Shift),
718                        alt: mask.contains(NSEventModifierFlags::Option),
719                    }),
720                    enabled: item.isEnabled(),
721                    check: match original.map(|s| s.check) {
722                        Some(MenuCheck::Radio(_)) => MenuCheck::Radio(on),
723                        Some(MenuCheck::Check(_)) => MenuCheck::Check(on),
724                        _ if on => MenuCheck::Check(true),
725                        _ => MenuCheck::None,
726                    },
727                    role: original.map(|s| s.role).unwrap_or_default(),
728                })
729            })
730            .collect()
731    }
732    read(menu, sent)
733}
734
735/// The item of a context menu with this id, submenus' included, and the
736/// menu holding it.
737pub(crate) fn find_tagged(menu: &NSMenu, id: u32) -> Option<(Retained<NSMenuItem>, Retained<NSMenu>)> {
738    menu.itemArray().iter().find_map(|item| match item.submenu() {
739        Some(submenu) => find_tagged(&submenu, id),
740        None if !item.isSeparatorItem() && item.tag() as u32 == id => Some((item, menu.retain())),
741        None => None,
742    })
743}
744
745/// The app menu, the app's File menu (if any), Edit (what makes ⌘C/⌘V/⌘Z
746/// work in text fields), then the app's other menus. Items with a role go
747/// to the app menu, with AppKit's titles and shortcuts, as Qt puts them,
748/// and so do the items of a menu titled with the app's name.
749/// Titles of our own are in the app's language (`mitsuami.ftl`), and so
750/// is the File menu's, which the app's File menu is known by.
751fn menu_bar(mtm: MainThreadMarker, mut menus: MenuBarData, name: &str, target: &MenuTarget) -> Retained<NSMenu> {
752    let target = ItemTarget::from(target);
753    let bar = NSMenu::new(mtm);
754    let command = |key| Some(Shortcut::primary(key));
755    let app = |id: &str| tr(id, &[("app", name.to_arg())]);
756    let mut app_menu = Vec::new();
757    if let Some(about) = menus.take_role(MenuRole::About) {
758        app_menu.push(app_item(mtm, &about, &app("mitsuami-menu-about"), None, target));
759        app_menu.push(NSMenuItem::separatorItem(mtm));
760    }
761    if let Some(settings) = menus.take_role(MenuRole::Settings) {
762        app_menu.push(app_item(mtm, &settings, &tr("mitsuami-menu-settings", &[]), command(','), target));
763        app_menu.push(NSMenuItem::separatorItem(mtm));
764    }
765    // The app's own menu, titled with its name, joins the app menu, where
766    // macOS apps put their app-wide commands (Check for Updates…).
767    let (own, others): (Vec<_>, Vec<_>) = std::mem::take(&mut menus.menus).into_iter().partition(|m| m.title == name);
768    menus.menus = others;
769    for menu in own {
770        app_menu.extend(app_items(mtm, &menu.entries, target));
771        app_menu.push(NSMenuItem::separatorItem(mtm));
772    }
773    app_menu.push(item(mtm, &app("mitsuami-menu-hide"), Some(sel!(hide:)), "h"));
774    app_menu.push(NSMenuItem::separatorItem(mtm));
775    let quit = app("mitsuami-menu-quit-app");
776    app_menu.push(match menus.take_role(MenuRole::Quit) {
777        Some(item) => app_item(mtm, &item, &quit, command('q'), target),
778        None => item(mtm, &quit, Some(sel!(terminate:)), "q"),
779    });
780    bar.addItem(&menu_of(mtm, name, app_menu, true));
781    let file_title = tr("mitsuami-menu-file", &[]);
782    let (file, others): (Vec<_>, Vec<_>) = menus.menus.iter().partition(|m| m.title == file_title);
783    for menu in file {
784        bar.addItem(&menu_of(mtm, &menu.title, app_items(mtm, &menu.entries, target), false));
785    }
786    bar.addItem(&menu_of(
787        mtm,
788        &tr("mitsuami-menu-edit", &[]),
789        vec![
790            item(mtm, &tr("mitsuami-menu-undo", &[]), Some(sel!(undo:)), "z"),
791            item(mtm, &tr("mitsuami-menu-redo", &[]), Some(sel!(redo:)), "Z"),
792            NSMenuItem::separatorItem(mtm),
793            item(mtm, &tr("mitsuami-menu-cut", &[]), Some(sel!(cut:)), "x"),
794            item(mtm, &tr("mitsuami-menu-copy", &[]), Some(sel!(copy:)), "c"),
795            item(mtm, &tr("mitsuami-menu-paste", &[]), Some(sel!(paste:)), "v"),
796            item(mtm, &tr("mitsuami-menu-select-all", &[]), Some(sel!(selectAll:)), "a"),
797        ],
798        true,
799    ));
800    for menu in others {
801        bar.addItem(&menu_of(mtm, &menu.title, app_items(mtm, &menu.entries, target), false));
802    }
803    bar
804}