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