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    NSApplication, NSApplicationActivationPolicy, NSApplicationDelegate, NSApplicationTerminateReply, NSEvent,
11    NSEventModifierFlags, NSEventType,
12};
13use std::sync::Arc;
14
15use objc2_core_foundation::{
16    CFAbsoluteTimeGetCurrent, CFRunLoop, CFRunLoopActivity, CFRunLoopObserver, CFRunLoopTimer, kCFRunLoopCommonModes,
17};
18use objc2_foundation::NSPoint;
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/// Starts the app: `setup` creates the windows, then AppKit's run loop takes
97/// over. Returns when the last window closes.
98pub fn run(info: AppInfo, setup: impl FnOnce(&Ui)) {
99    let mtm = main_thread();
100    let app = NSApplication::sharedApplication(mtm);
101    app.setActivationPolicy(NSApplicationActivationPolicy::Regular);
102
103    let backend = AppKitBackend::new(mtm, BackendOptions::default());
104    let handle = backend.handle();
105    let ui = Ui::new(backend);
106    // Before the menus, which show the name.
107    ui.set_app_info(info);
108    // The standard app and Edit menus, until the app installs its own.
109    ui.set_menu(MenuBar::new());
110    ui.set_commit_scheduler(wake_main_run_loop);
111    // Tasks woken from other threads (background work finishing) make the
112    // main run loop turn, which ticks the UI.
113    ui.set_waker(Arc::new(wake_main_run_loop));
114
115    setup(&ui);
116    ui.tick();
117    handle.show_pending_windows();
118
119    // The app's own handlers run now, in this turn: the answer is due
120    // before `applicationShouldTerminate:` returns.
121    let delegate = {
122        let (ui, handle) = (ui.clone(), handle.clone());
123        AppDelegate::new(mtm, move || {
124            ui.request_quit();
125            ui.tick();
126            handle.show_pending_windows();
127            ui.windows().is_empty()
128        })
129    };
130    app.setDelegate(Some(ProtocolObject::from_ref(&*delegate)));
131
132    let run_loop = CFRunLoop::main().expect("main run loop");
133    // Common modes include event tracking, so live resizing relayouts too.
134    let common = unsafe { kCFRunLoopCommonModes };
135
136    // One timer, re-armed after every tick for the next `sleep` deadline.
137    // Firing just makes the loop turn; the observer below does the work.
138    let fire = RcBlock::new(|_: *mut CFRunLoopTimer| {});
139    let timer =
140        unsafe { CFRunLoopTimer::with_handler(None, NEVER, 1.0e9, 0, 0, Some(&fire)) }.expect("create run loop timer");
141    run_loop.add_timer(Some(&timer), common);
142
143    let tick = RcBlock::new(move |_: *mut CFRunLoopObserver, _: CFRunLoopActivity| {
144        ui.tick();
145        handle.show_pending_windows();
146        let next = ui.time_to_next_timer().map_or(NEVER, |d| CFAbsoluteTimeGetCurrent() + d.as_secs_f64());
147        timer.set_next_fire_date(next);
148        if ui.windows().is_empty() {
149            stop(&NSApplication::sharedApplication(main_thread()));
150        }
151    });
152    let observer =
153        unsafe { CFRunLoopObserver::with_handler(None, CFRunLoopActivity::BeforeWaiting.0, true, 0, Some(&tick)) };
154    run_loop.add_observer(observer.as_deref(), common);
155
156    app.activate();
157    app.run();
158}
159
160/// Prepares AppKit for tests: no Dock icon, no menu bar takeover.
161pub fn init_for_tests() -> MainThreadMarker {
162    let mtm = main_thread();
163    let app = NSApplication::sharedApplication(mtm);
164    app.setActivationPolicy(NSApplicationActivationPolicy::Accessory);
165    mtm
166}