platform.rs

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