platform.rs

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