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