platform.rs

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