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