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