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