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            renderer_context,
 614        )))
 615    }
 616
 617    fn window_appearance(&self) -> WindowAppearance {
 618        unsafe {
 619            let app = NSApplication::sharedApplication(nil);
 620            let appearance: id = msg_send![app, effectiveAppearance];
 621            WindowAppearance::from_native(appearance)
 622        }
 623    }
 624
 625    fn open_url(&self, url: &str) {
 626        unsafe {
 627            let ns_url = NSURL::alloc(nil).initWithString_(ns_string(url));
 628            if ns_url.is_null() {
 629                log::error!("Failed to create NSURL from string: {}", url);
 630                return;
 631            }
 632            let url = ns_url.autorelease();
 633            let workspace: id = msg_send![class!(NSWorkspace), sharedWorkspace];
 634            msg_send![workspace, openURL: url]
 635        }
 636    }
 637
 638    fn register_url_scheme(&self, scheme: &str) -> Task<anyhow::Result<()>> {
 639        // API only available post Monterey
 640        // https://developer.apple.com/documentation/appkit/nsworkspace/3753004-setdefaultapplicationaturl
 641        let (done_tx, done_rx) = oneshot::channel();
 642        if Self::os_version() < Version::new(12, 0, 0) {
 643            return Task::ready(Err(anyhow!(
 644                "macOS 12.0 or later is required to register URL schemes"
 645            )));
 646        }
 647
 648        let bundle_id = unsafe {
 649            let bundle: id = msg_send![class!(NSBundle), mainBundle];
 650            let bundle_id: id = msg_send![bundle, bundleIdentifier];
 651            if bundle_id == nil {
 652                return Task::ready(Err(anyhow!("Can only register URL scheme in bundled apps")));
 653            }
 654            bundle_id
 655        };
 656
 657        unsafe {
 658            let workspace: id = msg_send![class!(NSWorkspace), sharedWorkspace];
 659            let scheme: id = ns_string(scheme);
 660            let app: id = msg_send![workspace, URLForApplicationWithBundleIdentifier: bundle_id];
 661            if app == nil {
 662                return Task::ready(Err(anyhow!(
 663                    "Cannot register URL scheme until app is installed"
 664                )));
 665            }
 666            let done_tx = Cell::new(Some(done_tx));
 667            let block = ConcreteBlock::new(move |error: id| {
 668                let result = if error == nil {
 669                    Ok(())
 670                } else {
 671                    let msg: id = msg_send![error, localizedDescription];
 672                    Err(anyhow!("Failed to register: {msg:?}"))
 673                };
 674
 675                if let Some(done_tx) = done_tx.take() {
 676                    let _ = done_tx.send(result);
 677                }
 678            });
 679            let block = block.copy();
 680            let _: () = msg_send![workspace, setDefaultApplicationAtURL: app toOpenURLsWithScheme: scheme completionHandler: block];
 681        }
 682
 683        self.background_executor()
 684            .spawn(async { done_rx.await.map_err(|e| anyhow!(e))? })
 685    }
 686
 687    fn on_open_urls(&self, callback: Box<dyn FnMut(Vec<String>)>) {
 688        self.0.lock().open_urls = Some(callback);
 689    }
 690
 691    fn prompt_for_paths(
 692        &self,
 693        options: PathPromptOptions,
 694    ) -> oneshot::Receiver<Result<Option<Vec<PathBuf>>>> {
 695        let (done_tx, done_rx) = oneshot::channel();
 696        self.foreground_executor()
 697            .spawn(async move {
 698                unsafe {
 699                    let panel = NSOpenPanel::openPanel(nil);
 700                    panel.setCanChooseDirectories_(options.directories.to_objc());
 701                    panel.setCanChooseFiles_(options.files.to_objc());
 702                    panel.setAllowsMultipleSelection_(options.multiple.to_objc());
 703
 704                    panel.setCanCreateDirectories(true.to_objc());
 705                    panel.setResolvesAliases_(false.to_objc());
 706                    let done_tx = Cell::new(Some(done_tx));
 707                    let block = ConcreteBlock::new(move |response: NSModalResponse| {
 708                        let result = if response == NSModalResponse::NSModalResponseOk {
 709                            let mut result = Vec::new();
 710                            let urls = panel.URLs();
 711                            for i in 0..urls.count() {
 712                                let url = urls.objectAtIndex(i);
 713                                if url.isFileURL() == YES
 714                                    && let Ok(path) = ns_url_to_path(url)
 715                                {
 716                                    result.push(path)
 717                                }
 718                            }
 719                            Some(result)
 720                        } else {
 721                            None
 722                        };
 723
 724                        if let Some(done_tx) = done_tx.take() {
 725                            let _ = done_tx.send(Ok(result));
 726                        }
 727                    });
 728                    let block = block.copy();
 729
 730                    if let Some(prompt) = options.prompt {
 731                        let _: () = msg_send![panel, setPrompt: ns_string(&prompt)];
 732                    }
 733
 734                    let _: () = msg_send![panel, beginWithCompletionHandler: block];
 735                }
 736            })
 737            .detach();
 738        done_rx
 739    }
 740
 741    fn prompt_for_new_path(
 742        &self,
 743        directory: &Path,
 744        suggested_name: Option<&str>,
 745    ) -> oneshot::Receiver<Result<Option<PathBuf>>> {
 746        let directory = directory.to_owned();
 747        let suggested_name = suggested_name.map(|s| s.to_owned());
 748        let (done_tx, done_rx) = oneshot::channel();
 749        self.foreground_executor()
 750            .spawn(async move {
 751                unsafe {
 752                    let panel = NSSavePanel::savePanel(nil);
 753                    let path = ns_string(directory.to_string_lossy().as_ref());
 754                    let url = NSURL::fileURLWithPath_isDirectory_(nil, path, true.to_objc());
 755                    panel.setDirectoryURL(url);
 756
 757                    if let Some(suggested_name) = suggested_name {
 758                        let name_string = ns_string(&suggested_name);
 759                        let _: () = msg_send![panel, setNameFieldStringValue: name_string];
 760                    }
 761
 762                    let done_tx = Cell::new(Some(done_tx));
 763                    let block = ConcreteBlock::new(move |response: NSModalResponse| {
 764                        let mut result = None;
 765                        if response == NSModalResponse::NSModalResponseOk {
 766                            let url = panel.URL();
 767                            if url.isFileURL() == YES {
 768                                result = ns_url_to_path(panel.URL()).ok().map(|mut result| {
 769                                    let Some(filename) = result.file_name() else {
 770                                        return result;
 771                                    };
 772                                    let chunks = filename
 773                                        .as_bytes()
 774                                        .split(|&b| b == b'.')
 775                                        .collect::<Vec<_>>();
 776
 777                                    // https://github.com/zed-industries/zed/issues/16969
 778                                    // Workaround a bug in macOS Sequoia that adds an extra file-extension
 779                                    // sometimes. e.g. `a.sql` becomes `a.sql.s` or `a.txtx` becomes `a.txtx.txt`
 780                                    //
 781                                    // This is conditional on OS version because I'd like to get rid of it, so that
 782                                    // you can manually create a file called `a.sql.s`. That said it seems better
 783                                    // to break that use-case than breaking `a.sql`.
 784                                    if chunks.len() == 3
 785                                        && chunks[1].starts_with(chunks[2])
 786                                        && Self::os_version() >= Version::new(15, 0, 0)
 787                                    {
 788                                        let new_filename = OsStr::from_bytes(
 789                                            &filename.as_bytes()
 790                                                [..chunks[0].len() + 1 + chunks[1].len()],
 791                                        )
 792                                        .to_owned();
 793                                        result.set_file_name(&new_filename);
 794                                    }
 795                                    result
 796                                })
 797                            }
 798                        }
 799
 800                        if let Some(done_tx) = done_tx.take() {
 801                            let _ = done_tx.send(Ok(result));
 802                        }
 803                    });
 804                    let block = block.copy();
 805                    let _: () = msg_send![panel, beginWithCompletionHandler: block];
 806                }
 807            })
 808            .detach();
 809
 810        done_rx
 811    }
 812
 813    fn can_select_mixed_files_and_dirs(&self) -> bool {
 814        true
 815    }
 816
 817    fn reveal_path(&self, path: &Path) {
 818        unsafe {
 819            let path = path.to_path_buf();
 820            self.0
 821                .lock()
 822                .background_executor
 823                .spawn(async move {
 824                    let full_path = ns_string(path.to_str().unwrap_or(""));
 825                    let root_full_path = ns_string("");
 826                    let workspace: id = msg_send![class!(NSWorkspace), sharedWorkspace];
 827                    let _: BOOL = msg_send![
 828                        workspace,
 829                        selectFile: full_path
 830                        inFileViewerRootedAtPath: root_full_path
 831                    ];
 832                })
 833                .detach();
 834        }
 835    }
 836
 837    fn open_with_system(&self, path: &Path) {
 838        let path = path.to_owned();
 839        self.0
 840            .lock()
 841            .background_executor
 842            .spawn(async move {
 843                if let Some(mut child) = new_smol_command("open")
 844                    .arg(path)
 845                    .spawn()
 846                    .context("invoking open command")
 847                    .log_err()
 848                {
 849                    child.status().await.log_err();
 850                }
 851            })
 852            .detach();
 853    }
 854
 855    fn on_quit(&self, callback: Box<dyn FnMut()>) {
 856        self.0.lock().quit = Some(callback);
 857    }
 858
 859    fn on_reopen(&self, callback: Box<dyn FnMut()>) {
 860        self.0.lock().reopen = Some(callback);
 861    }
 862
 863    fn on_keyboard_layout_change(&self, callback: Box<dyn FnMut()>) {
 864        self.0.lock().on_keyboard_layout_change = Some(callback);
 865    }
 866
 867    fn on_app_menu_action(&self, callback: Box<dyn FnMut(&dyn Action)>) {
 868        self.0.lock().menu_command = Some(callback);
 869    }
 870
 871    fn on_will_open_app_menu(&self, callback: Box<dyn FnMut()>) {
 872        self.0.lock().will_open_menu = Some(callback);
 873    }
 874
 875    fn on_validate_app_menu_command(&self, callback: Box<dyn FnMut(&dyn Action) -> bool>) {
 876        self.0.lock().validate_menu_command = Some(callback);
 877    }
 878
 879    fn keyboard_layout(&self) -> Box<dyn PlatformKeyboardLayout> {
 880        Box::new(MacKeyboardLayout::new())
 881    }
 882
 883    fn keyboard_mapper(&self) -> Rc<dyn PlatformKeyboardMapper> {
 884        self.0.lock().keyboard_mapper.clone()
 885    }
 886
 887    fn app_path(&self) -> Result<PathBuf> {
 888        unsafe {
 889            let bundle: id = NSBundle::mainBundle();
 890            anyhow::ensure!(!bundle.is_null(), "app is not running inside a bundle");
 891            Ok(path_from_objc(msg_send![bundle, bundlePath]))
 892        }
 893    }
 894
 895    fn set_menus(&self, menus: Vec<Menu>, keymap: &Keymap) {
 896        unsafe {
 897            let app: id = msg_send![APP_CLASS, sharedApplication];
 898            let mut state = self.0.lock();
 899            let actions = &mut state.menu_actions;
 900            let menu = self.create_menu_bar(&menus, NSWindow::delegate(app), actions, keymap);
 901            drop(state);
 902            app.setMainMenu_(menu);
 903        }
 904        self.0.lock().menus = Some(menus.into_iter().map(|menu| menu.owned()).collect());
 905    }
 906
 907    fn get_menus(&self) -> Option<Vec<OwnedMenu>> {
 908        self.0.lock().menus.clone()
 909    }
 910
 911    fn set_dock_menu(&self, menu: Vec<MenuItem>, keymap: &Keymap) {
 912        unsafe {
 913            let app: id = msg_send![APP_CLASS, sharedApplication];
 914            let mut state = self.0.lock();
 915            let actions = &mut state.menu_actions;
 916            let new = self.create_dock_menu(menu, NSWindow::delegate(app), actions, keymap);
 917            if let Some(old) = state.dock_menu.replace(new) {
 918                CFRelease(old as _)
 919            }
 920        }
 921    }
 922
 923    fn add_recent_document(&self, path: &Path) {
 924        if let Some(path_str) = path.to_str() {
 925            unsafe {
 926                let document_controller: id =
 927                    msg_send![class!(NSDocumentController), sharedDocumentController];
 928                let url: id = NSURL::fileURLWithPath_(nil, ns_string(path_str));
 929                let _: () = msg_send![document_controller, noteNewRecentDocumentURL:url];
 930            }
 931        }
 932    }
 933
 934    fn path_for_auxiliary_executable(&self, name: &str) -> Result<PathBuf> {
 935        unsafe {
 936            let bundle: id = NSBundle::mainBundle();
 937            anyhow::ensure!(!bundle.is_null(), "app is not running inside a bundle");
 938            let name = ns_string(name);
 939            let url: id = msg_send![bundle, URLForAuxiliaryExecutable: name];
 940            anyhow::ensure!(!url.is_null(), "resource not found");
 941            ns_url_to_path(url)
 942        }
 943    }
 944
 945    /// Match cursor style to one of the styles available
 946    /// in macOS's [NSCursor](https://developer.apple.com/documentation/appkit/nscursor).
 947    fn set_cursor_style(&self, style: CursorStyle) {
 948        unsafe {
 949            if style == CursorStyle::None {
 950                let _: () = msg_send![class!(NSCursor), setHiddenUntilMouseMoves:YES];
 951                return;
 952            }
 953
 954            let new_cursor: id = match style {
 955                CursorStyle::Arrow => msg_send![class!(NSCursor), arrowCursor],
 956                CursorStyle::IBeam => msg_send![class!(NSCursor), IBeamCursor],
 957                CursorStyle::Crosshair => msg_send![class!(NSCursor), crosshairCursor],
 958                CursorStyle::ClosedHand => msg_send![class!(NSCursor), closedHandCursor],
 959                CursorStyle::OpenHand => msg_send![class!(NSCursor), openHandCursor],
 960                CursorStyle::PointingHand => msg_send![class!(NSCursor), pointingHandCursor],
 961                CursorStyle::ResizeLeftRight => msg_send![class!(NSCursor), resizeLeftRightCursor],
 962                CursorStyle::ResizeUpDown => msg_send![class!(NSCursor), resizeUpDownCursor],
 963                CursorStyle::ResizeLeft => msg_send![class!(NSCursor), resizeLeftCursor],
 964                CursorStyle::ResizeRight => msg_send![class!(NSCursor), resizeRightCursor],
 965                CursorStyle::ResizeColumn => msg_send![class!(NSCursor), resizeLeftRightCursor],
 966                CursorStyle::ResizeRow => msg_send![class!(NSCursor), resizeUpDownCursor],
 967                CursorStyle::ResizeUp => msg_send![class!(NSCursor), resizeUpCursor],
 968                CursorStyle::ResizeDown => msg_send![class!(NSCursor), resizeDownCursor],
 969
 970                // Undocumented, private class methods:
 971                // https://stackoverflow.com/questions/27242353/cocoa-predefined-resize-mouse-cursor
 972                CursorStyle::ResizeUpLeftDownRight => {
 973                    msg_send![class!(NSCursor), _windowResizeNorthWestSouthEastCursor]
 974                }
 975                CursorStyle::ResizeUpRightDownLeft => {
 976                    msg_send![class!(NSCursor), _windowResizeNorthEastSouthWestCursor]
 977                }
 978
 979                CursorStyle::IBeamCursorForVerticalLayout => {
 980                    msg_send![class!(NSCursor), IBeamCursorForVerticalLayout]
 981                }
 982                CursorStyle::OperationNotAllowed => {
 983                    msg_send![class!(NSCursor), operationNotAllowedCursor]
 984                }
 985                CursorStyle::DragLink => msg_send![class!(NSCursor), dragLinkCursor],
 986                CursorStyle::DragCopy => msg_send![class!(NSCursor), dragCopyCursor],
 987                CursorStyle::ContextualMenu => msg_send![class!(NSCursor), contextualMenuCursor],
 988                CursorStyle::None => unreachable!(),
 989            };
 990
 991            let old_cursor: id = msg_send![class!(NSCursor), currentCursor];
 992            if new_cursor != old_cursor {
 993                let _: () = msg_send![new_cursor, set];
 994            }
 995        }
 996    }
 997
 998    fn should_auto_hide_scrollbars(&self) -> bool {
 999        #[allow(non_upper_case_globals)]
1000        const NSScrollerStyleOverlay: NSInteger = 1;
1001
1002        unsafe {
1003            let style: NSInteger = msg_send![class!(NSScroller), preferredScrollerStyle];
1004            style == NSScrollerStyleOverlay
1005        }
1006    }
1007
1008    fn read_from_clipboard(&self) -> Option<ClipboardItem> {
1009        let state = self.0.lock();
1010        state.general_pasteboard.read()
1011    }
1012
1013    fn write_to_clipboard(&self, item: ClipboardItem) {
1014        let state = self.0.lock();
1015        state.general_pasteboard.write(item);
1016    }
1017
1018    fn read_from_find_pasteboard(&self) -> Option<ClipboardItem> {
1019        let state = self.0.lock();
1020        state.find_pasteboard.read()
1021    }
1022
1023    fn write_to_find_pasteboard(&self, item: ClipboardItem) {
1024        let state = self.0.lock();
1025        state.find_pasteboard.write(item);
1026    }
1027
1028    fn write_credentials(&self, url: &str, username: &str, password: &[u8]) -> Task<Result<()>> {
1029        let url = url.to_string();
1030        let username = username.to_string();
1031        let password = password.to_vec();
1032        self.background_executor().spawn(async move {
1033            unsafe {
1034                use security::*;
1035
1036                let url = CFString::from(url.as_str());
1037                let username = CFString::from(username.as_str());
1038                let password = CFData::from_buffer(&password);
1039
1040                // First, check if there are already credentials for the given server. If so, then
1041                // update the username and password.
1042                let mut verb = "updating";
1043                let mut query_attrs = CFMutableDictionary::with_capacity(2);
1044                query_attrs.set(kSecClass as *const _, kSecClassInternetPassword as *const _);
1045                query_attrs.set(kSecAttrServer as *const _, url.as_CFTypeRef());
1046
1047                let mut attrs = CFMutableDictionary::with_capacity(4);
1048                attrs.set(kSecClass as *const _, kSecClassInternetPassword as *const _);
1049                attrs.set(kSecAttrServer as *const _, url.as_CFTypeRef());
1050                attrs.set(kSecAttrAccount as *const _, username.as_CFTypeRef());
1051                attrs.set(kSecValueData as *const _, password.as_CFTypeRef());
1052
1053                let mut status = SecItemUpdate(
1054                    query_attrs.as_concrete_TypeRef(),
1055                    attrs.as_concrete_TypeRef(),
1056                );
1057
1058                // If there were no existing credentials for the given server, then create them.
1059                if status == errSecItemNotFound {
1060                    verb = "creating";
1061                    status = SecItemAdd(attrs.as_concrete_TypeRef(), ptr::null_mut());
1062                }
1063                anyhow::ensure!(status == errSecSuccess, "{verb} password failed: {status}");
1064            }
1065            Ok(())
1066        })
1067    }
1068
1069    fn read_credentials(&self, url: &str) -> Task<Result<Option<(String, Vec<u8>)>>> {
1070        let url = url.to_string();
1071        self.background_executor().spawn(async move {
1072            let url = CFString::from(url.as_str());
1073            let cf_true = CFBoolean::true_value().as_CFTypeRef();
1074
1075            unsafe {
1076                use security::*;
1077
1078                // Find any credentials for the given server URL.
1079                let mut attrs = CFMutableDictionary::with_capacity(5);
1080                attrs.set(kSecClass as *const _, kSecClassInternetPassword as *const _);
1081                attrs.set(kSecAttrServer as *const _, url.as_CFTypeRef());
1082                attrs.set(kSecReturnAttributes as *const _, cf_true);
1083                attrs.set(kSecReturnData as *const _, cf_true);
1084
1085                let mut result = CFTypeRef::from(ptr::null());
1086                let status = SecItemCopyMatching(attrs.as_concrete_TypeRef(), &mut result);
1087                match status {
1088                    security::errSecSuccess => {}
1089                    security::errSecItemNotFound | security::errSecUserCanceled => return Ok(None),
1090                    _ => anyhow::bail!("reading password failed: {status}"),
1091                }
1092
1093                let result = CFType::wrap_under_create_rule(result)
1094                    .downcast::<CFDictionary>()
1095                    .context("keychain item was not a dictionary")?;
1096                let username = result
1097                    .find(kSecAttrAccount as *const _)
1098                    .context("account was missing from keychain item")?;
1099                let username = CFType::wrap_under_get_rule(*username)
1100                    .downcast::<CFString>()
1101                    .context("account was not a string")?;
1102                let password = result
1103                    .find(kSecValueData as *const _)
1104                    .context("password was missing from keychain item")?;
1105                let password = CFType::wrap_under_get_rule(*password)
1106                    .downcast::<CFData>()
1107                    .context("password was not a string")?;
1108
1109                Ok(Some((username.to_string(), password.bytes().to_vec())))
1110            }
1111        })
1112    }
1113
1114    fn delete_credentials(&self, url: &str) -> Task<Result<()>> {
1115        let url = url.to_string();
1116
1117        self.background_executor().spawn(async move {
1118            unsafe {
1119                use security::*;
1120
1121                let url = CFString::from(url.as_str());
1122                let mut query_attrs = CFMutableDictionary::with_capacity(2);
1123                query_attrs.set(kSecClass as *const _, kSecClassInternetPassword as *const _);
1124                query_attrs.set(kSecAttrServer as *const _, url.as_CFTypeRef());
1125
1126                let status = SecItemDelete(query_attrs.as_concrete_TypeRef());
1127                anyhow::ensure!(status == errSecSuccess, "delete password failed: {status}");
1128            }
1129            Ok(())
1130        })
1131    }
1132}
1133
1134unsafe fn path_from_objc(path: id) -> PathBuf {
1135    let len = msg_send![path, lengthOfBytesUsingEncoding: NSUTF8StringEncoding];
1136    let bytes = unsafe { path.UTF8String() as *const u8 };
1137    let path = str::from_utf8(unsafe { slice::from_raw_parts(bytes, len) }).unwrap();
1138    PathBuf::from(path)
1139}
1140
1141unsafe fn get_mac_platform(object: &mut Object) -> &MacPlatform {
1142    unsafe {
1143        let platform_ptr: *mut c_void = *object.get_ivar(MAC_PLATFORM_IVAR);
1144        assert!(!platform_ptr.is_null());
1145        &*(platform_ptr as *const MacPlatform)
1146    }
1147}
1148
1149extern "C" fn will_finish_launching(_this: &mut Object, _: Sel, _: id) {
1150    unsafe {
1151        let user_defaults: id = msg_send![class!(NSUserDefaults), standardUserDefaults];
1152
1153        // The autofill heuristic controller causes slowdown and high CPU usage.
1154        // We don't know exactly why. This disables the full heuristic controller.
1155        //
1156        // Adapted from: https://github.com/ghostty-org/ghostty/pull/8625
1157        let name = ns_string("NSAutoFillHeuristicControllerEnabled");
1158        let existing_value: id = msg_send![user_defaults, objectForKey: name];
1159        if existing_value == nil {
1160            let false_value: id = msg_send![class!(NSNumber), numberWithBool:false];
1161            let _: () = msg_send![user_defaults, setObject: false_value forKey: name];
1162        }
1163    }
1164}
1165
1166extern "C" fn did_finish_launching(this: &mut Object, _: Sel, _: id) {
1167    unsafe {
1168        let app: id = msg_send![APP_CLASS, sharedApplication];
1169        app.setActivationPolicy_(NSApplicationActivationPolicyRegular);
1170
1171        let notification_center: *mut Object =
1172            msg_send![class!(NSNotificationCenter), defaultCenter];
1173        let name = ns_string("NSTextInputContextKeyboardSelectionDidChangeNotification");
1174        let _: () = msg_send![notification_center, addObserver: this as id
1175            selector: sel!(onKeyboardLayoutChange:)
1176            name: name
1177            object: nil
1178        ];
1179
1180        let platform = get_mac_platform(this);
1181        let callback = platform.0.lock().finish_launching.take();
1182        if let Some(callback) = callback {
1183            callback();
1184        }
1185    }
1186}
1187
1188extern "C" fn should_handle_reopen(this: &mut Object, _: Sel, _: id, has_open_windows: bool) {
1189    if !has_open_windows {
1190        let platform = unsafe { get_mac_platform(this) };
1191        let mut lock = platform.0.lock();
1192        if let Some(mut callback) = lock.reopen.take() {
1193            drop(lock);
1194            callback();
1195            platform.0.lock().reopen.get_or_insert(callback);
1196        }
1197    }
1198}
1199
1200extern "C" fn will_terminate(this: &mut Object, _: Sel, _: id) {
1201    let platform = unsafe { get_mac_platform(this) };
1202    let mut lock = platform.0.lock();
1203    if let Some(mut callback) = lock.quit.take() {
1204        drop(lock);
1205        callback();
1206        platform.0.lock().quit.get_or_insert(callback);
1207    }
1208}
1209
1210extern "C" fn on_keyboard_layout_change(this: &mut Object, _: Sel, _: id) {
1211    let platform = unsafe { get_mac_platform(this) };
1212    let mut lock = platform.0.lock();
1213    let keyboard_layout = MacKeyboardLayout::new();
1214    lock.keyboard_mapper = Rc::new(MacKeyboardMapper::new(keyboard_layout.id()));
1215    if let Some(mut callback) = lock.on_keyboard_layout_change.take() {
1216        drop(lock);
1217        callback();
1218        platform
1219            .0
1220            .lock()
1221            .on_keyboard_layout_change
1222            .get_or_insert(callback);
1223    }
1224}
1225
1226extern "C" fn open_urls(this: &mut Object, _: Sel, _: id, urls: id) {
1227    let urls = unsafe {
1228        (0..urls.count())
1229            .filter_map(|i| {
1230                let url = urls.objectAtIndex(i);
1231                match CStr::from_ptr(url.absoluteString().UTF8String() as *mut c_char).to_str() {
1232                    Ok(string) => Some(string.to_string()),
1233                    Err(err) => {
1234                        log::error!("error converting path to string: {}", err);
1235                        None
1236                    }
1237                }
1238            })
1239            .collect::<Vec<_>>()
1240    };
1241    let platform = unsafe { get_mac_platform(this) };
1242    let mut lock = platform.0.lock();
1243    if let Some(mut callback) = lock.open_urls.take() {
1244        drop(lock);
1245        callback(urls);
1246        platform.0.lock().open_urls.get_or_insert(callback);
1247    }
1248}
1249
1250extern "C" fn handle_menu_item(this: &mut Object, _: Sel, item: id) {
1251    unsafe {
1252        let platform = get_mac_platform(this);
1253        let mut lock = platform.0.lock();
1254        if let Some(mut callback) = lock.menu_command.take() {
1255            let tag: NSInteger = msg_send![item, tag];
1256            let index = tag as usize;
1257            if let Some(action) = lock.menu_actions.get(index) {
1258                let action = action.boxed_clone();
1259                drop(lock);
1260                callback(&*action);
1261            }
1262            platform.0.lock().menu_command.get_or_insert(callback);
1263        }
1264    }
1265}
1266
1267extern "C" fn validate_menu_item(this: &mut Object, _: Sel, item: id) -> bool {
1268    unsafe {
1269        let mut result = false;
1270        let platform = get_mac_platform(this);
1271        let mut lock = platform.0.lock();
1272        if let Some(mut callback) = lock.validate_menu_command.take() {
1273            let tag: NSInteger = msg_send![item, tag];
1274            let index = tag as usize;
1275            if let Some(action) = lock.menu_actions.get(index) {
1276                let action = action.boxed_clone();
1277                drop(lock);
1278                result = callback(action.as_ref());
1279            }
1280            platform
1281                .0
1282                .lock()
1283                .validate_menu_command
1284                .get_or_insert(callback);
1285        }
1286        result
1287    }
1288}
1289
1290extern "C" fn menu_will_open(this: &mut Object, _: Sel, _: id) {
1291    unsafe {
1292        let platform = get_mac_platform(this);
1293        let mut lock = platform.0.lock();
1294        if let Some(mut callback) = lock.will_open_menu.take() {
1295            drop(lock);
1296            callback();
1297            platform.0.lock().will_open_menu.get_or_insert(callback);
1298        }
1299    }
1300}
1301
1302extern "C" fn handle_dock_menu(this: &mut Object, _: Sel, _: id) -> id {
1303    unsafe {
1304        let platform = get_mac_platform(this);
1305        let mut state = platform.0.lock();
1306        if let Some(id) = state.dock_menu {
1307            id
1308        } else {
1309            nil
1310        }
1311    }
1312}
1313
1314unsafe fn ns_url_to_path(url: id) -> Result<PathBuf> {
1315    let path: *mut c_char = msg_send![url, fileSystemRepresentation];
1316    anyhow::ensure!(!path.is_null(), "url is not a file path: {}", unsafe {
1317        CStr::from_ptr(url.absoluteString().UTF8String()).to_string_lossy()
1318    });
1319    Ok(PathBuf::from(OsStr::from_bytes(unsafe {
1320        CStr::from_ptr(path).to_bytes()
1321    })))
1322}
1323
1324#[link(name = "Carbon", kind = "framework")]
1325unsafe extern "C" {
1326    pub(super) fn TISCopyCurrentKeyboardLayoutInputSource() -> *mut Object;
1327    pub(super) fn TISGetInputSourceProperty(
1328        inputSource: *mut Object,
1329        propertyKey: *const c_void,
1330    ) -> *mut Object;
1331
1332    pub(super) fn UCKeyTranslate(
1333        keyLayoutPtr: *const ::std::os::raw::c_void,
1334        virtualKeyCode: u16,
1335        keyAction: u16,
1336        modifierKeyState: u32,
1337        keyboardType: u32,
1338        keyTranslateOptions: u32,
1339        deadKeyState: *mut u32,
1340        maxStringLength: usize,
1341        actualStringLength: *mut usize,
1342        unicodeString: *mut u16,
1343    ) -> u32;
1344    pub(super) fn LMGetKbdType() -> u16;
1345    pub(super) static kTISPropertyUnicodeKeyLayoutData: CFStringRef;
1346    pub(super) static kTISPropertyInputSourceID: CFStringRef;
1347    pub(super) static kTISPropertyLocalizedName: CFStringRef;
1348}
1349
1350mod security {
1351    #![allow(non_upper_case_globals)]
1352    use super::*;
1353
1354    #[link(name = "Security", kind = "framework")]
1355    unsafe extern "C" {
1356        pub static kSecClass: CFStringRef;
1357        pub static kSecClassInternetPassword: CFStringRef;
1358        pub static kSecAttrServer: CFStringRef;
1359        pub static kSecAttrAccount: CFStringRef;
1360        pub static kSecValueData: CFStringRef;
1361        pub static kSecReturnAttributes: CFStringRef;
1362        pub static kSecReturnData: CFStringRef;
1363
1364        pub fn SecItemAdd(attributes: CFDictionaryRef, result: *mut CFTypeRef) -> OSStatus;
1365        pub fn SecItemUpdate(query: CFDictionaryRef, attributes: CFDictionaryRef) -> OSStatus;
1366        pub fn SecItemDelete(query: CFDictionaryRef) -> OSStatus;
1367        pub fn SecItemCopyMatching(query: CFDictionaryRef, result: *mut CFTypeRef) -> OSStatus;
1368    }
1369
1370    pub const errSecSuccess: OSStatus = 0;
1371    pub const errSecUserCanceled: OSStatus = -128;
1372    pub const errSecItemNotFound: OSStatus = -25300;
1373}