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