1use 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
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 #[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 #[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
106const NEVER: f64 = 1.0e9;
108
109fn 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
120pub 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
138pub fn run(info: AppInfo, setup: impl FnOnce(&Ui)) {
141 run_with(info, RunOptions::default(), setup);
142}
143
144pub 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 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 ui.set_app_info(info);
172 ui.set_menu(MenuBar::new());
174 ui.set_commit_scheduler(wake_main_run_loop);
175 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 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 let common = unsafe { kCFRunLoopCommonModes };
209
210 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 if !ui_was_empty {
233 app.activate();
234 }
235 app.run();
236}
237
238pub fn init_for_tests() -> MainThreadMarker {
240 let mtm = main_thread();
241 let app = NSApplication::sharedApplication(mtm);
242 app.setActivationPolicy(NSApplicationActivationPolicy::Accessory);
243 mtm
244}