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