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