platform.rs

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