use block2::RcBlock;
use mitsuami_core::services::{MenuBar, Reopen};
use mitsuami_core::{AppInfo, RunOptions, 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::{NSArray, NSBundle, NSNumber, NSPoint, NSString, NSURL};
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
}
}
#[unsafe(method(applicationShouldHandleReopen:hasVisibleWindows:))]
fn application_should_handle_reopen(&self, _sender: &NSApplication, _visible: bool) -> bool {
crate::instance::reopened(Reopen::default());
true
}
#[unsafe(method(application:openURLs:))]
fn application_open_urls(&self, _application: &NSApplication, urls: &NSArray<NSURL>) {
let files: Vec<_> = urls
.iter()
.filter(|url| url.isFileURL())
.filter_map(|url| url.path())
.map(|path| std::path::PathBuf::from(path.to_string()))
.collect();
if !files.is_empty() {
crate::instance::reopened(Reopen::new(Vec::new(), None, files));
}
}
}
);
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)) {
run_with(info, RunOptions::default(), setup);
}
pub fn run_with(info: AppInfo, options: RunOptions, setup: impl FnOnce(&Ui)) {
let mtm = main_thread();
if options.single_instance
&& let Some(id) = &info.id
&& !crate::instance::claim(id)
{
return;
}
let app = NSApplication::sharedApplication(mtm);
let ui_element = NSBundle::mainBundle()
.objectForInfoDictionaryKey(&NSString::from_str("LSUIElement"))
.and_then(|value| value.downcast::<NSNumber>().ok())
.is_some_and(|value| value.boolValue());
if !ui_element {
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));
crate::instance::connect({
let weak = ui.downgrade();
std::rc::Rc::new(move |reopen| {
if let Some(ui) = weak.upgrade() {
ui.reopen(reopen);
}
})
});
setup(&ui);
ui.tick();
handle.show_pending_windows();
let ui_was_empty = ui.windows().is_empty();
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);
if !ui_was_empty {
app.activate();
}
app.run();
}
pub fn init_for_tests() -> MainThreadMarker {
let mtm = main_thread();
let app = NSApplication::sharedApplication(mtm);
app.setActivationPolicy(NSApplicationActivationPolicy::Accessory);
mtm
}