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            menu.setTitle_(ns_string(&menu_config.name));
 220            menu.setDelegate_(delegate);
 221
 222            for item_config in menu_config.items {
 223                menu.addItem_(Self::create_menu_item(
 224                    item_config,
 225                    delegate,
 226                    actions,
 227                    keymap,
 228                ));
 229            }
 230
 231            let menu_item = NSMenuItem::new(nil).autorelease();
 232            menu_item.setSubmenu_(menu);
 233            application_menu.addItem_(menu_item);
 234
 235            if menu_config.name == "Window" {
 236                let app: id = msg_send![APP_CLASS, sharedApplication];
 237                app.setWindowsMenu_(menu);
 238            }
 239        }
 240
 241        application_menu
 242    }
 243
 244    unsafe fn create_dock_menu(
 245        &self,
 246        menu_items: Vec<MenuItem>,
 247        delegate: id,
 248        actions: &mut Vec<Box<dyn Action>>,
 249        keymap: &Keymap,
 250    ) -> id {
 251        let dock_menu = NSMenu::new(nil);
 252        dock_menu.setDelegate_(delegate);
 253        for item_config in menu_items {
 254            dock_menu.addItem_(Self::create_menu_item(
 255                item_config,
 256                delegate,
 257                actions,
 258                keymap,
 259            ));
 260        }
 261
 262        dock_menu
 263    }
 264
 265    unsafe fn create_menu_item(
 266        item: MenuItem,
 267        delegate: id,
 268        actions: &mut Vec<Box<dyn Action>>,
 269        keymap: &Keymap,
 270    ) -> id {
 271        match item {
 272            MenuItem::Separator => NSMenuItem::separatorItem(nil),
 273            MenuItem::Action {
 274                name,
 275                action,
 276                os_action,
 277            } => {
 278                let keystrokes = keymap
 279                    .bindings_for_action(action.as_ref())
 280                    .next()
 281                    .map(|binding| binding.keystrokes());
 282
 283                let selector = match os_action {
 284                    Some(crate::OsAction::Cut) => selector("cut:"),
 285                    Some(crate::OsAction::Copy) => selector("copy:"),
 286                    Some(crate::OsAction::Paste) => selector("paste:"),
 287                    Some(crate::OsAction::SelectAll) => selector("selectAll:"),
 288                    Some(crate::OsAction::Undo) => selector("undo:"),
 289                    Some(crate::OsAction::Redo) => selector("redo:"),
 290                    None => selector("handleGPUIMenuItem:"),
 291                };
 292
 293                let item;
 294                if let Some(keystrokes) = keystrokes {
 295                    if keystrokes.len() == 1 {
 296                        let keystroke = &keystrokes[0];
 297                        let mut mask = NSEventModifierFlags::empty();
 298                        for (modifier, flag) in &[
 299                            (
 300                                keystroke.modifiers.platform,
 301                                NSEventModifierFlags::NSCommandKeyMask,
 302                            ),
 303                            (
 304                                keystroke.modifiers.control,
 305                                NSEventModifierFlags::NSControlKeyMask,
 306                            ),
 307                            (
 308                                keystroke.modifiers.alt,
 309                                NSEventModifierFlags::NSAlternateKeyMask,
 310                            ),
 311                            (
 312                                keystroke.modifiers.shift,
 313                                NSEventModifierFlags::NSShiftKeyMask,
 314                            ),
 315                        ] {
 316                            if *modifier {
 317                                mask |= *flag;
 318                            }
 319                        }
 320
 321                        item = NSMenuItem::alloc(nil)
 322                            .initWithTitle_action_keyEquivalent_(
 323                                ns_string(&name),
 324                                selector,
 325                                ns_string(key_to_native(&keystroke.key).as_ref()),
 326                            )
 327                            .autorelease();
 328                        item.setKeyEquivalentModifierMask_(mask);
 329                    }
 330                    // For multi-keystroke bindings, render the keystroke as part of the title.
 331                    else {
 332                        use std::fmt::Write;
 333
 334                        let mut name = format!("{name} [");
 335                        for (i, keystroke) in keystrokes.iter().enumerate() {
 336                            if i > 0 {
 337                                name.push(' ');
 338                            }
 339                            write!(&mut name, "{}", keystroke).unwrap();
 340                        }
 341                        name.push(']');
 342
 343                        item = NSMenuItem::alloc(nil)
 344                            .initWithTitle_action_keyEquivalent_(
 345                                ns_string(&name),
 346                                selector,
 347                                ns_string(""),
 348                            )
 349                            .autorelease();
 350                    }
 351                } else {
 352                    item = NSMenuItem::alloc(nil)
 353                        .initWithTitle_action_keyEquivalent_(
 354                            ns_string(&name),
 355                            selector,
 356                            ns_string(""),
 357                        )
 358                        .autorelease();
 359                }
 360
 361                let tag = actions.len() as NSInteger;
 362                let _: () = msg_send![item, setTag: tag];
 363                actions.push(action);
 364                item
 365            }
 366            MenuItem::Submenu(Menu { name, items }) => {
 367                let item = NSMenuItem::new(nil).autorelease();
 368                let submenu = NSMenu::new(nil).autorelease();
 369                submenu.setDelegate_(delegate);
 370                for item in items {
 371                    submenu.addItem_(Self::create_menu_item(item, delegate, actions, keymap));
 372                }
 373                item.setSubmenu_(submenu);
 374                item.setTitle_(ns_string(&name));
 375                item
 376            }
 377        }
 378    }
 379
 380    fn os_version(&self) -> Result<SemanticVersion> {
 381        unsafe {
 382            let process_info = NSProcessInfo::processInfo(nil);
 383            let version = process_info.operatingSystemVersion();
 384            Ok(SemanticVersion::new(
 385                version.majorVersion as usize,
 386                version.minorVersion as usize,
 387                version.patchVersion as usize,
 388            ))
 389        }
 390    }
 391}
 392
 393impl Platform for MacPlatform {
 394    fn background_executor(&self) -> BackgroundExecutor {
 395        self.0.lock().background_executor.clone()
 396    }
 397
 398    fn foreground_executor(&self) -> crate::ForegroundExecutor {
 399        self.0.lock().foreground_executor.clone()
 400    }
 401
 402    fn text_system(&self) -> Arc<dyn PlatformTextSystem> {
 403        self.0.lock().text_system.clone()
 404    }
 405
 406    fn run(&self, on_finish_launching: Box<dyn FnOnce()>) {
 407        let mut state = self.0.lock();
 408        if state.headless {
 409            drop(state);
 410            on_finish_launching();
 411            unsafe { CFRunLoopRun() };
 412        } else {
 413            state.finish_launching = Some(on_finish_launching);
 414            drop(state);
 415        }
 416
 417        unsafe {
 418            let app: id = msg_send![APP_CLASS, sharedApplication];
 419            let app_delegate: id = msg_send![APP_DELEGATE_CLASS, new];
 420            app.setDelegate_(app_delegate);
 421
 422            let self_ptr = self as *const Self as *const c_void;
 423            (*app).set_ivar(MAC_PLATFORM_IVAR, self_ptr);
 424            (*app_delegate).set_ivar(MAC_PLATFORM_IVAR, self_ptr);
 425
 426            let pool = NSAutoreleasePool::new(nil);
 427            app.run();
 428            pool.drain();
 429
 430            (*app).set_ivar(MAC_PLATFORM_IVAR, null_mut::<c_void>());
 431            (*NSWindow::delegate(app)).set_ivar(MAC_PLATFORM_IVAR, null_mut::<c_void>());
 432        }
 433    }
 434
 435    fn quit(&self) {
 436        // Quitting the app causes us to close windows, which invokes `Window::on_close` callbacks
 437        // synchronously before this method terminates. If we call `Platform::quit` while holding a
 438        // borrow of the app state (which most of the time we will do), we will end up
 439        // double-borrowing the app state in the `on_close` callbacks for our open windows. To solve
 440        // this, we make quitting the application asynchronous so that we aren't holding borrows to
 441        // the app state on the stack when we actually terminate the app.
 442
 443        use super::dispatcher::{dispatch_get_main_queue, dispatch_sys::dispatch_async_f};
 444
 445        unsafe {
 446            dispatch_async_f(dispatch_get_main_queue(), ptr::null_mut(), Some(quit));
 447        }
 448
 449        unsafe extern "C" fn quit(_: *mut c_void) {
 450            let app = NSApplication::sharedApplication(nil);
 451            let _: () = msg_send![app, terminate: nil];
 452        }
 453    }
 454
 455    fn restart(&self, _binary_path: Option<PathBuf>) {
 456        use std::os::unix::process::CommandExt as _;
 457
 458        let app_pid = std::process::id().to_string();
 459        let app_path = self
 460            .app_path()
 461            .ok()
 462            // When the app is not bundled, `app_path` returns the
 463            // directory containing the executable. Disregard this
 464            // and get the path to the executable itself.
 465            .and_then(|path| (path.extension()?.to_str()? == "app").then_some(path))
 466            .unwrap_or_else(|| std::env::current_exe().unwrap());
 467
 468        // Wait until this process has exited and then re-open this path.
 469        let script = r#"
 470            while kill -0 $0 2> /dev/null; do
 471                sleep 0.1
 472            done
 473            open "$1"
 474        "#;
 475
 476        let restart_process = Command::new("/bin/bash")
 477            .arg("-c")
 478            .arg(script)
 479            .arg(app_pid)
 480            .arg(app_path)
 481            .process_group(0)
 482            .spawn();
 483
 484        match restart_process {
 485            Ok(_) => self.quit(),
 486            Err(e) => log::error!("failed to spawn restart script: {:?}", e),
 487        }
 488    }
 489
 490    fn activate(&self, ignoring_other_apps: bool) {
 491        unsafe {
 492            let app = NSApplication::sharedApplication(nil);
 493            app.activateIgnoringOtherApps_(ignoring_other_apps.to_objc());
 494        }
 495    }
 496
 497    fn hide(&self) {
 498        unsafe {
 499            let app = NSApplication::sharedApplication(nil);
 500            let _: () = msg_send![app, hide: nil];
 501        }
 502    }
 503
 504    fn hide_other_apps(&self) {
 505        unsafe {
 506            let app = NSApplication::sharedApplication(nil);
 507            let _: () = msg_send![app, hideOtherApplications: nil];
 508        }
 509    }
 510
 511    fn unhide_other_apps(&self) {
 512        unsafe {
 513            let app = NSApplication::sharedApplication(nil);
 514            let _: () = msg_send![app, unhideAllApplications: nil];
 515        }
 516    }
 517
 518    fn primary_display(&self) -> Option<Rc<dyn PlatformDisplay>> {
 519        Some(Rc::new(MacDisplay::primary()))
 520    }
 521
 522    fn displays(&self) -> Vec<Rc<dyn PlatformDisplay>> {
 523        MacDisplay::all()
 524            .map(|screen| Rc::new(screen) as Rc<_>)
 525            .collect()
 526    }
 527
 528    fn active_window(&self) -> Option<AnyWindowHandle> {
 529        MacWindow::active_window()
 530    }
 531
 532    // Returns the windows ordered front-to-back, meaning that the active
 533    // window is the first one in the returned vec.
 534    fn window_stack(&self) -> Option<Vec<AnyWindowHandle>> {
 535        Some(MacWindow::ordered_windows())
 536    }
 537
 538    fn open_window(
 539        &self,
 540        handle: AnyWindowHandle,
 541        options: WindowParams,
 542    ) -> Result<Box<dyn PlatformWindow>> {
 543        // Clippy thinks that this evaluates to `()`, for some reason.
 544        #[allow(clippy::unit_arg, clippy::clone_on_copy)]
 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 on_quit(&self, callback: Box<dyn FnMut()>) {
 724        self.0.lock().quit = Some(callback);
 725    }
 726
 727    fn on_reopen(&self, callback: Box<dyn FnMut()>) {
 728        self.0.lock().reopen = Some(callback);
 729    }
 730
 731    fn on_app_menu_action(&self, callback: Box<dyn FnMut(&dyn Action)>) {
 732        self.0.lock().menu_command = Some(callback);
 733    }
 734
 735    fn on_will_open_app_menu(&self, callback: Box<dyn FnMut()>) {
 736        self.0.lock().will_open_menu = Some(callback);
 737    }
 738
 739    fn on_validate_app_menu_command(&self, callback: Box<dyn FnMut(&dyn Action) -> bool>) {
 740        self.0.lock().validate_menu_command = Some(callback);
 741    }
 742
 743    fn app_path(&self) -> Result<PathBuf> {
 744        unsafe {
 745            let bundle: id = NSBundle::mainBundle();
 746            if bundle.is_null() {
 747                Err(anyhow!("app is not running inside a bundle"))
 748            } else {
 749                Ok(path_from_objc(msg_send![bundle, bundlePath]))
 750            }
 751        }
 752    }
 753
 754    fn set_menus(&self, menus: Vec<Menu>, keymap: &Keymap) {
 755        unsafe {
 756            let app: id = msg_send![APP_CLASS, sharedApplication];
 757            let mut state = self.0.lock();
 758            let actions = &mut state.menu_actions;
 759            app.setMainMenu_(self.create_menu_bar(menus, NSWindow::delegate(app), actions, keymap));
 760        }
 761    }
 762
 763    fn set_dock_menu(&self, menu: Vec<MenuItem>, keymap: &Keymap) {
 764        unsafe {
 765            let app: id = msg_send![APP_CLASS, sharedApplication];
 766            let mut state = self.0.lock();
 767            let actions = &mut state.menu_actions;
 768            let new = self.create_dock_menu(menu, NSWindow::delegate(app), actions, keymap);
 769            if let Some(old) = state.dock_menu.replace(new) {
 770                CFRelease(old as _)
 771            }
 772        }
 773    }
 774
 775    fn add_recent_document(&self, path: &Path) {
 776        if let Some(path_str) = path.to_str() {
 777            unsafe {
 778                let document_controller: id =
 779                    msg_send![class!(NSDocumentController), sharedDocumentController];
 780                let url: id = NSURL::fileURLWithPath_(nil, ns_string(path_str));
 781                let _: () = msg_send![document_controller, noteNewRecentDocumentURL:url];
 782            }
 783        }
 784    }
 785
 786    fn path_for_auxiliary_executable(&self, name: &str) -> Result<PathBuf> {
 787        unsafe {
 788            let bundle: id = NSBundle::mainBundle();
 789            if bundle.is_null() {
 790                Err(anyhow!("app is not running inside a bundle"))
 791            } else {
 792                let name = ns_string(name);
 793                let url: id = msg_send![bundle, URLForAuxiliaryExecutable: name];
 794                if url.is_null() {
 795                    Err(anyhow!("resource not found"))
 796                } else {
 797                    ns_url_to_path(url)
 798                }
 799            }
 800        }
 801    }
 802
 803    /// Match cursor style to one of the styles available
 804    /// in macOS's [NSCursor](https://developer.apple.com/documentation/appkit/nscursor).
 805    fn set_cursor_style(&self, style: CursorStyle) {
 806        unsafe {
 807            let new_cursor: id = match style {
 808                CursorStyle::Arrow => msg_send![class!(NSCursor), arrowCursor],
 809                CursorStyle::IBeam => msg_send![class!(NSCursor), IBeamCursor],
 810                CursorStyle::Crosshair => msg_send![class!(NSCursor), crosshairCursor],
 811                CursorStyle::ClosedHand => msg_send![class!(NSCursor), closedHandCursor],
 812                CursorStyle::OpenHand => msg_send![class!(NSCursor), openHandCursor],
 813                CursorStyle::PointingHand => msg_send![class!(NSCursor), pointingHandCursor],
 814                CursorStyle::ResizeLeftRight => msg_send![class!(NSCursor), resizeLeftRightCursor],
 815                CursorStyle::ResizeUpDown => msg_send![class!(NSCursor), resizeUpDownCursor],
 816                CursorStyle::ResizeLeft => msg_send![class!(NSCursor), resizeLeftCursor],
 817                CursorStyle::ResizeRight => msg_send![class!(NSCursor), resizeRightCursor],
 818                CursorStyle::ResizeColumn => msg_send![class!(NSCursor), resizeLeftRightCursor],
 819                CursorStyle::ResizeRow => msg_send![class!(NSCursor), resizeUpDownCursor],
 820                CursorStyle::ResizeUp => msg_send![class!(NSCursor), resizeUpCursor],
 821                CursorStyle::ResizeDown => msg_send![class!(NSCursor), resizeDownCursor],
 822
 823                // Undocumented, private class methods:
 824                // https://stackoverflow.com/questions/27242353/cocoa-predefined-resize-mouse-cursor
 825                CursorStyle::ResizeUpLeftDownRight => {
 826                    msg_send![class!(NSCursor), _windowResizeNorthWestSouthEastCursor]
 827                }
 828                CursorStyle::ResizeUpRightDownLeft => {
 829                    msg_send![class!(NSCursor), _windowResizeNorthEastSouthWestCursor]
 830                }
 831
 832                CursorStyle::IBeamCursorForVerticalLayout => {
 833                    msg_send![class!(NSCursor), IBeamCursorForVerticalLayout]
 834                }
 835                CursorStyle::OperationNotAllowed => {
 836                    msg_send![class!(NSCursor), operationNotAllowedCursor]
 837                }
 838                CursorStyle::DragLink => msg_send![class!(NSCursor), dragLinkCursor],
 839                CursorStyle::DragCopy => msg_send![class!(NSCursor), dragCopyCursor],
 840                CursorStyle::ContextualMenu => msg_send![class!(NSCursor), contextualMenuCursor],
 841            };
 842
 843            let old_cursor: id = msg_send![class!(NSCursor), currentCursor];
 844            if new_cursor != old_cursor {
 845                let _: () = msg_send![new_cursor, set];
 846            }
 847        }
 848    }
 849
 850    fn should_auto_hide_scrollbars(&self) -> bool {
 851        #[allow(non_upper_case_globals)]
 852        const NSScrollerStyleOverlay: NSInteger = 1;
 853
 854        unsafe {
 855            let style: NSInteger = msg_send![class!(NSScroller), preferredScrollerStyle];
 856            style == NSScrollerStyleOverlay
 857        }
 858    }
 859
 860    fn write_to_clipboard(&self, item: ClipboardItem) {
 861        use crate::ClipboardEntry;
 862
 863        unsafe {
 864            // We only want to use NSAttributedString if there are multiple entries to write.
 865            if item.entries.len() <= 1 {
 866                match item.entries.first() {
 867                    Some(entry) => match entry {
 868                        ClipboardEntry::String(string) => {
 869                            self.write_plaintext_to_clipboard(string);
 870                        }
 871                        ClipboardEntry::Image(image) => {
 872                            self.write_image_to_clipboard(image);
 873                        }
 874                    },
 875                    None => {
 876                        // Writing an empty list of entries just clears the clipboard.
 877                        let state = self.0.lock();
 878                        state.pasteboard.clearContents();
 879                    }
 880                }
 881            } else {
 882                let mut any_images = false;
 883                let attributed_string = {
 884                    let mut buf = NSMutableAttributedString::alloc(nil)
 885                        // TODO can we skip this? Or at least part of it?
 886                        .init_attributed_string(NSString::alloc(nil).init_str(""));
 887
 888                    for entry in item.entries {
 889                        if let ClipboardEntry::String(ClipboardString { text, metadata: _ }) = entry
 890                        {
 891                            let to_append = NSAttributedString::alloc(nil)
 892                                .init_attributed_string(NSString::alloc(nil).init_str(&text));
 893
 894                            buf.appendAttributedString_(to_append);
 895                        }
 896                    }
 897
 898                    buf
 899                };
 900
 901                let state = self.0.lock();
 902                state.pasteboard.clearContents();
 903
 904                // Only set rich text clipboard types if we actually have 1+ images to include.
 905                if any_images {
 906                    let rtfd_data = attributed_string.RTFDFromRange_documentAttributes_(
 907                        NSRange::new(0, msg_send![attributed_string, length]),
 908                        nil,
 909                    );
 910                    if rtfd_data != nil {
 911                        state
 912                            .pasteboard
 913                            .setData_forType(rtfd_data, NSPasteboardTypeRTFD);
 914                    }
 915
 916                    let rtf_data = attributed_string.RTFFromRange_documentAttributes_(
 917                        NSRange::new(0, attributed_string.length()),
 918                        nil,
 919                    );
 920                    if rtf_data != nil {
 921                        state
 922                            .pasteboard
 923                            .setData_forType(rtf_data, NSPasteboardTypeRTF);
 924                    }
 925                }
 926
 927                let plain_text = attributed_string.string();
 928                state
 929                    .pasteboard
 930                    .setString_forType(plain_text, NSPasteboardTypeString);
 931            }
 932        }
 933    }
 934
 935    fn read_from_clipboard(&self) -> Option<ClipboardItem> {
 936        let state = self.0.lock();
 937        let pasteboard = state.pasteboard;
 938
 939        // First, see if it's a string.
 940        unsafe {
 941            let types: id = pasteboard.types();
 942            let string_type: id = ns_string("public.utf8-plain-text");
 943
 944            if msg_send![types, containsObject: string_type] {
 945                let data = pasteboard.dataForType(string_type);
 946                if data == nil {
 947                    return None;
 948                } else if data.bytes().is_null() {
 949                    // https://developer.apple.com/documentation/foundation/nsdata/1410616-bytes?language=objc
 950                    // "If the length of the NSData object is 0, this property returns nil."
 951                    return Some(self.read_string_from_clipboard(&state, &[]));
 952                } else {
 953                    let bytes =
 954                        slice::from_raw_parts(data.bytes() as *mut u8, data.length() as usize);
 955
 956                    return Some(self.read_string_from_clipboard(&state, bytes));
 957                }
 958            }
 959
 960            // If it wasn't a string, try the various supported image types.
 961            for format in ImageFormat::iter() {
 962                if let Some(item) = try_clipboard_image(pasteboard, format) {
 963                    return Some(item);
 964                }
 965            }
 966        }
 967
 968        // If it wasn't a string or a supported image type, give up.
 969        None
 970    }
 971
 972    fn write_credentials(&self, url: &str, username: &str, password: &[u8]) -> Task<Result<()>> {
 973        let url = url.to_string();
 974        let username = username.to_string();
 975        let password = password.to_vec();
 976        self.background_executor().spawn(async move {
 977            unsafe {
 978                use security::*;
 979
 980                let url = CFString::from(url.as_str());
 981                let username = CFString::from(username.as_str());
 982                let password = CFData::from_buffer(&password);
 983
 984                // First, check if there are already credentials for the given server. If so, then
 985                // update the username and password.
 986                let mut verb = "updating";
 987                let mut query_attrs = CFMutableDictionary::with_capacity(2);
 988                query_attrs.set(kSecClass as *const _, kSecClassInternetPassword as *const _);
 989                query_attrs.set(kSecAttrServer as *const _, url.as_CFTypeRef());
 990
 991                let mut attrs = CFMutableDictionary::with_capacity(4);
 992                attrs.set(kSecClass as *const _, kSecClassInternetPassword as *const _);
 993                attrs.set(kSecAttrServer as *const _, url.as_CFTypeRef());
 994                attrs.set(kSecAttrAccount as *const _, username.as_CFTypeRef());
 995                attrs.set(kSecValueData as *const _, password.as_CFTypeRef());
 996
 997                let mut status = SecItemUpdate(
 998                    query_attrs.as_concrete_TypeRef(),
 999                    attrs.as_concrete_TypeRef(),
1000                );
1001
1002                // If there were no existing credentials for the given server, then create them.
1003                if status == errSecItemNotFound {
1004                    verb = "creating";
1005                    status = SecItemAdd(attrs.as_concrete_TypeRef(), ptr::null_mut());
1006                }
1007
1008                if status != errSecSuccess {
1009                    return Err(anyhow!("{} password failed: {}", verb, status));
1010                }
1011            }
1012            Ok(())
1013        })
1014    }
1015
1016    fn read_credentials(&self, url: &str) -> Task<Result<Option<(String, Vec<u8>)>>> {
1017        let url = url.to_string();
1018        self.background_executor().spawn(async move {
1019            let url = CFString::from(url.as_str());
1020            let cf_true = CFBoolean::true_value().as_CFTypeRef();
1021
1022            unsafe {
1023                use security::*;
1024
1025                // Find any credentials for the given server URL.
1026                let mut attrs = CFMutableDictionary::with_capacity(5);
1027                attrs.set(kSecClass as *const _, kSecClassInternetPassword as *const _);
1028                attrs.set(kSecAttrServer as *const _, url.as_CFTypeRef());
1029                attrs.set(kSecReturnAttributes as *const _, cf_true);
1030                attrs.set(kSecReturnData as *const _, cf_true);
1031
1032                let mut result = CFTypeRef::from(ptr::null());
1033                let status = SecItemCopyMatching(attrs.as_concrete_TypeRef(), &mut result);
1034                match status {
1035                    security::errSecSuccess => {}
1036                    security::errSecItemNotFound | security::errSecUserCanceled => return Ok(None),
1037                    _ => return Err(anyhow!("reading password failed: {}", status)),
1038                }
1039
1040                let result = CFType::wrap_under_create_rule(result)
1041                    .downcast::<CFDictionary>()
1042                    .ok_or_else(|| anyhow!("keychain item was not a dictionary"))?;
1043                let username = result
1044                    .find(kSecAttrAccount as *const _)
1045                    .ok_or_else(|| anyhow!("account was missing from keychain item"))?;
1046                let username = CFType::wrap_under_get_rule(*username)
1047                    .downcast::<CFString>()
1048                    .ok_or_else(|| anyhow!("account was not a string"))?;
1049                let password = result
1050                    .find(kSecValueData as *const _)
1051                    .ok_or_else(|| anyhow!("password was missing from keychain item"))?;
1052                let password = CFType::wrap_under_get_rule(*password)
1053                    .downcast::<CFData>()
1054                    .ok_or_else(|| anyhow!("password was not a string"))?;
1055
1056                Ok(Some((username.to_string(), password.bytes().to_vec())))
1057            }
1058        })
1059    }
1060
1061    fn delete_credentials(&self, url: &str) -> Task<Result<()>> {
1062        let url = url.to_string();
1063
1064        self.background_executor().spawn(async move {
1065            unsafe {
1066                use security::*;
1067
1068                let url = CFString::from(url.as_str());
1069                let mut query_attrs = CFMutableDictionary::with_capacity(2);
1070                query_attrs.set(kSecClass as *const _, kSecClassInternetPassword as *const _);
1071                query_attrs.set(kSecAttrServer as *const _, url.as_CFTypeRef());
1072
1073                let status = SecItemDelete(query_attrs.as_concrete_TypeRef());
1074
1075                if status != errSecSuccess {
1076                    return Err(anyhow!("delete password failed: {}", status));
1077                }
1078            }
1079            Ok(())
1080        })
1081    }
1082}
1083
1084impl MacPlatform {
1085    unsafe fn read_string_from_clipboard(
1086        &self,
1087        state: &MacPlatformState,
1088        text_bytes: &[u8],
1089    ) -> ClipboardItem {
1090        let text = String::from_utf8_lossy(text_bytes).to_string();
1091        let metadata = self
1092            .read_from_pasteboard(state.pasteboard, state.text_hash_pasteboard_type)
1093            .and_then(|hash_bytes| {
1094                let hash_bytes = hash_bytes.try_into().ok()?;
1095                let hash = u64::from_be_bytes(hash_bytes);
1096                let metadata =
1097                    self.read_from_pasteboard(state.pasteboard, state.metadata_pasteboard_type)?;
1098
1099                if hash == ClipboardString::text_hash(&text) {
1100                    String::from_utf8(metadata.to_vec()).ok()
1101                } else {
1102                    None
1103                }
1104            });
1105
1106        ClipboardItem {
1107            entries: vec![ClipboardEntry::String(ClipboardString { text, metadata })],
1108        }
1109    }
1110
1111    unsafe fn write_plaintext_to_clipboard(&self, string: &ClipboardString) {
1112        let state = self.0.lock();
1113        state.pasteboard.clearContents();
1114
1115        let text_bytes = NSData::dataWithBytes_length_(
1116            nil,
1117            string.text.as_ptr() as *const c_void,
1118            string.text.len() as u64,
1119        );
1120        state
1121            .pasteboard
1122            .setData_forType(text_bytes, NSPasteboardTypeString);
1123
1124        if let Some(metadata) = string.metadata.as_ref() {
1125            let hash_bytes = ClipboardString::text_hash(&string.text).to_be_bytes();
1126            let hash_bytes = NSData::dataWithBytes_length_(
1127                nil,
1128                hash_bytes.as_ptr() as *const c_void,
1129                hash_bytes.len() as u64,
1130            );
1131            state
1132                .pasteboard
1133                .setData_forType(hash_bytes, state.text_hash_pasteboard_type);
1134
1135            let metadata_bytes = NSData::dataWithBytes_length_(
1136                nil,
1137                metadata.as_ptr() as *const c_void,
1138                metadata.len() as u64,
1139            );
1140            state
1141                .pasteboard
1142                .setData_forType(metadata_bytes, state.metadata_pasteboard_type);
1143        }
1144    }
1145
1146    unsafe fn write_image_to_clipboard(&self, image: &Image) {
1147        let state = self.0.lock();
1148        state.pasteboard.clearContents();
1149
1150        let bytes = NSData::dataWithBytes_length_(
1151            nil,
1152            image.bytes.as_ptr() as *const c_void,
1153            image.bytes.len() as u64,
1154        );
1155
1156        state
1157            .pasteboard
1158            .setData_forType(bytes, Into::<UTType>::into(image.format).inner_mut());
1159    }
1160}
1161
1162fn try_clipboard_image(pasteboard: id, format: ImageFormat) -> Option<ClipboardItem> {
1163    let mut ut_type: UTType = format.into();
1164
1165    unsafe {
1166        let types: id = pasteboard.types();
1167        if msg_send![types, containsObject: ut_type.inner()] {
1168            let data = pasteboard.dataForType(ut_type.inner_mut());
1169            if data == nil {
1170                None
1171            } else {
1172                let bytes = Vec::from(slice::from_raw_parts(
1173                    data.bytes() as *mut u8,
1174                    data.length() as usize,
1175                ));
1176                let id = hash(&bytes);
1177
1178                Some(ClipboardItem {
1179                    entries: vec![ClipboardEntry::Image(Image { format, bytes, id })],
1180                })
1181            }
1182        } else {
1183            None
1184        }
1185    }
1186}
1187
1188unsafe fn path_from_objc(path: id) -> PathBuf {
1189    let len = msg_send![path, lengthOfBytesUsingEncoding: NSUTF8StringEncoding];
1190    let bytes = path.UTF8String() as *const u8;
1191    let path = str::from_utf8(slice::from_raw_parts(bytes, len)).unwrap();
1192    PathBuf::from(path)
1193}
1194
1195unsafe fn get_mac_platform(object: &mut Object) -> &MacPlatform {
1196    let platform_ptr: *mut c_void = *object.get_ivar(MAC_PLATFORM_IVAR);
1197    assert!(!platform_ptr.is_null());
1198    &*(platform_ptr as *const MacPlatform)
1199}
1200
1201extern "C" fn did_finish_launching(this: &mut Object, _: Sel, _: id) {
1202    unsafe {
1203        let app: id = msg_send![APP_CLASS, sharedApplication];
1204        app.setActivationPolicy_(NSApplicationActivationPolicyRegular);
1205        let platform = get_mac_platform(this);
1206        let callback = platform.0.lock().finish_launching.take();
1207        if let Some(callback) = callback {
1208            callback();
1209        }
1210    }
1211}
1212
1213extern "C" fn should_handle_reopen(this: &mut Object, _: Sel, _: id, has_open_windows: bool) {
1214    if !has_open_windows {
1215        let platform = unsafe { get_mac_platform(this) };
1216        let mut lock = platform.0.lock();
1217        if let Some(mut callback) = lock.reopen.take() {
1218            drop(lock);
1219            callback();
1220            platform.0.lock().reopen.get_or_insert(callback);
1221        }
1222    }
1223}
1224
1225extern "C" fn will_terminate(this: &mut Object, _: Sel, _: id) {
1226    let platform = unsafe { get_mac_platform(this) };
1227    let mut lock = platform.0.lock();
1228    if let Some(mut callback) = lock.quit.take() {
1229        drop(lock);
1230        callback();
1231        platform.0.lock().quit.get_or_insert(callback);
1232    }
1233}
1234
1235extern "C" fn open_urls(this: &mut Object, _: Sel, _: id, urls: id) {
1236    let urls = unsafe {
1237        (0..urls.count())
1238            .filter_map(|i| {
1239                let url = urls.objectAtIndex(i);
1240                match CStr::from_ptr(url.absoluteString().UTF8String() as *mut c_char).to_str() {
1241                    Ok(string) => Some(string.to_string()),
1242                    Err(err) => {
1243                        log::error!("error converting path to string: {}", err);
1244                        None
1245                    }
1246                }
1247            })
1248            .collect::<Vec<_>>()
1249    };
1250    let platform = unsafe { get_mac_platform(this) };
1251    let mut lock = platform.0.lock();
1252    if let Some(mut callback) = lock.open_urls.take() {
1253        drop(lock);
1254        callback(urls);
1255        platform.0.lock().open_urls.get_or_insert(callback);
1256    }
1257}
1258
1259extern "C" fn handle_menu_item(this: &mut Object, _: Sel, item: id) {
1260    unsafe {
1261        let platform = get_mac_platform(this);
1262        let mut lock = platform.0.lock();
1263        if let Some(mut callback) = lock.menu_command.take() {
1264            let tag: NSInteger = msg_send![item, tag];
1265            let index = tag as usize;
1266            if let Some(action) = lock.menu_actions.get(index) {
1267                let action = action.boxed_clone();
1268                drop(lock);
1269                callback(&*action);
1270            }
1271            platform.0.lock().menu_command.get_or_insert(callback);
1272        }
1273    }
1274}
1275
1276extern "C" fn validate_menu_item(this: &mut Object, _: Sel, item: id) -> bool {
1277    unsafe {
1278        let mut result = false;
1279        let platform = get_mac_platform(this);
1280        let mut lock = platform.0.lock();
1281        if let Some(mut callback) = lock.validate_menu_command.take() {
1282            let tag: NSInteger = msg_send![item, tag];
1283            let index = tag as usize;
1284            if let Some(action) = lock.menu_actions.get(index) {
1285                let action = action.boxed_clone();
1286                drop(lock);
1287                result = callback(action.as_ref());
1288            }
1289            platform
1290                .0
1291                .lock()
1292                .validate_menu_command
1293                .get_or_insert(callback);
1294        }
1295        result
1296    }
1297}
1298
1299extern "C" fn menu_will_open(this: &mut Object, _: Sel, _: id) {
1300    unsafe {
1301        let platform = get_mac_platform(this);
1302        let mut lock = platform.0.lock();
1303        if let Some(mut callback) = lock.will_open_menu.take() {
1304            drop(lock);
1305            callback();
1306            platform.0.lock().will_open_menu.get_or_insert(callback);
1307        }
1308    }
1309}
1310
1311extern "C" fn handle_dock_menu(this: &mut Object, _: Sel, _: id) -> id {
1312    unsafe {
1313        let platform = get_mac_platform(this);
1314        let mut state = platform.0.lock();
1315        if let Some(id) = state.dock_menu {
1316            id
1317        } else {
1318            nil
1319        }
1320    }
1321}
1322
1323unsafe fn ns_string(string: &str) -> id {
1324    NSString::alloc(nil).init_str(string).autorelease()
1325}
1326
1327unsafe fn ns_url_to_path(url: id) -> Result<PathBuf> {
1328    let path: *mut c_char = msg_send![url, fileSystemRepresentation];
1329    if path.is_null() {
1330        Err(anyhow!(
1331            "url is not a file path: {}",
1332            CStr::from_ptr(url.absoluteString().UTF8String()).to_string_lossy()
1333        ))
1334    } else {
1335        Ok(PathBuf::from(OsStr::from_bytes(
1336            CStr::from_ptr(path).to_bytes(),
1337        )))
1338    }
1339}
1340
1341mod security {
1342    #![allow(non_upper_case_globals)]
1343    use super::*;
1344
1345    #[link(name = "Security", kind = "framework")]
1346    extern "C" {
1347        pub static kSecClass: CFStringRef;
1348        pub static kSecClassInternetPassword: CFStringRef;
1349        pub static kSecAttrServer: CFStringRef;
1350        pub static kSecAttrAccount: CFStringRef;
1351        pub static kSecValueData: CFStringRef;
1352        pub static kSecReturnAttributes: CFStringRef;
1353        pub static kSecReturnData: CFStringRef;
1354
1355        pub fn SecItemAdd(attributes: CFDictionaryRef, result: *mut CFTypeRef) -> OSStatus;
1356        pub fn SecItemUpdate(query: CFDictionaryRef, attributes: CFDictionaryRef) -> OSStatus;
1357        pub fn SecItemDelete(query: CFDictionaryRef) -> OSStatus;
1358        pub fn SecItemCopyMatching(query: CFDictionaryRef, result: *mut CFTypeRef) -> OSStatus;
1359    }
1360
1361    pub const errSecSuccess: OSStatus = 0;
1362    pub const errSecUserCanceled: OSStatus = -128;
1363    pub const errSecItemNotFound: OSStatus = -25300;
1364}
1365
1366impl From<ImageFormat> for UTType {
1367    fn from(value: ImageFormat) -> Self {
1368        match value {
1369            ImageFormat::Png => Self::png(),
1370            ImageFormat::Jpeg => Self::jpeg(),
1371            ImageFormat::Tiff => Self::tiff(),
1372            ImageFormat::Webp => Self::webp(),
1373            ImageFormat::Gif => Self::gif(),
1374            ImageFormat::Bmp => Self::bmp(),
1375            ImageFormat::Svg => Self::svg(),
1376        }
1377    }
1378}
1379
1380// See https://developer.apple.com/documentation/uniformtypeidentifiers/uttype-swift.struct/
1381struct UTType(id);
1382
1383impl UTType {
1384    pub fn png() -> Self {
1385        // https://developer.apple.com/documentation/uniformtypeidentifiers/uttype-swift.struct/png
1386        Self(unsafe { NSPasteboardTypePNG }) // This is a rare case where there's a built-in NSPasteboardType
1387    }
1388
1389    pub fn jpeg() -> Self {
1390        // https://developer.apple.com/documentation/uniformtypeidentifiers/uttype-swift.struct/jpeg
1391        Self(unsafe { ns_string("public.jpeg") })
1392    }
1393
1394    pub fn gif() -> Self {
1395        // https://developer.apple.com/documentation/uniformtypeidentifiers/uttype-swift.struct/gif
1396        Self(unsafe { ns_string("com.compuserve.gif") })
1397    }
1398
1399    pub fn webp() -> Self {
1400        // https://developer.apple.com/documentation/uniformtypeidentifiers/uttype-swift.struct/webp
1401        Self(unsafe { ns_string("org.webmproject.webp") })
1402    }
1403
1404    pub fn bmp() -> Self {
1405        // https://developer.apple.com/documentation/uniformtypeidentifiers/uttype-swift.struct/bmp
1406        Self(unsafe { ns_string("com.microsoft.bmp") })
1407    }
1408
1409    pub fn svg() -> Self {
1410        // https://developer.apple.com/documentation/uniformtypeidentifiers/uttype-swift.struct/svg
1411        Self(unsafe { ns_string("public.svg-image") })
1412    }
1413
1414    pub fn tiff() -> Self {
1415        // https://developer.apple.com/documentation/uniformtypeidentifiers/uttype-swift.struct/tiff
1416        Self(unsafe { NSPasteboardTypeTIFF }) // This is a rare case where there's a built-in NSPasteboardType
1417    }
1418
1419    fn inner(&self) -> *const Object {
1420        self.0
1421    }
1422
1423    fn inner_mut(&mut self) -> *mut Object {
1424        self.0 as *mut _
1425    }
1426}
1427
1428#[cfg(test)]
1429mod tests {
1430    use crate::ClipboardItem;
1431
1432    use super::*;
1433
1434    #[test]
1435    fn test_clipboard() {
1436        let platform = build_platform();
1437        assert_eq!(platform.read_from_clipboard(), None);
1438
1439        let item = ClipboardItem::new_string("1".to_string());
1440        platform.write_to_clipboard(item.clone());
1441        assert_eq!(platform.read_from_clipboard(), Some(item));
1442
1443        let item = ClipboardItem {
1444            entries: vec![ClipboardEntry::String(
1445                ClipboardString::new("2".to_string()).with_json_metadata(vec![3, 4]),
1446            )],
1447        };
1448        platform.write_to_clipboard(item.clone());
1449        assert_eq!(platform.read_from_clipboard(), Some(item));
1450
1451        let text_from_other_app = "text from other app";
1452        unsafe {
1453            let bytes = NSData::dataWithBytes_length_(
1454                nil,
1455                text_from_other_app.as_ptr() as *const c_void,
1456                text_from_other_app.len() as u64,
1457            );
1458            platform
1459                .0
1460                .lock()
1461                .pasteboard
1462                .setData_forType(bytes, NSPasteboardTypeString);
1463        }
1464        assert_eq!(
1465            platform.read_from_clipboard(),
1466            Some(ClipboardItem::new_string(text_from_other_app.to_string()))
1467        );
1468    }
1469
1470    fn build_platform() -> MacPlatform {
1471        let platform = MacPlatform::new(false);
1472        platform.0.lock().pasteboard = unsafe { NSPasteboard::pasteboardWithUniqueName(nil) };
1473        platform
1474    }
1475}