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