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            // If it wasn't a string, try the various supported image types.
1136            for format in ImageFormat::iter() {
1137                if let Some(item) = try_clipboard_image(pasteboard, format) {
1138                    return Some(item);
1139                }
1140            }
1141        }
1142
1143        // If it wasn't a string or a supported image type, give up.
1144        None
1145    }
1146
1147    fn write_credentials(&self, url: &str, username: &str, password: &[u8]) -> Task<Result<()>> {
1148        let url = url.to_string();
1149        let username = username.to_string();
1150        let password = password.to_vec();
1151        self.background_executor().spawn(async move {
1152            unsafe {
1153                use security::*;
1154
1155                let url = CFString::from(url.as_str());
1156                let username = CFString::from(username.as_str());
1157                let password = CFData::from_buffer(&password);
1158
1159                // First, check if there are already credentials for the given server. If so, then
1160                // update the username and password.
1161                let mut verb = "updating";
1162                let mut query_attrs = CFMutableDictionary::with_capacity(2);
1163                query_attrs.set(kSecClass as *const _, kSecClassInternetPassword as *const _);
1164                query_attrs.set(kSecAttrServer as *const _, url.as_CFTypeRef());
1165
1166                let mut attrs = CFMutableDictionary::with_capacity(4);
1167                attrs.set(kSecClass as *const _, kSecClassInternetPassword as *const _);
1168                attrs.set(kSecAttrServer as *const _, url.as_CFTypeRef());
1169                attrs.set(kSecAttrAccount as *const _, username.as_CFTypeRef());
1170                attrs.set(kSecValueData as *const _, password.as_CFTypeRef());
1171
1172                let mut status = SecItemUpdate(
1173                    query_attrs.as_concrete_TypeRef(),
1174                    attrs.as_concrete_TypeRef(),
1175                );
1176
1177                // If there were no existing credentials for the given server, then create them.
1178                if status == errSecItemNotFound {
1179                    verb = "creating";
1180                    status = SecItemAdd(attrs.as_concrete_TypeRef(), ptr::null_mut());
1181                }
1182                anyhow::ensure!(status == errSecSuccess, "{verb} password failed: {status}");
1183            }
1184            Ok(())
1185        })
1186    }
1187
1188    fn read_credentials(&self, url: &str) -> Task<Result<Option<(String, Vec<u8>)>>> {
1189        let url = url.to_string();
1190        self.background_executor().spawn(async move {
1191            let url = CFString::from(url.as_str());
1192            let cf_true = CFBoolean::true_value().as_CFTypeRef();
1193
1194            unsafe {
1195                use security::*;
1196
1197                // Find any credentials for the given server URL.
1198                let mut attrs = CFMutableDictionary::with_capacity(5);
1199                attrs.set(kSecClass as *const _, kSecClassInternetPassword as *const _);
1200                attrs.set(kSecAttrServer as *const _, url.as_CFTypeRef());
1201                attrs.set(kSecReturnAttributes as *const _, cf_true);
1202                attrs.set(kSecReturnData as *const _, cf_true);
1203
1204                let mut result = CFTypeRef::from(ptr::null());
1205                let status = SecItemCopyMatching(attrs.as_concrete_TypeRef(), &mut result);
1206                match status {
1207                    security::errSecSuccess => {}
1208                    security::errSecItemNotFound | security::errSecUserCanceled => return Ok(None),
1209                    _ => anyhow::bail!("reading password failed: {status}"),
1210                }
1211
1212                let result = CFType::wrap_under_create_rule(result)
1213                    .downcast::<CFDictionary>()
1214                    .context("keychain item was not a dictionary")?;
1215                let username = result
1216                    .find(kSecAttrAccount as *const _)
1217                    .context("account was missing from keychain item")?;
1218                let username = CFType::wrap_under_get_rule(*username)
1219                    .downcast::<CFString>()
1220                    .context("account was not a string")?;
1221                let password = result
1222                    .find(kSecValueData as *const _)
1223                    .context("password was missing from keychain item")?;
1224                let password = CFType::wrap_under_get_rule(*password)
1225                    .downcast::<CFData>()
1226                    .context("password was not a string")?;
1227
1228                Ok(Some((username.to_string(), password.bytes().to_vec())))
1229            }
1230        })
1231    }
1232
1233    fn delete_credentials(&self, url: &str) -> Task<Result<()>> {
1234        let url = url.to_string();
1235
1236        self.background_executor().spawn(async move {
1237            unsafe {
1238                use security::*;
1239
1240                let url = CFString::from(url.as_str());
1241                let mut query_attrs = CFMutableDictionary::with_capacity(2);
1242                query_attrs.set(kSecClass as *const _, kSecClassInternetPassword as *const _);
1243                query_attrs.set(kSecAttrServer as *const _, url.as_CFTypeRef());
1244
1245                let status = SecItemDelete(query_attrs.as_concrete_TypeRef());
1246                anyhow::ensure!(status == errSecSuccess, "delete password failed: {status}");
1247            }
1248            Ok(())
1249        })
1250    }
1251}
1252
1253impl MacPlatform {
1254    unsafe fn read_string_from_clipboard(
1255        &self,
1256        state: &MacPlatformState,
1257        text_bytes: &[u8],
1258    ) -> ClipboardItem {
1259        unsafe {
1260            let text = String::from_utf8_lossy(text_bytes).to_string();
1261            let metadata = self
1262                .read_from_pasteboard(state.pasteboard, state.text_hash_pasteboard_type)
1263                .and_then(|hash_bytes| {
1264                    let hash_bytes = hash_bytes.try_into().ok()?;
1265                    let hash = u64::from_be_bytes(hash_bytes);
1266                    let metadata = self
1267                        .read_from_pasteboard(state.pasteboard, state.metadata_pasteboard_type)?;
1268
1269                    if hash == ClipboardString::text_hash(&text) {
1270                        String::from_utf8(metadata.to_vec()).ok()
1271                    } else {
1272                        None
1273                    }
1274                });
1275
1276            ClipboardItem {
1277                entries: vec![ClipboardEntry::String(ClipboardString { text, metadata })],
1278            }
1279        }
1280    }
1281
1282    unsafe fn write_plaintext_to_clipboard(&self, string: &ClipboardString) {
1283        unsafe {
1284            let state = self.0.lock();
1285            state.pasteboard.clearContents();
1286
1287            let text_bytes = NSData::dataWithBytes_length_(
1288                nil,
1289                string.text.as_ptr() as *const c_void,
1290                string.text.len() as u64,
1291            );
1292            state
1293                .pasteboard
1294                .setData_forType(text_bytes, NSPasteboardTypeString);
1295
1296            if let Some(metadata) = string.metadata.as_ref() {
1297                let hash_bytes = ClipboardString::text_hash(&string.text).to_be_bytes();
1298                let hash_bytes = NSData::dataWithBytes_length_(
1299                    nil,
1300                    hash_bytes.as_ptr() as *const c_void,
1301                    hash_bytes.len() as u64,
1302                );
1303                state
1304                    .pasteboard
1305                    .setData_forType(hash_bytes, state.text_hash_pasteboard_type);
1306
1307                let metadata_bytes = NSData::dataWithBytes_length_(
1308                    nil,
1309                    metadata.as_ptr() as *const c_void,
1310                    metadata.len() as u64,
1311                );
1312                state
1313                    .pasteboard
1314                    .setData_forType(metadata_bytes, state.metadata_pasteboard_type);
1315            }
1316        }
1317    }
1318
1319    unsafe fn write_image_to_clipboard(&self, image: &Image) {
1320        unsafe {
1321            let state = self.0.lock();
1322            state.pasteboard.clearContents();
1323
1324            let bytes = NSData::dataWithBytes_length_(
1325                nil,
1326                image.bytes.as_ptr() as *const c_void,
1327                image.bytes.len() as u64,
1328            );
1329
1330            state
1331                .pasteboard
1332                .setData_forType(bytes, Into::<UTType>::into(image.format).inner_mut());
1333        }
1334    }
1335}
1336
1337fn try_clipboard_image(pasteboard: id, format: ImageFormat) -> Option<ClipboardItem> {
1338    let mut ut_type: UTType = format.into();
1339
1340    unsafe {
1341        let types: id = pasteboard.types();
1342        if msg_send![types, containsObject: ut_type.inner()] {
1343            let data = pasteboard.dataForType(ut_type.inner_mut());
1344            if data == nil {
1345                None
1346            } else {
1347                let bytes = Vec::from(slice::from_raw_parts(
1348                    data.bytes() as *mut u8,
1349                    data.length() as usize,
1350                ));
1351                let id = hash(&bytes);
1352
1353                Some(ClipboardItem {
1354                    entries: vec![ClipboardEntry::Image(Image { format, bytes, id })],
1355                })
1356            }
1357        } else {
1358            None
1359        }
1360    }
1361}
1362
1363unsafe fn path_from_objc(path: id) -> PathBuf {
1364    let len = msg_send![path, lengthOfBytesUsingEncoding: NSUTF8StringEncoding];
1365    let bytes = unsafe { path.UTF8String() as *const u8 };
1366    let path = str::from_utf8(unsafe { slice::from_raw_parts(bytes, len) }).unwrap();
1367    PathBuf::from(path)
1368}
1369
1370unsafe fn get_mac_platform(object: &mut Object) -> &MacPlatform {
1371    unsafe {
1372        let platform_ptr: *mut c_void = *object.get_ivar(MAC_PLATFORM_IVAR);
1373        assert!(!platform_ptr.is_null());
1374        &*(platform_ptr as *const MacPlatform)
1375    }
1376}
1377
1378extern "C" fn will_finish_launching(_this: &mut Object, _: Sel, _: id) {
1379    unsafe {
1380        let user_defaults: id = msg_send![class!(NSUserDefaults), standardUserDefaults];
1381
1382        // The autofill heuristic controller causes slowdown and high CPU usage.
1383        // We don't know exactly why. This disables the full heuristic controller.
1384        //
1385        // Adapted from: https://github.com/ghostty-org/ghostty/pull/8625
1386        let name = ns_string("NSAutoFillHeuristicControllerEnabled");
1387        let existing_value: id = msg_send![user_defaults, objectForKey: name];
1388        if existing_value == nil {
1389            let false_value: id = msg_send![class!(NSNumber), numberWithBool:false];
1390            let _: () = msg_send![user_defaults, setObject: false_value forKey: name];
1391        }
1392    }
1393}
1394
1395extern "C" fn did_finish_launching(this: &mut Object, _: Sel, _: id) {
1396    unsafe {
1397        let app: id = msg_send![APP_CLASS, sharedApplication];
1398        app.setActivationPolicy_(NSApplicationActivationPolicyRegular);
1399
1400        let notification_center: *mut Object =
1401            msg_send![class!(NSNotificationCenter), defaultCenter];
1402        let name = ns_string("NSTextInputContextKeyboardSelectionDidChangeNotification");
1403        let _: () = msg_send![notification_center, addObserver: this as id
1404            selector: sel!(onKeyboardLayoutChange:)
1405            name: name
1406            object: nil
1407        ];
1408
1409        let platform = get_mac_platform(this);
1410        let callback = platform.0.lock().finish_launching.take();
1411        if let Some(callback) = callback {
1412            callback();
1413        }
1414    }
1415}
1416
1417extern "C" fn should_handle_reopen(this: &mut Object, _: Sel, _: id, has_open_windows: bool) {
1418    if !has_open_windows {
1419        let platform = unsafe { get_mac_platform(this) };
1420        let mut lock = platform.0.lock();
1421        if let Some(mut callback) = lock.reopen.take() {
1422            drop(lock);
1423            callback();
1424            platform.0.lock().reopen.get_or_insert(callback);
1425        }
1426    }
1427}
1428
1429extern "C" fn will_terminate(this: &mut Object, _: Sel, _: id) {
1430    let platform = unsafe { get_mac_platform(this) };
1431    let mut lock = platform.0.lock();
1432    if let Some(mut callback) = lock.quit.take() {
1433        drop(lock);
1434        callback();
1435        platform.0.lock().quit.get_or_insert(callback);
1436    }
1437}
1438
1439extern "C" fn on_keyboard_layout_change(this: &mut Object, _: Sel, _: id) {
1440    let platform = unsafe { get_mac_platform(this) };
1441    let mut lock = platform.0.lock();
1442    let keyboard_layout = MacKeyboardLayout::new();
1443    lock.keyboard_mapper = Rc::new(MacKeyboardMapper::new(keyboard_layout.id()));
1444    if let Some(mut callback) = lock.on_keyboard_layout_change.take() {
1445        drop(lock);
1446        callback();
1447        platform
1448            .0
1449            .lock()
1450            .on_keyboard_layout_change
1451            .get_or_insert(callback);
1452    }
1453}
1454
1455extern "C" fn open_urls(this: &mut Object, _: Sel, _: id, urls: id) {
1456    let urls = unsafe {
1457        (0..urls.count())
1458            .filter_map(|i| {
1459                let url = urls.objectAtIndex(i);
1460                match CStr::from_ptr(url.absoluteString().UTF8String() as *mut c_char).to_str() {
1461                    Ok(string) => Some(string.to_string()),
1462                    Err(err) => {
1463                        log::error!("error converting path to string: {}", err);
1464                        None
1465                    }
1466                }
1467            })
1468            .collect::<Vec<_>>()
1469    };
1470    let platform = unsafe { get_mac_platform(this) };
1471    let mut lock = platform.0.lock();
1472    if let Some(mut callback) = lock.open_urls.take() {
1473        drop(lock);
1474        callback(urls);
1475        platform.0.lock().open_urls.get_or_insert(callback);
1476    }
1477}
1478
1479extern "C" fn handle_menu_item(this: &mut Object, _: Sel, item: id) {
1480    unsafe {
1481        let platform = get_mac_platform(this);
1482        let mut lock = platform.0.lock();
1483        if let Some(mut callback) = lock.menu_command.take() {
1484            let tag: NSInteger = msg_send![item, tag];
1485            let index = tag as usize;
1486            if let Some(action) = lock.menu_actions.get(index) {
1487                let action = action.boxed_clone();
1488                drop(lock);
1489                callback(&*action);
1490            }
1491            platform.0.lock().menu_command.get_or_insert(callback);
1492        }
1493    }
1494}
1495
1496extern "C" fn validate_menu_item(this: &mut Object, _: Sel, item: id) -> bool {
1497    unsafe {
1498        let mut result = false;
1499        let platform = get_mac_platform(this);
1500        let mut lock = platform.0.lock();
1501        if let Some(mut callback) = lock.validate_menu_command.take() {
1502            let tag: NSInteger = msg_send![item, tag];
1503            let index = tag as usize;
1504            if let Some(action) = lock.menu_actions.get(index) {
1505                let action = action.boxed_clone();
1506                drop(lock);
1507                result = callback(action.as_ref());
1508            }
1509            platform
1510                .0
1511                .lock()
1512                .validate_menu_command
1513                .get_or_insert(callback);
1514        }
1515        result
1516    }
1517}
1518
1519extern "C" fn menu_will_open(this: &mut Object, _: Sel, _: id) {
1520    unsafe {
1521        let platform = get_mac_platform(this);
1522        let mut lock = platform.0.lock();
1523        if let Some(mut callback) = lock.will_open_menu.take() {
1524            drop(lock);
1525            callback();
1526            platform.0.lock().will_open_menu.get_or_insert(callback);
1527        }
1528    }
1529}
1530
1531extern "C" fn handle_dock_menu(this: &mut Object, _: Sel, _: id) -> id {
1532    unsafe {
1533        let platform = get_mac_platform(this);
1534        let mut state = platform.0.lock();
1535        if let Some(id) = state.dock_menu {
1536            id
1537        } else {
1538            nil
1539        }
1540    }
1541}
1542
1543unsafe fn ns_string(string: &str) -> id {
1544    unsafe { NSString::alloc(nil).init_str(string).autorelease() }
1545}
1546
1547unsafe fn ns_url_to_path(url: id) -> Result<PathBuf> {
1548    let path: *mut c_char = msg_send![url, fileSystemRepresentation];
1549    anyhow::ensure!(!path.is_null(), "url is not a file path: {}", unsafe {
1550        CStr::from_ptr(url.absoluteString().UTF8String()).to_string_lossy()
1551    });
1552    Ok(PathBuf::from(OsStr::from_bytes(unsafe {
1553        CStr::from_ptr(path).to_bytes()
1554    })))
1555}
1556
1557#[link(name = "Carbon", kind = "framework")]
1558unsafe extern "C" {
1559    pub(super) fn TISCopyCurrentKeyboardLayoutInputSource() -> *mut Object;
1560    pub(super) fn TISGetInputSourceProperty(
1561        inputSource: *mut Object,
1562        propertyKey: *const c_void,
1563    ) -> *mut Object;
1564
1565    pub(super) fn UCKeyTranslate(
1566        keyLayoutPtr: *const ::std::os::raw::c_void,
1567        virtualKeyCode: u16,
1568        keyAction: u16,
1569        modifierKeyState: u32,
1570        keyboardType: u32,
1571        keyTranslateOptions: u32,
1572        deadKeyState: *mut u32,
1573        maxStringLength: usize,
1574        actualStringLength: *mut usize,
1575        unicodeString: *mut u16,
1576    ) -> u32;
1577    pub(super) fn LMGetKbdType() -> u16;
1578    pub(super) static kTISPropertyUnicodeKeyLayoutData: CFStringRef;
1579    pub(super) static kTISPropertyInputSourceID: CFStringRef;
1580    pub(super) static kTISPropertyLocalizedName: CFStringRef;
1581}
1582
1583mod security {
1584    #![allow(non_upper_case_globals)]
1585    use super::*;
1586
1587    #[link(name = "Security", kind = "framework")]
1588    unsafe extern "C" {
1589        pub static kSecClass: CFStringRef;
1590        pub static kSecClassInternetPassword: CFStringRef;
1591        pub static kSecAttrServer: CFStringRef;
1592        pub static kSecAttrAccount: CFStringRef;
1593        pub static kSecValueData: CFStringRef;
1594        pub static kSecReturnAttributes: CFStringRef;
1595        pub static kSecReturnData: CFStringRef;
1596
1597        pub fn SecItemAdd(attributes: CFDictionaryRef, result: *mut CFTypeRef) -> OSStatus;
1598        pub fn SecItemUpdate(query: CFDictionaryRef, attributes: CFDictionaryRef) -> OSStatus;
1599        pub fn SecItemDelete(query: CFDictionaryRef) -> OSStatus;
1600        pub fn SecItemCopyMatching(query: CFDictionaryRef, result: *mut CFTypeRef) -> OSStatus;
1601    }
1602
1603    pub const errSecSuccess: OSStatus = 0;
1604    pub const errSecUserCanceled: OSStatus = -128;
1605    pub const errSecItemNotFound: OSStatus = -25300;
1606}
1607
1608impl From<ImageFormat> for UTType {
1609    fn from(value: ImageFormat) -> Self {
1610        match value {
1611            ImageFormat::Png => Self::png(),
1612            ImageFormat::Jpeg => Self::jpeg(),
1613            ImageFormat::Tiff => Self::tiff(),
1614            ImageFormat::Webp => Self::webp(),
1615            ImageFormat::Gif => Self::gif(),
1616            ImageFormat::Bmp => Self::bmp(),
1617            ImageFormat::Svg => Self::svg(),
1618            ImageFormat::Ico => Self::ico(),
1619        }
1620    }
1621}
1622
1623// See https://developer.apple.com/documentation/uniformtypeidentifiers/uttype-swift.struct/
1624struct UTType(id);
1625
1626impl UTType {
1627    pub fn png() -> Self {
1628        // https://developer.apple.com/documentation/uniformtypeidentifiers/uttype-swift.struct/png
1629        Self(unsafe { NSPasteboardTypePNG }) // This is a rare case where there's a built-in NSPasteboardType
1630    }
1631
1632    pub fn jpeg() -> Self {
1633        // https://developer.apple.com/documentation/uniformtypeidentifiers/uttype-swift.struct/jpeg
1634        Self(unsafe { ns_string("public.jpeg") })
1635    }
1636
1637    pub fn gif() -> Self {
1638        // https://developer.apple.com/documentation/uniformtypeidentifiers/uttype-swift.struct/gif
1639        Self(unsafe { ns_string("com.compuserve.gif") })
1640    }
1641
1642    pub fn webp() -> Self {
1643        // https://developer.apple.com/documentation/uniformtypeidentifiers/uttype-swift.struct/webp
1644        Self(unsafe { ns_string("org.webmproject.webp") })
1645    }
1646
1647    pub fn bmp() -> Self {
1648        // https://developer.apple.com/documentation/uniformtypeidentifiers/uttype-swift.struct/bmp
1649        Self(unsafe { ns_string("com.microsoft.bmp") })
1650    }
1651
1652    pub fn svg() -> Self {
1653        // https://developer.apple.com/documentation/uniformtypeidentifiers/uttype-swift.struct/svg
1654        Self(unsafe { ns_string("public.svg-image") })
1655    }
1656
1657    pub fn ico() -> Self {
1658        // https://developer.apple.com/documentation/uniformtypeidentifiers/uttype-swift.struct/ico
1659        Self(unsafe { ns_string("com.microsoft.ico") })
1660    }
1661
1662    pub fn tiff() -> Self {
1663        // https://developer.apple.com/documentation/uniformtypeidentifiers/uttype-swift.struct/tiff
1664        Self(unsafe { NSPasteboardTypeTIFF }) // This is a rare case where there's a built-in NSPasteboardType
1665    }
1666
1667    fn inner(&self) -> *const Object {
1668        self.0
1669    }
1670
1671    fn inner_mut(&self) -> *mut Object {
1672        self.0 as *mut _
1673    }
1674}
1675
1676#[cfg(test)]
1677mod tests {
1678    use crate::ClipboardItem;
1679
1680    use super::*;
1681
1682    #[test]
1683    fn test_clipboard() {
1684        let platform = build_platform();
1685        assert_eq!(platform.read_from_clipboard(), None);
1686
1687        let item = ClipboardItem::new_string("1".to_string());
1688        platform.write_to_clipboard(item.clone());
1689        assert_eq!(platform.read_from_clipboard(), Some(item));
1690
1691        let item = ClipboardItem {
1692            entries: vec![ClipboardEntry::String(
1693                ClipboardString::new("2".to_string()).with_json_metadata(vec![3, 4]),
1694            )],
1695        };
1696        platform.write_to_clipboard(item.clone());
1697        assert_eq!(platform.read_from_clipboard(), Some(item));
1698
1699        let text_from_other_app = "text from other app";
1700        unsafe {
1701            let bytes = NSData::dataWithBytes_length_(
1702                nil,
1703                text_from_other_app.as_ptr() as *const c_void,
1704                text_from_other_app.len() as u64,
1705            );
1706            platform
1707                .0
1708                .lock()
1709                .pasteboard
1710                .setData_forType(bytes, NSPasteboardTypeString);
1711        }
1712        assert_eq!(
1713            platform.read_from_clipboard(),
1714            Some(ClipboardItem::new_string(text_from_other_app.to_string()))
1715        );
1716    }
1717
1718    fn build_platform() -> MacPlatform {
1719        let platform = MacPlatform::new(false);
1720        platform.0.lock().pasteboard = unsafe { NSPasteboard::pasteboardWithUniqueName(nil) };
1721        platform
1722    }
1723}