platform.rs

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