platform.rs

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