Skip to main content

mitsuami_appkit/
app.rs

1//! Running an app: NSApplication, the menu bar and the run-loop hook.
2
3use block2::RcBlock;
4use mitsuami_core::services::MenuBar;
5use mitsuami_core::{AppInfo, Ui};
6use objc2::rc::Retained;
7use objc2::runtime::{NSObject, NSObjectProtocol, ProtocolObject};
8use objc2::{DefinedClass, MainThreadMarker, MainThreadOnly, define_class, msg_send};
9use objc2_app_kit::{
10    NSAlert, NSAlertStyle, NSApplication, NSApplicationActivationPolicy, NSApplicationDelegate,
11    NSApplicationTerminateReply, NSEvent, NSEventModifierFlags, NSEventType,
12};
13use std::sync::Arc;
14
15use objc2_core_foundation::{
16    CFAbsoluteTimeGetCurrent, CFRunLoop, CFRunLoopActivity, CFRunLoopObserver, CFRunLoopTimer, kCFRunLoopCommonModes,
17};
18use objc2_foundation::{NSPoint, NSString};
19
20use crate::backend::{AppKitBackend, BackendOptions};
21
22/// Ends `NSApplication::run`. `stop:` only takes effect once an event has
23/// been processed, and we're in a run-loop observer rather than an event
24/// handler, so post an empty one.
25fn stop(app: &NSApplication) {
26    app.stop(None);
27    let event = NSEvent::otherEventWithType_location_modifierFlags_timestamp_windowNumber_context_subtype_data1_data2(
28        NSEventType::ApplicationDefined,
29        NSPoint::new(0.0, 0.0),
30        NSEventModifierFlags::empty(),
31        0.0,
32        0,
33        None,
34        0,
35        0,
36        0,
37    );
38    if let Some(event) = event {
39        app.postEvent_atStart(&event, true);
40    }
41}
42
43pub(crate) struct AppIvars {
44    /// Asks the app to quit, as its Quit item or its windows' close
45    /// buttons would; returns whether it did (no window is left).
46    quit: Box<dyn Fn() -> bool>,
47}
48
49define_class!(
50    /// The app's delegate, for the system's Quit.
51    #[unsafe(super(NSObject))]
52    #[thread_kind = MainThreadOnly]
53    #[ivars = AppIvars]
54    struct AppDelegate;
55
56    unsafe impl NSObjectProtocol for AppDelegate {}
57
58    unsafe impl NSApplicationDelegate for AppDelegate {
59        /// `terminate:` from anywhere: the app menu's own Quit, the Dock's,
60        /// logging out or restarting. The app decides, as for its own
61        /// Quit, and a quit it doesn't go through with is cancelled (macOS
62        /// says the app cancelled the log out, as for TextEdit with unsaved
63        /// documents). If it closed every window, the process ends here.
64        #[unsafe(method(applicationShouldTerminate:))]
65        fn application_should_terminate(&self, _sender: &NSApplication) -> NSApplicationTerminateReply {
66            if (self.ivars().quit)() {
67                NSApplicationTerminateReply::TerminateNow
68            } else {
69                NSApplicationTerminateReply::TerminateCancel
70            }
71        }
72    }
73);
74
75impl AppDelegate {
76    fn new(mtm: MainThreadMarker, quit: impl Fn() -> bool + 'static) -> Retained<AppDelegate> {
77        let this = AppDelegate::alloc(mtm).set_ivars(AppIvars { quit: Box::new(quit) });
78        unsafe { msg_send![super(this), init] }
79    }
80}
81
82/// A fire date that never comes (about 30 years out).
83const NEVER: f64 = 1.0e9;
84
85/// Safe from any thread.
86fn wake_main_run_loop() {
87    if let Some(run_loop) = CFRunLoop::main() {
88        run_loop.wake_up();
89    }
90}
91
92fn main_thread() -> MainThreadMarker {
93    MainThreadMarker::new().expect("mitsuami: AppKit must be driven from the main thread")
94}
95
96/// Tells the user the app can't run, in an app-modal critical `NSAlert`
97/// (`runModal`, which runs its own loop: there may be no window to put a
98/// sheet on), and returns once they dismiss it. The app comes to the
99/// front for it, as a launch that fails would otherwise show nothing.
100/// Off the main thread there's nothing AppKit can show, and it returns at
101/// once.
102pub fn fatal_error(title: &str, message: &str) {
103    let Some(mtm) = MainThreadMarker::new() else { return };
104    let app = NSApplication::sharedApplication(mtm);
105    app.setActivationPolicy(NSApplicationActivationPolicy::Regular);
106    app.activate();
107    let alert = NSAlert::new(mtm);
108    alert.setAlertStyle(NSAlertStyle::Critical);
109    alert.setMessageText(&NSString::from_str(title));
110    alert.setInformativeText(&NSString::from_str(message));
111    alert.runModal();
112}
113
114/// Starts the app: `setup` creates the windows, then AppKit's run loop takes
115/// over. Returns when the last window closes.
116pub fn run(info: AppInfo, setup: impl FnOnce(&Ui)) {
117    let mtm = main_thread();
118    let app = NSApplication::sharedApplication(mtm);
119    app.setActivationPolicy(NSApplicationActivationPolicy::Regular);
120
121    let backend = AppKitBackend::new(mtm, BackendOptions::default());
122    let handle = backend.handle();
123    let ui = Ui::new(backend);
124    // Before the menus, which show the name.
125    ui.set_app_info(info);
126    // The standard app and Edit menus, until the app installs its own.
127    ui.set_menu(MenuBar::new());
128    ui.set_commit_scheduler(wake_main_run_loop);
129    // Tasks woken from other threads (background work finishing) make the
130    // main run loop turn, which ticks the UI.
131    ui.set_waker(Arc::new(wake_main_run_loop));
132
133    setup(&ui);
134    ui.tick();
135    handle.show_pending_windows();
136
137    // The app's own handlers run now, in this turn: the answer is due
138    // before `applicationShouldTerminate:` returns.
139    let delegate = {
140        let (ui, handle) = (ui.clone(), handle.clone());
141        AppDelegate::new(mtm, move || {
142            ui.request_quit();
143            ui.tick();
144            handle.show_pending_windows();
145            ui.windows().is_empty()
146        })
147    };
148    app.setDelegate(Some(ProtocolObject::from_ref(&*delegate)));
149    crate::notifications::listen();
150
151    let run_loop = CFRunLoop::main().expect("main run loop");
152    // Common modes include event tracking, so live resizing relayouts too.
153    let common = unsafe { kCFRunLoopCommonModes };
154
155    // One timer, re-armed after every tick for the next `sleep` deadline.
156    // Firing just makes the loop turn; the observer below does the work.
157    let fire = RcBlock::new(|_: *mut CFRunLoopTimer| {});
158    let timer =
159        unsafe { CFRunLoopTimer::with_handler(None, NEVER, 1.0e9, 0, 0, Some(&fire)) }.expect("create run loop timer");
160    run_loop.add_timer(Some(&timer), common);
161
162    let tick = RcBlock::new(move |_: *mut CFRunLoopObserver, _: CFRunLoopActivity| {
163        ui.tick();
164        handle.show_pending_windows();
165        let next = ui.time_to_next_timer().map_or(NEVER, |d| CFAbsoluteTimeGetCurrent() + d.as_secs_f64());
166        timer.set_next_fire_date(next);
167        if ui.should_end() {
168            stop(&NSApplication::sharedApplication(main_thread()));
169        }
170    });
171    let observer =
172        unsafe { CFRunLoopObserver::with_handler(None, CFRunLoopActivity::BeforeWaiting.0, true, 0, Some(&tick)) };
173    run_loop.add_observer(observer.as_deref(), common);
174
175    app.activate();
176    app.run();
177}
178
179/// Prepares AppKit for tests: no Dock icon, no menu bar takeover.
180pub fn init_for_tests() -> MainThreadMarker {
181    let mtm = main_thread();
182    let app = NSApplication::sharedApplication(mtm);
183    app.setActivationPolicy(NSApplicationActivationPolicy::Accessory);
184    mtm
185}