mitsuami-appkit 2.5.1

AppKit (macOS) backend for mitsuami
Documentation
//! Running an app: NSApplication, the menu bar and the run-loop hook.

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};

/// Ends `NSApplication::run`. `stop:` only takes effect once an event has
/// been processed, and we're in a run-loop observer rather than an event
/// handler, so post an empty one.
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 {
    /// Asks the app to quit, as its Quit item or its windows' close
    /// buttons would; returns whether it did (no window is left).
    quit: Box<dyn Fn() -> bool>,
}

define_class!(
    /// The app's delegate, for the system's Quit and later launches.
    #[unsafe(super(NSObject))]
    #[thread_kind = MainThreadOnly]
    #[ivars = AppIvars]
    struct AppDelegate;

    unsafe impl NSObjectProtocol for AppDelegate {}

    unsafe impl NSApplicationDelegate for AppDelegate {
        /// `terminate:` from anywhere: the app menu's own Quit, the Dock's,
        /// logging out or restarting. The app decides, as for its own
        /// Quit, and a quit it doesn't go through with is cancelled (macOS
        /// says the app cancelled the log out, as for TextEdit with unsaved
        /// documents). If it closed every window, the process ends here.
        #[unsafe(method(applicationShouldTerminate:))]
        fn application_should_terminate(&self, _sender: &NSApplication) -> NSApplicationTerminateReply {
            if (self.ivars().quit)() {
                NSApplicationTerminateReply::TerminateNow
            } else {
                NSApplicationTerminateReply::TerminateCancel
            }
        }

        /// Launched again (a second `open`, a click on its Dock icon):
        /// AppKit brings a window forward, restoring a minimized one, and
        /// the app hears.
        #[unsafe(method(applicationShouldHandleReopen:hasVisibleWindows:))]
        fn application_should_handle_reopen(&self, _sender: &NSApplication, _visible: bool) -> bool {
            crate::instance::reopened(Reopen::default());
            true
        }

        /// Files from Finder (Open With, a drop on the Dock icon), at
        /// launch or later.
        #[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] }
    }
}

/// A fire date that never comes (about 30 years out).
const NEVER: f64 = 1.0e9;

/// Safe from any thread.
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")
}

/// Tells the user the app can't run, in an app-modal critical `NSAlert`
/// (`runModal`, which runs its own loop: there may be no window to put a
/// sheet on), and returns once they dismiss it. The app comes to the
/// front for it, as a launch that fails would otherwise show nothing.
/// Off the main thread there's nothing AppKit can show, and it returns at
/// once.
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();
}

/// Starts the app: `setup` creates the windows, then AppKit's run loop takes
/// over. Returns when the last window closes.
pub fn run(info: AppInfo, setup: impl FnOnce(&Ui)) {
    run_with(info, RunOptions::default(), setup);
}

/// [`run`], with options. Launch Services keeps a bundled app to one
/// process already; for a single-instance app, a process it didn't start
/// (run from a terminal, or outside a bundle) hands its launch to the
/// running one over a Unix socket and returns.
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);
    // A bundle with `LSUIElement` (a menu bar app) has said it wants no
    // Dock icon: Launch Services set its policy already.
    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);
    // Before the menus, which show the name.
    ui.set_app_info(info);
    // The standard app and Edit menus, until the app installs its own.
    ui.set_menu(MenuBar::new());
    ui.set_commit_scheduler(wake_main_run_loop);
    // Tasks woken from other threads (background work finishing) make the
    // main run loop turn, which ticks the UI.
    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();

    // The app's own handlers run now, in this turn: the answer is due
    // before `applicationShouldTerminate:` returns.
    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");
    // Common modes include event tracking, so live resizing relayouts too.
    let common = unsafe { kCFRunLoopCommonModes };

    // One timer, re-armed after every tick for the next `sleep` deadline.
    // Firing just makes the loop turn; the observer below does the work.
    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);

    // An app that starts with no window (one that runs in the background,
    // perhaps started at login) doesn't take the focus.
    if !ui_was_empty {
        app.activate();
    }
    app.run();
}

/// Prepares AppKit for tests: no Dock icon, no menu bar takeover.
pub fn init_for_tests() -> MainThreadMarker {
    let mtm = main_thread();
    let app = NSApplication::sharedApplication(mtm);
    app.setActivationPolicy(NSApplicationActivationPolicy::Accessory);
    mtm
}