platform.rs

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