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        let renderer_context = self.0.lock().renderer_context.clone();
 544        Ok(Box::new(MacWindow::open(
 545            handle,
 546            options,
 547            self.foreground_executor(),
 548            renderer_context,
 549        )))
 550    }
 551
 552    fn window_appearance(&self) -> WindowAppearance {
 553        unsafe {
 554            let app = NSApplication::sharedApplication(nil);
 555            let appearance: id = msg_send![app, effectiveAppearance];
 556            WindowAppearance::from_native(appearance)
 557        }
 558    }
 559
 560    fn open_url(&self, url: &str) {
 561        unsafe {
 562            let url = NSURL::alloc(nil)
 563                .initWithString_(ns_string(url))
 564                .autorelease();
 565            let workspace: id = msg_send![class!(NSWorkspace), sharedWorkspace];
 566            msg_send![workspace, openURL: url]
 567        }
 568    }
 569
 570    fn register_url_scheme(&self, scheme: &str) -> Task<anyhow::Result<()>> {
 571        // API only available post Monterey
 572        // https://developer.apple.com/documentation/appkit/nsworkspace/3753004-setdefaultapplicationaturl
 573        let (done_tx, done_rx) = oneshot::channel();
 574        if self.os_version().ok() < Some(SemanticVersion::new(12, 0, 0)) {
 575            return Task::ready(Err(anyhow!(
 576                "macOS 12.0 or later is required to register URL schemes"
 577            )));
 578        }
 579
 580        let bundle_id = unsafe {
 581            let bundle: id = msg_send![class!(NSBundle), mainBundle];
 582            let bundle_id: id = msg_send![bundle, bundleIdentifier];
 583            if bundle_id == nil {
 584                return Task::ready(Err(anyhow!("Can only register URL scheme in bundled apps")));
 585            }
 586            bundle_id
 587        };
 588
 589        unsafe {
 590            let workspace: id = msg_send![class!(NSWorkspace), sharedWorkspace];
 591            let scheme: id = ns_string(scheme);
 592            let app: id = msg_send![workspace, URLForApplicationWithBundleIdentifier: bundle_id];
 593            if app == nil {
 594                return Task::ready(Err(anyhow!(
 595                    "Cannot register URL scheme until app is installed"
 596                )));
 597            }
 598            let done_tx = Cell::new(Some(done_tx));
 599            let block = ConcreteBlock::new(move |error: id| {
 600                let result = if error == nil {
 601                    Ok(())
 602                } else {
 603                    let msg: id = msg_send![error, localizedDescription];
 604                    Err(anyhow!("Failed to register: {:?}", msg))
 605                };
 606
 607                if let Some(done_tx) = done_tx.take() {
 608                    let _ = done_tx.send(result);
 609                }
 610            });
 611            let block = block.copy();
 612            let _: () = msg_send![workspace, setDefaultApplicationAtURL: app toOpenURLsWithScheme: scheme completionHandler: block];
 613        }
 614
 615        self.background_executor()
 616            .spawn(async { crate::Flatten::flatten(done_rx.await.map_err(|e| anyhow!(e))) })
 617    }
 618
 619    fn on_open_urls(&self, callback: Box<dyn FnMut(Vec<String>)>) {
 620        self.0.lock().open_urls = Some(callback);
 621    }
 622
 623    fn prompt_for_paths(
 624        &self,
 625        options: PathPromptOptions,
 626    ) -> oneshot::Receiver<Result<Option<Vec<PathBuf>>>> {
 627        let (done_tx, done_rx) = oneshot::channel();
 628        self.foreground_executor()
 629            .spawn(async move {
 630                unsafe {
 631                    let panel = NSOpenPanel::openPanel(nil);
 632                    panel.setCanChooseDirectories_(options.directories.to_objc());
 633                    panel.setCanChooseFiles_(options.files.to_objc());
 634                    panel.setAllowsMultipleSelection_(options.multiple.to_objc());
 635                    panel.setCanCreateDirectories(true.to_objc());
 636                    panel.setResolvesAliases_(false.to_objc());
 637                    let done_tx = Cell::new(Some(done_tx));
 638                    let block = ConcreteBlock::new(move |response: NSModalResponse| {
 639                        let result = if response == NSModalResponse::NSModalResponseOk {
 640                            let mut result = Vec::new();
 641                            let urls = panel.URLs();
 642                            for i in 0..urls.count() {
 643                                let url = urls.objectAtIndex(i);
 644                                if url.isFileURL() == YES {
 645                                    if let Ok(path) = ns_url_to_path(url) {
 646                                        result.push(path)
 647                                    }
 648                                }
 649                            }
 650                            Some(result)
 651                        } else {
 652                            None
 653                        };
 654
 655                        if let Some(done_tx) = done_tx.take() {
 656                            let _ = done_tx.send(Ok(result));
 657                        }
 658                    });
 659                    let block = block.copy();
 660                    let _: () = msg_send![panel, beginWithCompletionHandler: block];
 661                }
 662            })
 663            .detach();
 664        done_rx
 665    }
 666
 667    fn prompt_for_new_path(&self, directory: &Path) -> oneshot::Receiver<Result<Option<PathBuf>>> {
 668        let directory = directory.to_owned();
 669        let (done_tx, done_rx) = oneshot::channel();
 670        self.foreground_executor()
 671            .spawn(async move {
 672                unsafe {
 673                    let panel = NSSavePanel::savePanel(nil);
 674                    let path = ns_string(directory.to_string_lossy().as_ref());
 675                    let url = NSURL::fileURLWithPath_isDirectory_(nil, path, true.to_objc());
 676                    panel.setDirectoryURL(url);
 677
 678                    let done_tx = Cell::new(Some(done_tx));
 679                    let block = ConcreteBlock::new(move |response: NSModalResponse| {
 680                        let mut result = None;
 681                        if response == NSModalResponse::NSModalResponseOk {
 682                            let url = panel.URL();
 683                            if url.isFileURL() == YES {
 684                                result = ns_url_to_path(panel.URL()).ok()
 685                            }
 686                        }
 687
 688                        if let Some(done_tx) = done_tx.take() {
 689                            let _ = done_tx.send(Ok(result));
 690                        }
 691                    });
 692                    let block = block.copy();
 693                    let _: () = msg_send![panel, beginWithCompletionHandler: block];
 694                }
 695            })
 696            .detach();
 697
 698        done_rx
 699    }
 700
 701    fn reveal_path(&self, path: &Path) {
 702        unsafe {
 703            let path = path.to_path_buf();
 704            self.0
 705                .lock()
 706                .background_executor
 707                .spawn(async move {
 708                    let full_path = ns_string(path.to_str().unwrap_or(""));
 709                    let root_full_path = ns_string("");
 710                    let workspace: id = msg_send![class!(NSWorkspace), sharedWorkspace];
 711                    let _: BOOL = msg_send![
 712                        workspace,
 713                        selectFile: full_path
 714                        inFileViewerRootedAtPath: root_full_path
 715                    ];
 716                })
 717                .detach();
 718        }
 719    }
 720
 721    fn open_with_system(&self, path: &Path) {
 722        let path = path.to_path_buf();
 723        self.0
 724            .lock()
 725            .background_executor
 726            .spawn(async move {
 727                std::process::Command::new("open")
 728                    .arg(path)
 729                    .spawn()
 730                    .expect("Failed to open file");
 731            })
 732            .detach();
 733    }
 734
 735    fn on_quit(&self, callback: Box<dyn FnMut()>) {
 736        self.0.lock().quit = Some(callback);
 737    }
 738
 739    fn on_reopen(&self, callback: Box<dyn FnMut()>) {
 740        self.0.lock().reopen = Some(callback);
 741    }
 742
 743    fn on_app_menu_action(&self, callback: Box<dyn FnMut(&dyn Action)>) {
 744        self.0.lock().menu_command = Some(callback);
 745    }
 746
 747    fn on_will_open_app_menu(&self, callback: Box<dyn FnMut()>) {
 748        self.0.lock().will_open_menu = Some(callback);
 749    }
 750
 751    fn on_validate_app_menu_command(&self, callback: Box<dyn FnMut(&dyn Action) -> bool>) {
 752        self.0.lock().validate_menu_command = Some(callback);
 753    }
 754
 755    fn app_path(&self) -> Result<PathBuf> {
 756        unsafe {
 757            let bundle: id = NSBundle::mainBundle();
 758            if bundle.is_null() {
 759                Err(anyhow!("app is not running inside a bundle"))
 760            } else {
 761                Ok(path_from_objc(msg_send![bundle, bundlePath]))
 762            }
 763        }
 764    }
 765
 766    fn set_menus(&self, menus: Vec<Menu>, keymap: &Keymap) {
 767        unsafe {
 768            let app: id = msg_send![APP_CLASS, sharedApplication];
 769            let mut state = self.0.lock();
 770            let actions = &mut state.menu_actions;
 771            app.setMainMenu_(self.create_menu_bar(menus, NSWindow::delegate(app), actions, keymap));
 772        }
 773    }
 774
 775    fn set_dock_menu(&self, menu: Vec<MenuItem>, keymap: &Keymap) {
 776        unsafe {
 777            let app: id = msg_send![APP_CLASS, sharedApplication];
 778            let mut state = self.0.lock();
 779            let actions = &mut state.menu_actions;
 780            let new = self.create_dock_menu(menu, NSWindow::delegate(app), actions, keymap);
 781            if let Some(old) = state.dock_menu.replace(new) {
 782                CFRelease(old as _)
 783            }
 784        }
 785    }
 786
 787    fn add_recent_document(&self, path: &Path) {
 788        if let Some(path_str) = path.to_str() {
 789            unsafe {
 790                let document_controller: id =
 791                    msg_send![class!(NSDocumentController), sharedDocumentController];
 792                let url: id = NSURL::fileURLWithPath_(nil, ns_string(path_str));
 793                let _: () = msg_send![document_controller, noteNewRecentDocumentURL:url];
 794            }
 795        }
 796    }
 797
 798    fn path_for_auxiliary_executable(&self, name: &str) -> Result<PathBuf> {
 799        unsafe {
 800            let bundle: id = NSBundle::mainBundle();
 801            if bundle.is_null() {
 802                Err(anyhow!("app is not running inside a bundle"))
 803            } else {
 804                let name = ns_string(name);
 805                let url: id = msg_send![bundle, URLForAuxiliaryExecutable: name];
 806                if url.is_null() {
 807                    Err(anyhow!("resource not found"))
 808                } else {
 809                    ns_url_to_path(url)
 810                }
 811            }
 812        }
 813    }
 814
 815    /// Match cursor style to one of the styles available
 816    /// in macOS's [NSCursor](https://developer.apple.com/documentation/appkit/nscursor).
 817    fn set_cursor_style(&self, style: CursorStyle) {
 818        unsafe {
 819            let new_cursor: id = match style {
 820                CursorStyle::Arrow => msg_send![class!(NSCursor), arrowCursor],
 821                CursorStyle::IBeam => msg_send![class!(NSCursor), IBeamCursor],
 822                CursorStyle::Crosshair => msg_send![class!(NSCursor), crosshairCursor],
 823                CursorStyle::ClosedHand => msg_send![class!(NSCursor), closedHandCursor],
 824                CursorStyle::OpenHand => msg_send![class!(NSCursor), openHandCursor],
 825                CursorStyle::PointingHand => msg_send![class!(NSCursor), pointingHandCursor],
 826                CursorStyle::ResizeLeftRight => msg_send![class!(NSCursor), resizeLeftRightCursor],
 827                CursorStyle::ResizeUpDown => msg_send![class!(NSCursor), resizeUpDownCursor],
 828                CursorStyle::ResizeLeft => msg_send![class!(NSCursor), resizeLeftCursor],
 829                CursorStyle::ResizeRight => msg_send![class!(NSCursor), resizeRightCursor],
 830                CursorStyle::ResizeColumn => msg_send![class!(NSCursor), resizeLeftRightCursor],
 831                CursorStyle::ResizeRow => msg_send![class!(NSCursor), resizeUpDownCursor],
 832                CursorStyle::ResizeUp => msg_send![class!(NSCursor), resizeUpCursor],
 833                CursorStyle::ResizeDown => msg_send![class!(NSCursor), resizeDownCursor],
 834
 835                // Undocumented, private class methods:
 836                // https://stackoverflow.com/questions/27242353/cocoa-predefined-resize-mouse-cursor
 837                CursorStyle::ResizeUpLeftDownRight => {
 838                    msg_send![class!(NSCursor), _windowResizeNorthWestSouthEastCursor]
 839                }
 840                CursorStyle::ResizeUpRightDownLeft => {
 841                    msg_send![class!(NSCursor), _windowResizeNorthEastSouthWestCursor]
 842                }
 843
 844                CursorStyle::IBeamCursorForVerticalLayout => {
 845                    msg_send![class!(NSCursor), IBeamCursorForVerticalLayout]
 846                }
 847                CursorStyle::OperationNotAllowed => {
 848                    msg_send![class!(NSCursor), operationNotAllowedCursor]
 849                }
 850                CursorStyle::DragLink => msg_send![class!(NSCursor), dragLinkCursor],
 851                CursorStyle::DragCopy => msg_send![class!(NSCursor), dragCopyCursor],
 852                CursorStyle::ContextualMenu => msg_send![class!(NSCursor), contextualMenuCursor],
 853            };
 854
 855            let old_cursor: id = msg_send![class!(NSCursor), currentCursor];
 856            if new_cursor != old_cursor {
 857                let _: () = msg_send![new_cursor, set];
 858            }
 859        }
 860    }
 861
 862    fn should_auto_hide_scrollbars(&self) -> bool {
 863        #[allow(non_upper_case_globals)]
 864        const NSScrollerStyleOverlay: NSInteger = 1;
 865
 866        unsafe {
 867            let style: NSInteger = msg_send![class!(NSScroller), preferredScrollerStyle];
 868            style == NSScrollerStyleOverlay
 869        }
 870    }
 871
 872    fn write_to_clipboard(&self, item: ClipboardItem) {
 873        use crate::ClipboardEntry;
 874
 875        unsafe {
 876            // We only want to use NSAttributedString if there are multiple entries to write.
 877            if item.entries.len() <= 1 {
 878                match item.entries.first() {
 879                    Some(entry) => match entry {
 880                        ClipboardEntry::String(string) => {
 881                            self.write_plaintext_to_clipboard(string);
 882                        }
 883                        ClipboardEntry::Image(image) => {
 884                            self.write_image_to_clipboard(image);
 885                        }
 886                    },
 887                    None => {
 888                        // Writing an empty list of entries just clears the clipboard.
 889                        let state = self.0.lock();
 890                        state.pasteboard.clearContents();
 891                    }
 892                }
 893            } else {
 894                let mut any_images = false;
 895                let attributed_string = {
 896                    let mut buf = NSMutableAttributedString::alloc(nil)
 897                        // TODO can we skip this? Or at least part of it?
 898                        .init_attributed_string(NSString::alloc(nil).init_str(""));
 899
 900                    for entry in item.entries {
 901                        if let ClipboardEntry::String(ClipboardString { text, metadata: _ }) = entry
 902                        {
 903                            let to_append = NSAttributedString::alloc(nil)
 904                                .init_attributed_string(NSString::alloc(nil).init_str(&text));
 905
 906                            buf.appendAttributedString_(to_append);
 907                        }
 908                    }
 909
 910                    buf
 911                };
 912
 913                let state = self.0.lock();
 914                state.pasteboard.clearContents();
 915
 916                // Only set rich text clipboard types if we actually have 1+ images to include.
 917                if any_images {
 918                    let rtfd_data = attributed_string.RTFDFromRange_documentAttributes_(
 919                        NSRange::new(0, msg_send![attributed_string, length]),
 920                        nil,
 921                    );
 922                    if rtfd_data != nil {
 923                        state
 924                            .pasteboard
 925                            .setData_forType(rtfd_data, NSPasteboardTypeRTFD);
 926                    }
 927
 928                    let rtf_data = attributed_string.RTFFromRange_documentAttributes_(
 929                        NSRange::new(0, attributed_string.length()),
 930                        nil,
 931                    );
 932                    if rtf_data != nil {
 933                        state
 934                            .pasteboard
 935                            .setData_forType(rtf_data, NSPasteboardTypeRTF);
 936                    }
 937                }
 938
 939                let plain_text = attributed_string.string();
 940                state
 941                    .pasteboard
 942                    .setString_forType(plain_text, NSPasteboardTypeString);
 943            }
 944        }
 945    }
 946
 947    fn read_from_clipboard(&self) -> Option<ClipboardItem> {
 948        let state = self.0.lock();
 949        let pasteboard = state.pasteboard;
 950
 951        // First, see if it's a string.
 952        unsafe {
 953            let types: id = pasteboard.types();
 954            let string_type: id = ns_string("public.utf8-plain-text");
 955
 956            if msg_send![types, containsObject: string_type] {
 957                let data = pasteboard.dataForType(string_type);
 958                if data == nil {
 959                    return None;
 960                } else if data.bytes().is_null() {
 961                    // https://developer.apple.com/documentation/foundation/nsdata/1410616-bytes?language=objc
 962                    // "If the length of the NSData object is 0, this property returns nil."
 963                    return Some(self.read_string_from_clipboard(&state, &[]));
 964                } else {
 965                    let bytes =
 966                        slice::from_raw_parts(data.bytes() as *mut u8, data.length() as usize);
 967
 968                    return Some(self.read_string_from_clipboard(&state, bytes));
 969                }
 970            }
 971
 972            // If it wasn't a string, try the various supported image types.
 973            for format in ImageFormat::iter() {
 974                if let Some(item) = try_clipboard_image(pasteboard, format) {
 975                    return Some(item);
 976                }
 977            }
 978        }
 979
 980        // If it wasn't a string or a supported image type, give up.
 981        None
 982    }
 983
 984    fn write_credentials(&self, url: &str, username: &str, password: &[u8]) -> Task<Result<()>> {
 985        let url = url.to_string();
 986        let username = username.to_string();
 987        let password = password.to_vec();
 988        self.background_executor().spawn(async move {
 989            unsafe {
 990                use security::*;
 991
 992                let url = CFString::from(url.as_str());
 993                let username = CFString::from(username.as_str());
 994                let password = CFData::from_buffer(&password);
 995
 996                // First, check if there are already credentials for the given server. If so, then
 997                // update the username and password.
 998                let mut verb = "updating";
 999                let mut query_attrs = CFMutableDictionary::with_capacity(2);
1000                query_attrs.set(kSecClass as *const _, kSecClassInternetPassword as *const _);
1001                query_attrs.set(kSecAttrServer as *const _, url.as_CFTypeRef());
1002
1003                let mut attrs = CFMutableDictionary::with_capacity(4);
1004                attrs.set(kSecClass as *const _, kSecClassInternetPassword as *const _);
1005                attrs.set(kSecAttrServer as *const _, url.as_CFTypeRef());
1006                attrs.set(kSecAttrAccount as *const _, username.as_CFTypeRef());
1007                attrs.set(kSecValueData as *const _, password.as_CFTypeRef());
1008
1009                let mut status = SecItemUpdate(
1010                    query_attrs.as_concrete_TypeRef(),
1011                    attrs.as_concrete_TypeRef(),
1012                );
1013
1014                // If there were no existing credentials for the given server, then create them.
1015                if status == errSecItemNotFound {
1016                    verb = "creating";
1017                    status = SecItemAdd(attrs.as_concrete_TypeRef(), ptr::null_mut());
1018                }
1019
1020                if status != errSecSuccess {
1021                    return Err(anyhow!("{} password failed: {}", verb, status));
1022                }
1023            }
1024            Ok(())
1025        })
1026    }
1027
1028    fn read_credentials(&self, url: &str) -> Task<Result<Option<(String, Vec<u8>)>>> {
1029        let url = url.to_string();
1030        self.background_executor().spawn(async move {
1031            let url = CFString::from(url.as_str());
1032            let cf_true = CFBoolean::true_value().as_CFTypeRef();
1033
1034            unsafe {
1035                use security::*;
1036
1037                // Find any credentials for the given server URL.
1038                let mut attrs = CFMutableDictionary::with_capacity(5);
1039                attrs.set(kSecClass as *const _, kSecClassInternetPassword as *const _);
1040                attrs.set(kSecAttrServer as *const _, url.as_CFTypeRef());
1041                attrs.set(kSecReturnAttributes as *const _, cf_true);
1042                attrs.set(kSecReturnData as *const _, cf_true);
1043
1044                let mut result = CFTypeRef::from(ptr::null());
1045                let status = SecItemCopyMatching(attrs.as_concrete_TypeRef(), &mut result);
1046                match status {
1047                    security::errSecSuccess => {}
1048                    security::errSecItemNotFound | security::errSecUserCanceled => return Ok(None),
1049                    _ => return Err(anyhow!("reading password failed: {}", status)),
1050                }
1051
1052                let result = CFType::wrap_under_create_rule(result)
1053                    .downcast::<CFDictionary>()
1054                    .ok_or_else(|| anyhow!("keychain item was not a dictionary"))?;
1055                let username = result
1056                    .find(kSecAttrAccount as *const _)
1057                    .ok_or_else(|| anyhow!("account was missing from keychain item"))?;
1058                let username = CFType::wrap_under_get_rule(*username)
1059                    .downcast::<CFString>()
1060                    .ok_or_else(|| anyhow!("account was not a string"))?;
1061                let password = result
1062                    .find(kSecValueData as *const _)
1063                    .ok_or_else(|| anyhow!("password was missing from keychain item"))?;
1064                let password = CFType::wrap_under_get_rule(*password)
1065                    .downcast::<CFData>()
1066                    .ok_or_else(|| anyhow!("password was not a string"))?;
1067
1068                Ok(Some((username.to_string(), password.bytes().to_vec())))
1069            }
1070        })
1071    }
1072
1073    fn delete_credentials(&self, url: &str) -> Task<Result<()>> {
1074        let url = url.to_string();
1075
1076        self.background_executor().spawn(async move {
1077            unsafe {
1078                use security::*;
1079
1080                let url = CFString::from(url.as_str());
1081                let mut query_attrs = CFMutableDictionary::with_capacity(2);
1082                query_attrs.set(kSecClass as *const _, kSecClassInternetPassword as *const _);
1083                query_attrs.set(kSecAttrServer as *const _, url.as_CFTypeRef());
1084
1085                let status = SecItemDelete(query_attrs.as_concrete_TypeRef());
1086
1087                if status != errSecSuccess {
1088                    return Err(anyhow!("delete password failed: {}", status));
1089                }
1090            }
1091            Ok(())
1092        })
1093    }
1094}
1095
1096impl MacPlatform {
1097    unsafe fn read_string_from_clipboard(
1098        &self,
1099        state: &MacPlatformState,
1100        text_bytes: &[u8],
1101    ) -> ClipboardItem {
1102        let text = String::from_utf8_lossy(text_bytes).to_string();
1103        let metadata = self
1104            .read_from_pasteboard(state.pasteboard, state.text_hash_pasteboard_type)
1105            .and_then(|hash_bytes| {
1106                let hash_bytes = hash_bytes.try_into().ok()?;
1107                let hash = u64::from_be_bytes(hash_bytes);
1108                let metadata =
1109                    self.read_from_pasteboard(state.pasteboard, state.metadata_pasteboard_type)?;
1110
1111                if hash == ClipboardString::text_hash(&text) {
1112                    String::from_utf8(metadata.to_vec()).ok()
1113                } else {
1114                    None
1115                }
1116            });
1117
1118        ClipboardItem {
1119            entries: vec![ClipboardEntry::String(ClipboardString { text, metadata })],
1120        }
1121    }
1122
1123    unsafe fn write_plaintext_to_clipboard(&self, string: &ClipboardString) {
1124        let state = self.0.lock();
1125        state.pasteboard.clearContents();
1126
1127        let text_bytes = NSData::dataWithBytes_length_(
1128            nil,
1129            string.text.as_ptr() as *const c_void,
1130            string.text.len() as u64,
1131        );
1132        state
1133            .pasteboard
1134            .setData_forType(text_bytes, NSPasteboardTypeString);
1135
1136        if let Some(metadata) = string.metadata.as_ref() {
1137            let hash_bytes = ClipboardString::text_hash(&string.text).to_be_bytes();
1138            let hash_bytes = NSData::dataWithBytes_length_(
1139                nil,
1140                hash_bytes.as_ptr() as *const c_void,
1141                hash_bytes.len() as u64,
1142            );
1143            state
1144                .pasteboard
1145                .setData_forType(hash_bytes, state.text_hash_pasteboard_type);
1146
1147            let metadata_bytes = NSData::dataWithBytes_length_(
1148                nil,
1149                metadata.as_ptr() as *const c_void,
1150                metadata.len() as u64,
1151            );
1152            state
1153                .pasteboard
1154                .setData_forType(metadata_bytes, state.metadata_pasteboard_type);
1155        }
1156    }
1157
1158    unsafe fn write_image_to_clipboard(&self, image: &Image) {
1159        let state = self.0.lock();
1160        state.pasteboard.clearContents();
1161
1162        let bytes = NSData::dataWithBytes_length_(
1163            nil,
1164            image.bytes.as_ptr() as *const c_void,
1165            image.bytes.len() as u64,
1166        );
1167
1168        state
1169            .pasteboard
1170            .setData_forType(bytes, Into::<UTType>::into(image.format).inner_mut());
1171    }
1172}
1173
1174fn try_clipboard_image(pasteboard: id, format: ImageFormat) -> Option<ClipboardItem> {
1175    let mut ut_type: UTType = format.into();
1176
1177    unsafe {
1178        let types: id = pasteboard.types();
1179        if msg_send![types, containsObject: ut_type.inner()] {
1180            let data = pasteboard.dataForType(ut_type.inner_mut());
1181            if data == nil {
1182                None
1183            } else {
1184                let bytes = Vec::from(slice::from_raw_parts(
1185                    data.bytes() as *mut u8,
1186                    data.length() as usize,
1187                ));
1188                let id = hash(&bytes);
1189
1190                Some(ClipboardItem {
1191                    entries: vec![ClipboardEntry::Image(Image { format, bytes, id })],
1192                })
1193            }
1194        } else {
1195            None
1196        }
1197    }
1198}
1199
1200unsafe fn path_from_objc(path: id) -> PathBuf {
1201    let len = msg_send![path, lengthOfBytesUsingEncoding: NSUTF8StringEncoding];
1202    let bytes = path.UTF8String() as *const u8;
1203    let path = str::from_utf8(slice::from_raw_parts(bytes, len)).unwrap();
1204    PathBuf::from(path)
1205}
1206
1207unsafe fn get_mac_platform(object: &mut Object) -> &MacPlatform {
1208    let platform_ptr: *mut c_void = *object.get_ivar(MAC_PLATFORM_IVAR);
1209    assert!(!platform_ptr.is_null());
1210    &*(platform_ptr as *const MacPlatform)
1211}
1212
1213extern "C" fn did_finish_launching(this: &mut Object, _: Sel, _: id) {
1214    unsafe {
1215        let app: id = msg_send![APP_CLASS, sharedApplication];
1216        app.setActivationPolicy_(NSApplicationActivationPolicyRegular);
1217        let platform = get_mac_platform(this);
1218        let callback = platform.0.lock().finish_launching.take();
1219        if let Some(callback) = callback {
1220            callback();
1221        }
1222    }
1223}
1224
1225extern "C" fn should_handle_reopen(this: &mut Object, _: Sel, _: id, has_open_windows: bool) {
1226    if !has_open_windows {
1227        let platform = unsafe { get_mac_platform(this) };
1228        let mut lock = platform.0.lock();
1229        if let Some(mut callback) = lock.reopen.take() {
1230            drop(lock);
1231            callback();
1232            platform.0.lock().reopen.get_or_insert(callback);
1233        }
1234    }
1235}
1236
1237extern "C" fn will_terminate(this: &mut Object, _: Sel, _: id) {
1238    let platform = unsafe { get_mac_platform(this) };
1239    let mut lock = platform.0.lock();
1240    if let Some(mut callback) = lock.quit.take() {
1241        drop(lock);
1242        callback();
1243        platform.0.lock().quit.get_or_insert(callback);
1244    }
1245}
1246
1247extern "C" fn open_urls(this: &mut Object, _: Sel, _: id, urls: id) {
1248    let urls = unsafe {
1249        (0..urls.count())
1250            .filter_map(|i| {
1251                let url = urls.objectAtIndex(i);
1252                match CStr::from_ptr(url.absoluteString().UTF8String() as *mut c_char).to_str() {
1253                    Ok(string) => Some(string.to_string()),
1254                    Err(err) => {
1255                        log::error!("error converting path to string: {}", err);
1256                        None
1257                    }
1258                }
1259            })
1260            .collect::<Vec<_>>()
1261    };
1262    let platform = unsafe { get_mac_platform(this) };
1263    let mut lock = platform.0.lock();
1264    if let Some(mut callback) = lock.open_urls.take() {
1265        drop(lock);
1266        callback(urls);
1267        platform.0.lock().open_urls.get_or_insert(callback);
1268    }
1269}
1270
1271extern "C" fn handle_menu_item(this: &mut Object, _: Sel, item: id) {
1272    unsafe {
1273        let platform = get_mac_platform(this);
1274        let mut lock = platform.0.lock();
1275        if let Some(mut callback) = lock.menu_command.take() {
1276            let tag: NSInteger = msg_send![item, tag];
1277            let index = tag as usize;
1278            if let Some(action) = lock.menu_actions.get(index) {
1279                let action = action.boxed_clone();
1280                drop(lock);
1281                callback(&*action);
1282            }
1283            platform.0.lock().menu_command.get_or_insert(callback);
1284        }
1285    }
1286}
1287
1288extern "C" fn validate_menu_item(this: &mut Object, _: Sel, item: id) -> bool {
1289    unsafe {
1290        let mut result = false;
1291        let platform = get_mac_platform(this);
1292        let mut lock = platform.0.lock();
1293        if let Some(mut callback) = lock.validate_menu_command.take() {
1294            let tag: NSInteger = msg_send![item, tag];
1295            let index = tag as usize;
1296            if let Some(action) = lock.menu_actions.get(index) {
1297                let action = action.boxed_clone();
1298                drop(lock);
1299                result = callback(action.as_ref());
1300            }
1301            platform
1302                .0
1303                .lock()
1304                .validate_menu_command
1305                .get_or_insert(callback);
1306        }
1307        result
1308    }
1309}
1310
1311extern "C" fn menu_will_open(this: &mut Object, _: Sel, _: id) {
1312    unsafe {
1313        let platform = get_mac_platform(this);
1314        let mut lock = platform.0.lock();
1315        if let Some(mut callback) = lock.will_open_menu.take() {
1316            drop(lock);
1317            callback();
1318            platform.0.lock().will_open_menu.get_or_insert(callback);
1319        }
1320    }
1321}
1322
1323extern "C" fn handle_dock_menu(this: &mut Object, _: Sel, _: id) -> id {
1324    unsafe {
1325        let platform = get_mac_platform(this);
1326        let mut state = platform.0.lock();
1327        if let Some(id) = state.dock_menu {
1328            id
1329        } else {
1330            nil
1331        }
1332    }
1333}
1334
1335unsafe fn ns_string(string: &str) -> id {
1336    NSString::alloc(nil).init_str(string).autorelease()
1337}
1338
1339unsafe fn ns_url_to_path(url: id) -> Result<PathBuf> {
1340    let path: *mut c_char = msg_send![url, fileSystemRepresentation];
1341    if path.is_null() {
1342        Err(anyhow!(
1343            "url is not a file path: {}",
1344            CStr::from_ptr(url.absoluteString().UTF8String()).to_string_lossy()
1345        ))
1346    } else {
1347        Ok(PathBuf::from(OsStr::from_bytes(
1348            CStr::from_ptr(path).to_bytes(),
1349        )))
1350    }
1351}
1352
1353mod security {
1354    #![allow(non_upper_case_globals)]
1355    use super::*;
1356
1357    #[link(name = "Security", kind = "framework")]
1358    extern "C" {
1359        pub static kSecClass: CFStringRef;
1360        pub static kSecClassInternetPassword: CFStringRef;
1361        pub static kSecAttrServer: CFStringRef;
1362        pub static kSecAttrAccount: CFStringRef;
1363        pub static kSecValueData: CFStringRef;
1364        pub static kSecReturnAttributes: CFStringRef;
1365        pub static kSecReturnData: CFStringRef;
1366
1367        pub fn SecItemAdd(attributes: CFDictionaryRef, result: *mut CFTypeRef) -> OSStatus;
1368        pub fn SecItemUpdate(query: CFDictionaryRef, attributes: CFDictionaryRef) -> OSStatus;
1369        pub fn SecItemDelete(query: CFDictionaryRef) -> OSStatus;
1370        pub fn SecItemCopyMatching(query: CFDictionaryRef, result: *mut CFTypeRef) -> OSStatus;
1371    }
1372
1373    pub const errSecSuccess: OSStatus = 0;
1374    pub const errSecUserCanceled: OSStatus = -128;
1375    pub const errSecItemNotFound: OSStatus = -25300;
1376}
1377
1378impl From<ImageFormat> for UTType {
1379    fn from(value: ImageFormat) -> Self {
1380        match value {
1381            ImageFormat::Png => Self::png(),
1382            ImageFormat::Jpeg => Self::jpeg(),
1383            ImageFormat::Tiff => Self::tiff(),
1384            ImageFormat::Webp => Self::webp(),
1385            ImageFormat::Gif => Self::gif(),
1386            ImageFormat::Bmp => Self::bmp(),
1387            ImageFormat::Svg => Self::svg(),
1388        }
1389    }
1390}
1391
1392// See https://developer.apple.com/documentation/uniformtypeidentifiers/uttype-swift.struct/
1393struct UTType(id);
1394
1395impl UTType {
1396    pub fn png() -> Self {
1397        // https://developer.apple.com/documentation/uniformtypeidentifiers/uttype-swift.struct/png
1398        Self(unsafe { NSPasteboardTypePNG }) // This is a rare case where there's a built-in NSPasteboardType
1399    }
1400
1401    pub fn jpeg() -> Self {
1402        // https://developer.apple.com/documentation/uniformtypeidentifiers/uttype-swift.struct/jpeg
1403        Self(unsafe { ns_string("public.jpeg") })
1404    }
1405
1406    pub fn gif() -> Self {
1407        // https://developer.apple.com/documentation/uniformtypeidentifiers/uttype-swift.struct/gif
1408        Self(unsafe { ns_string("com.compuserve.gif") })
1409    }
1410
1411    pub fn webp() -> Self {
1412        // https://developer.apple.com/documentation/uniformtypeidentifiers/uttype-swift.struct/webp
1413        Self(unsafe { ns_string("org.webmproject.webp") })
1414    }
1415
1416    pub fn bmp() -> Self {
1417        // https://developer.apple.com/documentation/uniformtypeidentifiers/uttype-swift.struct/bmp
1418        Self(unsafe { ns_string("com.microsoft.bmp") })
1419    }
1420
1421    pub fn svg() -> Self {
1422        // https://developer.apple.com/documentation/uniformtypeidentifiers/uttype-swift.struct/svg
1423        Self(unsafe { ns_string("public.svg-image") })
1424    }
1425
1426    pub fn tiff() -> Self {
1427        // https://developer.apple.com/documentation/uniformtypeidentifiers/uttype-swift.struct/tiff
1428        Self(unsafe { NSPasteboardTypeTIFF }) // This is a rare case where there's a built-in NSPasteboardType
1429    }
1430
1431    fn inner(&self) -> *const Object {
1432        self.0
1433    }
1434
1435    fn inner_mut(&self) -> *mut Object {
1436        self.0 as *mut _
1437    }
1438}
1439
1440#[cfg(test)]
1441mod tests {
1442    use crate::ClipboardItem;
1443
1444    use super::*;
1445
1446    #[test]
1447    fn test_clipboard() {
1448        let platform = build_platform();
1449        assert_eq!(platform.read_from_clipboard(), None);
1450
1451        let item = ClipboardItem::new_string("1".to_string());
1452        platform.write_to_clipboard(item.clone());
1453        assert_eq!(platform.read_from_clipboard(), Some(item));
1454
1455        let item = ClipboardItem {
1456            entries: vec![ClipboardEntry::String(
1457                ClipboardString::new("2".to_string()).with_json_metadata(vec![3, 4]),
1458            )],
1459        };
1460        platform.write_to_clipboard(item.clone());
1461        assert_eq!(platform.read_from_clipboard(), Some(item));
1462
1463        let text_from_other_app = "text from other app";
1464        unsafe {
1465            let bytes = NSData::dataWithBytes_length_(
1466                nil,
1467                text_from_other_app.as_ptr() as *const c_void,
1468                text_from_other_app.len() as u64,
1469            );
1470            platform
1471                .0
1472                .lock()
1473                .pasteboard
1474                .setData_forType(bytes, NSPasteboardTypeString);
1475        }
1476        assert_eq!(
1477            platform.read_from_clipboard(),
1478            Some(ClipboardItem::new_string(text_from_other_app.to_string()))
1479        );
1480    }
1481
1482    fn build_platform() -> MacPlatform {
1483        let platform = MacPlatform::new(false);
1484        platform.0.lock().pasteboard = unsafe { NSPasteboard::pasteboardWithUniqueName(nil) };
1485        platform
1486    }
1487}