platform.rs

   1use crate::{
   2    BoolExt, MacDispatcher, MacDisplay, MacKeyboardLayout, MacKeyboardMapper, MacWindow,
   3    events::key_to_native, ns_string, pasteboard::Pasteboard, renderer,
   4};
   5use anyhow::{Context as _, anyhow};
   6use block::ConcreteBlock;
   7use cocoa::{
   8    appkit::{
   9        NSApplication, NSApplicationActivationPolicy::NSApplicationActivationPolicyRegular,
  10        NSEventModifierFlags, NSMenu, NSMenuItem, NSModalResponse, NSOpenPanel, NSSavePanel,
  11        NSVisualEffectState, NSVisualEffectView, NSWindow,
  12    },
  13    base::{BOOL, NO, YES, id, nil, selector},
  14    foundation::{
  15        NSArray, NSAutoreleasePool, NSBundle, NSInteger, NSProcessInfo, NSString, NSUInteger, NSURL,
  16    },
  17};
  18use core_foundation::{
  19    base::{CFRelease, CFType, CFTypeRef, OSStatus, TCFType},
  20    boolean::CFBoolean,
  21    data::CFData,
  22    dictionary::{CFDictionary, CFDictionaryRef, CFMutableDictionary},
  23    runloop::CFRunLoopRun,
  24    string::{CFString, CFStringRef},
  25};
  26use ctor::ctor;
  27use futures::channel::oneshot;
  28use gpui::{
  29    Action, AnyWindowHandle, BackgroundExecutor, ClipboardItem, CursorStyle, ForegroundExecutor,
  30    KeyContext, Keymap, Menu, MenuItem, OsMenu, OwnedMenu, PathPromptOptions, Platform,
  31    PlatformDisplay, PlatformKeyboardLayout, PlatformKeyboardMapper, PlatformTextSystem,
  32    PlatformWindow, Result, SystemMenuType, Task, ThermalState, WindowAppearance, WindowParams,
  33};
  34use itertools::Itertools;
  35use objc::{
  36    class,
  37    declare::ClassDecl,
  38    msg_send,
  39    runtime::{Class, Object, Sel},
  40    sel, sel_impl,
  41};
  42use parking_lot::Mutex;
  43use ptr::null_mut;
  44use semver::Version;
  45use std::{
  46    cell::Cell,
  47    ffi::{CStr, OsStr, c_void},
  48    os::{raw::c_char, unix::ffi::OsStrExt},
  49    path::{Path, PathBuf},
  50    ptr,
  51    rc::Rc,
  52    slice, str,
  53    sync::{Arc, OnceLock},
  54};
  55use util::{
  56    ResultExt,
  57    command::{new_command, new_std_command},
  58};
  59
  60#[allow(non_upper_case_globals)]
  61const NSUTF8StringEncoding: NSUInteger = 4;
  62
  63const MAC_PLATFORM_IVAR: &str = "platform";
  64static mut APP_CLASS: *const Class = ptr::null();
  65static mut APP_DELEGATE_CLASS: *const Class = ptr::null();
  66
  67#[ctor]
  68unsafe fn build_classes() {
  69    unsafe {
  70        APP_CLASS = {
  71            let mut decl = ClassDecl::new("GPUIApplication", class!(NSApplication)).unwrap();
  72            decl.add_ivar::<*mut c_void>(MAC_PLATFORM_IVAR);
  73            decl.register()
  74        }
  75    };
  76    unsafe {
  77        APP_DELEGATE_CLASS = unsafe {
  78            let mut decl = ClassDecl::new("GPUIApplicationDelegate", class!(NSResponder)).unwrap();
  79            decl.add_ivar::<*mut c_void>(MAC_PLATFORM_IVAR);
  80            decl.add_method(
  81                sel!(applicationWillFinishLaunching:),
  82                will_finish_launching as extern "C" fn(&mut Object, Sel, id),
  83            );
  84            decl.add_method(
  85                sel!(applicationDidFinishLaunching:),
  86                did_finish_launching as extern "C" fn(&mut Object, Sel, id),
  87            );
  88            decl.add_method(
  89                sel!(applicationShouldHandleReopen:hasVisibleWindows:),
  90                should_handle_reopen as extern "C" fn(&mut Object, Sel, id, bool),
  91            );
  92            decl.add_method(
  93                sel!(applicationWillTerminate:),
  94                will_terminate as extern "C" fn(&mut Object, Sel, id),
  95            );
  96            decl.add_method(
  97                sel!(handleGPUIMenuItem:),
  98                handle_menu_item as extern "C" fn(&mut Object, Sel, id),
  99            );
 100            // Add menu item handlers so that OS save panels have the correct key commands
 101            decl.add_method(
 102                sel!(cut:),
 103                handle_menu_item as extern "C" fn(&mut Object, Sel, id),
 104            );
 105            decl.add_method(
 106                sel!(copy:),
 107                handle_menu_item as extern "C" fn(&mut Object, Sel, id),
 108            );
 109            decl.add_method(
 110                sel!(paste:),
 111                handle_menu_item as extern "C" fn(&mut Object, Sel, id),
 112            );
 113            decl.add_method(
 114                sel!(selectAll:),
 115                handle_menu_item as extern "C" fn(&mut Object, Sel, id),
 116            );
 117            decl.add_method(
 118                sel!(undo:),
 119                handle_menu_item as extern "C" fn(&mut Object, Sel, id),
 120            );
 121            decl.add_method(
 122                sel!(redo:),
 123                handle_menu_item as extern "C" fn(&mut Object, Sel, id),
 124            );
 125            decl.add_method(
 126                sel!(validateMenuItem:),
 127                validate_menu_item as extern "C" fn(&mut Object, Sel, id) -> bool,
 128            );
 129            decl.add_method(
 130                sel!(menuWillOpen:),
 131                menu_will_open as extern "C" fn(&mut Object, Sel, id),
 132            );
 133            decl.add_method(
 134                sel!(applicationDockMenu:),
 135                handle_dock_menu as extern "C" fn(&mut Object, Sel, id) -> id,
 136            );
 137            decl.add_method(
 138                sel!(application:openURLs:),
 139                open_urls as extern "C" fn(&mut Object, Sel, id, id),
 140            );
 141
 142            decl.add_method(
 143                sel!(onKeyboardLayoutChange:),
 144                on_keyboard_layout_change as extern "C" fn(&mut Object, Sel, id),
 145            );
 146
 147            decl.add_method(
 148                sel!(onThermalStateChange:),
 149                on_thermal_state_change as extern "C" fn(&mut Object, Sel, id),
 150            );
 151
 152            decl.register()
 153        }
 154    }
 155}
 156
 157pub struct MacPlatform(Mutex<MacPlatformState>);
 158
 159pub(crate) struct MacPlatformState {
 160    background_executor: BackgroundExecutor,
 161    foreground_executor: ForegroundExecutor,
 162    text_system: Arc<dyn PlatformTextSystem>,
 163    renderer_context: renderer::Context,
 164    headless: bool,
 165    general_pasteboard: Pasteboard,
 166    find_pasteboard: Pasteboard,
 167    reopen: Option<Box<dyn FnMut()>>,
 168    on_keyboard_layout_change: Option<Box<dyn FnMut()>>,
 169    on_thermal_state_change: Option<Box<dyn FnMut()>>,
 170    quit: Option<Box<dyn FnMut()>>,
 171    menu_command: Option<Box<dyn FnMut(&dyn Action)>>,
 172    validate_menu_command: Option<Box<dyn FnMut(&dyn Action) -> bool>>,
 173    will_open_menu: Option<Box<dyn FnMut()>>,
 174    menu_actions: Vec<Box<dyn Action>>,
 175    open_urls: Option<Box<dyn FnMut(Vec<String>)>>,
 176    finish_launching: Option<Box<dyn FnOnce()>>,
 177    dock_menu: Option<id>,
 178    menus: Option<Vec<OwnedMenu>>,
 179    keyboard_mapper: Rc<MacKeyboardMapper>,
 180}
 181
 182impl MacPlatform {
 183    pub fn new(headless: bool) -> Self {
 184        let dispatcher = Arc::new(MacDispatcher::new());
 185
 186        #[cfg(feature = "font-kit")]
 187        let text_system = Arc::new(crate::MacTextSystem::new());
 188
 189        #[cfg(not(feature = "font-kit"))]
 190        let text_system = Arc::new(gpui::NoopTextSystem::new());
 191
 192        let keyboard_layout = MacKeyboardLayout::new();
 193        let keyboard_mapper = Rc::new(MacKeyboardMapper::new(keyboard_layout.id()));
 194
 195        Self(Mutex::new(MacPlatformState {
 196            headless,
 197            text_system,
 198            background_executor: BackgroundExecutor::new(dispatcher.clone()),
 199            foreground_executor: ForegroundExecutor::new(dispatcher),
 200            renderer_context: renderer::Context::default(),
 201            general_pasteboard: Pasteboard::general(),
 202            find_pasteboard: Pasteboard::find(),
 203            reopen: None,
 204            quit: None,
 205            menu_command: None,
 206            validate_menu_command: None,
 207            will_open_menu: None,
 208            menu_actions: Default::default(),
 209            open_urls: None,
 210            finish_launching: None,
 211            dock_menu: None,
 212            on_keyboard_layout_change: None,
 213            on_thermal_state_change: None,
 214            menus: None,
 215            keyboard_mapper,
 216        }))
 217    }
 218
 219    unsafe fn create_menu_bar(
 220        &self,
 221        menus: &Vec<Menu>,
 222        delegate: id,
 223        actions: &mut Vec<Box<dyn Action>>,
 224        keymap: &Keymap,
 225    ) -> id {
 226        unsafe {
 227            let application_menu = NSMenu::new(nil).autorelease();
 228            application_menu.setDelegate_(delegate);
 229
 230            for menu_config in menus {
 231                let menu = NSMenu::new(nil).autorelease();
 232                let menu_title = ns_string(&menu_config.name);
 233                menu.setTitle_(menu_title);
 234                menu.setDelegate_(delegate);
 235
 236                for item_config in &menu_config.items {
 237                    menu.addItem_(Self::create_menu_item(
 238                        item_config,
 239                        delegate,
 240                        actions,
 241                        keymap,
 242                    ));
 243                }
 244
 245                let menu_item = NSMenuItem::new(nil).autorelease();
 246                menu_item.setTitle_(menu_title);
 247                menu_item.setSubmenu_(menu);
 248                application_menu.addItem_(menu_item);
 249
 250                if menu_config.name == "Window" {
 251                    let app: id = msg_send![APP_CLASS, sharedApplication];
 252                    app.setWindowsMenu_(menu);
 253                }
 254            }
 255
 256            application_menu
 257        }
 258    }
 259
 260    unsafe fn create_dock_menu(
 261        &self,
 262        menu_items: Vec<MenuItem>,
 263        delegate: id,
 264        actions: &mut Vec<Box<dyn Action>>,
 265        keymap: &Keymap,
 266    ) -> id {
 267        unsafe {
 268            let dock_menu = NSMenu::new(nil);
 269            dock_menu.setDelegate_(delegate);
 270            for item_config in menu_items {
 271                dock_menu.addItem_(Self::create_menu_item(
 272                    &item_config,
 273                    delegate,
 274                    actions,
 275                    keymap,
 276                ));
 277            }
 278
 279            dock_menu
 280        }
 281    }
 282
 283    unsafe fn create_menu_item(
 284        item: &MenuItem,
 285        delegate: id,
 286        actions: &mut Vec<Box<dyn Action>>,
 287        keymap: &Keymap,
 288    ) -> id {
 289        static DEFAULT_CONTEXT: OnceLock<Vec<KeyContext>> = OnceLock::new();
 290
 291        unsafe {
 292            match item {
 293                MenuItem::Separator => NSMenuItem::separatorItem(nil),
 294                MenuItem::Action {
 295                    name,
 296                    action,
 297                    os_action,
 298                    checked,
 299                } => {
 300                    // Note that this is intentionally using earlier bindings, whereas typically
 301                    // later ones take display precedence. See the discussion on
 302                    // https://github.com/zed-industries/zed/issues/23621
 303                    let keystrokes = keymap
 304                        .bindings_for_action(action.as_ref())
 305                        .find_or_first(|binding| {
 306                            binding.predicate().is_none_or(|predicate| {
 307                                predicate.eval(DEFAULT_CONTEXT.get_or_init(|| {
 308                                    let mut workspace_context = KeyContext::new_with_defaults();
 309                                    workspace_context.add("Workspace");
 310                                    let mut pane_context = KeyContext::new_with_defaults();
 311                                    pane_context.add("Pane");
 312                                    let mut editor_context = KeyContext::new_with_defaults();
 313                                    editor_context.add("Editor");
 314
 315                                    pane_context.extend(&editor_context);
 316                                    workspace_context.extend(&pane_context);
 317                                    vec![workspace_context]
 318                                }))
 319                            })
 320                        })
 321                        .map(|binding| binding.keystrokes());
 322
 323                    let selector = match os_action {
 324                        Some(gpui::OsAction::Cut) => selector("cut:"),
 325                        Some(gpui::OsAction::Copy) => selector("copy:"),
 326                        Some(gpui::OsAction::Paste) => selector("paste:"),
 327                        Some(gpui::OsAction::SelectAll) => selector("selectAll:"),
 328                        // "undo:" and "redo:" are always disabled in our case, as
 329                        // we don't have a NSTextView/NSTextField to enable them on.
 330                        Some(gpui::OsAction::Undo) => selector("handleGPUIMenuItem:"),
 331                        Some(gpui::OsAction::Redo) => selector("handleGPUIMenuItem:"),
 332                        None => selector("handleGPUIMenuItem:"),
 333                    };
 334
 335                    let item;
 336                    if let Some(keystrokes) = keystrokes {
 337                        if keystrokes.len() == 1 {
 338                            let keystroke = &keystrokes[0];
 339                            let mut mask = NSEventModifierFlags::empty();
 340                            for (modifier, flag) in &[
 341                                (
 342                                    keystroke.modifiers().platform,
 343                                    NSEventModifierFlags::NSCommandKeyMask,
 344                                ),
 345                                (
 346                                    keystroke.modifiers().control,
 347                                    NSEventModifierFlags::NSControlKeyMask,
 348                                ),
 349                                (
 350                                    keystroke.modifiers().alt,
 351                                    NSEventModifierFlags::NSAlternateKeyMask,
 352                                ),
 353                                (
 354                                    keystroke.modifiers().shift,
 355                                    NSEventModifierFlags::NSShiftKeyMask,
 356                                ),
 357                            ] {
 358                                if *modifier {
 359                                    mask |= *flag;
 360                                }
 361                            }
 362
 363                            item = NSMenuItem::alloc(nil)
 364                                .initWithTitle_action_keyEquivalent_(
 365                                    ns_string(name),
 366                                    selector,
 367                                    ns_string(key_to_native(keystroke.key()).as_ref()),
 368                                )
 369                                .autorelease();
 370                            if Self::os_version() >= Version::new(12, 0, 0) {
 371                                let _: () = msg_send![item, setAllowsAutomaticKeyEquivalentLocalization: NO];
 372                            }
 373                            item.setKeyEquivalentModifierMask_(mask);
 374                        } else {
 375                            item = NSMenuItem::alloc(nil)
 376                                .initWithTitle_action_keyEquivalent_(
 377                                    ns_string(name),
 378                                    selector,
 379                                    ns_string(""),
 380                                )
 381                                .autorelease();
 382                        }
 383                    } else {
 384                        item = NSMenuItem::alloc(nil)
 385                            .initWithTitle_action_keyEquivalent_(
 386                                ns_string(name),
 387                                selector,
 388                                ns_string(""),
 389                            )
 390                            .autorelease();
 391                    }
 392
 393                    if *checked {
 394                        item.setState_(NSVisualEffectState::Active);
 395                    }
 396
 397                    let tag = actions.len() as NSInteger;
 398                    let _: () = msg_send![item, setTag: tag];
 399                    actions.push(action.boxed_clone());
 400                    item
 401                }
 402                MenuItem::Submenu(Menu { name, items }) => {
 403                    let item = NSMenuItem::new(nil).autorelease();
 404                    let submenu = NSMenu::new(nil).autorelease();
 405                    submenu.setDelegate_(delegate);
 406                    for item in items {
 407                        submenu.addItem_(Self::create_menu_item(item, delegate, actions, keymap));
 408                    }
 409                    item.setSubmenu_(submenu);
 410                    item.setTitle_(ns_string(name));
 411                    item
 412                }
 413                MenuItem::SystemMenu(OsMenu { name, menu_type }) => {
 414                    let item = NSMenuItem::new(nil).autorelease();
 415                    let submenu = NSMenu::new(nil).autorelease();
 416                    submenu.setDelegate_(delegate);
 417                    item.setSubmenu_(submenu);
 418                    item.setTitle_(ns_string(name));
 419
 420                    match menu_type {
 421                        SystemMenuType::Services => {
 422                            let app: id = msg_send![APP_CLASS, sharedApplication];
 423                            app.setServicesMenu_(item);
 424                        }
 425                    }
 426
 427                    item
 428                }
 429            }
 430        }
 431    }
 432
 433    fn os_version() -> Version {
 434        let version = unsafe {
 435            let process_info = NSProcessInfo::processInfo(nil);
 436            process_info.operatingSystemVersion()
 437        };
 438        Version::new(
 439            version.majorVersion,
 440            version.minorVersion,
 441            version.patchVersion,
 442        )
 443    }
 444}
 445
 446impl Platform for MacPlatform {
 447    fn background_executor(&self) -> BackgroundExecutor {
 448        self.0.lock().background_executor.clone()
 449    }
 450
 451    fn foreground_executor(&self) -> gpui::ForegroundExecutor {
 452        self.0.lock().foreground_executor.clone()
 453    }
 454
 455    fn text_system(&self) -> Arc<dyn PlatformTextSystem> {
 456        self.0.lock().text_system.clone()
 457    }
 458
 459    fn run(&self, on_finish_launching: Box<dyn FnOnce()>) {
 460        let mut state = self.0.lock();
 461        if state.headless {
 462            drop(state);
 463            on_finish_launching();
 464            unsafe { CFRunLoopRun() };
 465        } else {
 466            state.finish_launching = Some(on_finish_launching);
 467            drop(state);
 468        }
 469
 470        unsafe {
 471            let app: id = msg_send![APP_CLASS, sharedApplication];
 472            let app_delegate: id = msg_send![APP_DELEGATE_CLASS, new];
 473            app.setDelegate_(app_delegate);
 474
 475            let self_ptr = self as *const Self as *const c_void;
 476            (*app).set_ivar(MAC_PLATFORM_IVAR, self_ptr);
 477            (*app_delegate).set_ivar(MAC_PLATFORM_IVAR, self_ptr);
 478
 479            let pool = NSAutoreleasePool::new(nil);
 480            app.run();
 481            pool.drain();
 482
 483            (*app).set_ivar(MAC_PLATFORM_IVAR, null_mut::<c_void>());
 484            (*NSWindow::delegate(app)).set_ivar(MAC_PLATFORM_IVAR, null_mut::<c_void>());
 485        }
 486    }
 487
 488    fn quit(&self) {
 489        // Quitting the app causes us to close windows, which invokes `Window::on_close` callbacks
 490        // synchronously before this method terminates. If we call `Platform::quit` while holding a
 491        // borrow of the app state (which most of the time we will do), we will end up
 492        // double-borrowing the app state in the `on_close` callbacks for our open windows. To solve
 493        // this, we make quitting the application asynchronous so that we aren't holding borrows to
 494        // the app state on the stack when we actually terminate the app.
 495
 496        use crate::dispatcher::{dispatch_get_main_queue, dispatch_sys::dispatch_async_f};
 497
 498        unsafe {
 499            dispatch_async_f(dispatch_get_main_queue(), ptr::null_mut(), Some(quit));
 500        }
 501
 502        unsafe extern "C" fn quit(_: *mut c_void) {
 503            unsafe {
 504                let app = NSApplication::sharedApplication(nil);
 505                let _: () = msg_send![app, terminate: nil];
 506            }
 507        }
 508    }
 509
 510    fn restart(&self, _binary_path: Option<PathBuf>) {
 511        use std::os::unix::process::CommandExt as _;
 512
 513        let app_pid = std::process::id().to_string();
 514        let app_path = self
 515            .app_path()
 516            .ok()
 517            // When the app is not bundled, `app_path` returns the
 518            // directory containing the executable. Disregard this
 519            // and get the path to the executable itself.
 520            .and_then(|path| (path.extension()?.to_str()? == "app").then_some(path))
 521            .unwrap_or_else(|| std::env::current_exe().unwrap());
 522
 523        // Wait until this process has exited and then re-open this path.
 524        let script = r#"
 525            while kill -0 $0 2> /dev/null; do
 526                sleep 0.1
 527            done
 528            open "$1"
 529        "#;
 530
 531        #[allow(
 532            clippy::disallowed_methods,
 533            reason = "We are restarting ourselves, using std command thus is fine"
 534        )]
 535        let restart_process = new_std_command("/bin/bash")
 536            .arg("-c")
 537            .arg(script)
 538            .arg(app_pid)
 539            .arg(app_path)
 540            .process_group(0)
 541            .spawn();
 542
 543        match restart_process {
 544            Ok(_) => self.quit(),
 545            Err(e) => log::error!("failed to spawn restart script: {:?}", e),
 546        }
 547    }
 548
 549    fn activate(&self, ignoring_other_apps: bool) {
 550        unsafe {
 551            let app = NSApplication::sharedApplication(nil);
 552            app.activateIgnoringOtherApps_(ignoring_other_apps.to_objc());
 553        }
 554    }
 555
 556    fn hide(&self) {
 557        unsafe {
 558            let app = NSApplication::sharedApplication(nil);
 559            let _: () = msg_send![app, hide: nil];
 560        }
 561    }
 562
 563    fn hide_other_apps(&self) {
 564        unsafe {
 565            let app = NSApplication::sharedApplication(nil);
 566            let _: () = msg_send![app, hideOtherApplications: nil];
 567        }
 568    }
 569
 570    fn unhide_other_apps(&self) {
 571        unsafe {
 572            let app = NSApplication::sharedApplication(nil);
 573            let _: () = msg_send![app, unhideAllApplications: nil];
 574        }
 575    }
 576
 577    fn primary_display(&self) -> Option<Rc<dyn PlatformDisplay>> {
 578        Some(Rc::new(MacDisplay::primary()))
 579    }
 580
 581    fn displays(&self) -> Vec<Rc<dyn PlatformDisplay>> {
 582        MacDisplay::all()
 583            .map(|screen| Rc::new(screen) as Rc<_>)
 584            .collect()
 585    }
 586
 587    #[cfg(feature = "screen-capture")]
 588    fn is_screen_capture_supported(&self) -> bool {
 589        let min_version = cocoa::foundation::NSOperatingSystemVersion::new(12, 3, 0);
 590        crate::is_macos_version_at_least(min_version)
 591    }
 592
 593    #[cfg(feature = "screen-capture")]
 594    fn screen_capture_sources(
 595        &self,
 596    ) -> oneshot::Receiver<Result<Vec<Rc<dyn gpui::ScreenCaptureSource>>>> {
 597        crate::screen_capture::get_sources()
 598    }
 599
 600    fn active_window(&self) -> Option<AnyWindowHandle> {
 601        MacWindow::active_window()
 602    }
 603
 604    // Returns the windows ordered front-to-back, meaning that the active
 605    // window is the first one in the returned vec.
 606    fn window_stack(&self) -> Option<Vec<AnyWindowHandle>> {
 607        Some(MacWindow::ordered_windows())
 608    }
 609
 610    fn open_window(
 611        &self,
 612        handle: AnyWindowHandle,
 613        options: WindowParams,
 614    ) -> Result<Box<dyn PlatformWindow>> {
 615        let renderer_context = self.0.lock().renderer_context.clone();
 616        Ok(Box::new(MacWindow::open(
 617            handle,
 618            options,
 619            self.foreground_executor(),
 620            self.background_executor(),
 621            renderer_context,
 622        )))
 623    }
 624
 625    fn window_appearance(&self) -> WindowAppearance {
 626        unsafe {
 627            let app = NSApplication::sharedApplication(nil);
 628            let appearance: id = msg_send![app, effectiveAppearance];
 629            crate::window_appearance::window_appearance_from_native(appearance)
 630        }
 631    }
 632
 633    fn open_url(&self, url: &str) {
 634        unsafe {
 635            let ns_url = NSURL::alloc(nil).initWithString_(ns_string(url));
 636            if ns_url.is_null() {
 637                log::error!("Failed to create NSURL from string: {}", url);
 638                return;
 639            }
 640            let url = ns_url.autorelease();
 641            let workspace: id = msg_send![class!(NSWorkspace), sharedWorkspace];
 642            msg_send![workspace, openURL: url]
 643        }
 644    }
 645
 646    fn register_url_scheme(&self, scheme: &str) -> Task<anyhow::Result<()>> {
 647        // API only available post Monterey
 648        // https://developer.apple.com/documentation/appkit/nsworkspace/3753004-setdefaultapplicationaturl
 649        let (done_tx, done_rx) = oneshot::channel();
 650        if Self::os_version() < Version::new(12, 0, 0) {
 651            return Task::ready(Err(anyhow!(
 652                "macOS 12.0 or later is required to register URL schemes"
 653            )));
 654        }
 655
 656        let bundle_id = unsafe {
 657            let bundle: id = msg_send![class!(NSBundle), mainBundle];
 658            let bundle_id: id = msg_send![bundle, bundleIdentifier];
 659            if bundle_id == nil {
 660                return Task::ready(Err(anyhow!("Can only register URL scheme in bundled apps")));
 661            }
 662            bundle_id
 663        };
 664
 665        unsafe {
 666            let workspace: id = msg_send![class!(NSWorkspace), sharedWorkspace];
 667            let scheme: id = ns_string(scheme);
 668            let app: id = msg_send![workspace, URLForApplicationWithBundleIdentifier: bundle_id];
 669            if app == nil {
 670                return Task::ready(Err(anyhow!(
 671                    "Cannot register URL scheme until app is installed"
 672                )));
 673            }
 674            let done_tx = Cell::new(Some(done_tx));
 675            let block = ConcreteBlock::new(move |error: id| {
 676                let result = if error == nil {
 677                    Ok(())
 678                } else {
 679                    let msg: id = msg_send![error, localizedDescription];
 680                    Err(anyhow!("Failed to register: {msg:?}"))
 681                };
 682
 683                if let Some(done_tx) = done_tx.take() {
 684                    let _ = done_tx.send(result);
 685                }
 686            });
 687            let block = block.copy();
 688            let _: () = msg_send![workspace, setDefaultApplicationAtURL: app toOpenURLsWithScheme: scheme completionHandler: block];
 689        }
 690
 691        self.background_executor()
 692            .spawn(async { done_rx.await.map_err(|e| anyhow!(e))? })
 693    }
 694
 695    fn on_open_urls(&self, callback: Box<dyn FnMut(Vec<String>)>) {
 696        self.0.lock().open_urls = Some(callback);
 697    }
 698
 699    fn prompt_for_paths(
 700        &self,
 701        options: PathPromptOptions,
 702    ) -> oneshot::Receiver<Result<Option<Vec<PathBuf>>>> {
 703        let (done_tx, done_rx) = oneshot::channel();
 704        self.foreground_executor()
 705            .spawn(async move {
 706                unsafe {
 707                    let panel = NSOpenPanel::openPanel(nil);
 708                    panel.setCanChooseDirectories_(options.directories.to_objc());
 709                    panel.setCanChooseFiles_(options.files.to_objc());
 710                    panel.setAllowsMultipleSelection_(options.multiple.to_objc());
 711
 712                    panel.setCanCreateDirectories(true.to_objc());
 713                    panel.setResolvesAliases_(false.to_objc());
 714                    let done_tx = Cell::new(Some(done_tx));
 715                    let block = ConcreteBlock::new(move |response: NSModalResponse| {
 716                        let result = if response == NSModalResponse::NSModalResponseOk {
 717                            let mut result = Vec::new();
 718                            let urls = panel.URLs();
 719                            for i in 0..urls.count() {
 720                                let url = urls.objectAtIndex(i);
 721                                if url.isFileURL() == YES
 722                                    && let Ok(path) = ns_url_to_path(url)
 723                                {
 724                                    result.push(path)
 725                                }
 726                            }
 727                            Some(result)
 728                        } else {
 729                            None
 730                        };
 731
 732                        if let Some(done_tx) = done_tx.take() {
 733                            let _ = done_tx.send(Ok(result));
 734                        }
 735                    });
 736                    let block = block.copy();
 737
 738                    if let Some(prompt) = options.prompt {
 739                        let _: () = msg_send![panel, setPrompt: ns_string(&prompt)];
 740                    }
 741
 742                    let _: () = msg_send![panel, beginWithCompletionHandler: block];
 743                }
 744            })
 745            .detach();
 746        done_rx
 747    }
 748
 749    fn prompt_for_new_path(
 750        &self,
 751        directory: &Path,
 752        suggested_name: Option<&str>,
 753    ) -> oneshot::Receiver<Result<Option<PathBuf>>> {
 754        let directory = directory.to_owned();
 755        let suggested_name = suggested_name.map(|s| s.to_owned());
 756        let (done_tx, done_rx) = oneshot::channel();
 757        self.foreground_executor()
 758            .spawn(async move {
 759                unsafe {
 760                    let panel = NSSavePanel::savePanel(nil);
 761                    let path = ns_string(directory.to_string_lossy().as_ref());
 762                    let url = NSURL::fileURLWithPath_isDirectory_(nil, path, true.to_objc());
 763                    panel.setDirectoryURL(url);
 764
 765                    if let Some(suggested_name) = suggested_name {
 766                        let name_string = ns_string(&suggested_name);
 767                        let _: () = msg_send![panel, setNameFieldStringValue: name_string];
 768                    }
 769
 770                    let done_tx = Cell::new(Some(done_tx));
 771                    let block = ConcreteBlock::new(move |response: NSModalResponse| {
 772                        let mut result = None;
 773                        if response == NSModalResponse::NSModalResponseOk {
 774                            let url = panel.URL();
 775                            if url.isFileURL() == YES {
 776                                result = ns_url_to_path(panel.URL()).ok().map(|mut result| {
 777                                    let Some(filename) = result.file_name() else {
 778                                        return result;
 779                                    };
 780                                    let chunks = filename
 781                                        .as_bytes()
 782                                        .split(|&b| b == b'.')
 783                                        .collect::<Vec<_>>();
 784
 785                                    // https://github.com/zed-industries/zed/issues/16969
 786                                    // Workaround a bug in macOS Sequoia that adds an extra file-extension
 787                                    // sometimes. e.g. `a.sql` becomes `a.sql.s` or `a.txtx` becomes `a.txtx.txt`
 788                                    //
 789                                    // This is conditional on OS version because I'd like to get rid of it, so that
 790                                    // you can manually create a file called `a.sql.s`. That said it seems better
 791                                    // to break that use-case than breaking `a.sql`.
 792                                    if chunks.len() == 3
 793                                        && chunks[1].starts_with(chunks[2])
 794                                        && Self::os_version() >= Version::new(15, 0, 0)
 795                                    {
 796                                        let new_filename = OsStr::from_bytes(
 797                                            &filename.as_bytes()
 798                                                [..chunks[0].len() + 1 + chunks[1].len()],
 799                                        )
 800                                        .to_owned();
 801                                        result.set_file_name(&new_filename);
 802                                    }
 803                                    result
 804                                })
 805                            }
 806                        }
 807
 808                        if let Some(done_tx) = done_tx.take() {
 809                            let _ = done_tx.send(Ok(result));
 810                        }
 811                    });
 812                    let block = block.copy();
 813                    let _: () = msg_send![panel, beginWithCompletionHandler: block];
 814                }
 815            })
 816            .detach();
 817
 818        done_rx
 819    }
 820
 821    fn can_select_mixed_files_and_dirs(&self) -> bool {
 822        true
 823    }
 824
 825    fn reveal_path(&self, path: &Path) {
 826        unsafe {
 827            let path = path.to_path_buf();
 828            self.0
 829                .lock()
 830                .background_executor
 831                .spawn(async move {
 832                    let full_path = ns_string(path.to_str().unwrap_or(""));
 833                    let root_full_path = ns_string("");
 834                    let workspace: id = msg_send![class!(NSWorkspace), sharedWorkspace];
 835                    let _: BOOL = msg_send![
 836                        workspace,
 837                        selectFile: full_path
 838                        inFileViewerRootedAtPath: root_full_path
 839                    ];
 840                })
 841                .detach();
 842        }
 843    }
 844
 845    fn open_with_system(&self, path: &Path) {
 846        let path = path.to_owned();
 847        self.0
 848            .lock()
 849            .background_executor
 850            .spawn(async move {
 851                if let Some(mut child) = new_command("open")
 852                    .arg(path)
 853                    .spawn()
 854                    .context("invoking open command")
 855                    .log_err()
 856                {
 857                    child.status().await.log_err();
 858                }
 859            })
 860            .detach();
 861    }
 862
 863    fn on_quit(&self, callback: Box<dyn FnMut()>) {
 864        self.0.lock().quit = Some(callback);
 865    }
 866
 867    fn on_reopen(&self, callback: Box<dyn FnMut()>) {
 868        self.0.lock().reopen = Some(callback);
 869    }
 870
 871    fn on_keyboard_layout_change(&self, callback: Box<dyn FnMut()>) {
 872        self.0.lock().on_keyboard_layout_change = Some(callback);
 873    }
 874
 875    fn on_app_menu_action(&self, callback: Box<dyn FnMut(&dyn Action)>) {
 876        self.0.lock().menu_command = Some(callback);
 877    }
 878
 879    fn on_will_open_app_menu(&self, callback: Box<dyn FnMut()>) {
 880        self.0.lock().will_open_menu = Some(callback);
 881    }
 882
 883    fn on_validate_app_menu_command(&self, callback: Box<dyn FnMut(&dyn Action) -> bool>) {
 884        self.0.lock().validate_menu_command = Some(callback);
 885    }
 886
 887    fn on_thermal_state_change(&self, callback: Box<dyn FnMut()>) {
 888        self.0.lock().on_thermal_state_change = Some(callback);
 889    }
 890
 891    fn thermal_state(&self) -> ThermalState {
 892        unsafe {
 893            let process_info: id = msg_send![class!(NSProcessInfo), processInfo];
 894            let state: NSInteger = msg_send![process_info, thermalState];
 895            match state {
 896                0 => ThermalState::Nominal,
 897                1 => ThermalState::Fair,
 898                2 => ThermalState::Serious,
 899                3 => ThermalState::Critical,
 900                _ => ThermalState::Nominal,
 901            }
 902        }
 903    }
 904
 905    fn keyboard_layout(&self) -> Box<dyn PlatformKeyboardLayout> {
 906        Box::new(MacKeyboardLayout::new())
 907    }
 908
 909    fn keyboard_mapper(&self) -> Rc<dyn PlatformKeyboardMapper> {
 910        self.0.lock().keyboard_mapper.clone()
 911    }
 912
 913    fn app_path(&self) -> Result<PathBuf> {
 914        unsafe {
 915            let bundle: id = NSBundle::mainBundle();
 916            anyhow::ensure!(!bundle.is_null(), "app is not running inside a bundle");
 917            Ok(path_from_objc(msg_send![bundle, bundlePath]))
 918        }
 919    }
 920
 921    fn set_menus(&self, menus: Vec<Menu>, keymap: &Keymap) {
 922        unsafe {
 923            let app: id = msg_send![APP_CLASS, sharedApplication];
 924            let mut state = self.0.lock();
 925            let actions = &mut state.menu_actions;
 926            let menu = self.create_menu_bar(&menus, NSWindow::delegate(app), actions, keymap);
 927            drop(state);
 928            app.setMainMenu_(menu);
 929        }
 930        self.0.lock().menus = Some(menus.into_iter().map(|menu| menu.owned()).collect());
 931    }
 932
 933    fn get_menus(&self) -> Option<Vec<OwnedMenu>> {
 934        self.0.lock().menus.clone()
 935    }
 936
 937    fn set_dock_menu(&self, menu: Vec<MenuItem>, keymap: &Keymap) {
 938        unsafe {
 939            let app: id = msg_send![APP_CLASS, sharedApplication];
 940            let mut state = self.0.lock();
 941            let actions = &mut state.menu_actions;
 942            let new = self.create_dock_menu(menu, NSWindow::delegate(app), actions, keymap);
 943            if let Some(old) = state.dock_menu.replace(new) {
 944                CFRelease(old as _)
 945            }
 946        }
 947    }
 948
 949    fn add_recent_document(&self, path: &Path) {
 950        if let Some(path_str) = path.to_str() {
 951            unsafe {
 952                let document_controller: id =
 953                    msg_send![class!(NSDocumentController), sharedDocumentController];
 954                let url: id = NSURL::fileURLWithPath_(nil, ns_string(path_str));
 955                let _: () = msg_send![document_controller, noteNewRecentDocumentURL:url];
 956            }
 957        }
 958    }
 959
 960    fn path_for_auxiliary_executable(&self, name: &str) -> Result<PathBuf> {
 961        unsafe {
 962            let bundle: id = NSBundle::mainBundle();
 963            anyhow::ensure!(!bundle.is_null(), "app is not running inside a bundle");
 964            let name = ns_string(name);
 965            let url: id = msg_send![bundle, URLForAuxiliaryExecutable: name];
 966            anyhow::ensure!(!url.is_null(), "resource not found");
 967            ns_url_to_path(url)
 968        }
 969    }
 970
 971    /// Match cursor style to one of the styles available
 972    /// in macOS's [NSCursor](https://developer.apple.com/documentation/appkit/nscursor).
 973    fn set_cursor_style(&self, style: CursorStyle) {
 974        unsafe {
 975            if style == CursorStyle::None {
 976                let _: () = msg_send![class!(NSCursor), setHiddenUntilMouseMoves:YES];
 977                return;
 978            }
 979
 980            let new_cursor: id = match style {
 981                CursorStyle::Arrow => msg_send![class!(NSCursor), arrowCursor],
 982                CursorStyle::IBeam => msg_send![class!(NSCursor), IBeamCursor],
 983                CursorStyle::Crosshair => msg_send![class!(NSCursor), crosshairCursor],
 984                CursorStyle::ClosedHand => msg_send![class!(NSCursor), closedHandCursor],
 985                CursorStyle::OpenHand => msg_send![class!(NSCursor), openHandCursor],
 986                CursorStyle::PointingHand => msg_send![class!(NSCursor), pointingHandCursor],
 987                CursorStyle::ResizeLeftRight => msg_send![class!(NSCursor), resizeLeftRightCursor],
 988                CursorStyle::ResizeUpDown => msg_send![class!(NSCursor), resizeUpDownCursor],
 989                CursorStyle::ResizeLeft => msg_send![class!(NSCursor), resizeLeftCursor],
 990                CursorStyle::ResizeRight => msg_send![class!(NSCursor), resizeRightCursor],
 991                CursorStyle::ResizeColumn => msg_send![class!(NSCursor), resizeLeftRightCursor],
 992                CursorStyle::ResizeRow => msg_send![class!(NSCursor), resizeUpDownCursor],
 993                CursorStyle::ResizeUp => msg_send![class!(NSCursor), resizeUpCursor],
 994                CursorStyle::ResizeDown => msg_send![class!(NSCursor), resizeDownCursor],
 995
 996                // Undocumented, private class methods:
 997                // https://stackoverflow.com/questions/27242353/cocoa-predefined-resize-mouse-cursor
 998                CursorStyle::ResizeUpLeftDownRight => {
 999                    msg_send![class!(NSCursor), _windowResizeNorthWestSouthEastCursor]
1000                }
1001                CursorStyle::ResizeUpRightDownLeft => {
1002                    msg_send![class!(NSCursor), _windowResizeNorthEastSouthWestCursor]
1003                }
1004
1005                CursorStyle::IBeamCursorForVerticalLayout => {
1006                    msg_send![class!(NSCursor), IBeamCursorForVerticalLayout]
1007                }
1008                CursorStyle::OperationNotAllowed => {
1009                    msg_send![class!(NSCursor), operationNotAllowedCursor]
1010                }
1011                CursorStyle::DragLink => msg_send![class!(NSCursor), dragLinkCursor],
1012                CursorStyle::DragCopy => msg_send![class!(NSCursor), dragCopyCursor],
1013                CursorStyle::ContextualMenu => msg_send![class!(NSCursor), contextualMenuCursor],
1014                CursorStyle::None => unreachable!(),
1015            };
1016
1017            let old_cursor: id = msg_send![class!(NSCursor), currentCursor];
1018            if new_cursor != old_cursor {
1019                let _: () = msg_send![new_cursor, set];
1020            }
1021        }
1022    }
1023
1024    fn should_auto_hide_scrollbars(&self) -> bool {
1025        #[allow(non_upper_case_globals)]
1026        const NSScrollerStyleOverlay: NSInteger = 1;
1027
1028        unsafe {
1029            let style: NSInteger = msg_send![class!(NSScroller), preferredScrollerStyle];
1030            style == NSScrollerStyleOverlay
1031        }
1032    }
1033
1034    fn read_from_clipboard(&self) -> Option<ClipboardItem> {
1035        let state = self.0.lock();
1036        state.general_pasteboard.read()
1037    }
1038
1039    fn write_to_clipboard(&self, item: ClipboardItem) {
1040        let state = self.0.lock();
1041        state.general_pasteboard.write(item);
1042    }
1043
1044    fn read_from_find_pasteboard(&self) -> Option<ClipboardItem> {
1045        let state = self.0.lock();
1046        state.find_pasteboard.read()
1047    }
1048
1049    fn write_to_find_pasteboard(&self, item: ClipboardItem) {
1050        let state = self.0.lock();
1051        state.find_pasteboard.write(item);
1052    }
1053
1054    fn write_credentials(&self, url: &str, username: &str, password: &[u8]) -> Task<Result<()>> {
1055        let url = url.to_string();
1056        let username = username.to_string();
1057        let password = password.to_vec();
1058        self.background_executor().spawn(async move {
1059            unsafe {
1060                use security::*;
1061
1062                let url = CFString::from(url.as_str());
1063                let username = CFString::from(username.as_str());
1064                let password = CFData::from_buffer(&password);
1065
1066                // First, check if there are already credentials for the given server. If so, then
1067                // update the username and password.
1068                let mut verb = "updating";
1069                let mut query_attrs = CFMutableDictionary::with_capacity(2);
1070                query_attrs.set(kSecClass as *const _, kSecClassInternetPassword as *const _);
1071                query_attrs.set(kSecAttrServer as *const _, url.as_CFTypeRef());
1072
1073                let mut attrs = CFMutableDictionary::with_capacity(4);
1074                attrs.set(kSecClass as *const _, kSecClassInternetPassword as *const _);
1075                attrs.set(kSecAttrServer as *const _, url.as_CFTypeRef());
1076                attrs.set(kSecAttrAccount as *const _, username.as_CFTypeRef());
1077                attrs.set(kSecValueData as *const _, password.as_CFTypeRef());
1078
1079                let mut status = SecItemUpdate(
1080                    query_attrs.as_concrete_TypeRef(),
1081                    attrs.as_concrete_TypeRef(),
1082                );
1083
1084                // If there were no existing credentials for the given server, then create them.
1085                if status == errSecItemNotFound {
1086                    verb = "creating";
1087                    status = SecItemAdd(attrs.as_concrete_TypeRef(), ptr::null_mut());
1088                }
1089                anyhow::ensure!(status == errSecSuccess, "{verb} password failed: {status}");
1090            }
1091            Ok(())
1092        })
1093    }
1094
1095    fn read_credentials(&self, url: &str) -> Task<Result<Option<(String, Vec<u8>)>>> {
1096        let url = url.to_string();
1097        self.background_executor().spawn(async move {
1098            let url = CFString::from(url.as_str());
1099            let cf_true = CFBoolean::true_value().as_CFTypeRef();
1100
1101            unsafe {
1102                use security::*;
1103
1104                // Find any credentials for the given server URL.
1105                let mut attrs = CFMutableDictionary::with_capacity(5);
1106                attrs.set(kSecClass as *const _, kSecClassInternetPassword as *const _);
1107                attrs.set(kSecAttrServer as *const _, url.as_CFTypeRef());
1108                attrs.set(kSecReturnAttributes as *const _, cf_true);
1109                attrs.set(kSecReturnData as *const _, cf_true);
1110
1111                let mut result = CFTypeRef::from(ptr::null());
1112                let status = SecItemCopyMatching(attrs.as_concrete_TypeRef(), &mut result);
1113                match status {
1114                    security::errSecSuccess => {}
1115                    security::errSecItemNotFound | security::errSecUserCanceled => return Ok(None),
1116                    _ => anyhow::bail!("reading password failed: {status}"),
1117                }
1118
1119                let result = CFType::wrap_under_create_rule(result)
1120                    .downcast::<CFDictionary>()
1121                    .context("keychain item was not a dictionary")?;
1122                let username = result
1123                    .find(kSecAttrAccount as *const _)
1124                    .context("account was missing from keychain item")?;
1125                let username = CFType::wrap_under_get_rule(*username)
1126                    .downcast::<CFString>()
1127                    .context("account was not a string")?;
1128                let password = result
1129                    .find(kSecValueData as *const _)
1130                    .context("password was missing from keychain item")?;
1131                let password = CFType::wrap_under_get_rule(*password)
1132                    .downcast::<CFData>()
1133                    .context("password was not a string")?;
1134
1135                Ok(Some((username.to_string(), password.bytes().to_vec())))
1136            }
1137        })
1138    }
1139
1140    fn delete_credentials(&self, url: &str) -> Task<Result<()>> {
1141        let url = url.to_string();
1142
1143        self.background_executor().spawn(async move {
1144            unsafe {
1145                use security::*;
1146
1147                let url = CFString::from(url.as_str());
1148                let mut query_attrs = CFMutableDictionary::with_capacity(2);
1149                query_attrs.set(kSecClass as *const _, kSecClassInternetPassword as *const _);
1150                query_attrs.set(kSecAttrServer as *const _, url.as_CFTypeRef());
1151
1152                let status = SecItemDelete(query_attrs.as_concrete_TypeRef());
1153                anyhow::ensure!(status == errSecSuccess, "delete password failed: {status}");
1154            }
1155            Ok(())
1156        })
1157    }
1158}
1159
1160unsafe fn path_from_objc(path: id) -> PathBuf {
1161    let len = msg_send![path, lengthOfBytesUsingEncoding: NSUTF8StringEncoding];
1162    let bytes = unsafe { path.UTF8String() as *const u8 };
1163    let path = str::from_utf8(unsafe { slice::from_raw_parts(bytes, len) }).unwrap();
1164    PathBuf::from(path)
1165}
1166
1167unsafe fn get_mac_platform(object: &mut Object) -> &MacPlatform {
1168    unsafe {
1169        let platform_ptr: *mut c_void = *object.get_ivar(MAC_PLATFORM_IVAR);
1170        assert!(!platform_ptr.is_null());
1171        &*(platform_ptr as *const MacPlatform)
1172    }
1173}
1174
1175extern "C" fn will_finish_launching(_this: &mut Object, _: Sel, _: id) {
1176    unsafe {
1177        let user_defaults: id = msg_send![class!(NSUserDefaults), standardUserDefaults];
1178
1179        // The autofill heuristic controller causes slowdown and high CPU usage.
1180        // We don't know exactly why. This disables the full heuristic controller.
1181        //
1182        // Adapted from: https://github.com/ghostty-org/ghostty/pull/8625
1183        let name = ns_string("NSAutoFillHeuristicControllerEnabled");
1184        let existing_value: id = msg_send![user_defaults, objectForKey: name];
1185        if existing_value == nil {
1186            let false_value: id = msg_send![class!(NSNumber), numberWithBool:false];
1187            let _: () = msg_send![user_defaults, setObject: false_value forKey: name];
1188        }
1189    }
1190}
1191
1192extern "C" fn did_finish_launching(this: &mut Object, _: Sel, _: id) {
1193    unsafe {
1194        let app: id = msg_send![APP_CLASS, sharedApplication];
1195        app.setActivationPolicy_(NSApplicationActivationPolicyRegular);
1196
1197        let notification_center: *mut Object =
1198            msg_send![class!(NSNotificationCenter), defaultCenter];
1199        let name = ns_string("NSTextInputContextKeyboardSelectionDidChangeNotification");
1200        let _: () = msg_send![notification_center, addObserver: this as id
1201            selector: sel!(onKeyboardLayoutChange:)
1202            name: name
1203            object: nil
1204        ];
1205
1206        let thermal_name = ns_string("NSProcessInfoThermalStateDidChangeNotification");
1207        let process_info: id = msg_send![class!(NSProcessInfo), processInfo];
1208        let _: () = msg_send![notification_center, addObserver: this as id
1209            selector: sel!(onThermalStateChange:)
1210            name: thermal_name
1211            object: process_info
1212        ];
1213
1214        let platform = get_mac_platform(this);
1215        let callback = platform.0.lock().finish_launching.take();
1216        if let Some(callback) = callback {
1217            callback();
1218        }
1219    }
1220}
1221
1222extern "C" fn should_handle_reopen(this: &mut Object, _: Sel, _: id, has_open_windows: bool) {
1223    if !has_open_windows {
1224        let platform = unsafe { get_mac_platform(this) };
1225        let mut lock = platform.0.lock();
1226        if let Some(mut callback) = lock.reopen.take() {
1227            drop(lock);
1228            callback();
1229            platform.0.lock().reopen.get_or_insert(callback);
1230        }
1231    }
1232}
1233
1234extern "C" fn will_terminate(this: &mut Object, _: Sel, _: id) {
1235    let platform = unsafe { get_mac_platform(this) };
1236    let mut lock = platform.0.lock();
1237    if let Some(mut callback) = lock.quit.take() {
1238        drop(lock);
1239        callback();
1240        platform.0.lock().quit.get_or_insert(callback);
1241    }
1242}
1243
1244extern "C" fn on_keyboard_layout_change(this: &mut Object, _: Sel, _: id) {
1245    let platform = unsafe { get_mac_platform(this) };
1246    let mut lock = platform.0.lock();
1247    let keyboard_layout = MacKeyboardLayout::new();
1248    lock.keyboard_mapper = Rc::new(MacKeyboardMapper::new(keyboard_layout.id()));
1249    if let Some(mut callback) = lock.on_keyboard_layout_change.take() {
1250        drop(lock);
1251        callback();
1252        platform
1253            .0
1254            .lock()
1255            .on_keyboard_layout_change
1256            .get_or_insert(callback);
1257    }
1258}
1259
1260extern "C" fn on_thermal_state_change(this: &mut Object, _: Sel, _: id) {
1261    // Defer to the next run loop iteration to avoid re-entrant borrows of the App RefCell,
1262    // as NSNotificationCenter delivers this notification synchronously and it may fire while
1263    // the App is already borrowed (same pattern as quit() above).
1264    use crate::dispatcher::{dispatch_get_main_queue, dispatch_sys::dispatch_async_f};
1265
1266    let platform = unsafe { get_mac_platform(this) };
1267    let platform_ptr = platform as *const MacPlatform as *mut c_void;
1268    unsafe {
1269        dispatch_async_f(
1270            dispatch_get_main_queue(),
1271            platform_ptr,
1272            Some(on_thermal_state_change),
1273        );
1274    }
1275
1276    unsafe extern "C" fn on_thermal_state_change(context: *mut c_void) {
1277        let platform = unsafe { &*(context as *const MacPlatform) };
1278        let mut lock = platform.0.lock();
1279        if let Some(mut callback) = lock.on_thermal_state_change.take() {
1280            drop(lock);
1281            callback();
1282            platform
1283                .0
1284                .lock()
1285                .on_thermal_state_change
1286                .get_or_insert(callback);
1287        }
1288    }
1289}
1290
1291extern "C" fn open_urls(this: &mut Object, _: Sel, _: id, urls: id) {
1292    let urls = unsafe {
1293        (0..urls.count())
1294            .filter_map(|i| {
1295                let url = urls.objectAtIndex(i);
1296                match CStr::from_ptr(url.absoluteString().UTF8String() as *mut c_char).to_str() {
1297                    Ok(string) => Some(string.to_string()),
1298                    Err(err) => {
1299                        log::error!("error converting path to string: {}", err);
1300                        None
1301                    }
1302                }
1303            })
1304            .collect::<Vec<_>>()
1305    };
1306    let platform = unsafe { get_mac_platform(this) };
1307    let mut lock = platform.0.lock();
1308    if let Some(mut callback) = lock.open_urls.take() {
1309        drop(lock);
1310        callback(urls);
1311        platform.0.lock().open_urls.get_or_insert(callback);
1312    }
1313}
1314
1315extern "C" fn handle_menu_item(this: &mut Object, _: Sel, item: id) {
1316    unsafe {
1317        let platform = get_mac_platform(this);
1318        let mut lock = platform.0.lock();
1319        if let Some(mut callback) = lock.menu_command.take() {
1320            let tag: NSInteger = msg_send![item, tag];
1321            let index = tag as usize;
1322            if let Some(action) = lock.menu_actions.get(index) {
1323                let action = action.boxed_clone();
1324                drop(lock);
1325                callback(&*action);
1326            }
1327            platform.0.lock().menu_command.get_or_insert(callback);
1328        }
1329    }
1330}
1331
1332extern "C" fn validate_menu_item(this: &mut Object, _: Sel, item: id) -> bool {
1333    unsafe {
1334        let mut result = false;
1335        let platform = get_mac_platform(this);
1336        let mut lock = platform.0.lock();
1337        if let Some(mut callback) = lock.validate_menu_command.take() {
1338            let tag: NSInteger = msg_send![item, tag];
1339            let index = tag as usize;
1340            if let Some(action) = lock.menu_actions.get(index) {
1341                let action = action.boxed_clone();
1342                drop(lock);
1343                result = callback(action.as_ref());
1344            }
1345            platform
1346                .0
1347                .lock()
1348                .validate_menu_command
1349                .get_or_insert(callback);
1350        }
1351        result
1352    }
1353}
1354
1355extern "C" fn menu_will_open(this: &mut Object, _: Sel, _: id) {
1356    unsafe {
1357        let platform = get_mac_platform(this);
1358        let mut lock = platform.0.lock();
1359        if let Some(mut callback) = lock.will_open_menu.take() {
1360            drop(lock);
1361            callback();
1362            platform.0.lock().will_open_menu.get_or_insert(callback);
1363        }
1364    }
1365}
1366
1367extern "C" fn handle_dock_menu(this: &mut Object, _: Sel, _: id) -> id {
1368    unsafe {
1369        let platform = get_mac_platform(this);
1370        let state = platform.0.lock();
1371        if let Some(id) = state.dock_menu {
1372            id
1373        } else {
1374            nil
1375        }
1376    }
1377}
1378
1379unsafe fn ns_url_to_path(url: id) -> Result<PathBuf> {
1380    let path: *mut c_char = msg_send![url, fileSystemRepresentation];
1381    anyhow::ensure!(!path.is_null(), "url is not a file path: {}", unsafe {
1382        CStr::from_ptr(url.absoluteString().UTF8String()).to_string_lossy()
1383    });
1384    Ok(PathBuf::from(OsStr::from_bytes(unsafe {
1385        CStr::from_ptr(path).to_bytes()
1386    })))
1387}
1388
1389#[link(name = "Carbon", kind = "framework")]
1390unsafe extern "C" {
1391    pub(super) fn TISCopyCurrentKeyboardLayoutInputSource() -> *mut Object;
1392    pub(super) fn TISGetInputSourceProperty(
1393        inputSource: *mut Object,
1394        propertyKey: *const c_void,
1395    ) -> *mut Object;
1396
1397    pub(super) fn UCKeyTranslate(
1398        keyLayoutPtr: *const ::std::os::raw::c_void,
1399        virtualKeyCode: u16,
1400        keyAction: u16,
1401        modifierKeyState: u32,
1402        keyboardType: u32,
1403        keyTranslateOptions: u32,
1404        deadKeyState: *mut u32,
1405        maxStringLength: usize,
1406        actualStringLength: *mut usize,
1407        unicodeString: *mut u16,
1408    ) -> u32;
1409    pub(super) fn LMGetKbdType() -> u16;
1410    pub(super) static kTISPropertyUnicodeKeyLayoutData: CFStringRef;
1411    pub(super) static kTISPropertyInputSourceID: CFStringRef;
1412    pub(super) static kTISPropertyLocalizedName: CFStringRef;
1413}
1414
1415mod security {
1416    #![allow(non_upper_case_globals)]
1417    use super::*;
1418
1419    #[link(name = "Security", kind = "framework")]
1420    unsafe extern "C" {
1421        pub static kSecClass: CFStringRef;
1422        pub static kSecClassInternetPassword: CFStringRef;
1423        pub static kSecAttrServer: CFStringRef;
1424        pub static kSecAttrAccount: CFStringRef;
1425        pub static kSecValueData: CFStringRef;
1426        pub static kSecReturnAttributes: CFStringRef;
1427        pub static kSecReturnData: CFStringRef;
1428
1429        pub fn SecItemAdd(attributes: CFDictionaryRef, result: *mut CFTypeRef) -> OSStatus;
1430        pub fn SecItemUpdate(query: CFDictionaryRef, attributes: CFDictionaryRef) -> OSStatus;
1431        pub fn SecItemDelete(query: CFDictionaryRef) -> OSStatus;
1432        pub fn SecItemCopyMatching(query: CFDictionaryRef, result: *mut CFTypeRef) -> OSStatus;
1433    }
1434
1435    pub const errSecSuccess: OSStatus = 0;
1436    pub const errSecUserCanceled: OSStatus = -128;
1437    pub const errSecItemNotFound: OSStatus = -25300;
1438}