1use 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
22fn 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 quit: Box<dyn Fn() -> bool>,
47}
48
49define_class!(
50 #[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 #[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
82const NEVER: f64 = 1.0e9;
84
85fn 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
96pub 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
114pub 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 ui.set_app_info(info);
126 ui.set_menu(MenuBar::new());
128 ui.set_commit_scheduler(wake_main_run_loop);
129 ui.set_waker(Arc::new(wake_main_run_loop));
132
133 setup(&ui);
134 ui.tick();
135 handle.show_pending_windows();
136
137 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 let common = unsafe { kCFRunLoopCommonModes };
154
155 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.windows().is_empty() {
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
179pub fn init_for_tests() -> MainThreadMarker {
181 let mtm = main_thread();
182 let app = NSApplication::sharedApplication(mtm);
183 app.setActivationPolicy(NSApplicationActivationPolicy::Accessory);
184 mtm
185}