platform.rs

   1use super::{events::key_to_native, BoolExt};
   2use crate::{
   3    Action, AnyWindowHandle, BackgroundExecutor, ClipboardItem, CursorStyle, DisplayId,
   4    ForegroundExecutor, Keymap, MacDispatcher, MacDisplay, MacTextSystem, MacWindow, Menu,
   5    MenuItem, PathPromptOptions, Platform, PlatformDisplay, PlatformInput, PlatformTextSystem,
   6    PlatformWindow, Result, SemanticVersion, Task, WindowAppearance, WindowParams,
   7};
   8use anyhow::{anyhow, bail};
   9use block::ConcreteBlock;
  10use cocoa::{
  11    appkit::{
  12        NSApplication, NSApplicationActivationPolicy::NSApplicationActivationPolicyRegular,
  13        NSEventModifierFlags, NSMenu, NSMenuItem, NSModalResponse, NSOpenPanel, NSPasteboard,
  14        NSPasteboardTypeString, NSSavePanel, NSWindow,
  15    },
  16    base::{id, nil, selector, BOOL, YES},
  17    foundation::{
  18        NSArray, NSAutoreleasePool, NSBundle, NSData, NSInteger, NSProcessInfo, NSString,
  19        NSUInteger, NSURL,
  20    },
  21};
  22use core_foundation::{
  23    base::{CFType, CFTypeRef, OSStatus, TCFType as _},
  24    boolean::CFBoolean,
  25    data::CFData,
  26    dictionary::{CFDictionary, CFDictionaryRef, CFMutableDictionary},
  27    string::{CFString, CFStringRef},
  28};
  29use ctor::ctor;
  30use futures::channel::oneshot;
  31use objc::{
  32    class,
  33    declare::ClassDecl,
  34    msg_send,
  35    runtime::{Class, Object, Sel},
  36    sel, sel_impl,
  37};
  38use parking_lot::Mutex;
  39use ptr::null_mut;
  40use std::{
  41    cell::Cell,
  42    convert::TryInto,
  43    ffi::{c_void, CStr, OsStr},
  44    os::{raw::c_char, unix::ffi::OsStrExt},
  45    path::{Path, PathBuf},
  46    process::Command,
  47    ptr,
  48    rc::Rc,
  49    slice, str,
  50    sync::Arc,
  51    time::Duration,
  52};
  53use time::UtcOffset;
  54
  55use super::renderer;
  56
  57#[allow(non_upper_case_globals)]
  58const NSUTF8StringEncoding: NSUInteger = 4;
  59
  60const MAC_PLATFORM_IVAR: &str = "platform";
  61static mut APP_CLASS: *const Class = ptr::null();
  62static mut APP_DELEGATE_CLASS: *const Class = ptr::null();
  63
  64#[ctor]
  65unsafe fn build_classes() {
  66    APP_CLASS = {
  67        let mut decl = ClassDecl::new("GPUIApplication", class!(NSApplication)).unwrap();
  68        decl.add_ivar::<*mut c_void>(MAC_PLATFORM_IVAR);
  69        decl.add_method(
  70            sel!(sendEvent:),
  71            send_event as extern "C" fn(&mut Object, Sel, id),
  72        );
  73        decl.register()
  74    };
  75
  76    APP_DELEGATE_CLASS = {
  77        let mut decl = ClassDecl::new("GPUIApplicationDelegate", class!(NSResponder)).unwrap();
  78        decl.add_ivar::<*mut c_void>(MAC_PLATFORM_IVAR);
  79        decl.add_method(
  80            sel!(applicationDidFinishLaunching:),
  81            did_finish_launching as extern "C" fn(&mut Object, Sel, id),
  82        );
  83        decl.add_method(
  84            sel!(applicationShouldHandleReopen:hasVisibleWindows:),
  85            should_handle_reopen as extern "C" fn(&mut Object, Sel, id, bool),
  86        );
  87        decl.add_method(
  88            sel!(applicationDidBecomeActive:),
  89            did_become_active as extern "C" fn(&mut Object, Sel, id),
  90        );
  91        decl.add_method(
  92            sel!(applicationDidResignActive:),
  93            did_resign_active as extern "C" fn(&mut Object, Sel, id),
  94        );
  95        decl.add_method(
  96            sel!(applicationWillTerminate:),
  97            will_terminate as extern "C" fn(&mut Object, Sel, id),
  98        );
  99        decl.add_method(
 100            sel!(handleGPUIMenuItem:),
 101            handle_menu_item as extern "C" fn(&mut Object, Sel, id),
 102        );
 103        // Add menu item handlers so that OS save panels have the correct key commands
 104        decl.add_method(
 105            sel!(cut:),
 106            handle_menu_item as extern "C" fn(&mut Object, Sel, id),
 107        );
 108        decl.add_method(
 109            sel!(copy:),
 110            handle_menu_item as extern "C" fn(&mut Object, Sel, id),
 111        );
 112        decl.add_method(
 113            sel!(paste:),
 114            handle_menu_item as extern "C" fn(&mut Object, Sel, id),
 115        );
 116        decl.add_method(
 117            sel!(selectAll:),
 118            handle_menu_item as extern "C" fn(&mut Object, Sel, id),
 119        );
 120        decl.add_method(
 121            sel!(undo:),
 122            handle_menu_item as extern "C" fn(&mut Object, Sel, id),
 123        );
 124        decl.add_method(
 125            sel!(redo:),
 126            handle_menu_item as extern "C" fn(&mut Object, Sel, id),
 127        );
 128        decl.add_method(
 129            sel!(validateMenuItem:),
 130            validate_menu_item as extern "C" fn(&mut Object, Sel, id) -> bool,
 131        );
 132        decl.add_method(
 133            sel!(menuWillOpen:),
 134            menu_will_open as extern "C" fn(&mut Object, Sel, id),
 135        );
 136        decl.add_method(
 137            sel!(application:openURLs:),
 138            open_urls as extern "C" fn(&mut Object, Sel, id, id),
 139        );
 140
 141        decl.register()
 142    }
 143}
 144
 145pub(crate) struct MacPlatform(Mutex<MacPlatformState>);
 146
 147pub(crate) struct MacPlatformState {
 148    background_executor: BackgroundExecutor,
 149    foreground_executor: ForegroundExecutor,
 150    text_system: Arc<MacTextSystem>,
 151    renderer_context: renderer::Context,
 152    pasteboard: id,
 153    text_hash_pasteboard_type: id,
 154    metadata_pasteboard_type: id,
 155    become_active: Option<Box<dyn FnMut()>>,
 156    resign_active: Option<Box<dyn FnMut()>>,
 157    reopen: Option<Box<dyn FnMut()>>,
 158    quit: Option<Box<dyn FnMut()>>,
 159    event: Option<Box<dyn FnMut(PlatformInput) -> bool>>,
 160    menu_command: Option<Box<dyn FnMut(&dyn Action)>>,
 161    validate_menu_command: Option<Box<dyn FnMut(&dyn Action) -> bool>>,
 162    will_open_menu: Option<Box<dyn FnMut()>>,
 163    menu_actions: Vec<Box<dyn Action>>,
 164    open_urls: Option<Box<dyn FnMut(Vec<String>)>>,
 165    finish_launching: Option<Box<dyn FnOnce()>>,
 166}
 167
 168impl Default for MacPlatform {
 169    fn default() -> Self {
 170        Self::new()
 171    }
 172}
 173
 174impl MacPlatform {
 175    pub(crate) fn new() -> Self {
 176        let dispatcher = Arc::new(MacDispatcher::new());
 177        Self(Mutex::new(MacPlatformState {
 178            background_executor: BackgroundExecutor::new(dispatcher.clone()),
 179            foreground_executor: ForegroundExecutor::new(dispatcher),
 180            text_system: Arc::new(MacTextSystem::new()),
 181            renderer_context: renderer::Context::default(),
 182            pasteboard: unsafe { NSPasteboard::generalPasteboard(nil) },
 183            text_hash_pasteboard_type: unsafe { ns_string("zed-text-hash") },
 184            metadata_pasteboard_type: unsafe { ns_string("zed-metadata") },
 185            become_active: None,
 186            resign_active: None,
 187            reopen: None,
 188            quit: None,
 189            event: None,
 190            menu_command: None,
 191            validate_menu_command: None,
 192            will_open_menu: None,
 193            menu_actions: Default::default(),
 194            open_urls: None,
 195            finish_launching: None,
 196        }))
 197    }
 198
 199    unsafe fn read_from_pasteboard(&self, pasteboard: *mut Object, kind: id) -> Option<&[u8]> {
 200        let data = pasteboard.dataForType(kind);
 201        if data == nil {
 202            None
 203        } else {
 204            Some(slice::from_raw_parts(
 205                data.bytes() as *mut u8,
 206                data.length() as usize,
 207            ))
 208        }
 209    }
 210
 211    unsafe fn create_menu_bar(
 212        &self,
 213        menus: Vec<Menu>,
 214        delegate: id,
 215        actions: &mut Vec<Box<dyn Action>>,
 216        keymap: &Keymap,
 217    ) -> id {
 218        let application_menu = NSMenu::new(nil).autorelease();
 219        application_menu.setDelegate_(delegate);
 220
 221        for menu_config in menus {
 222            let menu = NSMenu::new(nil).autorelease();
 223            menu.setTitle_(ns_string(menu_config.name));
 224            menu.setDelegate_(delegate);
 225
 226            for item_config in menu_config.items {
 227                menu.addItem_(Self::create_menu_item(
 228                    item_config,
 229                    delegate,
 230                    actions,
 231                    keymap,
 232                ));
 233            }
 234
 235            let menu_item = NSMenuItem::new(nil).autorelease();
 236            menu_item.setSubmenu_(menu);
 237            application_menu.addItem_(menu_item);
 238
 239            if menu_config.name == "Window" {
 240                let app: id = msg_send![APP_CLASS, sharedApplication];
 241                app.setWindowsMenu_(menu);
 242            }
 243        }
 244
 245        application_menu
 246    }
 247
 248    unsafe fn create_menu_item(
 249        item: MenuItem,
 250        delegate: id,
 251        actions: &mut Vec<Box<dyn Action>>,
 252        keymap: &Keymap,
 253    ) -> id {
 254        match item {
 255            MenuItem::Separator => NSMenuItem::separatorItem(nil),
 256            MenuItem::Action {
 257                name,
 258                action,
 259                os_action,
 260            } => {
 261                let keystrokes = keymap
 262                    .bindings_for_action(action.as_ref())
 263                    .next()
 264                    .map(|binding| binding.keystrokes());
 265
 266                let selector = match os_action {
 267                    Some(crate::OsAction::Cut) => selector("cut:"),
 268                    Some(crate::OsAction::Copy) => selector("copy:"),
 269                    Some(crate::OsAction::Paste) => selector("paste:"),
 270                    Some(crate::OsAction::SelectAll) => selector("selectAll:"),
 271                    Some(crate::OsAction::Undo) => selector("undo:"),
 272                    Some(crate::OsAction::Redo) => selector("redo:"),
 273                    None => selector("handleGPUIMenuItem:"),
 274                };
 275
 276                let item;
 277                if let Some(keystrokes) = keystrokes {
 278                    if keystrokes.len() == 1 {
 279                        let keystroke = &keystrokes[0];
 280                        let mut mask = NSEventModifierFlags::empty();
 281                        for (modifier, flag) in &[
 282                            (
 283                                keystroke.modifiers.command,
 284                                NSEventModifierFlags::NSCommandKeyMask,
 285                            ),
 286                            (
 287                                keystroke.modifiers.control,
 288                                NSEventModifierFlags::NSControlKeyMask,
 289                            ),
 290                            (
 291                                keystroke.modifiers.alt,
 292                                NSEventModifierFlags::NSAlternateKeyMask,
 293                            ),
 294                            (
 295                                keystroke.modifiers.shift,
 296                                NSEventModifierFlags::NSShiftKeyMask,
 297                            ),
 298                        ] {
 299                            if *modifier {
 300                                mask |= *flag;
 301                            }
 302                        }
 303
 304                        item = NSMenuItem::alloc(nil)
 305                            .initWithTitle_action_keyEquivalent_(
 306                                ns_string(name),
 307                                selector,
 308                                ns_string(key_to_native(&keystroke.key).as_ref()),
 309                            )
 310                            .autorelease();
 311                        item.setKeyEquivalentModifierMask_(mask);
 312                    }
 313                    // For multi-keystroke bindings, render the keystroke as part of the title.
 314                    else {
 315                        use std::fmt::Write;
 316
 317                        let mut name = format!("{name} [");
 318                        for (i, keystroke) in keystrokes.iter().enumerate() {
 319                            if i > 0 {
 320                                name.push(' ');
 321                            }
 322                            write!(&mut name, "{}", keystroke).unwrap();
 323                        }
 324                        name.push(']');
 325
 326                        item = NSMenuItem::alloc(nil)
 327                            .initWithTitle_action_keyEquivalent_(
 328                                ns_string(&name),
 329                                selector,
 330                                ns_string(""),
 331                            )
 332                            .autorelease();
 333                    }
 334                } else {
 335                    item = NSMenuItem::alloc(nil)
 336                        .initWithTitle_action_keyEquivalent_(
 337                            ns_string(name),
 338                            selector,
 339                            ns_string(""),
 340                        )
 341                        .autorelease();
 342                }
 343
 344                let tag = actions.len() as NSInteger;
 345                let _: () = msg_send![item, setTag: tag];
 346                actions.push(action);
 347                item
 348            }
 349            MenuItem::Submenu(Menu { name, items }) => {
 350                let item = NSMenuItem::new(nil).autorelease();
 351                let submenu = NSMenu::new(nil).autorelease();
 352                submenu.setDelegate_(delegate);
 353                for item in items {
 354                    submenu.addItem_(Self::create_menu_item(item, delegate, actions, keymap));
 355                }
 356                item.setSubmenu_(submenu);
 357                item.setTitle_(ns_string(name));
 358                item
 359            }
 360        }
 361    }
 362}
 363
 364impl Platform for MacPlatform {
 365    fn background_executor(&self) -> BackgroundExecutor {
 366        self.0.lock().background_executor.clone()
 367    }
 368
 369    fn foreground_executor(&self) -> crate::ForegroundExecutor {
 370        self.0.lock().foreground_executor.clone()
 371    }
 372
 373    fn text_system(&self) -> Arc<dyn PlatformTextSystem> {
 374        self.0.lock().text_system.clone()
 375    }
 376
 377    fn run(&self, on_finish_launching: Box<dyn FnOnce()>) {
 378        self.0.lock().finish_launching = Some(on_finish_launching);
 379
 380        unsafe {
 381            let app: id = msg_send![APP_CLASS, sharedApplication];
 382            let app_delegate: id = msg_send![APP_DELEGATE_CLASS, new];
 383            app.setDelegate_(app_delegate);
 384
 385            let self_ptr = self as *const Self as *const c_void;
 386            (*app).set_ivar(MAC_PLATFORM_IVAR, self_ptr);
 387            (*app_delegate).set_ivar(MAC_PLATFORM_IVAR, self_ptr);
 388
 389            let pool = NSAutoreleasePool::new(nil);
 390            app.run();
 391            pool.drain();
 392
 393            (*app).set_ivar(MAC_PLATFORM_IVAR, null_mut::<c_void>());
 394            (*app.delegate()).set_ivar(MAC_PLATFORM_IVAR, null_mut::<c_void>());
 395        }
 396    }
 397
 398    fn quit(&self) {
 399        // Quitting the app causes us to close windows, which invokes `Window::on_close` callbacks
 400        // synchronously before this method terminates. If we call `Platform::quit` while holding a
 401        // borrow of the app state (which most of the time we will do), we will end up
 402        // double-borrowing the app state in the `on_close` callbacks for our open windows. To solve
 403        // this, we make quitting the application asynchronous so that we aren't holding borrows to
 404        // the app state on the stack when we actually terminate the app.
 405
 406        use super::dispatcher::{dispatch_get_main_queue, dispatch_sys::dispatch_async_f};
 407
 408        unsafe {
 409            dispatch_async_f(dispatch_get_main_queue(), ptr::null_mut(), Some(quit));
 410        }
 411
 412        unsafe extern "C" fn quit(_: *mut c_void) {
 413            let app = NSApplication::sharedApplication(nil);
 414            let _: () = msg_send![app, terminate: nil];
 415        }
 416    }
 417
 418    fn restart(&self) {
 419        use std::os::unix::process::CommandExt as _;
 420
 421        let app_pid = std::process::id().to_string();
 422        let app_path = self
 423            .app_path()
 424            .ok()
 425            // When the app is not bundled, `app_path` returns the
 426            // directory containing the executable. Disregard this
 427            // and get the path to the executable itself.
 428            .and_then(|path| (path.extension()?.to_str()? == "app").then_some(path))
 429            .unwrap_or_else(|| std::env::current_exe().unwrap());
 430
 431        // Wait until this process has exited and then re-open this path.
 432        let script = r#"
 433            while kill -0 $0 2> /dev/null; do
 434                sleep 0.1
 435            done
 436            open "$1"
 437        "#;
 438
 439        let restart_process = Command::new("/bin/bash")
 440            .arg("-c")
 441            .arg(script)
 442            .arg(app_pid)
 443            .arg(app_path)
 444            .process_group(0)
 445            .spawn();
 446
 447        match restart_process {
 448            Ok(_) => self.quit(),
 449            Err(e) => log::error!("failed to spawn restart script: {:?}", e),
 450        }
 451    }
 452
 453    fn activate(&self, ignoring_other_apps: bool) {
 454        unsafe {
 455            let app = NSApplication::sharedApplication(nil);
 456            app.activateIgnoringOtherApps_(ignoring_other_apps.to_objc());
 457        }
 458    }
 459
 460    fn hide(&self) {
 461        unsafe {
 462            let app = NSApplication::sharedApplication(nil);
 463            let _: () = msg_send![app, hide: nil];
 464        }
 465    }
 466
 467    fn hide_other_apps(&self) {
 468        unsafe {
 469            let app = NSApplication::sharedApplication(nil);
 470            let _: () = msg_send![app, hideOtherApplications: nil];
 471        }
 472    }
 473
 474    fn unhide_other_apps(&self) {
 475        unsafe {
 476            let app = NSApplication::sharedApplication(nil);
 477            let _: () = msg_send![app, unhideAllApplications: nil];
 478        }
 479    }
 480
 481    fn primary_display(&self) -> Option<Rc<dyn PlatformDisplay>> {
 482        Some(Rc::new(MacDisplay::primary()))
 483    }
 484
 485    fn displays(&self) -> Vec<Rc<dyn PlatformDisplay>> {
 486        MacDisplay::all()
 487            .map(|screen| Rc::new(screen) as Rc<_>)
 488            .collect()
 489    }
 490
 491    fn display(&self, id: DisplayId) -> Option<Rc<dyn PlatformDisplay>> {
 492        MacDisplay::find_by_id(id).map(|screen| Rc::new(screen) as Rc<_>)
 493    }
 494
 495    fn active_window(&self) -> Option<AnyWindowHandle> {
 496        MacWindow::active_window()
 497    }
 498
 499    fn open_window(
 500        &self,
 501        handle: AnyWindowHandle,
 502        options: WindowParams,
 503    ) -> Box<dyn PlatformWindow> {
 504        // Clippy thinks that this evaluates to `()`, for some reason.
 505        #[allow(clippy::unit_arg, clippy::clone_on_copy)]
 506        let renderer_context = self.0.lock().renderer_context.clone();
 507        Box::new(MacWindow::open(
 508            handle,
 509            options,
 510            self.foreground_executor(),
 511            renderer_context,
 512        ))
 513    }
 514
 515    fn window_appearance(&self) -> WindowAppearance {
 516        unsafe {
 517            let app = NSApplication::sharedApplication(nil);
 518            let appearance: id = msg_send![app, effectiveAppearance];
 519            WindowAppearance::from_native(appearance)
 520        }
 521    }
 522
 523    fn open_url(&self, url: &str) {
 524        unsafe {
 525            let url = NSURL::alloc(nil)
 526                .initWithString_(ns_string(url))
 527                .autorelease();
 528            let workspace: id = msg_send![class!(NSWorkspace), sharedWorkspace];
 529            msg_send![workspace, openURL: url]
 530        }
 531    }
 532
 533    fn register_url_scheme(&self, scheme: &str) -> Task<anyhow::Result<()>> {
 534        // API only available post Monterey
 535        // https://developer.apple.com/documentation/appkit/nsworkspace/3753004-setdefaultapplicationaturl
 536        let (done_tx, done_rx) = oneshot::channel();
 537        if self.os_version().ok() < Some(SemanticVersion::new(12, 0, 0)) {
 538            return Task::ready(Err(anyhow!(
 539                "macOS 12.0 or later is required to register URL schemes"
 540            )));
 541        }
 542
 543        let bundle_id = unsafe {
 544            let bundle: id = msg_send![class!(NSBundle), mainBundle];
 545            let bundle_id: id = msg_send![bundle, bundleIdentifier];
 546            if bundle_id == nil {
 547                return Task::ready(Err(anyhow!("Can only register URL scheme in bundled apps")));
 548            }
 549            bundle_id
 550        };
 551
 552        unsafe {
 553            let workspace: id = msg_send![class!(NSWorkspace), sharedWorkspace];
 554            let scheme: id = ns_string(scheme);
 555            let app: id = msg_send![workspace, URLForApplicationWithBundleIdentifier: bundle_id];
 556            let done_tx = Cell::new(Some(done_tx));
 557            let block = ConcreteBlock::new(move |error: id| {
 558                let result = if error == nil {
 559                    Ok(())
 560                } else {
 561                    let msg: id = msg_send![error, localizedDescription];
 562                    Err(anyhow!("Failed to register: {:?}", msg))
 563                };
 564
 565                if let Some(done_tx) = done_tx.take() {
 566                    let _ = done_tx.send(result);
 567                }
 568            });
 569            let _: () = msg_send![workspace, setDefaultApplicationAtURL: app toOpenURLsWithScheme: scheme completionHandler: block];
 570        }
 571
 572        self.background_executor()
 573            .spawn(async { crate::Flatten::flatten(done_rx.await.map_err(|e| anyhow!(e))) })
 574    }
 575
 576    fn on_open_urls(&self, callback: Box<dyn FnMut(Vec<String>)>) {
 577        self.0.lock().open_urls = Some(callback);
 578    }
 579
 580    fn prompt_for_paths(
 581        &self,
 582        options: PathPromptOptions,
 583    ) -> oneshot::Receiver<Option<Vec<PathBuf>>> {
 584        let (done_tx, done_rx) = oneshot::channel();
 585        self.foreground_executor()
 586            .spawn(async move {
 587                unsafe {
 588                    let panel = NSOpenPanel::openPanel(nil);
 589                    panel.setCanChooseDirectories_(options.directories.to_objc());
 590                    panel.setCanChooseFiles_(options.files.to_objc());
 591                    panel.setAllowsMultipleSelection_(options.multiple.to_objc());
 592                    panel.setResolvesAliases_(false.to_objc());
 593                    let done_tx = Cell::new(Some(done_tx));
 594                    let block = ConcreteBlock::new(move |response: NSModalResponse| {
 595                        let result = if response == NSModalResponse::NSModalResponseOk {
 596                            let mut result = Vec::new();
 597                            let urls = panel.URLs();
 598                            for i in 0..urls.count() {
 599                                let url = urls.objectAtIndex(i);
 600                                if url.isFileURL() == YES {
 601                                    if let Ok(path) = ns_url_to_path(url) {
 602                                        result.push(path)
 603                                    }
 604                                }
 605                            }
 606                            Some(result)
 607                        } else {
 608                            None
 609                        };
 610
 611                        if let Some(done_tx) = done_tx.take() {
 612                            let _ = done_tx.send(result);
 613                        }
 614                    });
 615                    let block = block.copy();
 616                    let _: () = msg_send![panel, beginWithCompletionHandler: block];
 617                }
 618            })
 619            .detach();
 620        done_rx
 621    }
 622
 623    fn prompt_for_new_path(&self, directory: &Path) -> oneshot::Receiver<Option<PathBuf>> {
 624        let directory = directory.to_owned();
 625        let (done_tx, done_rx) = oneshot::channel();
 626        self.foreground_executor()
 627            .spawn(async move {
 628                unsafe {
 629                    let panel = NSSavePanel::savePanel(nil);
 630                    let path = ns_string(directory.to_string_lossy().as_ref());
 631                    let url = NSURL::fileURLWithPath_isDirectory_(nil, path, true.to_objc());
 632                    panel.setDirectoryURL(url);
 633
 634                    let done_tx = Cell::new(Some(done_tx));
 635                    let block = ConcreteBlock::new(move |response: NSModalResponse| {
 636                        let mut result = None;
 637                        if response == NSModalResponse::NSModalResponseOk {
 638                            let url = panel.URL();
 639                            if url.isFileURL() == YES {
 640                                result = ns_url_to_path(panel.URL()).ok()
 641                            }
 642                        }
 643
 644                        if let Some(done_tx) = done_tx.take() {
 645                            let _ = done_tx.send(result);
 646                        }
 647                    });
 648                    let block = block.copy();
 649                    let _: () = msg_send![panel, beginWithCompletionHandler: block];
 650                }
 651            })
 652            .detach();
 653
 654        done_rx
 655    }
 656
 657    fn reveal_path(&self, path: &Path) {
 658        unsafe {
 659            let path = path.to_path_buf();
 660            self.0
 661                .lock()
 662                .background_executor
 663                .spawn(async move {
 664                    let full_path = ns_string(path.to_str().unwrap_or(""));
 665                    let root_full_path = ns_string("");
 666                    let workspace: id = msg_send![class!(NSWorkspace), sharedWorkspace];
 667                    let _: BOOL = msg_send![
 668                        workspace,
 669                        selectFile: full_path
 670                        inFileViewerRootedAtPath: root_full_path
 671                    ];
 672                })
 673                .detach();
 674        }
 675    }
 676
 677    fn on_become_active(&self, callback: Box<dyn FnMut()>) {
 678        self.0.lock().become_active = Some(callback);
 679    }
 680
 681    fn on_resign_active(&self, callback: Box<dyn FnMut()>) {
 682        self.0.lock().resign_active = Some(callback);
 683    }
 684
 685    fn on_quit(&self, callback: Box<dyn FnMut()>) {
 686        self.0.lock().quit = Some(callback);
 687    }
 688
 689    fn on_reopen(&self, callback: Box<dyn FnMut()>) {
 690        self.0.lock().reopen = Some(callback);
 691    }
 692
 693    fn on_event(&self, callback: Box<dyn FnMut(PlatformInput) -> bool>) {
 694        self.0.lock().event = Some(callback);
 695    }
 696
 697    fn on_app_menu_action(&self, callback: Box<dyn FnMut(&dyn Action)>) {
 698        self.0.lock().menu_command = Some(callback);
 699    }
 700
 701    fn on_will_open_app_menu(&self, callback: Box<dyn FnMut()>) {
 702        self.0.lock().will_open_menu = Some(callback);
 703    }
 704
 705    fn on_validate_app_menu_command(&self, callback: Box<dyn FnMut(&dyn Action) -> bool>) {
 706        self.0.lock().validate_menu_command = Some(callback);
 707    }
 708
 709    fn os_name(&self) -> &'static str {
 710        "macOS"
 711    }
 712
 713    fn double_click_interval(&self) -> Duration {
 714        unsafe {
 715            let double_click_interval: f64 = msg_send![class!(NSEvent), doubleClickInterval];
 716            Duration::from_secs_f64(double_click_interval)
 717        }
 718    }
 719
 720    fn os_version(&self) -> Result<SemanticVersion> {
 721        unsafe {
 722            let process_info = NSProcessInfo::processInfo(nil);
 723            let version = process_info.operatingSystemVersion();
 724            Ok(SemanticVersion {
 725                major: version.majorVersion as usize,
 726                minor: version.minorVersion as usize,
 727                patch: version.patchVersion as usize,
 728            })
 729        }
 730    }
 731
 732    fn app_version(&self) -> Result<SemanticVersion> {
 733        unsafe {
 734            let bundle: id = NSBundle::mainBundle();
 735            if bundle.is_null() {
 736                Err(anyhow!("app is not running inside a bundle"))
 737            } else {
 738                let version: id = msg_send![bundle, objectForInfoDictionaryKey: ns_string("CFBundleShortVersionString")];
 739                if version.is_null() {
 740                    bail!("bundle does not have version");
 741                }
 742                let len = msg_send![version, lengthOfBytesUsingEncoding: NSUTF8StringEncoding];
 743                let bytes = version.UTF8String() as *const u8;
 744                let version = str::from_utf8(slice::from_raw_parts(bytes, len)).unwrap();
 745                version.parse()
 746            }
 747        }
 748    }
 749
 750    fn app_path(&self) -> Result<PathBuf> {
 751        unsafe {
 752            let bundle: id = NSBundle::mainBundle();
 753            if bundle.is_null() {
 754                Err(anyhow!("app is not running inside a bundle"))
 755            } else {
 756                Ok(path_from_objc(msg_send![bundle, bundlePath]))
 757            }
 758        }
 759    }
 760
 761    fn set_menus(&self, menus: Vec<Menu>, keymap: &Keymap) {
 762        unsafe {
 763            let app: id = msg_send![APP_CLASS, sharedApplication];
 764            let mut state = self.0.lock();
 765            let actions = &mut state.menu_actions;
 766            app.setMainMenu_(self.create_menu_bar(menus, app.delegate(), actions, keymap));
 767        }
 768    }
 769
 770    fn add_recent_documents(&self, paths: &[PathBuf]) {
 771        for path in paths {
 772            let Some(path_str) = path.to_str() else {
 773                log::error!("Not adding to recent documents a non-unicode path: {path:?}");
 774                continue;
 775            };
 776            unsafe {
 777                let document_controller: id =
 778                    msg_send![class!(NSDocumentController), sharedDocumentController];
 779                let url: id = NSURL::fileURLWithPath_(nil, ns_string(path_str));
 780                let _: () = msg_send![document_controller, noteNewRecentDocumentURL:url];
 781            }
 782        }
 783    }
 784
 785    fn clear_recent_documents(&self) {
 786        unsafe {
 787            let document_controller: id =
 788                msg_send![class!(NSDocumentController), sharedDocumentController];
 789            let _: () = msg_send![document_controller, clearRecentDocuments:nil];
 790        }
 791    }
 792
 793    fn local_timezone(&self) -> UtcOffset {
 794        unsafe {
 795            let local_timezone: id = msg_send![class!(NSTimeZone), localTimeZone];
 796            let seconds_from_gmt: NSInteger = msg_send![local_timezone, secondsFromGMT];
 797            UtcOffset::from_whole_seconds(seconds_from_gmt.try_into().unwrap()).unwrap()
 798        }
 799    }
 800
 801    fn path_for_auxiliary_executable(&self, name: &str) -> Result<PathBuf> {
 802        unsafe {
 803            let bundle: id = NSBundle::mainBundle();
 804            if bundle.is_null() {
 805                Err(anyhow!("app is not running inside a bundle"))
 806            } else {
 807                let name = ns_string(name);
 808                let url: id = msg_send![bundle, URLForAuxiliaryExecutable: name];
 809                if url.is_null() {
 810                    Err(anyhow!("resource not found"))
 811                } else {
 812                    ns_url_to_path(url)
 813                }
 814            }
 815        }
 816    }
 817
 818    /// Match cursor style to one of the styles available
 819    /// in macOS's [NSCursor](https://developer.apple.com/documentation/appkit/nscursor).
 820    fn set_cursor_style(&self, style: CursorStyle) {
 821        unsafe {
 822            let new_cursor: id = match style {
 823                CursorStyle::Arrow => msg_send![class!(NSCursor), arrowCursor],
 824                CursorStyle::IBeam => msg_send![class!(NSCursor), IBeamCursor],
 825                CursorStyle::Crosshair => msg_send![class!(NSCursor), crosshairCursor],
 826                CursorStyle::ClosedHand => msg_send![class!(NSCursor), closedHandCursor],
 827                CursorStyle::OpenHand => msg_send![class!(NSCursor), openHandCursor],
 828                CursorStyle::PointingHand => msg_send![class!(NSCursor), pointingHandCursor],
 829                CursorStyle::ResizeLeft => msg_send![class!(NSCursor), resizeLeftCursor],
 830                CursorStyle::ResizeRight => msg_send![class!(NSCursor), resizeRightCursor],
 831                CursorStyle::ResizeLeftRight => msg_send![class!(NSCursor), resizeLeftRightCursor],
 832                CursorStyle::ResizeUp => msg_send![class!(NSCursor), resizeUpCursor],
 833                CursorStyle::ResizeDown => msg_send![class!(NSCursor), resizeDownCursor],
 834                CursorStyle::ResizeUpDown => msg_send![class!(NSCursor), resizeUpDownCursor],
 835                CursorStyle::DisappearingItem => {
 836                    msg_send![class!(NSCursor), disappearingItemCursor]
 837                }
 838                CursorStyle::IBeamCursorForVerticalLayout => {
 839                    msg_send![class!(NSCursor), IBeamCursorForVerticalLayout]
 840                }
 841                CursorStyle::OperationNotAllowed => {
 842                    msg_send![class!(NSCursor), operationNotAllowedCursor]
 843                }
 844                CursorStyle::DragLink => msg_send![class!(NSCursor), dragLinkCursor],
 845                CursorStyle::DragCopy => msg_send![class!(NSCursor), dragCopyCursor],
 846                CursorStyle::ContextualMenu => msg_send![class!(NSCursor), contextualMenuCursor],
 847            };
 848
 849            let old_cursor: id = msg_send![class!(NSCursor), currentCursor];
 850            if new_cursor != old_cursor {
 851                let _: () = msg_send![new_cursor, set];
 852            }
 853        }
 854    }
 855
 856    fn should_auto_hide_scrollbars(&self) -> bool {
 857        #[allow(non_upper_case_globals)]
 858        const NSScrollerStyleOverlay: NSInteger = 1;
 859
 860        unsafe {
 861            let style: NSInteger = msg_send![class!(NSScroller), preferredScrollerStyle];
 862            style == NSScrollerStyleOverlay
 863        }
 864    }
 865
 866    fn write_to_clipboard(&self, item: ClipboardItem) {
 867        let state = self.0.lock();
 868        unsafe {
 869            state.pasteboard.clearContents();
 870
 871            let text_bytes = NSData::dataWithBytes_length_(
 872                nil,
 873                item.text.as_ptr() as *const c_void,
 874                item.text.len() as u64,
 875            );
 876            state
 877                .pasteboard
 878                .setData_forType(text_bytes, NSPasteboardTypeString);
 879
 880            if let Some(metadata) = item.metadata.as_ref() {
 881                let hash_bytes = ClipboardItem::text_hash(&item.text).to_be_bytes();
 882                let hash_bytes = NSData::dataWithBytes_length_(
 883                    nil,
 884                    hash_bytes.as_ptr() as *const c_void,
 885                    hash_bytes.len() as u64,
 886                );
 887                state
 888                    .pasteboard
 889                    .setData_forType(hash_bytes, state.text_hash_pasteboard_type);
 890
 891                let metadata_bytes = NSData::dataWithBytes_length_(
 892                    nil,
 893                    metadata.as_ptr() as *const c_void,
 894                    metadata.len() as u64,
 895                );
 896                state
 897                    .pasteboard
 898                    .setData_forType(metadata_bytes, state.metadata_pasteboard_type);
 899            }
 900        }
 901    }
 902
 903    fn read_from_clipboard(&self) -> Option<ClipboardItem> {
 904        let state = self.0.lock();
 905        unsafe {
 906            if let Some(text_bytes) =
 907                self.read_from_pasteboard(state.pasteboard, NSPasteboardTypeString)
 908            {
 909                let text = String::from_utf8_lossy(text_bytes).to_string();
 910                let hash_bytes = self
 911                    .read_from_pasteboard(state.pasteboard, state.text_hash_pasteboard_type)
 912                    .and_then(|bytes| bytes.try_into().ok())
 913                    .map(u64::from_be_bytes);
 914                let metadata_bytes = self
 915                    .read_from_pasteboard(state.pasteboard, state.metadata_pasteboard_type)
 916                    .and_then(|bytes| String::from_utf8(bytes.to_vec()).ok());
 917
 918                if let Some((hash, metadata)) = hash_bytes.zip(metadata_bytes) {
 919                    if hash == ClipboardItem::text_hash(&text) {
 920                        Some(ClipboardItem {
 921                            text,
 922                            metadata: Some(metadata),
 923                        })
 924                    } else {
 925                        Some(ClipboardItem {
 926                            text,
 927                            metadata: None,
 928                        })
 929                    }
 930                } else {
 931                    Some(ClipboardItem {
 932                        text,
 933                        metadata: None,
 934                    })
 935                }
 936            } else {
 937                None
 938            }
 939        }
 940    }
 941
 942    fn write_credentials(&self, url: &str, username: &str, password: &[u8]) -> Task<Result<()>> {
 943        let url = url.to_string();
 944        let username = username.to_string();
 945        let password = password.to_vec();
 946        self.background_executor().spawn(async move {
 947            unsafe {
 948                use security::*;
 949
 950                let url = CFString::from(url.as_str());
 951                let username = CFString::from(username.as_str());
 952                let password = CFData::from_buffer(&password);
 953
 954                // First, check if there are already credentials for the given server. If so, then
 955                // update the username and password.
 956                let mut verb = "updating";
 957                let mut query_attrs = CFMutableDictionary::with_capacity(2);
 958                query_attrs.set(kSecClass as *const _, kSecClassInternetPassword as *const _);
 959                query_attrs.set(kSecAttrServer as *const _, url.as_CFTypeRef());
 960
 961                let mut attrs = CFMutableDictionary::with_capacity(4);
 962                attrs.set(kSecClass as *const _, kSecClassInternetPassword as *const _);
 963                attrs.set(kSecAttrServer as *const _, url.as_CFTypeRef());
 964                attrs.set(kSecAttrAccount as *const _, username.as_CFTypeRef());
 965                attrs.set(kSecValueData as *const _, password.as_CFTypeRef());
 966
 967                let mut status = SecItemUpdate(
 968                    query_attrs.as_concrete_TypeRef(),
 969                    attrs.as_concrete_TypeRef(),
 970                );
 971
 972                // If there were no existing credentials for the given server, then create them.
 973                if status == errSecItemNotFound {
 974                    verb = "creating";
 975                    status = SecItemAdd(attrs.as_concrete_TypeRef(), ptr::null_mut());
 976                }
 977
 978                if status != errSecSuccess {
 979                    return Err(anyhow!("{} password failed: {}", verb, status));
 980                }
 981            }
 982            Ok(())
 983        })
 984    }
 985
 986    fn read_credentials(&self, url: &str) -> Task<Result<Option<(String, Vec<u8>)>>> {
 987        let url = url.to_string();
 988        self.background_executor().spawn(async move {
 989            let url = CFString::from(url.as_str());
 990            let cf_true = CFBoolean::true_value().as_CFTypeRef();
 991
 992            unsafe {
 993                use security::*;
 994
 995                // Find any credentials for the given server URL.
 996                let mut attrs = CFMutableDictionary::with_capacity(5);
 997                attrs.set(kSecClass as *const _, kSecClassInternetPassword as *const _);
 998                attrs.set(kSecAttrServer as *const _, url.as_CFTypeRef());
 999                attrs.set(kSecReturnAttributes as *const _, cf_true);
1000                attrs.set(kSecReturnData as *const _, cf_true);
1001
1002                let mut result = CFTypeRef::from(ptr::null());
1003                let status = SecItemCopyMatching(attrs.as_concrete_TypeRef(), &mut result);
1004                match status {
1005                    security::errSecSuccess => {}
1006                    security::errSecItemNotFound | security::errSecUserCanceled => return Ok(None),
1007                    _ => return Err(anyhow!("reading password failed: {}", status)),
1008                }
1009
1010                let result = CFType::wrap_under_create_rule(result)
1011                    .downcast::<CFDictionary>()
1012                    .ok_or_else(|| anyhow!("keychain item was not a dictionary"))?;
1013                let username = result
1014                    .find(kSecAttrAccount as *const _)
1015                    .ok_or_else(|| anyhow!("account was missing from keychain item"))?;
1016                let username = CFType::wrap_under_get_rule(*username)
1017                    .downcast::<CFString>()
1018                    .ok_or_else(|| anyhow!("account was not a string"))?;
1019                let password = result
1020                    .find(kSecValueData as *const _)
1021                    .ok_or_else(|| anyhow!("password was missing from keychain item"))?;
1022                let password = CFType::wrap_under_get_rule(*password)
1023                    .downcast::<CFData>()
1024                    .ok_or_else(|| anyhow!("password was not a string"))?;
1025
1026                Ok(Some((username.to_string(), password.bytes().to_vec())))
1027            }
1028        })
1029    }
1030
1031    fn delete_credentials(&self, url: &str) -> Task<Result<()>> {
1032        let url = url.to_string();
1033
1034        self.background_executor().spawn(async move {
1035            unsafe {
1036                use security::*;
1037
1038                let url = CFString::from(url.as_str());
1039                let mut query_attrs = CFMutableDictionary::with_capacity(2);
1040                query_attrs.set(kSecClass as *const _, kSecClassInternetPassword as *const _);
1041                query_attrs.set(kSecAttrServer as *const _, url.as_CFTypeRef());
1042
1043                let status = SecItemDelete(query_attrs.as_concrete_TypeRef());
1044
1045                if status != errSecSuccess {
1046                    return Err(anyhow!("delete password failed: {}", status));
1047                }
1048            }
1049            Ok(())
1050        })
1051    }
1052}
1053
1054unsafe fn path_from_objc(path: id) -> PathBuf {
1055    let len = msg_send![path, lengthOfBytesUsingEncoding: NSUTF8StringEncoding];
1056    let bytes = path.UTF8String() as *const u8;
1057    let path = str::from_utf8(slice::from_raw_parts(bytes, len)).unwrap();
1058    PathBuf::from(path)
1059}
1060
1061unsafe fn get_mac_platform(object: &mut Object) -> &MacPlatform {
1062    let platform_ptr: *mut c_void = *object.get_ivar(MAC_PLATFORM_IVAR);
1063    assert!(!platform_ptr.is_null());
1064    &*(platform_ptr as *const MacPlatform)
1065}
1066
1067extern "C" fn send_event(this: &mut Object, _sel: Sel, native_event: id) {
1068    unsafe {
1069        if let Some(event) = PlatformInput::from_native(native_event, None) {
1070            let platform = get_mac_platform(this);
1071            let mut lock = platform.0.lock();
1072            if let Some(mut callback) = lock.event.take() {
1073                drop(lock);
1074                let result = callback(event);
1075                platform.0.lock().event.get_or_insert(callback);
1076                if !result {
1077                    return;
1078                }
1079            }
1080        }
1081        msg_send![super(this, class!(NSApplication)), sendEvent: native_event]
1082    }
1083}
1084
1085extern "C" fn did_finish_launching(this: &mut Object, _: Sel, _: id) {
1086    unsafe {
1087        let app: id = msg_send![APP_CLASS, sharedApplication];
1088        app.setActivationPolicy_(NSApplicationActivationPolicyRegular);
1089        let platform = get_mac_platform(this);
1090        let callback = platform.0.lock().finish_launching.take();
1091        if let Some(callback) = callback {
1092            callback();
1093        }
1094    }
1095}
1096
1097extern "C" fn should_handle_reopen(this: &mut Object, _: Sel, _: id, has_open_windows: bool) {
1098    if !has_open_windows {
1099        let platform = unsafe { get_mac_platform(this) };
1100        let mut lock = platform.0.lock();
1101        if let Some(mut callback) = lock.reopen.take() {
1102            drop(lock);
1103            callback();
1104            platform.0.lock().reopen.get_or_insert(callback);
1105        }
1106    }
1107}
1108
1109extern "C" fn did_become_active(this: &mut Object, _: Sel, _: id) {
1110    let platform = unsafe { get_mac_platform(this) };
1111    let mut lock = platform.0.lock();
1112    if let Some(mut callback) = lock.become_active.take() {
1113        drop(lock);
1114        callback();
1115        platform.0.lock().become_active.get_or_insert(callback);
1116    }
1117}
1118
1119extern "C" fn did_resign_active(this: &mut Object, _: Sel, _: id) {
1120    let platform = unsafe { get_mac_platform(this) };
1121    let mut lock = platform.0.lock();
1122    if let Some(mut callback) = lock.resign_active.take() {
1123        drop(lock);
1124        callback();
1125        platform.0.lock().resign_active.get_or_insert(callback);
1126    }
1127}
1128
1129extern "C" fn will_terminate(this: &mut Object, _: Sel, _: id) {
1130    let platform = unsafe { get_mac_platform(this) };
1131    let mut lock = platform.0.lock();
1132    if let Some(mut callback) = lock.quit.take() {
1133        drop(lock);
1134        callback();
1135        platform.0.lock().quit.get_or_insert(callback);
1136    }
1137}
1138
1139extern "C" fn open_urls(this: &mut Object, _: Sel, _: id, urls: id) {
1140    let urls = unsafe {
1141        (0..urls.count())
1142            .filter_map(|i| {
1143                let url = urls.objectAtIndex(i);
1144                match CStr::from_ptr(url.absoluteString().UTF8String() as *mut c_char).to_str() {
1145                    Ok(string) => Some(string.to_string()),
1146                    Err(err) => {
1147                        log::error!("error converting path to string: {}", err);
1148                        None
1149                    }
1150                }
1151            })
1152            .collect::<Vec<_>>()
1153    };
1154    let platform = unsafe { get_mac_platform(this) };
1155    let mut lock = platform.0.lock();
1156    if let Some(mut callback) = lock.open_urls.take() {
1157        drop(lock);
1158        callback(urls);
1159        platform.0.lock().open_urls.get_or_insert(callback);
1160    }
1161}
1162
1163extern "C" fn handle_menu_item(this: &mut Object, _: Sel, item: id) {
1164    unsafe {
1165        let platform = get_mac_platform(this);
1166        let mut lock = platform.0.lock();
1167        if let Some(mut callback) = lock.menu_command.take() {
1168            let tag: NSInteger = msg_send![item, tag];
1169            let index = tag as usize;
1170            if let Some(action) = lock.menu_actions.get(index) {
1171                let action = action.boxed_clone();
1172                drop(lock);
1173                callback(&*action);
1174            }
1175            platform.0.lock().menu_command.get_or_insert(callback);
1176        }
1177    }
1178}
1179
1180extern "C" fn validate_menu_item(this: &mut Object, _: Sel, item: id) -> bool {
1181    unsafe {
1182        let mut result = false;
1183        let platform = get_mac_platform(this);
1184        let mut lock = platform.0.lock();
1185        if let Some(mut callback) = lock.validate_menu_command.take() {
1186            let tag: NSInteger = msg_send![item, tag];
1187            let index = tag as usize;
1188            if let Some(action) = lock.menu_actions.get(index) {
1189                let action = action.boxed_clone();
1190                drop(lock);
1191                result = callback(action.as_ref());
1192            }
1193            platform
1194                .0
1195                .lock()
1196                .validate_menu_command
1197                .get_or_insert(callback);
1198        }
1199        result
1200    }
1201}
1202
1203extern "C" fn menu_will_open(this: &mut Object, _: Sel, _: id) {
1204    unsafe {
1205        let platform = get_mac_platform(this);
1206        let mut lock = platform.0.lock();
1207        if let Some(mut callback) = lock.will_open_menu.take() {
1208            drop(lock);
1209            callback();
1210            platform.0.lock().will_open_menu.get_or_insert(callback);
1211        }
1212    }
1213}
1214
1215unsafe fn ns_string(string: &str) -> id {
1216    NSString::alloc(nil).init_str(string).autorelease()
1217}
1218
1219unsafe fn ns_url_to_path(url: id) -> Result<PathBuf> {
1220    let path: *mut c_char = msg_send![url, fileSystemRepresentation];
1221    if path.is_null() {
1222        Err(anyhow!(
1223            "url is not a file path: {}",
1224            CStr::from_ptr(url.absoluteString().UTF8String()).to_string_lossy()
1225        ))
1226    } else {
1227        Ok(PathBuf::from(OsStr::from_bytes(
1228            CStr::from_ptr(path).to_bytes(),
1229        )))
1230    }
1231}
1232
1233mod security {
1234    #![allow(non_upper_case_globals)]
1235    use super::*;
1236
1237    #[link(name = "Security", kind = "framework")]
1238    extern "C" {
1239        pub static kSecClass: CFStringRef;
1240        pub static kSecClassInternetPassword: CFStringRef;
1241        pub static kSecAttrServer: CFStringRef;
1242        pub static kSecAttrAccount: CFStringRef;
1243        pub static kSecValueData: CFStringRef;
1244        pub static kSecReturnAttributes: CFStringRef;
1245        pub static kSecReturnData: CFStringRef;
1246
1247        pub fn SecItemAdd(attributes: CFDictionaryRef, result: *mut CFTypeRef) -> OSStatus;
1248        pub fn SecItemUpdate(query: CFDictionaryRef, attributes: CFDictionaryRef) -> OSStatus;
1249        pub fn SecItemDelete(query: CFDictionaryRef) -> OSStatus;
1250        pub fn SecItemCopyMatching(query: CFDictionaryRef, result: *mut CFTypeRef) -> OSStatus;
1251    }
1252
1253    pub const errSecSuccess: OSStatus = 0;
1254    pub const errSecUserCanceled: OSStatus = -128;
1255    pub const errSecItemNotFound: OSStatus = -25300;
1256}
1257
1258#[cfg(test)]
1259mod tests {
1260    use crate::ClipboardItem;
1261
1262    use super::*;
1263
1264    #[test]
1265    fn test_clipboard() {
1266        let platform = build_platform();
1267        assert_eq!(platform.read_from_clipboard(), None);
1268
1269        let item = ClipboardItem::new("1".to_string());
1270        platform.write_to_clipboard(item.clone());
1271        assert_eq!(platform.read_from_clipboard(), Some(item));
1272
1273        let item = ClipboardItem::new("2".to_string()).with_metadata(vec![3, 4]);
1274        platform.write_to_clipboard(item.clone());
1275        assert_eq!(platform.read_from_clipboard(), Some(item));
1276
1277        let text_from_other_app = "text from other app";
1278        unsafe {
1279            let bytes = NSData::dataWithBytes_length_(
1280                nil,
1281                text_from_other_app.as_ptr() as *const c_void,
1282                text_from_other_app.len() as u64,
1283            );
1284            platform
1285                .0
1286                .lock()
1287                .pasteboard
1288                .setData_forType(bytes, NSPasteboardTypeString);
1289        }
1290        assert_eq!(
1291            platform.read_from_clipboard(),
1292            Some(ClipboardItem::new(text_from_other_app.to_string()))
1293        );
1294    }
1295
1296    fn build_platform() -> MacPlatform {
1297        let platform = MacPlatform::new();
1298        platform.0.lock().pasteboard = unsafe { NSPasteboard::pasteboardWithUniqueName(nil) };
1299        platform
1300    }
1301}