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