mitsuami-appkit 2.5.2

AppKit (macOS) backend for mitsuami
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
//! Clipboard, dialogs, the trash, launching, notifications and the menu
//! bar on macOS.

use mitsuami_core::l10n::{ToArg, tr};
use std::cell::{Cell, RefCell};
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::rc::{Rc, Weak};

use block2::RcBlock;
use dispatch2::{DispatchQoS, DispatchQueue, GlobalQueueIdentifier};
use mitsuami_core::services::{
    Alert, AlertStyle, FileFilter, Launch, MenuBarData, MenuCheck, MenuData, MenuEntry, MenuItemData, MenuRole,
    Notification, OpenFile, Reply, SaveFile, ServiceError, Services, Shortcut, TrayData, existing_folder,
    menu_item_by_id,
};
use mitsuami_core::{Key, NodeId};
use objc2::rc::Retained;
use objc2::runtime::{AnyObject, NSObject, NSObjectProtocol, Sel};
use objc2::{ClassType, DefinedClass, MainThreadMarker, MainThreadOnly, Message, define_class, msg_send, sel};
use objc2_app_kit::{
    NSAlert, NSAlertFirstButtonReturn, NSAlertStyle, NSApplication, NSControlStateValueOff, NSControlStateValueOn,
    NSEventModifierFlags, NSMenu, NSMenuItem, NSModalResponse, NSModalResponseCancel, NSModalResponseOK, NSOpenPanel,
    NSPasteboard, NSPasteboardTypeString, NSRunningApplication, NSSavePanel, NSWindow,
    NSWindowDidBecomeMainNotification, NSWindowDidResignMainNotification, NSWorkspace, NSWorkspaceOpenConfiguration,
};
use objc2_core_foundation::{CFRunLoop, kCFRunLoopCommonModes};
use objc2_foundation::{
    NSArray, NSCocoaErrorDomain, NSError, NSFeatureUnsupportedError, NSFileManager, NSNotification,
    NSNotificationCenter, NSOSStatusErrorDomain, NSString, NSURL, NSUserCancelledError,
};
use objc2_uniform_type_identifiers::UTType;

use crate::backend::AppKitHandle;

/// The menus the bar shows: the app's, and the main window's own.
struct Menus {
    mtm: MainThreadMarker,
    backend: AppKitHandle,
    app: MenuBarData,
    windows: HashMap<NodeId, MenuBarData>,
    /// The main window, the one the menus act on.
    main: Option<NodeId>,
    activate: Option<Rc<dyn Fn(u32)>>,
}

impl Menus {
    fn shown(&self) -> MenuBarData {
        match self.main.and_then(|main| self.windows.get(&main)) {
            Some(window) => self.app.merged(window),
            None => self.app.clone(),
        }
    }
}

pub(crate) struct MenuIvars {
    menus: Weak<RefCell<Menus>>,
}

define_class!(
    /// Target of the app's own menu items (the item's tag is its id), and
    /// observer of which window is main.
    #[unsafe(super(NSObject))]
    #[thread_kind = MainThreadOnly]
    #[ivars = MenuIvars]
    struct MenuTarget;

    impl MenuTarget {
        #[unsafe(method(choose:))]
        fn choose(&self, sender: &NSMenuItem) {
            let activate = self.ivars().menus.upgrade().and_then(|menus| menus.borrow().activate.clone());
            if let Some(activate) = activate {
                activate(sender.tag() as u32);
            }
        }

        #[unsafe(method(windowDidBecomeMain:))]
        fn window_did_become_main(&self, notification: &NSNotification) {
            self.main_changed(notification, true);
        }

        #[unsafe(method(windowDidResignMain:))]
        fn window_did_resign_main(&self, notification: &NSNotification) {
            self.main_changed(notification, false);
        }
    }

    unsafe impl NSObjectProtocol for MenuTarget {}
);

impl MenuTarget {
    fn new(mtm: MainThreadMarker, menus: Weak<RefCell<Menus>>) -> Retained<MenuTarget> {
        let this = MenuTarget::alloc(mtm).set_ivars(MenuIvars { menus });
        unsafe { msg_send![super(this), init] }
    }

    /// A window's menus are in the bar while it's main. AppKit posts
    /// these while a window closes, which the backend does while it applies
    /// commands, its state borrowed: look the window up once that's over.
    fn main_changed(&self, notification: &NSNotification, became: bool) {
        let Some(window) = notification.object().and_then(|o| o.downcast::<NSWindow>().ok()) else { return };
        let target = self.retain();
        later(move || target.main_changed_now(&window, became));
    }

    fn main_changed_now(&self, window: &NSWindow, became: bool) {
        let Some(menus) = self.ivars().menus.upgrade() else { return };
        let node = menus.borrow().backend.window_node(window);
        let changed = {
            let mut menus = menus.borrow_mut();
            let before = menus.main;
            if became {
                menus.main = node;
            } else if node.is_some() && before == node {
                menus.main = None;
            }
            let has_menus = |id: Option<NodeId>| id.is_some_and(|id| menus.windows.contains_key(&id));
            before != menus.main && (has_menus(before) || has_menus(menus.main))
        };
        if changed {
            self.install(&menus.borrow());
        }
    }

    fn install(&self, menus: &Menus) {
        let bar = menu_bar(menus.mtm, menus.shown(), &menus.backend.app_name(), self);
        NSApplication::sharedApplication(menus.mtm).setMainMenu(Some(&bar));
    }
}

pub struct AppKitServices {
    mtm: MainThreadMarker,
    backend: AppKitHandle,
    pasteboard: Retained<NSPasteboard>,
    menus: Rc<RefCell<Menus>>,
    /// Menu items only hold weak references to their target.
    menu_target: Retained<MenuTarget>,
    sheets: Rc<RefCell<Sheets>>,
    tray: crate::tray::Tray,
}

/// Alerts and panels shown as sheets, until they answer: the window each is
/// on, and the response that cancels it.
#[derive(Default)]
struct Sheets {
    next: u64,
    open: Vec<Sheet>,
}

struct Sheet {
    ticket: u64,
    window: NodeId,
    parent: Retained<NSWindow>,
    sheet: Retained<NSWindow>,
    cancel: NSModalResponse,
}

impl Drop for AppKitServices {
    fn drop(&mut self) {
        unsafe { NSNotificationCenter::defaultCenter().removeObserver(&self.menu_target) };
    }
}

fn ns(s: &str) -> Retained<NSString> {
    NSString::from_str(s)
}

/// The panel's start folder: its `directoryURL`, if the folder is there.
fn start_in(panel: &NSSavePanel, folder: &Option<PathBuf>) {
    if let Some(folder) = existing_folder(folder) {
        panel.setDirectoryURL(Some(&NSURL::fileURLWithPath_isDirectory(&ns(&folder.to_string_lossy()), true)));
    }
}

fn path(url: &NSURL) -> Option<PathBuf> {
    url.path().map(|p| PathBuf::from(p.to_string()))
}

/// The types a panel allows: every filter's at once, since AppKit's panels
/// have no filter menu. Every file when a filter lets every file through,
/// so a file the types miss can still be chosen, as on the platforms where
/// the user picks that filter.
fn content_types(filters: &[FileFilter]) -> Option<Retained<NSArray<UTType>>> {
    if filters.iter().any(FileFilter::is_all) {
        return None;
    }
    let types: Vec<Retained<UTType>> = filters
        .iter()
        .flat_map(|f| &f.extensions)
        .filter_map(|ext| UTType::typeWithFilenameExtension(&ns(ext.trim_start_matches('.'))))
        .collect();
    (!types.is_empty()).then(|| NSArray::from_retained_slice(&types))
}

/// Moves an item to its disk's trash, where Finder's Put Back finds it.
fn trash_item(path: &Path) -> Result<(), ServiceError> {
    let url = NSURL::fileURLWithPath(&ns(&path.to_string_lossy()));
    NSFileManager::defaultManager().trashItemAtURL_resultingItemURL_error(&url, None).map_err(|error| {
        if error.code() == NSFeatureUnsupportedError && error.domain().isEqualToString(unsafe { NSCocoaErrorDomain }) {
            ServiceError::Unavailable
        } else {
            ServiceError::Failed(error.localizedDescription().to_string())
        }
    })
}

thread_local! {
    /// Replies waiting for work done on another thread (`NSWorkspace`'s
    /// completion handlers, the trash), by ticket.
    static WAITING: RefCell<HashMap<u64, Reply<Result<(), ServiceError>>>> = RefCell::new(HashMap::new());
    static NEXT_TICKET: Cell<u64> = const { Cell::new(0) };
}

/// Keeps a reply, which stays on the main thread, until [`answer`].
pub(crate) fn wait(reply: Reply<Result<(), ServiceError>>) -> u64 {
    let ticket = NEXT_TICKET.replace(NEXT_TICKET.get() + 1);
    WAITING.with(|w| w.borrow_mut().insert(ticket, reply));
    ticket
}

/// Answers a kept reply from any thread, on the main one.
pub(crate) fn answer(ticket: u64, result: Result<(), ServiceError>) {
    DispatchQueue::main().exec_async(move || {
        if let Some(reply) = WAITING.with(|w| w.borrow_mut().remove(&ticket)) {
            reply(result);
        }
    });
}

/// Launch Services' "no application" and "the user cancelled".
const APPLICATION_NOT_FOUND: isize = -10814;
const USER_CANCELED: isize = -128;

fn launch_error(error: &NSError) -> ServiceError {
    let (domain, code) = (error.domain(), error.code());
    let cocoa = domain.isEqualToString(unsafe { NSCocoaErrorDomain });
    let status = domain.isEqualToString(unsafe { NSOSStatusErrorDomain });
    match code {
        APPLICATION_NOT_FOUND if status => ServiceError::Unavailable,
        USER_CANCELED if status => ServiceError::Cancelled,
        code if cocoa && code == NSUserCancelledError => ServiceError::Cancelled,
        _ => ServiceError::Failed(error.localizedDescription().to_string()),
    }
}

/// AppKit gives a sandboxed process no open or save panel without the
/// user-selected files entitlement (a child that inherits its parent's
/// sandbox never has it), and objc2-app-kit's bindings panic on that nil:
/// the request is answered as a cancel instead, and the reason said here,
/// since the user sees nothing happen.
fn no_panel(kind: &str) {
    eprintln!(
        "mitsuami: AppKit gave no {kind} panel; in the App Sandbox, the app needs the \
         com.apple.security.files.user-selected.read-only or .read-write entitlement"
    );
}

/// Runs `f` on the main run loop soon, outside whatever is calling us now.
fn later(f: impl Fn() + 'static) {
    let block = RcBlock::new(f);
    if let Some(run_loop) = CFRunLoop::main() {
        unsafe { run_loop.perform_block(kCFRunLoopCommonModes.map(|m| &**m), Some(&block)) };
        run_loop.wake_up();
    }
}

/// Wraps a one-shot reply for AppKit's (reusable) completion blocks.
fn once<T>(reply: Reply<T>) -> impl Fn(T) {
    let reply = Cell::new(Some(reply));
    move |value| {
        if let Some(reply) = reply.take() {
            reply(value);
        }
    }
}

impl AppKitServices {
    pub(crate) fn new(mtm: MainThreadMarker, backend: AppKitHandle, private_clipboard: bool) -> AppKitServices {
        let pasteboard = if private_clipboard {
            NSPasteboard::pasteboardWithUniqueName()
        } else {
            NSPasteboard::generalPasteboard()
        };
        let menus = Rc::new(RefCell::new(Menus {
            mtm,
            backend: backend.clone(),
            app: MenuBarData::default(),
            windows: HashMap::new(),
            main: None,
            activate: None,
        }));
        let menu_target = MenuTarget::new(mtm, Rc::downgrade(&menus));
        let center = NSNotificationCenter::defaultCenter();
        // SAFETY: the target is removed as an observer when the services go.
        unsafe {
            center.addObserver_selector_name_object(
                &menu_target,
                sel!(windowDidBecomeMain:),
                Some(NSWindowDidBecomeMainNotification),
                None,
            );
            center.addObserver_selector_name_object(
                &menu_target,
                sel!(windowDidResignMain:),
                Some(NSWindowDidResignMainNotification),
                None,
            );
        }
        let tray = crate::tray::Tray::new(mtm, backend.clone());
        AppKitServices { mtm, backend, pasteboard, menus, menu_target, sheets: Rc::default(), tray }
    }

    /// What a dialog needs once it goes up, which may be after this call
    /// (`AppKitHandle::when_shown`).
    fn dialogs(&self) -> Dialogs {
        Dialogs { mtm: self.mtm, backend: self.backend.clone(), sheets: self.sheets.clone() }
    }
}

/// Puts dialogs up: on the window they belong to, as sheets.
#[derive(Clone)]
struct Dialogs {
    mtm: MainThreadMarker,
    backend: AppKitHandle,
    sheets: Rc<RefCell<Sheets>>,
}

impl Dialogs {
    /// Remembers a sheet on `parent` until it answers, so it ends with its
    /// window; returns what forgets it.
    fn track_sheet(&self, parent: &NSWindow, sheet: &NSWindow, cancel: NSModalResponse) -> impl Fn() + 'static {
        let ticket = self.backend.window_node(parent).map(|window| {
            let mut sheets = self.sheets.borrow_mut();
            sheets.next += 1;
            let ticket = sheets.next;
            sheets.open.push(Sheet { ticket, window, parent: parent.retain(), sheet: sheet.retain(), cancel });
            ticket
        });
        let sheets = Rc::downgrade(&self.sheets);
        move || {
            if let (Some(ticket), Some(sheets)) = (ticket, sheets.upgrade()) {
                sheets.borrow_mut().open.retain(|s| s.ticket != ticket);
            }
        }
    }

    /// The window a dialog belongs to: the requested one, or the active one.
    fn parent(&self, parent: Option<NodeId>) -> Option<Retained<NSWindow>> {
        let app = NSApplication::sharedApplication(self.mtm);
        parent.and_then(|id| self.backend.ns_window(id)).or_else(|| app.keyWindow()).or_else(|| app.mainWindow())
    }

    /// Runs `show` with the window the dialog belongs to, once that window
    /// is on screen.
    fn present(self, parent: Option<NodeId>, show: impl FnOnce(&Dialogs, Option<Retained<NSWindow>>) + 'static) {
        let backend = self.backend.clone();
        backend.when_shown(parent, move || show(&self, self.parent(parent)));
    }
}

impl Services for AppKitServices {
    fn clipboard_text(&mut self, reply: Reply<Option<String>>) {
        // NSPasteboard reads synchronously: answer right away.
        reply(self.pasteboard.stringForType(unsafe { NSPasteboardTypeString }).map(|s| s.to_string()));
    }

    fn set_clipboard_text(&mut self, text: &str, reply: Reply<Result<(), ServiceError>>) {
        self.pasteboard.clearContents();
        let written = self.pasteboard.setString_forType(&ns(text), unsafe { NSPasteboardTypeString });
        reply(if written { Ok(()) } else { Err(ServiceError::Failed("the pasteboard refused the text".into())) });
    }

    fn alert(&mut self, parent: Option<NodeId>, alert: &Alert, reply: Reply<usize>) {
        let ns_alert = NSAlert::new(self.mtm);
        ns_alert.setMessageText(&ns(&alert.title));
        if let Some(message) = &alert.message {
            ns_alert.setInformativeText(&ns(message));
        }
        ns_alert.setAlertStyle(match alert.style {
            AlertStyle::Info => NSAlertStyle::Informational,
            AlertStyle::Warning => NSAlertStyle::Warning,
            AlertStyle::Critical => NSAlertStyle::Critical,
        });
        let buttons = alert.effective_buttons();
        for (i, button) in buttons.iter().enumerate() {
            let button = ns_alert.addButtonWithTitle(&ns(button));
            // An alert draws it red; a window's button doesn't.
            button.setHasDestructiveAction(alert.destructive == Some(i));
        }
        let reply = once(reply);
        let answer = move |response: NSModalResponse| reply((response - NSAlertFirstButtonReturn).max(0) as usize);
        self.dialogs().present(parent, move |dialogs, window| match window {
            // A sheet on the window it belongs to.
            Some(window) => {
                // The last button is the cancel one, as Escape chooses.
                let cancel = NSAlertFirstButtonReturn + buttons.len() as NSModalResponse - 1;
                let forget = dialogs.track_sheet(&window, &ns_alert.window(), cancel);
                let done = RcBlock::new(move |response| {
                    forget();
                    answer(response)
                });
                ns_alert.beginSheetModalForWindow_completionHandler(&window, Some(&done));
            }
            // No window: an app-modal alert, run once the caller has returned.
            None => later(move || answer(ns_alert.runModal())),
        });
    }

    fn open_file(&mut self, parent: Option<NodeId>, request: &OpenFile, reply: Reply<Option<Vec<PathBuf>>>) {
        let panel: Option<Retained<NSOpenPanel>> = unsafe { msg_send![NSOpenPanel::class(), openPanel] };
        let Some(panel) = panel else {
            no_panel("open");
            return reply(None);
        };
        panel.setCanChooseFiles(!request.directories);
        panel.setCanChooseDirectories(request.directories);
        // A folder can be made where one is chosen, as GTK's, Qt's and
        // Windows' folder dialogs offer and Mac apps' folder panels do;
        // AppKit's open panel leaves New Folder off (§14.9).
        panel.setCanCreateDirectories(request.directories);
        panel.setAllowsMultipleSelection(request.multiple);
        if let Some(title) = &request.title {
            panel.setMessage(Some(&ns(title)));
        }
        if let Some(types) = content_types(&request.filters) {
            panel.setAllowedContentTypes(&types);
        }
        start_in(&panel, &request.start_folder);
        let reply = once(reply);
        let chosen = panel.clone();
        let answer = move |response: NSModalResponse| {
            reply((response == NSModalResponseOK).then(|| chosen.URLs().iter().filter_map(|u| path(&u)).collect()));
        };
        self.dialogs().present(parent, move |dialogs, window| match window {
            Some(window) => {
                let forget = dialogs.track_sheet(&window, &panel, NSModalResponseCancel);
                let done = RcBlock::new(move |response| {
                    forget();
                    answer(response)
                });
                panel.beginSheetModalForWindow_completionHandler(&window, &done)
            }
            None => panel.beginWithCompletionHandler(&RcBlock::new(answer)),
        });
    }

    fn save_file(&mut self, parent: Option<NodeId>, request: &SaveFile, reply: Reply<Option<PathBuf>>) {
        let panel: Option<Retained<NSSavePanel>> = unsafe { msg_send![NSSavePanel::class(), savePanel] };
        let Some(panel) = panel else {
            no_panel("save");
            return reply(None);
        };
        if let Some(title) = &request.title {
            panel.setMessage(Some(&ns(title)));
        }
        if let Some(name) = &request.default_name {
            panel.setNameFieldStringValue(&ns(name));
        }
        if let Some(types) = content_types(&request.filters) {
            panel.setAllowedContentTypes(&types);
        }
        start_in(&panel, &request.start_folder);
        let reply = once(reply);
        let chosen = panel.clone();
        let answer = move |response: NSModalResponse| {
            reply(if response == NSModalResponseOK { chosen.URL().and_then(|u| path(&u)) } else { None });
        };
        self.dialogs().present(parent, move |dialogs, window| match window {
            Some(window) => {
                let forget = dialogs.track_sheet(&window, &panel, NSModalResponseCancel);
                let done = RcBlock::new(move |response| {
                    forget();
                    answer(response)
                });
                panel.beginSheetModalForWindow_completionHandler(&window, &done)
            }
            None => panel.beginWithCompletionHandler(&RcBlock::new(answer)),
        });
    }

    /// `NSFileManager` trashes synchronously, so on a queue of its own, as
    /// Finder does: within a disk it's a move, but each item on a network
    /// disk is a round trip to the server, which would stall the window.
    fn trash(&mut self, _parent: Option<NodeId>, paths: &[PathBuf], reply: Reply<Result<(), ServiceError>>) {
        let (ticket, paths) = (wait(reply), paths.to_vec());
        let queue = GlobalQueueIdentifier::QualityOfService(DispatchQoS::UserInitiated);
        // The shared file manager is safe to use from any thread.
        DispatchQueue::global_queue(queue)
            .exec_async(move || answer(ticket, paths.iter().try_for_each(|path| trash_item(path))));
    }

    /// `NSWorkspace` opens it as Finder would, asking which app (or
    /// saying there's none) itself when no app is set.
    fn launch(&mut self, _parent: Option<NodeId>, target: &Launch, reply: Reply<Result<(), ServiceError>>) {
        let url = match target {
            Launch::Path(path) => NSURL::fileURLWithPath(&ns(&path.to_string_lossy())),
            Launch::Url(url) => match NSURL::URLWithString(&ns(url)) {
                Some(url) => url,
                None => return reply(Err(ServiceError::Failed(format!("\u{201C}{url}\u{201D} isn't a URL")))),
            },
        };
        let ticket = wait(reply);
        let done = RcBlock::new(move |_app: *mut NSRunningApplication, error: *mut NSError| {
            // SAFETY: AppKit passes a valid error or null.
            answer(ticket, unsafe { error.as_ref() }.map_or(Ok(()), |error| Err(launch_error(error))));
        });
        let configuration = NSWorkspaceOpenConfiguration::configuration();
        NSWorkspace::sharedWorkspace().openURL_configuration_completionHandler(&url, &configuration, Some(&done));
    }

    fn notify(
        &mut self,
        notification: &Notification,
        activated: Rc<dyn Fn(String)>,
        reply: Reply<Result<(), ServiceError>>,
    ) {
        crate::notifications::notify(notification, activated, reply);
    }

    fn withdraw_notification(&mut self, id: &str) {
        crate::notifications::withdraw(id);
    }

    /// Each sheet on the window ends with its cancel response, as Escape
    /// would end it, while the window is still there to end it on.
    fn window_destroyed(&mut self, window: NodeId) {
        let gone: Vec<(Retained<NSWindow>, Retained<NSWindow>, NSModalResponse)> = {
            let sheets = self.sheets.borrow();
            let on = sheets.open.iter().filter(|s| s.window == window);
            on.map(|s| (s.parent.clone(), s.sheet.clone(), s.cancel)).collect()
        };
        for (parent, sheet, cancel) in gone {
            parent.endSheet_returnCode(&sheet, cancel);
        }
    }

    fn set_menu(&mut self, window: Option<NodeId>, menu: &MenuBarData, activate: Rc<dyn Fn(u32)>) {
        {
            let mut menus = self.menus.borrow_mut();
            menus.activate = Some(activate);
            match window {
                None => menus.app = menu.clone(),
                Some(window) if menu.menus.is_empty() => _ = menus.windows.remove(&window),
                Some(window) => _ = menus.windows.insert(window, menu.clone()),
            }
            if menus.main.is_none() {
                let main = NSApplication::sharedApplication(self.mtm).mainWindow();
                menus.main = main.and_then(|w| self.backend.window_node(&w));
            }
            // Another window's menus aren't in the bar.
            if window.is_some() && window != menus.main {
                return;
            }
        }
        self.menu_target.install(&self.menus.borrow());
    }
    fn set_tray(&mut self, tray: Option<&TrayData>, activate: Rc<dyn Fn(u32)>, shown: Rc<dyn Fn(bool)>) {
        let app_id = self.backend.app_id();
        self.tray.set(tray, app_id.as_deref(), activate, shown);
    }
}

fn item(mtm: MainThreadMarker, title: &str, action: Option<Sel>, key: &str) -> Retained<NSMenuItem> {
    unsafe { NSMenuItem::initWithTitle_action_keyEquivalent(NSMenuItem::alloc(mtm), &ns(title), action, &ns(key)) }
}

/// `auto_enable`: let AppKit enable items by responder chain (standard
/// menus); otherwise the app's `enabled` state decides.
fn menu_of(
    mtm: MainThreadMarker,
    title: &str,
    items: Vec<Retained<NSMenuItem>>,
    auto_enable: bool,
) -> Retained<NSMenuItem> {
    let menu = NSMenu::initWithTitle(NSMenu::alloc(mtm), &ns(title));
    menu.setAutoenablesItems(auto_enable);
    for item in items {
        menu.addItem(&item);
    }
    let holder = item(mtm, title, None, "");
    holder.setSubmenu(Some(&menu));
    holder
}

/// The character AppKit names a key by, in key equivalents and key
/// events: the key's own for those that type one, a function key's
/// (`NSUpArrowFunctionKey`) for the others.
pub(crate) fn key_character(key: Key) -> char {
    match key {
        Key::Char(c) => c,
        Key::Enter => '\r',
        Key::Escape => '\u{1b}',
        Key::Tab => '\t',
        // `NSBackspaceCharacter`, as Finder's Move to Trash has it.
        Key::Backspace => '\u{8}',
        Key::Delete => '\u{f728}',
        Key::Up => '\u{f700}',
        Key::Down => '\u{f701}',
        Key::Left => '\u{f702}',
        Key::Right => '\u{f703}',
        Key::Home => '\u{f729}',
        Key::End => '\u{f72b}',
        Key::PageUp => '\u{f72c}',
        Key::PageDown => '\u{f72d}',
        Key::F(n) => char::from_u32(0xf703 + u32::from(n)).unwrap_or('\u{f704}'),
    }
}

/// The character a key event of this key carries, as the keyboard sends
/// it: the Delete (⌫) key's is `NSDeleteCharacter`.
pub(crate) fn event_character(key: Key) -> char {
    match key {
        Key::Backspace => '\u{7f}',
        key => key_character(key),
    }
}

/// The key AppKit names by this character (see [`key_character`]).
/// `NSDeleteCharacter` is the Delete (⌫) key's own.
pub(crate) fn key_of(c: char) -> Key {
    match c {
        '\r' | '\u{3}' => Key::Enter,
        '\u{1b}' => Key::Escape,
        '\t' => Key::Tab,
        '\u{8}' | '\u{7f}' => Key::Backspace,
        '\u{f728}' => Key::Delete,
        '\u{f700}' => Key::Up,
        '\u{f701}' => Key::Down,
        '\u{f702}' => Key::Left,
        '\u{f703}' => Key::Right,
        '\u{f729}' => Key::Home,
        '\u{f72b}' => Key::End,
        '\u{f72c}' => Key::PageUp,
        '\u{f72d}' => Key::PageDown,
        '\u{f704}'..='\u{f726}' => Key::F((c as u32 - 0xf703) as u8),
        c => Key::Char(c),
    }
}

pub(crate) fn modifiers(shortcut: &Shortcut) -> NSEventModifierFlags {
    let mut mask = NSEventModifierFlags::empty();
    if shortcut.primary {
        mask |= NSEventModifierFlags::Command;
    }
    if shortcut.shift {
        mask |= NSEventModifierFlags::Shift;
    }
    if shortcut.alt {
        mask |= NSEventModifierFlags::Option;
    }
    mask
}

/// Where menu items send their action: the item's tag is its id.
#[derive(Clone, Copy)]
pub(crate) struct ItemTarget<'a> {
    pub(crate) object: &'a AnyObject,
    pub(crate) action: Sel,
}

impl<'a> From<&'a MenuTarget> for ItemTarget<'a> {
    fn from(target: &'a MenuTarget) -> ItemTarget<'a> {
        ItemTarget { object: target as &AnyObject, action: sel!(choose:) }
    }
}

/// One of the app's items. The check mark is AppKit's for radio items
/// too: its menus show a group's choice with one.
fn app_item(
    mtm: MainThreadMarker,
    data: &MenuItemData,
    title: &str,
    shortcut: Option<Shortcut>,
    target: ItemTarget,
) -> Retained<NSMenuItem> {
    let key = shortcut.map(|s| key_character(s.key).to_string()).unwrap_or_default();
    let item = item(mtm, title, Some(target.action), &key);
    unsafe { item.setTarget(Some(target.object)) };
    item.setTag(data.id as isize);
    item.setEnabled(data.enabled);
    if let Some(shortcut) = shortcut {
        item.setKeyEquivalentModifierMask(modifiers(&shortcut));
    }
    if let MenuCheck::Check(on) | MenuCheck::Radio(on) = data.check {
        item.setState(if on { NSControlStateValueOn } else { NSControlStateValueOff });
    }
    item
}

pub(crate) fn app_items(mtm: MainThreadMarker, entries: &[MenuEntry], target: ItemTarget) -> Vec<Retained<NSMenuItem>> {
    entries
        .iter()
        .map(|entry| match entry {
            MenuEntry::Separator => NSMenuItem::separatorItem(mtm),
            MenuEntry::Item(data) => app_item(mtm, data, &data.title, data.shortcut, target),
            MenuEntry::Submenu(menu) => menu_of(mtm, &menu.title, app_items(mtm, &menu.entries, target), false),
        })
        .collect()
}

/// A context menu: the app's entries, enabled as the app says.
pub(crate) fn context_menu(mtm: MainThreadMarker, entries: &[MenuEntry], target: ItemTarget) -> Retained<NSMenu> {
    let menu = NSMenu::new(mtm);
    menu.setAutoenablesItems(false);
    for item in app_items(mtm, entries, target) {
        menu.addItem(&item);
    }
    menu
}

/// What a context menu shows, read back from AppKit. It can't tell a
/// radio item from a check item, nor keep a role: those come from `sent`.
pub(crate) fn context_menu_entries(menu: &NSMenu, sent: &[MenuEntry]) -> Vec<MenuEntry> {
    fn read(menu: &NSMenu, sent: &[MenuEntry]) -> Vec<MenuEntry> {
        menu.itemArray()
            .iter()
            .map(|item| {
                if item.isSeparatorItem() {
                    return MenuEntry::Separator;
                }
                if let Some(submenu) = item.submenu() {
                    return MenuEntry::Submenu(MenuData {
                        title: item.title().to_string(),
                        entries: read(&submenu, sent),
                    });
                }
                let id = item.tag() as u32;
                let original = menu_item_by_id(sent, id);
                let on = item.state() == NSControlStateValueOn;
                let key = item.keyEquivalent().to_string();
                let mask = item.keyEquivalentModifierMask();
                MenuEntry::Item(MenuItemData {
                    id,
                    title: item.title().to_string(),
                    shortcut: key.chars().next().map(|key| Shortcut {
                        key: key_of(key),
                        primary: mask.contains(NSEventModifierFlags::Command),
                        shift: mask.contains(NSEventModifierFlags::Shift),
                        alt: mask.contains(NSEventModifierFlags::Option),
                    }),
                    enabled: item.isEnabled(),
                    check: match original.map(|s| s.check) {
                        Some(MenuCheck::Radio(_)) => MenuCheck::Radio(on),
                        Some(MenuCheck::Check(_)) => MenuCheck::Check(on),
                        _ if on => MenuCheck::Check(true),
                        _ => MenuCheck::None,
                    },
                    role: original.map(|s| s.role).unwrap_or_default(),
                })
            })
            .collect()
    }
    read(menu, sent)
}

/// The item of a context menu with this id, submenus' included, and the
/// menu holding it.
pub(crate) fn find_tagged(menu: &NSMenu, id: u32) -> Option<(Retained<NSMenuItem>, Retained<NSMenu>)> {
    menu.itemArray().iter().find_map(|item| match item.submenu() {
        Some(submenu) => find_tagged(&submenu, id),
        None if !item.isSeparatorItem() && item.tag() as u32 == id => Some((item, menu.retain())),
        None => None,
    })
}

/// The app menu, the app's File menu (if any), Edit (what makes ⌘C/⌘V/⌘Z
/// work in text fields), then the app's other menus. Items with a role go
/// to the app menu, with AppKit's titles and shortcuts, as Qt puts them,
/// and so do the items of a menu titled with the app's name.
/// Titles of our own are in the app's language (`mitsuami.ftl`), and so
/// is the File menu's, which the app's File menu is known by.
fn menu_bar(mtm: MainThreadMarker, mut menus: MenuBarData, name: &str, target: &MenuTarget) -> Retained<NSMenu> {
    let target = ItemTarget::from(target);
    let bar = NSMenu::new(mtm);
    let command = |key| Some(Shortcut::primary(key));
    let app = |id: &str| tr(id, &[("app", name.to_arg())]);
    let mut app_menu = Vec::new();
    if let Some(about) = menus.take_role(MenuRole::About) {
        app_menu.push(app_item(mtm, &about, &app("mitsuami-menu-about"), None, target));
        app_menu.push(NSMenuItem::separatorItem(mtm));
    }
    if let Some(settings) = menus.take_role(MenuRole::Settings) {
        app_menu.push(app_item(mtm, &settings, &tr("mitsuami-menu-settings", &[]), command(','), target));
        app_menu.push(NSMenuItem::separatorItem(mtm));
    }
    // The app's own menu, titled with its name, joins the app menu, where
    // macOS apps put their app-wide commands (Check for Updates…).
    let (own, others): (Vec<_>, Vec<_>) = std::mem::take(&mut menus.menus).into_iter().partition(|m| m.title == name);
    menus.menus = others;
    for menu in own {
        app_menu.extend(app_items(mtm, &menu.entries, target));
        app_menu.push(NSMenuItem::separatorItem(mtm));
    }
    app_menu.push(item(mtm, &app("mitsuami-menu-hide"), Some(sel!(hide:)), "h"));
    app_menu.push(NSMenuItem::separatorItem(mtm));
    let quit = app("mitsuami-menu-quit-app");
    app_menu.push(match menus.take_role(MenuRole::Quit) {
        Some(item) => app_item(mtm, &item, &quit, command('q'), target),
        None => item(mtm, &quit, Some(sel!(terminate:)), "q"),
    });
    bar.addItem(&menu_of(mtm, name, app_menu, true));
    let file_title = tr("mitsuami-menu-file", &[]);
    let (file, others): (Vec<_>, Vec<_>) = menus.menus.iter().partition(|m| m.title == file_title);
    for menu in file {
        bar.addItem(&menu_of(mtm, &menu.title, app_items(mtm, &menu.entries, target), false));
    }
    bar.addItem(&menu_of(
        mtm,
        &tr("mitsuami-menu-edit", &[]),
        vec![
            item(mtm, &tr("mitsuami-menu-undo", &[]), Some(sel!(undo:)), "z"),
            item(mtm, &tr("mitsuami-menu-redo", &[]), Some(sel!(redo:)), "Z"),
            NSMenuItem::separatorItem(mtm),
            item(mtm, &tr("mitsuami-menu-cut", &[]), Some(sel!(cut:)), "x"),
            item(mtm, &tr("mitsuami-menu-copy", &[]), Some(sel!(copy:)), "c"),
            item(mtm, &tr("mitsuami-menu-paste", &[]), Some(sel!(paste:)), "v"),
            item(mtm, &tr("mitsuami-menu-select-all", &[]), Some(sel!(selectAll:)), "a"),
        ],
        true,
    ));
    for menu in others {
        bar.addItem(&menu_of(mtm, &menu.title, app_items(mtm, &menu.entries, target), false));
    }
    bar
}