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 url = NSURL::alloc(nil)
 655                .initWithString_(ns_string(url))
 656                .autorelease();
 657            let workspace: id = msg_send![class!(NSWorkspace), sharedWorkspace];
 658            msg_send![workspace, openURL: url]
 659        }
 660    }
 661
 662    fn register_url_scheme(&self, scheme: &str) -> Task<anyhow::Result<()>> {
 663        // API only available post Monterey
 664        // https://developer.apple.com/documentation/appkit/nsworkspace/3753004-setdefaultapplicationaturl
 665        let (done_tx, done_rx) = oneshot::channel();
 666        if Self::os_version() < SemanticVersion::new(12, 0, 0) {
 667            return Task::ready(Err(anyhow!(
 668                "macOS 12.0 or later is required to register URL schemes"
 669            )));
 670        }
 671
 672        let bundle_id = unsafe {
 673            let bundle: id = msg_send![class!(NSBundle), mainBundle];
 674            let bundle_id: id = msg_send![bundle, bundleIdentifier];
 675            if bundle_id == nil {
 676                return Task::ready(Err(anyhow!("Can only register URL scheme in bundled apps")));
 677            }
 678            bundle_id
 679        };
 680
 681        unsafe {
 682            let workspace: id = msg_send![class!(NSWorkspace), sharedWorkspace];
 683            let scheme: id = ns_string(scheme);
 684            let app: id = msg_send![workspace, URLForApplicationWithBundleIdentifier: bundle_id];
 685            if app == nil {
 686                return Task::ready(Err(anyhow!(
 687                    "Cannot register URL scheme until app is installed"
 688                )));
 689            }
 690            let done_tx = Cell::new(Some(done_tx));
 691            let block = ConcreteBlock::new(move |error: id| {
 692                let result = if error == nil {
 693                    Ok(())
 694                } else {
 695                    let msg: id = msg_send![error, localizedDescription];
 696                    Err(anyhow!("Failed to register: {msg:?}"))
 697                };
 698
 699                if let Some(done_tx) = done_tx.take() {
 700                    let _ = done_tx.send(result);
 701                }
 702            });
 703            let block = block.copy();
 704            let _: () = msg_send![workspace, setDefaultApplicationAtURL: app toOpenURLsWithScheme: scheme completionHandler: block];
 705        }
 706
 707        self.background_executor()
 708            .spawn(async { crate::Flatten::flatten(done_rx.await.map_err(|e| anyhow!(e))) })
 709    }
 710
 711    fn on_open_urls(&self, callback: Box<dyn FnMut(Vec<String>)>) {
 712        self.0.lock().open_urls = Some(callback);
 713    }
 714
 715    fn prompt_for_paths(
 716        &self,
 717        options: PathPromptOptions,
 718    ) -> oneshot::Receiver<Result<Option<Vec<PathBuf>>>> {
 719        let (done_tx, done_rx) = oneshot::channel();
 720        self.foreground_executor()
 721            .spawn(async move {
 722                unsafe {
 723                    let panel = NSOpenPanel::openPanel(nil);
 724                    panel.setCanChooseDirectories_(options.directories.to_objc());
 725                    panel.setCanChooseFiles_(options.files.to_objc());
 726                    panel.setAllowsMultipleSelection_(options.multiple.to_objc());
 727
 728                    panel.setCanCreateDirectories(true.to_objc());
 729                    panel.setResolvesAliases_(false.to_objc());
 730                    let done_tx = Cell::new(Some(done_tx));
 731                    let block = ConcreteBlock::new(move |response: NSModalResponse| {
 732                        let result = if response == NSModalResponse::NSModalResponseOk {
 733                            let mut result = Vec::new();
 734                            let urls = panel.URLs();
 735                            for i in 0..urls.count() {
 736                                let url = urls.objectAtIndex(i);
 737                                if url.isFileURL() == YES
 738                                    && let Ok(path) = ns_url_to_path(url)
 739                                {
 740                                    result.push(path)
 741                                }
 742                            }
 743                            Some(result)
 744                        } else {
 745                            None
 746                        };
 747
 748                        if let Some(done_tx) = done_tx.take() {
 749                            let _ = done_tx.send(Ok(result));
 750                        }
 751                    });
 752                    let block = block.copy();
 753
 754                    if let Some(prompt) = options.prompt {
 755                        let _: () = msg_send![panel, setPrompt: ns_string(&prompt)];
 756                    }
 757
 758                    let _: () = msg_send![panel, beginWithCompletionHandler: block];
 759                }
 760            })
 761            .detach();
 762        done_rx
 763    }
 764
 765    fn prompt_for_new_path(
 766        &self,
 767        directory: &Path,
 768        suggested_name: Option<&str>,
 769    ) -> oneshot::Receiver<Result<Option<PathBuf>>> {
 770        let directory = directory.to_owned();
 771        let suggested_name = suggested_name.map(|s| s.to_owned());
 772        let (done_tx, done_rx) = oneshot::channel();
 773        self.foreground_executor()
 774            .spawn(async move {
 775                unsafe {
 776                    let panel = NSSavePanel::savePanel(nil);
 777                    let path = ns_string(directory.to_string_lossy().as_ref());
 778                    let url = NSURL::fileURLWithPath_isDirectory_(nil, path, true.to_objc());
 779                    panel.setDirectoryURL(url);
 780
 781                    if let Some(suggested_name) = suggested_name {
 782                        let name_string = ns_string(&suggested_name);
 783                        let _: () = msg_send![panel, setNameFieldStringValue: name_string];
 784                    }
 785
 786                    let done_tx = Cell::new(Some(done_tx));
 787                    let block = ConcreteBlock::new(move |response: NSModalResponse| {
 788                        let mut result = None;
 789                        if response == NSModalResponse::NSModalResponseOk {
 790                            let url = panel.URL();
 791                            if url.isFileURL() == YES {
 792                                result = ns_url_to_path(panel.URL()).ok().map(|mut result| {
 793                                    let Some(filename) = result.file_name() else {
 794                                        return result;
 795                                    };
 796                                    let chunks = filename
 797                                        .as_bytes()
 798                                        .split(|&b| b == b'.')
 799                                        .collect::<Vec<_>>();
 800
 801                                    // https://github.com/zed-industries/zed/issues/16969
 802                                    // Workaround a bug in macOS Sequoia that adds an extra file-extension
 803                                    // sometimes. e.g. `a.sql` becomes `a.sql.s` or `a.txtx` becomes `a.txtx.txt`
 804                                    //
 805                                    // This is conditional on OS version because I'd like to get rid of it, so that
 806                                    // you can manually create a file called `a.sql.s`. That said it seems better
 807                                    // to break that use-case than breaking `a.sql`.
 808                                    if chunks.len() == 3
 809                                        && chunks[1].starts_with(chunks[2])
 810                                        && Self::os_version() >= SemanticVersion::new(15, 0, 0)
 811                                    {
 812                                        let new_filename = OsStr::from_bytes(
 813                                            &filename.as_bytes()
 814                                                [..chunks[0].len() + 1 + chunks[1].len()],
 815                                        )
 816                                        .to_owned();
 817                                        result.set_file_name(&new_filename);
 818                                    }
 819                                    result
 820                                })
 821                            }
 822                        }
 823
 824                        if let Some(done_tx) = done_tx.take() {
 825                            let _ = done_tx.send(Ok(result));
 826                        }
 827                    });
 828                    let block = block.copy();
 829                    let _: () = msg_send![panel, beginWithCompletionHandler: block];
 830                }
 831            })
 832            .detach();
 833
 834        done_rx
 835    }
 836
 837    fn can_select_mixed_files_and_dirs(&self) -> bool {
 838        true
 839    }
 840
 841    fn reveal_path(&self, path: &Path) {
 842        unsafe {
 843            let path = path.to_path_buf();
 844            self.0
 845                .lock()
 846                .background_executor
 847                .spawn(async move {
 848                    let full_path = ns_string(path.to_str().unwrap_or(""));
 849                    let root_full_path = ns_string("");
 850                    let workspace: id = msg_send![class!(NSWorkspace), sharedWorkspace];
 851                    let _: BOOL = msg_send![
 852                        workspace,
 853                        selectFile: full_path
 854                        inFileViewerRootedAtPath: root_full_path
 855                    ];
 856                })
 857                .detach();
 858        }
 859    }
 860
 861    fn open_with_system(&self, path: &Path) {
 862        let path = path.to_owned();
 863        self.0
 864            .lock()
 865            .background_executor
 866            .spawn(async move {
 867                if let Some(mut child) = smol::process::Command::new("open")
 868                    .arg(path)
 869                    .spawn()
 870                    .context("invoking open command")
 871                    .log_err()
 872                {
 873                    child.status().await.log_err();
 874                }
 875            })
 876            .detach();
 877    }
 878
 879    fn on_quit(&self, callback: Box<dyn FnMut()>) {
 880        self.0.lock().quit = Some(callback);
 881    }
 882
 883    fn on_reopen(&self, callback: Box<dyn FnMut()>) {
 884        self.0.lock().reopen = Some(callback);
 885    }
 886
 887    fn on_keyboard_layout_change(&self, callback: Box<dyn FnMut()>) {
 888        self.0.lock().on_keyboard_layout_change = Some(callback);
 889    }
 890
 891    fn on_app_menu_action(&self, callback: Box<dyn FnMut(&dyn Action)>) {
 892        self.0.lock().menu_command = Some(callback);
 893    }
 894
 895    fn on_will_open_app_menu(&self, callback: Box<dyn FnMut()>) {
 896        self.0.lock().will_open_menu = Some(callback);
 897    }
 898
 899    fn on_validate_app_menu_command(&self, callback: Box<dyn FnMut(&dyn Action) -> bool>) {
 900        self.0.lock().validate_menu_command = Some(callback);
 901    }
 902
 903    fn keyboard_layout(&self) -> Box<dyn PlatformKeyboardLayout> {
 904        Box::new(MacKeyboardLayout::new())
 905    }
 906
 907    fn keyboard_mapper(&self) -> Rc<dyn PlatformKeyboardMapper> {
 908        self.0.lock().keyboard_mapper.clone()
 909    }
 910
 911    fn app_path(&self) -> Result<PathBuf> {
 912        unsafe {
 913            let bundle: id = NSBundle::mainBundle();
 914            anyhow::ensure!(!bundle.is_null(), "app is not running inside a bundle");
 915            Ok(path_from_objc(msg_send![bundle, bundlePath]))
 916        }
 917    }
 918
 919    fn set_menus(&self, menus: Vec<Menu>, keymap: &Keymap) {
 920        unsafe {
 921            let app: id = msg_send![APP_CLASS, sharedApplication];
 922            let mut state = self.0.lock();
 923            let actions = &mut state.menu_actions;
 924            let menu = self.create_menu_bar(&menus, NSWindow::delegate(app), actions, keymap);
 925            drop(state);
 926            app.setMainMenu_(menu);
 927        }
 928        self.0.lock().menus = Some(menus.into_iter().map(|menu| menu.owned()).collect());
 929    }
 930
 931    fn get_menus(&self) -> Option<Vec<OwnedMenu>> {
 932        self.0.lock().menus.clone()
 933    }
 934
 935    fn set_dock_menu(&self, menu: Vec<MenuItem>, keymap: &Keymap) {
 936        unsafe {
 937            let app: id = msg_send![APP_CLASS, sharedApplication];
 938            let mut state = self.0.lock();
 939            let actions = &mut state.menu_actions;
 940            let new = self.create_dock_menu(menu, NSWindow::delegate(app), actions, keymap);
 941            if let Some(old) = state.dock_menu.replace(new) {
 942                CFRelease(old as _)
 943            }
 944        }
 945    }
 946
 947    fn add_recent_document(&self, path: &Path) {
 948        if let Some(path_str) = path.to_str() {
 949            unsafe {
 950                let document_controller: id =
 951                    msg_send![class!(NSDocumentController), sharedDocumentController];
 952                let url: id = NSURL::fileURLWithPath_(nil, ns_string(path_str));
 953                let _: () = msg_send![document_controller, noteNewRecentDocumentURL:url];
 954            }
 955        }
 956    }
 957
 958    fn path_for_auxiliary_executable(&self, name: &str) -> Result<PathBuf> {
 959        unsafe {
 960            let bundle: id = NSBundle::mainBundle();
 961            anyhow::ensure!(!bundle.is_null(), "app is not running inside a bundle");
 962            let name = ns_string(name);
 963            let url: id = msg_send![bundle, URLForAuxiliaryExecutable: name];
 964            anyhow::ensure!(!url.is_null(), "resource not found");
 965            ns_url_to_path(url)
 966        }
 967    }
 968
 969    /// Match cursor style to one of the styles available
 970    /// in macOS's [NSCursor](https://developer.apple.com/documentation/appkit/nscursor).
 971    fn set_cursor_style(&self, style: CursorStyle) {
 972        unsafe {
 973            if style == CursorStyle::None {
 974                let _: () = msg_send![class!(NSCursor), setHiddenUntilMouseMoves:YES];
 975                return;
 976            }
 977
 978            let new_cursor: id = match style {
 979                CursorStyle::Arrow => msg_send![class!(NSCursor), arrowCursor],
 980                CursorStyle::IBeam => msg_send![class!(NSCursor), IBeamCursor],
 981                CursorStyle::Crosshair => msg_send![class!(NSCursor), crosshairCursor],
 982                CursorStyle::ClosedHand => msg_send![class!(NSCursor), closedHandCursor],
 983                CursorStyle::OpenHand => msg_send![class!(NSCursor), openHandCursor],
 984                CursorStyle::PointingHand => msg_send![class!(NSCursor), pointingHandCursor],
 985                CursorStyle::ResizeLeftRight => msg_send![class!(NSCursor), resizeLeftRightCursor],
 986                CursorStyle::ResizeUpDown => msg_send![class!(NSCursor), resizeUpDownCursor],
 987                CursorStyle::ResizeLeft => msg_send![class!(NSCursor), resizeLeftCursor],
 988                CursorStyle::ResizeRight => msg_send![class!(NSCursor), resizeRightCursor],
 989                CursorStyle::ResizeColumn => msg_send![class!(NSCursor), resizeLeftRightCursor],
 990                CursorStyle::ResizeRow => msg_send![class!(NSCursor), resizeUpDownCursor],
 991                CursorStyle::ResizeUp => msg_send![class!(NSCursor), resizeUpCursor],
 992                CursorStyle::ResizeDown => msg_send![class!(NSCursor), resizeDownCursor],
 993
 994                // Undocumented, private class methods:
 995                // https://stackoverflow.com/questions/27242353/cocoa-predefined-resize-mouse-cursor
 996                CursorStyle::ResizeUpLeftDownRight => {
 997                    msg_send![class!(NSCursor), _windowResizeNorthWestSouthEastCursor]
 998                }
 999                CursorStyle::ResizeUpRightDownLeft => {
1000                    msg_send![class!(NSCursor), _windowResizeNorthEastSouthWestCursor]
1001                }
1002
1003                CursorStyle::IBeamCursorForVerticalLayout => {
1004                    msg_send![class!(NSCursor), IBeamCursorForVerticalLayout]
1005                }
1006                CursorStyle::OperationNotAllowed => {
1007                    msg_send![class!(NSCursor), operationNotAllowedCursor]
1008                }
1009                CursorStyle::DragLink => msg_send![class!(NSCursor), dragLinkCursor],
1010                CursorStyle::DragCopy => msg_send![class!(NSCursor), dragCopyCursor],
1011                CursorStyle::ContextualMenu => msg_send![class!(NSCursor), contextualMenuCursor],
1012                CursorStyle::None => unreachable!(),
1013            };
1014
1015            let old_cursor: id = msg_send![class!(NSCursor), currentCursor];
1016            if new_cursor != old_cursor {
1017                let _: () = msg_send![new_cursor, set];
1018            }
1019        }
1020    }
1021
1022    fn should_auto_hide_scrollbars(&self) -> bool {
1023        #[allow(non_upper_case_globals)]
1024        const NSScrollerStyleOverlay: NSInteger = 1;
1025
1026        unsafe {
1027            let style: NSInteger = msg_send![class!(NSScroller), preferredScrollerStyle];
1028            style == NSScrollerStyleOverlay
1029        }
1030    }
1031
1032    fn write_to_clipboard(&self, item: ClipboardItem) {
1033        use crate::ClipboardEntry;
1034
1035        unsafe {
1036            // We only want to use NSAttributedString if there are multiple entries to write.
1037            if item.entries.len() <= 1 {
1038                match item.entries.first() {
1039                    Some(entry) => match entry {
1040                        ClipboardEntry::String(string) => {
1041                            self.write_plaintext_to_clipboard(string);
1042                        }
1043                        ClipboardEntry::Image(image) => {
1044                            self.write_image_to_clipboard(image);
1045                        }
1046                    },
1047                    None => {
1048                        // Writing an empty list of entries just clears the clipboard.
1049                        let state = self.0.lock();
1050                        state.pasteboard.clearContents();
1051                    }
1052                }
1053            } else {
1054                let mut any_images = false;
1055                let attributed_string = {
1056                    let mut buf = NSMutableAttributedString::alloc(nil)
1057                        // TODO can we skip this? Or at least part of it?
1058                        .init_attributed_string(NSString::alloc(nil).init_str(""));
1059
1060                    for entry in item.entries {
1061                        if let ClipboardEntry::String(ClipboardString { text, metadata: _ }) = entry
1062                        {
1063                            let to_append = NSAttributedString::alloc(nil)
1064                                .init_attributed_string(NSString::alloc(nil).init_str(&text));
1065
1066                            buf.appendAttributedString_(to_append);
1067                        }
1068                    }
1069
1070                    buf
1071                };
1072
1073                let state = self.0.lock();
1074                state.pasteboard.clearContents();
1075
1076                // Only set rich text clipboard types if we actually have 1+ images to include.
1077                if any_images {
1078                    let rtfd_data = attributed_string.RTFDFromRange_documentAttributes_(
1079                        NSRange::new(0, msg_send![attributed_string, length]),
1080                        nil,
1081                    );
1082                    if rtfd_data != nil {
1083                        state
1084                            .pasteboard
1085                            .setData_forType(rtfd_data, NSPasteboardTypeRTFD);
1086                    }
1087
1088                    let rtf_data = attributed_string.RTFFromRange_documentAttributes_(
1089                        NSRange::new(0, attributed_string.length()),
1090                        nil,
1091                    );
1092                    if rtf_data != nil {
1093                        state
1094                            .pasteboard
1095                            .setData_forType(rtf_data, NSPasteboardTypeRTF);
1096                    }
1097                }
1098
1099                let plain_text = attributed_string.string();
1100                state
1101                    .pasteboard
1102                    .setString_forType(plain_text, NSPasteboardTypeString);
1103            }
1104        }
1105    }
1106
1107    fn read_from_clipboard(&self) -> Option<ClipboardItem> {
1108        let state = self.0.lock();
1109        let pasteboard = state.pasteboard;
1110
1111        // First, see if it's a string.
1112        unsafe {
1113            let types: id = pasteboard.types();
1114            let string_type: id = ns_string("public.utf8-plain-text");
1115
1116            if msg_send![types, containsObject: string_type] {
1117                let data = pasteboard.dataForType(string_type);
1118                if data == nil {
1119                    return None;
1120                } else if data.bytes().is_null() {
1121                    // https://developer.apple.com/documentation/foundation/nsdata/1410616-bytes?language=objc
1122                    // "If the length of the NSData object is 0, this property returns nil."
1123                    return Some(self.read_string_from_clipboard(&state, &[]));
1124                } else {
1125                    let bytes =
1126                        slice::from_raw_parts(data.bytes() as *mut u8, data.length() as usize);
1127
1128                    return Some(self.read_string_from_clipboard(&state, bytes));
1129                }
1130            }
1131
1132            // Next, check for URL flavors (including file URLs). Some tools only provide a URL
1133            // with no plain text entry.
1134            {
1135                // Try the modern UTType identifiers first.
1136                let file_url_type: id = ns_string("public.file-url");
1137                let url_type: id = ns_string("public.url");
1138
1139                let url_data = if msg_send![types, containsObject: file_url_type] {
1140                    pasteboard.dataForType(file_url_type)
1141                } else if msg_send![types, containsObject: url_type] {
1142                    pasteboard.dataForType(url_type)
1143                } else {
1144                    nil
1145                };
1146
1147                if url_data != nil && !url_data.bytes().is_null() {
1148                    let bytes = slice::from_raw_parts(
1149                        url_data.bytes() as *mut u8,
1150                        url_data.length() as usize,
1151                    );
1152
1153                    return Some(self.read_string_from_clipboard(&state, bytes));
1154                }
1155            }
1156
1157            // If it wasn't a string or URL, try the various supported image types.
1158            for format in ImageFormat::iter() {
1159                if let Some(item) = try_clipboard_image(pasteboard, format) {
1160                    return Some(item);
1161                }
1162            }
1163        }
1164
1165        // If it wasn't a string, URL, or a supported image type, give up.
1166        None
1167    }
1168
1169    fn write_credentials(&self, url: &str, username: &str, password: &[u8]) -> Task<Result<()>> {
1170        let url = url.to_string();
1171        let username = username.to_string();
1172        let password = password.to_vec();
1173        self.background_executor().spawn(async move {
1174            unsafe {
1175                use security::*;
1176
1177                let url = CFString::from(url.as_str());
1178                let username = CFString::from(username.as_str());
1179                let password = CFData::from_buffer(&password);
1180
1181                // First, check if there are already credentials for the given server. If so, then
1182                // update the username and password.
1183                let mut verb = "updating";
1184                let mut query_attrs = CFMutableDictionary::with_capacity(2);
1185                query_attrs.set(kSecClass as *const _, kSecClassInternetPassword as *const _);
1186                query_attrs.set(kSecAttrServer as *const _, url.as_CFTypeRef());
1187
1188                let mut attrs = CFMutableDictionary::with_capacity(4);
1189                attrs.set(kSecClass as *const _, kSecClassInternetPassword as *const _);
1190                attrs.set(kSecAttrServer as *const _, url.as_CFTypeRef());
1191                attrs.set(kSecAttrAccount as *const _, username.as_CFTypeRef());
1192                attrs.set(kSecValueData as *const _, password.as_CFTypeRef());
1193
1194                let mut status = SecItemUpdate(
1195                    query_attrs.as_concrete_TypeRef(),
1196                    attrs.as_concrete_TypeRef(),
1197                );
1198
1199                // If there were no existing credentials for the given server, then create them.
1200                if status == errSecItemNotFound {
1201                    verb = "creating";
1202                    status = SecItemAdd(attrs.as_concrete_TypeRef(), ptr::null_mut());
1203                }
1204                anyhow::ensure!(status == errSecSuccess, "{verb} password failed: {status}");
1205            }
1206            Ok(())
1207        })
1208    }
1209
1210    fn read_credentials(&self, url: &str) -> Task<Result<Option<(String, Vec<u8>)>>> {
1211        let url = url.to_string();
1212        self.background_executor().spawn(async move {
1213            let url = CFString::from(url.as_str());
1214            let cf_true = CFBoolean::true_value().as_CFTypeRef();
1215
1216            unsafe {
1217                use security::*;
1218
1219                // Find any credentials for the given server URL.
1220                let mut attrs = CFMutableDictionary::with_capacity(5);
1221                attrs.set(kSecClass as *const _, kSecClassInternetPassword as *const _);
1222                attrs.set(kSecAttrServer as *const _, url.as_CFTypeRef());
1223                attrs.set(kSecReturnAttributes as *const _, cf_true);
1224                attrs.set(kSecReturnData as *const _, cf_true);
1225
1226                let mut result = CFTypeRef::from(ptr::null());
1227                let status = SecItemCopyMatching(attrs.as_concrete_TypeRef(), &mut result);
1228                match status {
1229                    security::errSecSuccess => {}
1230                    security::errSecItemNotFound | security::errSecUserCanceled => return Ok(None),
1231                    _ => anyhow::bail!("reading password failed: {status}"),
1232                }
1233
1234                let result = CFType::wrap_under_create_rule(result)
1235                    .downcast::<CFDictionary>()
1236                    .context("keychain item was not a dictionary")?;
1237                let username = result
1238                    .find(kSecAttrAccount as *const _)
1239                    .context("account was missing from keychain item")?;
1240                let username = CFType::wrap_under_get_rule(*username)
1241                    .downcast::<CFString>()
1242                    .context("account was not a string")?;
1243                let password = result
1244                    .find(kSecValueData as *const _)
1245                    .context("password was missing from keychain item")?;
1246                let password = CFType::wrap_under_get_rule(*password)
1247                    .downcast::<CFData>()
1248                    .context("password was not a string")?;
1249
1250                Ok(Some((username.to_string(), password.bytes().to_vec())))
1251            }
1252        })
1253    }
1254
1255    fn delete_credentials(&self, url: &str) -> Task<Result<()>> {
1256        let url = url.to_string();
1257
1258        self.background_executor().spawn(async move {
1259            unsafe {
1260                use security::*;
1261
1262                let url = CFString::from(url.as_str());
1263                let mut query_attrs = CFMutableDictionary::with_capacity(2);
1264                query_attrs.set(kSecClass as *const _, kSecClassInternetPassword as *const _);
1265                query_attrs.set(kSecAttrServer as *const _, url.as_CFTypeRef());
1266
1267                let status = SecItemDelete(query_attrs.as_concrete_TypeRef());
1268                anyhow::ensure!(status == errSecSuccess, "delete password failed: {status}");
1269            }
1270            Ok(())
1271        })
1272    }
1273}
1274
1275impl MacPlatform {
1276    unsafe fn read_string_from_clipboard(
1277        &self,
1278        state: &MacPlatformState,
1279        text_bytes: &[u8],
1280    ) -> ClipboardItem {
1281        unsafe {
1282            let text = String::from_utf8_lossy(text_bytes).to_string();
1283            let metadata = self
1284                .read_from_pasteboard(state.pasteboard, state.text_hash_pasteboard_type)
1285                .and_then(|hash_bytes| {
1286                    let hash_bytes = hash_bytes.try_into().ok()?;
1287                    let hash = u64::from_be_bytes(hash_bytes);
1288                    let metadata = self
1289                        .read_from_pasteboard(state.pasteboard, state.metadata_pasteboard_type)?;
1290
1291                    if hash == ClipboardString::text_hash(&text) {
1292                        String::from_utf8(metadata.to_vec()).ok()
1293                    } else {
1294                        None
1295                    }
1296                });
1297
1298            ClipboardItem {
1299                entries: vec![ClipboardEntry::String(ClipboardString { text, metadata })],
1300            }
1301        }
1302    }
1303
1304    unsafe fn write_plaintext_to_clipboard(&self, string: &ClipboardString) {
1305        unsafe {
1306            let state = self.0.lock();
1307            state.pasteboard.clearContents();
1308
1309            let text_bytes = NSData::dataWithBytes_length_(
1310                nil,
1311                string.text.as_ptr() as *const c_void,
1312                string.text.len() as u64,
1313            );
1314            state
1315                .pasteboard
1316                .setData_forType(text_bytes, NSPasteboardTypeString);
1317
1318            if let Some(metadata) = string.metadata.as_ref() {
1319                let hash_bytes = ClipboardString::text_hash(&string.text).to_be_bytes();
1320                let hash_bytes = NSData::dataWithBytes_length_(
1321                    nil,
1322                    hash_bytes.as_ptr() as *const c_void,
1323                    hash_bytes.len() as u64,
1324                );
1325                state
1326                    .pasteboard
1327                    .setData_forType(hash_bytes, state.text_hash_pasteboard_type);
1328
1329                let metadata_bytes = NSData::dataWithBytes_length_(
1330                    nil,
1331                    metadata.as_ptr() as *const c_void,
1332                    metadata.len() as u64,
1333                );
1334                state
1335                    .pasteboard
1336                    .setData_forType(metadata_bytes, state.metadata_pasteboard_type);
1337            }
1338        }
1339    }
1340
1341    unsafe fn write_image_to_clipboard(&self, image: &Image) {
1342        unsafe {
1343            let state = self.0.lock();
1344            state.pasteboard.clearContents();
1345
1346            let bytes = NSData::dataWithBytes_length_(
1347                nil,
1348                image.bytes.as_ptr() as *const c_void,
1349                image.bytes.len() as u64,
1350            );
1351
1352            state
1353                .pasteboard
1354                .setData_forType(bytes, Into::<UTType>::into(image.format).inner_mut());
1355        }
1356    }
1357}
1358
1359fn try_clipboard_image(pasteboard: id, format: ImageFormat) -> Option<ClipboardItem> {
1360    let mut ut_type: UTType = format.into();
1361
1362    unsafe {
1363        let types: id = pasteboard.types();
1364        if msg_send![types, containsObject: ut_type.inner()] {
1365            let data = pasteboard.dataForType(ut_type.inner_mut());
1366            if data == nil {
1367                None
1368            } else {
1369                let bytes = Vec::from(slice::from_raw_parts(
1370                    data.bytes() as *mut u8,
1371                    data.length() as usize,
1372                ));
1373                let id = hash(&bytes);
1374
1375                Some(ClipboardItem {
1376                    entries: vec![ClipboardEntry::Image(Image { format, bytes, id })],
1377                })
1378            }
1379        } else {
1380            None
1381        }
1382    }
1383}
1384
1385unsafe fn path_from_objc(path: id) -> PathBuf {
1386    let len = msg_send![path, lengthOfBytesUsingEncoding: NSUTF8StringEncoding];
1387    let bytes = unsafe { path.UTF8String() as *const u8 };
1388    let path = str::from_utf8(unsafe { slice::from_raw_parts(bytes, len) }).unwrap();
1389    PathBuf::from(path)
1390}
1391
1392unsafe fn get_mac_platform(object: &mut Object) -> &MacPlatform {
1393    unsafe {
1394        let platform_ptr: *mut c_void = *object.get_ivar(MAC_PLATFORM_IVAR);
1395        assert!(!platform_ptr.is_null());
1396        &*(platform_ptr as *const MacPlatform)
1397    }
1398}
1399
1400extern "C" fn will_finish_launching(_this: &mut Object, _: Sel, _: id) {
1401    unsafe {
1402        let user_defaults: id = msg_send![class!(NSUserDefaults), standardUserDefaults];
1403
1404        // The autofill heuristic controller causes slowdown and high CPU usage.
1405        // We don't know exactly why. This disables the full heuristic controller.
1406        //
1407        // Adapted from: https://github.com/ghostty-org/ghostty/pull/8625
1408        let name = ns_string("NSAutoFillHeuristicControllerEnabled");
1409        let existing_value: id = msg_send![user_defaults, objectForKey: name];
1410        if existing_value == nil {
1411            let false_value: id = msg_send![class!(NSNumber), numberWithBool:false];
1412            let _: () = msg_send![user_defaults, setObject: false_value forKey: name];
1413        }
1414    }
1415}
1416
1417extern "C" fn did_finish_launching(this: &mut Object, _: Sel, _: id) {
1418    unsafe {
1419        let app: id = msg_send![APP_CLASS, sharedApplication];
1420        app.setActivationPolicy_(NSApplicationActivationPolicyRegular);
1421
1422        let notification_center: *mut Object =
1423            msg_send![class!(NSNotificationCenter), defaultCenter];
1424        let name = ns_string("NSTextInputContextKeyboardSelectionDidChangeNotification");
1425        let _: () = msg_send![notification_center, addObserver: this as id
1426            selector: sel!(onKeyboardLayoutChange:)
1427            name: name
1428            object: nil
1429        ];
1430
1431        let platform = get_mac_platform(this);
1432        let callback = platform.0.lock().finish_launching.take();
1433        if let Some(callback) = callback {
1434            callback();
1435        }
1436    }
1437}
1438
1439extern "C" fn should_handle_reopen(this: &mut Object, _: Sel, _: id, has_open_windows: bool) {
1440    if !has_open_windows {
1441        let platform = unsafe { get_mac_platform(this) };
1442        let mut lock = platform.0.lock();
1443        if let Some(mut callback) = lock.reopen.take() {
1444            drop(lock);
1445            callback();
1446            platform.0.lock().reopen.get_or_insert(callback);
1447        }
1448    }
1449}
1450
1451extern "C" fn will_terminate(this: &mut Object, _: Sel, _: id) {
1452    let platform = unsafe { get_mac_platform(this) };
1453    let mut lock = platform.0.lock();
1454    if let Some(mut callback) = lock.quit.take() {
1455        drop(lock);
1456        callback();
1457        platform.0.lock().quit.get_or_insert(callback);
1458    }
1459}
1460
1461extern "C" fn on_keyboard_layout_change(this: &mut Object, _: Sel, _: id) {
1462    let platform = unsafe { get_mac_platform(this) };
1463    let mut lock = platform.0.lock();
1464    let keyboard_layout = MacKeyboardLayout::new();
1465    lock.keyboard_mapper = Rc::new(MacKeyboardMapper::new(keyboard_layout.id()));
1466    if let Some(mut callback) = lock.on_keyboard_layout_change.take() {
1467        drop(lock);
1468        callback();
1469        platform
1470            .0
1471            .lock()
1472            .on_keyboard_layout_change
1473            .get_or_insert(callback);
1474    }
1475}
1476
1477extern "C" fn open_urls(this: &mut Object, _: Sel, _: id, urls: id) {
1478    let urls = unsafe {
1479        (0..urls.count())
1480            .filter_map(|i| {
1481                let url = urls.objectAtIndex(i);
1482                match CStr::from_ptr(url.absoluteString().UTF8String() as *mut c_char).to_str() {
1483                    Ok(string) => Some(string.to_string()),
1484                    Err(err) => {
1485                        log::error!("error converting path to string: {}", err);
1486                        None
1487                    }
1488                }
1489            })
1490            .collect::<Vec<_>>()
1491    };
1492    let platform = unsafe { get_mac_platform(this) };
1493    let mut lock = platform.0.lock();
1494    if let Some(mut callback) = lock.open_urls.take() {
1495        drop(lock);
1496        callback(urls);
1497        platform.0.lock().open_urls.get_or_insert(callback);
1498    }
1499}
1500
1501extern "C" fn handle_menu_item(this: &mut Object, _: Sel, item: id) {
1502    unsafe {
1503        let platform = get_mac_platform(this);
1504        let mut lock = platform.0.lock();
1505        if let Some(mut callback) = lock.menu_command.take() {
1506            let tag: NSInteger = msg_send![item, tag];
1507            let index = tag as usize;
1508            if let Some(action) = lock.menu_actions.get(index) {
1509                let action = action.boxed_clone();
1510                drop(lock);
1511                callback(&*action);
1512            }
1513            platform.0.lock().menu_command.get_or_insert(callback);
1514        }
1515    }
1516}
1517
1518extern "C" fn validate_menu_item(this: &mut Object, _: Sel, item: id) -> bool {
1519    unsafe {
1520        let mut result = false;
1521        let platform = get_mac_platform(this);
1522        let mut lock = platform.0.lock();
1523        if let Some(mut callback) = lock.validate_menu_command.take() {
1524            let tag: NSInteger = msg_send![item, tag];
1525            let index = tag as usize;
1526            if let Some(action) = lock.menu_actions.get(index) {
1527                let action = action.boxed_clone();
1528                drop(lock);
1529                result = callback(action.as_ref());
1530            }
1531            platform
1532                .0
1533                .lock()
1534                .validate_menu_command
1535                .get_or_insert(callback);
1536        }
1537        result
1538    }
1539}
1540
1541extern "C" fn menu_will_open(this: &mut Object, _: Sel, _: id) {
1542    unsafe {
1543        let platform = get_mac_platform(this);
1544        let mut lock = platform.0.lock();
1545        if let Some(mut callback) = lock.will_open_menu.take() {
1546            drop(lock);
1547            callback();
1548            platform.0.lock().will_open_menu.get_or_insert(callback);
1549        }
1550    }
1551}
1552
1553extern "C" fn handle_dock_menu(this: &mut Object, _: Sel, _: id) -> id {
1554    unsafe {
1555        let platform = get_mac_platform(this);
1556        let mut state = platform.0.lock();
1557        if let Some(id) = state.dock_menu {
1558            id
1559        } else {
1560            nil
1561        }
1562    }
1563}
1564
1565unsafe fn ns_string(string: &str) -> id {
1566    unsafe { NSString::alloc(nil).init_str(string).autorelease() }
1567}
1568
1569unsafe fn ns_url_to_path(url: id) -> Result<PathBuf> {
1570    let path: *mut c_char = msg_send![url, fileSystemRepresentation];
1571    anyhow::ensure!(!path.is_null(), "url is not a file path: {}", unsafe {
1572        CStr::from_ptr(url.absoluteString().UTF8String()).to_string_lossy()
1573    });
1574    Ok(PathBuf::from(OsStr::from_bytes(unsafe {
1575        CStr::from_ptr(path).to_bytes()
1576    })))
1577}
1578
1579#[link(name = "Carbon", kind = "framework")]
1580unsafe extern "C" {
1581    pub(super) fn TISCopyCurrentKeyboardLayoutInputSource() -> *mut Object;
1582    pub(super) fn TISGetInputSourceProperty(
1583        inputSource: *mut Object,
1584        propertyKey: *const c_void,
1585    ) -> *mut Object;
1586
1587    pub(super) fn UCKeyTranslate(
1588        keyLayoutPtr: *const ::std::os::raw::c_void,
1589        virtualKeyCode: u16,
1590        keyAction: u16,
1591        modifierKeyState: u32,
1592        keyboardType: u32,
1593        keyTranslateOptions: u32,
1594        deadKeyState: *mut u32,
1595        maxStringLength: usize,
1596        actualStringLength: *mut usize,
1597        unicodeString: *mut u16,
1598    ) -> u32;
1599    pub(super) fn LMGetKbdType() -> u16;
1600    pub(super) static kTISPropertyUnicodeKeyLayoutData: CFStringRef;
1601    pub(super) static kTISPropertyInputSourceID: CFStringRef;
1602    pub(super) static kTISPropertyLocalizedName: CFStringRef;
1603}
1604
1605mod security {
1606    #![allow(non_upper_case_globals)]
1607    use super::*;
1608
1609    #[link(name = "Security", kind = "framework")]
1610    unsafe extern "C" {
1611        pub static kSecClass: CFStringRef;
1612        pub static kSecClassInternetPassword: CFStringRef;
1613        pub static kSecAttrServer: CFStringRef;
1614        pub static kSecAttrAccount: CFStringRef;
1615        pub static kSecValueData: CFStringRef;
1616        pub static kSecReturnAttributes: CFStringRef;
1617        pub static kSecReturnData: CFStringRef;
1618
1619        pub fn SecItemAdd(attributes: CFDictionaryRef, result: *mut CFTypeRef) -> OSStatus;
1620        pub fn SecItemUpdate(query: CFDictionaryRef, attributes: CFDictionaryRef) -> OSStatus;
1621        pub fn SecItemDelete(query: CFDictionaryRef) -> OSStatus;
1622        pub fn SecItemCopyMatching(query: CFDictionaryRef, result: *mut CFTypeRef) -> OSStatus;
1623    }
1624
1625    pub const errSecSuccess: OSStatus = 0;
1626    pub const errSecUserCanceled: OSStatus = -128;
1627    pub const errSecItemNotFound: OSStatus = -25300;
1628}
1629
1630impl From<ImageFormat> for UTType {
1631    fn from(value: ImageFormat) -> Self {
1632        match value {
1633            ImageFormat::Png => Self::png(),
1634            ImageFormat::Jpeg => Self::jpeg(),
1635            ImageFormat::Tiff => Self::tiff(),
1636            ImageFormat::Webp => Self::webp(),
1637            ImageFormat::Gif => Self::gif(),
1638            ImageFormat::Bmp => Self::bmp(),
1639            ImageFormat::Svg => Self::svg(),
1640            ImageFormat::Ico => Self::ico(),
1641        }
1642    }
1643}
1644
1645// See https://developer.apple.com/documentation/uniformtypeidentifiers/uttype-swift.struct/
1646struct UTType(id);
1647
1648impl UTType {
1649    pub fn png() -> Self {
1650        // https://developer.apple.com/documentation/uniformtypeidentifiers/uttype-swift.struct/png
1651        Self(unsafe { NSPasteboardTypePNG }) // This is a rare case where there's a built-in NSPasteboardType
1652    }
1653
1654    pub fn jpeg() -> Self {
1655        // https://developer.apple.com/documentation/uniformtypeidentifiers/uttype-swift.struct/jpeg
1656        Self(unsafe { ns_string("public.jpeg") })
1657    }
1658
1659    pub fn gif() -> Self {
1660        // https://developer.apple.com/documentation/uniformtypeidentifiers/uttype-swift.struct/gif
1661        Self(unsafe { ns_string("com.compuserve.gif") })
1662    }
1663
1664    pub fn webp() -> Self {
1665        // https://developer.apple.com/documentation/uniformtypeidentifiers/uttype-swift.struct/webp
1666        Self(unsafe { ns_string("org.webmproject.webp") })
1667    }
1668
1669    pub fn bmp() -> Self {
1670        // https://developer.apple.com/documentation/uniformtypeidentifiers/uttype-swift.struct/bmp
1671        Self(unsafe { ns_string("com.microsoft.bmp") })
1672    }
1673
1674    pub fn svg() -> Self {
1675        // https://developer.apple.com/documentation/uniformtypeidentifiers/uttype-swift.struct/svg
1676        Self(unsafe { ns_string("public.svg-image") })
1677    }
1678
1679    pub fn ico() -> Self {
1680        // https://developer.apple.com/documentation/uniformtypeidentifiers/uttype-swift.struct/ico
1681        Self(unsafe { ns_string("com.microsoft.ico") })
1682    }
1683
1684    pub fn tiff() -> Self {
1685        // https://developer.apple.com/documentation/uniformtypeidentifiers/uttype-swift.struct/tiff
1686        Self(unsafe { NSPasteboardTypeTIFF }) // This is a rare case where there's a built-in NSPasteboardType
1687    }
1688
1689    fn inner(&self) -> *const Object {
1690        self.0
1691    }
1692
1693    fn inner_mut(&self) -> *mut Object {
1694        self.0 as *mut _
1695    }
1696}
1697
1698#[cfg(test)]
1699mod tests {
1700    use crate::ClipboardItem;
1701
1702    use super::*;
1703
1704    #[test]
1705    fn test_clipboard() {
1706        let platform = build_platform();
1707        assert_eq!(platform.read_from_clipboard(), None);
1708
1709        let item = ClipboardItem::new_string("1".to_string());
1710        platform.write_to_clipboard(item.clone());
1711        assert_eq!(platform.read_from_clipboard(), Some(item));
1712
1713        let item = ClipboardItem {
1714            entries: vec![ClipboardEntry::String(
1715                ClipboardString::new("2".to_string()).with_json_metadata(vec![3, 4]),
1716            )],
1717        };
1718        platform.write_to_clipboard(item.clone());
1719        assert_eq!(platform.read_from_clipboard(), Some(item));
1720
1721        let text_from_other_app = "text from other app";
1722        unsafe {
1723            let bytes = NSData::dataWithBytes_length_(
1724                nil,
1725                text_from_other_app.as_ptr() as *const c_void,
1726                text_from_other_app.len() as u64,
1727            );
1728            platform
1729                .0
1730                .lock()
1731                .pasteboard
1732                .setData_forType(bytes, NSPasteboardTypeString);
1733        }
1734        assert_eq!(
1735            platform.read_from_clipboard(),
1736            Some(ClipboardItem::new_string(text_from_other_app.to_string()))
1737        );
1738    }
1739
1740    #[test]
1741    fn test_file_url_reads_as_url_string() {
1742        let platform = build_platform();
1743
1744        // Create a file URL for an arbitrary test path and write it to the pasteboard.
1745        // This path does not need to exist; we only validate URL→path conversion.
1746        let mock_path = "/tmp/zed-clipboard-file-url-test";
1747        unsafe {
1748            // Build an NSURL from the file path
1749            let url: id = msg_send![class!(NSURL), fileURLWithPath: ns_string(mock_path)];
1750            let abs: id = msg_send![url, absoluteString];
1751
1752            // Encode the URL string as UTF-8 bytes
1753            let len: usize = msg_send![abs, lengthOfBytesUsingEncoding: NSUTF8StringEncoding];
1754            let bytes_ptr = abs.UTF8String() as *const u8;
1755            let data = NSData::dataWithBytes_length_(nil, bytes_ptr as *const c_void, len as u64);
1756
1757            // Write as public.file-url to the unique pasteboard
1758            let file_url_type: id = ns_string("public.file-url");
1759            platform
1760                .0
1761                .lock()
1762                .pasteboard
1763                .setData_forType(data, file_url_type);
1764        }
1765
1766        // Ensure the clipboard read returns the URL string, not a converted path
1767        let expected_url = format!("file://{}", mock_path);
1768        assert_eq!(
1769            platform.read_from_clipboard(),
1770            Some(ClipboardItem::new_string(expected_url))
1771        );
1772    }
1773
1774    fn build_platform() -> MacPlatform {
1775        let platform = MacPlatform::new(false);
1776        platform.0.lock().pasteboard = unsafe { NSPasteboard::pasteboardWithUniqueName(nil) };
1777        platform
1778    }
1779}