platform.rs

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