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, Reopen};
5use mitsuami_core::{AppInfo, RunOptions, 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::{NSArray, NSBundle, NSNumber, NSPoint, NSString, NSURL};
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 and later launches.
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        /// Launched again (a second `open`, a click on its Dock icon):
74        /// AppKit brings a window forward, restoring a minimized one, and
75        /// the app hears.
76        #[unsafe(method(applicationShouldHandleReopen:hasVisibleWindows:))]
77        fn application_should_handle_reopen(&self, _sender: &NSApplication, _visible: bool) -> bool {
78            crate::instance::reopened(Reopen::default());
79            true
80        }
81
82        /// Files from Finder (Open With, a drop on the Dock icon), at
83        /// launch or later.
84        #[unsafe(method(application:openURLs:))]
85        fn application_open_urls(&self, _application: &NSApplication, urls: &NSArray<NSURL>) {
86            let files: Vec<_> = urls
87                .iter()
88                .filter(|url| url.isFileURL())
89                .filter_map(|url| url.path())
90                .map(|path| std::path::PathBuf::from(path.to_string()))
91                .collect();
92            if !files.is_empty() {
93                crate::instance::reopened(Reopen::new(Vec::new(), None, files));
94            }
95        }
96    }
97);
98
99impl AppDelegate {
100    fn new(mtm: MainThreadMarker, quit: impl Fn() -> bool + 'static) -> Retained<AppDelegate> {
101        let this = AppDelegate::alloc(mtm).set_ivars(AppIvars { quit: Box::new(quit) });
102        unsafe { msg_send![super(this), init] }
103    }
104}
105
106/// A fire date that never comes (about 30 years out).
107const NEVER: f64 = 1.0e9;
108
109/// Safe from any thread.
110fn wake_main_run_loop() {
111    if let Some(run_loop) = CFRunLoop::main() {
112        run_loop.wake_up();
113    }
114}
115
116fn main_thread() -> MainThreadMarker {
117    MainThreadMarker::new().expect("mitsuami: AppKit must be driven from the main thread")
118}
119
120/// Tells the user the app can't run, in an app-modal critical `NSAlert`
121/// (`runModal`, which runs its own loop: there may be no window to put a
122/// sheet on), and returns once they dismiss it. The app comes to the
123/// front for it, as a launch that fails would otherwise show nothing.
124/// Off the main thread there's nothing AppKit can show, and it returns at
125/// once.
126pub fn fatal_error(title: &str, message: &str) {
127    let Some(mtm) = MainThreadMarker::new() else { return };
128    let app = NSApplication::sharedApplication(mtm);
129    app.setActivationPolicy(NSApplicationActivationPolicy::Regular);
130    app.activate();
131    let alert = NSAlert::new(mtm);
132    alert.setAlertStyle(NSAlertStyle::Critical);
133    alert.setMessageText(&NSString::from_str(title));
134    alert.setInformativeText(&NSString::from_str(message));
135    alert.runModal();
136}
137
138/// Starts the app: `setup` creates the windows, then AppKit's run loop takes
139/// over. Returns when the last window closes.
140pub fn run(info: AppInfo, setup: impl FnOnce(&Ui)) {
141    run_with(info, RunOptions::default(), setup);
142}
143
144/// [`run`], with options. Launch Services keeps a bundled app to one
145/// process already; for a single-instance app, a process it didn't start
146/// (run from a terminal, or outside a bundle) hands its launch to the
147/// running one over a Unix socket and returns.
148pub fn run_with(info: AppInfo, options: RunOptions, setup: impl FnOnce(&Ui)) {
149    let mtm = main_thread();
150    if options.single_instance
151        && let Some(id) = &info.id
152        && !crate::instance::claim(id)
153    {
154        return;
155    }
156    let app = NSApplication::sharedApplication(mtm);
157    // A bundle with `LSUIElement` (a menu bar app) has said it wants no
158    // Dock icon: Launch Services set its policy already.
159    let ui_element = NSBundle::mainBundle()
160        .objectForInfoDictionaryKey(&NSString::from_str("LSUIElement"))
161        .and_then(|value| value.downcast::<NSNumber>().ok())
162        .is_some_and(|value| value.boolValue());
163    if !ui_element {
164        app.setActivationPolicy(NSApplicationActivationPolicy::Regular);
165    }
166
167    let backend = AppKitBackend::new(mtm, BackendOptions::default());
168    let handle = backend.handle();
169    let ui = Ui::new(backend);
170    // Before the menus, which show the name.
171    ui.set_app_info(info);
172    // The standard app and Edit menus, until the app installs its own.
173    ui.set_menu(MenuBar::new());
174    ui.set_commit_scheduler(wake_main_run_loop);
175    // Tasks woken from other threads (background work finishing) make the
176    // main run loop turn, which ticks the UI.
177    ui.set_waker(Arc::new(wake_main_run_loop));
178
179    crate::instance::connect({
180        let weak = ui.downgrade();
181        std::rc::Rc::new(move |reopen| {
182            if let Some(ui) = weak.upgrade() {
183                ui.reopen(reopen);
184            }
185        })
186    });
187    setup(&ui);
188    ui.tick();
189    handle.show_pending_windows();
190    let ui_was_empty = ui.windows().is_empty();
191
192    // The app's own handlers run now, in this turn: the answer is due
193    // before `applicationShouldTerminate:` returns.
194    let delegate = {
195        let (ui, handle) = (ui.clone(), handle.clone());
196        AppDelegate::new(mtm, move || {
197            ui.request_quit();
198            ui.tick();
199            handle.show_pending_windows();
200            ui.windows().is_empty()
201        })
202    };
203    app.setDelegate(Some(ProtocolObject::from_ref(&*delegate)));
204    crate::notifications::listen();
205
206    let run_loop = CFRunLoop::main().expect("main run loop");
207    // Common modes include event tracking, so live resizing relayouts too.
208    let common = unsafe { kCFRunLoopCommonModes };
209
210    // One timer, re-armed after every tick for the next `sleep` deadline.
211    // Firing just makes the loop turn; the observer below does the work.
212    let fire = RcBlock::new(|_: *mut CFRunLoopTimer| {});
213    let timer =
214        unsafe { CFRunLoopTimer::with_handler(None, NEVER, 1.0e9, 0, 0, Some(&fire)) }.expect("create run loop timer");
215    run_loop.add_timer(Some(&timer), common);
216
217    let tick = RcBlock::new(move |_: *mut CFRunLoopObserver, _: CFRunLoopActivity| {
218        ui.tick();
219        handle.show_pending_windows();
220        let next = ui.time_to_next_timer().map_or(NEVER, |d| CFAbsoluteTimeGetCurrent() + d.as_secs_f64());
221        timer.set_next_fire_date(next);
222        if ui.should_end() {
223            stop(&NSApplication::sharedApplication(main_thread()));
224        }
225    });
226    let observer =
227        unsafe { CFRunLoopObserver::with_handler(None, CFRunLoopActivity::BeforeWaiting.0, true, 0, Some(&tick)) };
228    run_loop.add_observer(observer.as_deref(), common);
229
230    // An app that starts with no window (one that runs in the background,
231    // perhaps started at login) doesn't take the focus.
232    if !ui_was_empty {
233        app.activate();
234    }
235    app.run();
236}
237
238/// Prepares AppKit for tests: no Dock icon, no menu bar takeover.
239pub fn init_for_tests() -> MainThreadMarker {
240    let mtm = main_thread();
241    let app = NSApplication::sharedApplication(mtm);
242    app.setActivationPolicy(NSApplicationActivationPolicy::Accessory);
243    mtm
244}