platform.rs

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