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