platform.rs

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