use block2::RcBlock;
use mitsuami_core::services::MenuBar;
use mitsuami_core::{AppInfo, Ui};
use objc2::rc::Retained;
use objc2::runtime::{NSObject, NSObjectProtocol, ProtocolObject};
use objc2::{DefinedClass, MainThreadMarker, MainThreadOnly, define_class, msg_send};
use objc2_app_kit::{
NSAlert, NSAlertStyle, NSApplication, NSApplicationActivationPolicy, NSApplicationDelegate,
NSApplicationTerminateReply, NSEvent, NSEventModifierFlags, NSEventType,
};
use std::sync::Arc;
use objc2_core_foundation::{
CFAbsoluteTimeGetCurrent, CFRunLoop, CFRunLoopActivity, CFRunLoopObserver, CFRunLoopTimer, kCFRunLoopCommonModes,
};
use objc2_foundation::{NSPoint, NSString};
use crate::backend::{AppKitBackend, BackendOptions};
fn stop(app: &NSApplication) {
app.stop(None);
let event = NSEvent::otherEventWithType_location_modifierFlags_timestamp_windowNumber_context_subtype_data1_data2(
NSEventType::ApplicationDefined,
NSPoint::new(0.0, 0.0),
NSEventModifierFlags::empty(),
0.0,
0,
None,
0,
0,
0,
);
if let Some(event) = event {
app.postEvent_atStart(&event, true);
}
}
pub(crate) struct AppIvars {
quit: Box<dyn Fn() -> bool>,
}
define_class!(
#[unsafe(super(NSObject))]
#[thread_kind = MainThreadOnly]
#[ivars = AppIvars]
struct AppDelegate;
unsafe impl NSObjectProtocol for AppDelegate {}
unsafe impl NSApplicationDelegate for AppDelegate {
#[unsafe(method(applicationShouldTerminate:))]
fn application_should_terminate(&self, _sender: &NSApplication) -> NSApplicationTerminateReply {
if (self.ivars().quit)() {
NSApplicationTerminateReply::TerminateNow
} else {
NSApplicationTerminateReply::TerminateCancel
}
}
}
);
impl AppDelegate {
fn new(mtm: MainThreadMarker, quit: impl Fn() -> bool + 'static) -> Retained<AppDelegate> {
let this = AppDelegate::alloc(mtm).set_ivars(AppIvars { quit: Box::new(quit) });
unsafe { msg_send![super(this), init] }
}
}
const NEVER: f64 = 1.0e9;
fn wake_main_run_loop() {
if let Some(run_loop) = CFRunLoop::main() {
run_loop.wake_up();
}
}
fn main_thread() -> MainThreadMarker {
MainThreadMarker::new().expect("mitsuami: AppKit must be driven from the main thread")
}
pub fn fatal_error(title: &str, message: &str) {
let Some(mtm) = MainThreadMarker::new() else { return };
let app = NSApplication::sharedApplication(mtm);
app.setActivationPolicy(NSApplicationActivationPolicy::Regular);
app.activate();
let alert = NSAlert::new(mtm);
alert.setAlertStyle(NSAlertStyle::Critical);
alert.setMessageText(&NSString::from_str(title));
alert.setInformativeText(&NSString::from_str(message));
alert.runModal();
}
pub fn run(info: AppInfo, setup: impl FnOnce(&Ui)) {
let mtm = main_thread();
let app = NSApplication::sharedApplication(mtm);
app.setActivationPolicy(NSApplicationActivationPolicy::Regular);
let backend = AppKitBackend::new(mtm, BackendOptions::default());
let handle = backend.handle();
let ui = Ui::new(backend);
ui.set_app_info(info);
ui.set_menu(MenuBar::new());
ui.set_commit_scheduler(wake_main_run_loop);
ui.set_waker(Arc::new(wake_main_run_loop));
setup(&ui);
ui.tick();
handle.show_pending_windows();
let delegate = {
let (ui, handle) = (ui.clone(), handle.clone());
AppDelegate::new(mtm, move || {
ui.request_quit();
ui.tick();
handle.show_pending_windows();
ui.windows().is_empty()
})
};
app.setDelegate(Some(ProtocolObject::from_ref(&*delegate)));
crate::notifications::listen();
let run_loop = CFRunLoop::main().expect("main run loop");
let common = unsafe { kCFRunLoopCommonModes };
let fire = RcBlock::new(|_: *mut CFRunLoopTimer| {});
let timer =
unsafe { CFRunLoopTimer::with_handler(None, NEVER, 1.0e9, 0, 0, Some(&fire)) }.expect("create run loop timer");
run_loop.add_timer(Some(&timer), common);
let tick = RcBlock::new(move |_: *mut CFRunLoopObserver, _: CFRunLoopActivity| {
ui.tick();
handle.show_pending_windows();
let next = ui.time_to_next_timer().map_or(NEVER, |d| CFAbsoluteTimeGetCurrent() + d.as_secs_f64());
timer.set_next_fire_date(next);
if ui.should_end() {
stop(&NSApplication::sharedApplication(main_thread()));
}
});
let observer =
unsafe { CFRunLoopObserver::with_handler(None, CFRunLoopActivity::BeforeWaiting.0, true, 0, Some(&tick)) };
run_loop.add_observer(observer.as_deref(), common);
app.activate();
app.run();
}
pub fn init_for_tests() -> MainThreadMarker {
let mtm = main_thread();
let app = NSApplication::sharedApplication(mtm);
app.setActivationPolicy(NSApplicationActivationPolicy::Accessory);
mtm
}