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