platform.rs

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