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    unsafe {
  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    unsafe {
  79        APP_DELEGATE_CLASS = unsafe {
  80            let mut decl = ClassDecl::new("GPUIApplicationDelegate", class!(NSResponder)).unwrap();
  81            decl.add_ivar::<*mut c_void>(MAC_PLATFORM_IVAR);
  82            decl.add_method(
  83                sel!(applicationDidFinishLaunching:),
  84                did_finish_launching as extern "C" fn(&mut Object, Sel, id),
  85            );
  86            decl.add_method(
  87                sel!(applicationShouldHandleReopen:hasVisibleWindows:),
  88                should_handle_reopen as extern "C" fn(&mut Object, Sel, id, bool),
  89            );
  90            decl.add_method(
  91                sel!(applicationWillTerminate:),
  92                will_terminate as extern "C" fn(&mut Object, Sel, id),
  93            );
  94            decl.add_method(
  95                sel!(handleGPUIMenuItem:),
  96                handle_menu_item as extern "C" fn(&mut Object, Sel, id),
  97            );
  98            // Add menu item handlers so that OS save panels have the correct key commands
  99            decl.add_method(
 100                sel!(cut:),
 101                handle_menu_item as extern "C" fn(&mut Object, Sel, id),
 102            );
 103            decl.add_method(
 104                sel!(copy:),
 105                handle_menu_item as extern "C" fn(&mut Object, Sel, id),
 106            );
 107            decl.add_method(
 108                sel!(paste:),
 109                handle_menu_item as extern "C" fn(&mut Object, Sel, id),
 110            );
 111            decl.add_method(
 112                sel!(selectAll:),
 113                handle_menu_item as extern "C" fn(&mut Object, Sel, id),
 114            );
 115            decl.add_method(
 116                sel!(undo:),
 117                handle_menu_item as extern "C" fn(&mut Object, Sel, id),
 118            );
 119            decl.add_method(
 120                sel!(redo:),
 121                handle_menu_item as extern "C" fn(&mut Object, Sel, id),
 122            );
 123            decl.add_method(
 124                sel!(validateMenuItem:),
 125                validate_menu_item as extern "C" fn(&mut Object, Sel, id) -> bool,
 126            );
 127            decl.add_method(
 128                sel!(menuWillOpen:),
 129                menu_will_open as extern "C" fn(&mut Object, Sel, id),
 130            );
 131            decl.add_method(
 132                sel!(applicationDockMenu:),
 133                handle_dock_menu as extern "C" fn(&mut Object, Sel, id) -> id,
 134            );
 135            decl.add_method(
 136                sel!(application:openURLs:),
 137                open_urls as extern "C" fn(&mut Object, Sel, id, id),
 138            );
 139
 140            decl.add_method(
 141                sel!(onKeyboardLayoutChange:),
 142                on_keyboard_layout_change as extern "C" fn(&mut Object, Sel, id),
 143            );
 144
 145            decl.register()
 146        }
 147    }
 148}
 149
 150pub(crate) struct MacPlatform(Mutex<MacPlatformState>);
 151
 152pub(crate) struct MacPlatformState {
 153    background_executor: BackgroundExecutor,
 154    foreground_executor: ForegroundExecutor,
 155    text_system: Arc<dyn PlatformTextSystem>,
 156    renderer_context: renderer::Context,
 157    headless: bool,
 158    pasteboard: id,
 159    text_hash_pasteboard_type: id,
 160    metadata_pasteboard_type: id,
 161    reopen: Option<Box<dyn FnMut()>>,
 162    on_keyboard_layout_change: Option<Box<dyn FnMut()>>,
 163    quit: Option<Box<dyn FnMut()>>,
 164    menu_command: Option<Box<dyn FnMut(&dyn Action)>>,
 165    validate_menu_command: Option<Box<dyn FnMut(&dyn Action) -> bool>>,
 166    will_open_menu: Option<Box<dyn FnMut()>>,
 167    menu_actions: Vec<Box<dyn Action>>,
 168    open_urls: Option<Box<dyn FnMut(Vec<String>)>>,
 169    finish_launching: Option<Box<dyn FnOnce()>>,
 170    dock_menu: Option<id>,
 171}
 172
 173impl Default for MacPlatform {
 174    fn default() -> Self {
 175        Self::new(false)
 176    }
 177}
 178
 179impl MacPlatform {
 180    pub(crate) fn new(headless: bool) -> Self {
 181        let dispatcher = Arc::new(MacDispatcher::new());
 182
 183        #[cfg(feature = "font-kit")]
 184        let text_system = Arc::new(crate::MacTextSystem::new());
 185
 186        #[cfg(not(feature = "font-kit"))]
 187        let text_system = Arc::new(crate::NoopTextSystem::new());
 188
 189        Self(Mutex::new(MacPlatformState {
 190            headless,
 191            text_system,
 192            background_executor: BackgroundExecutor::new(dispatcher.clone()),
 193            foreground_executor: ForegroundExecutor::new(dispatcher),
 194            renderer_context: renderer::Context::default(),
 195            pasteboard: unsafe { NSPasteboard::generalPasteboard(nil) },
 196            text_hash_pasteboard_type: unsafe { ns_string("zed-text-hash") },
 197            metadata_pasteboard_type: unsafe { ns_string("zed-metadata") },
 198            reopen: None,
 199            quit: None,
 200            menu_command: None,
 201            validate_menu_command: None,
 202            will_open_menu: None,
 203            menu_actions: Default::default(),
 204            open_urls: None,
 205            finish_launching: None,
 206            dock_menu: None,
 207            on_keyboard_layout_change: None,
 208        }))
 209    }
 210
 211    unsafe fn read_from_pasteboard(&self, pasteboard: *mut Object, kind: id) -> Option<&[u8]> {
 212        unsafe {
 213            let data = pasteboard.dataForType(kind);
 214            if data == nil {
 215                None
 216            } else {
 217                Some(slice::from_raw_parts(
 218                    data.bytes() as *mut u8,
 219                    data.length() as usize,
 220                ))
 221            }
 222        }
 223    }
 224
 225    unsafe fn create_menu_bar(
 226        &self,
 227        menus: Vec<Menu>,
 228        delegate: id,
 229        actions: &mut Vec<Box<dyn Action>>,
 230        keymap: &Keymap,
 231    ) -> id {
 232        unsafe {
 233            let application_menu = NSMenu::new(nil).autorelease();
 234            application_menu.setDelegate_(delegate);
 235
 236            for menu_config in menus {
 237                let menu = NSMenu::new(nil).autorelease();
 238                let menu_title = ns_string(&menu_config.name);
 239                menu.setTitle_(menu_title);
 240                menu.setDelegate_(delegate);
 241
 242                for item_config in menu_config.items {
 243                    menu.addItem_(Self::create_menu_item(
 244                        item_config,
 245                        delegate,
 246                        actions,
 247                        keymap,
 248                    ));
 249                }
 250
 251                let menu_item = NSMenuItem::new(nil).autorelease();
 252                menu_item.setTitle_(menu_title);
 253                menu_item.setSubmenu_(menu);
 254                application_menu.addItem_(menu_item);
 255
 256                if menu_config.name == "Window" {
 257                    let app: id = msg_send![APP_CLASS, sharedApplication];
 258                    app.setWindowsMenu_(menu);
 259                }
 260            }
 261
 262            application_menu
 263        }
 264    }
 265
 266    unsafe fn create_dock_menu(
 267        &self,
 268        menu_items: Vec<MenuItem>,
 269        delegate: id,
 270        actions: &mut Vec<Box<dyn Action>>,
 271        keymap: &Keymap,
 272    ) -> id {
 273        unsafe {
 274            let dock_menu = NSMenu::new(nil);
 275            dock_menu.setDelegate_(delegate);
 276            for item_config in menu_items {
 277                dock_menu.addItem_(Self::create_menu_item(
 278                    item_config,
 279                    delegate,
 280                    actions,
 281                    keymap,
 282                ));
 283            }
 284
 285            dock_menu
 286        }
 287    }
 288
 289    unsafe fn create_menu_item(
 290        item: MenuItem,
 291        delegate: id,
 292        actions: &mut Vec<Box<dyn Action>>,
 293        keymap: &Keymap,
 294    ) -> id {
 295        unsafe {
 296            match item {
 297                MenuItem::Separator => NSMenuItem::separatorItem(nil),
 298                MenuItem::Action {
 299                    name,
 300                    action,
 301                    os_action,
 302                } => {
 303                    let keystrokes = crate::Keymap::binding_to_display_from_bindings_iterator(
 304                        keymap.bindings_for_action(action.as_ref()),
 305                    )
 306                    .map(|binding| binding.keystrokes());
 307
 308                    let selector = match os_action {
 309                        Some(crate::OsAction::Cut) => selector("cut:"),
 310                        Some(crate::OsAction::Copy) => selector("copy:"),
 311                        Some(crate::OsAction::Paste) => selector("paste:"),
 312                        Some(crate::OsAction::SelectAll) => selector("selectAll:"),
 313                        // "undo:" and "redo:" are always disabled in our case, as
 314                        // we don't have a NSTextView/NSTextField to enable them on.
 315                        Some(crate::OsAction::Undo) => selector("handleGPUIMenuItem:"),
 316                        Some(crate::OsAction::Redo) => selector("handleGPUIMenuItem:"),
 317                        None => selector("handleGPUIMenuItem:"),
 318                    };
 319
 320                    let item;
 321                    if let Some(keystrokes) = keystrokes {
 322                        if keystrokes.len() == 1 {
 323                            let keystroke = &keystrokes[0];
 324                            let mut mask = NSEventModifierFlags::empty();
 325                            for (modifier, flag) in &[
 326                                (
 327                                    keystroke.modifiers.platform,
 328                                    NSEventModifierFlags::NSCommandKeyMask,
 329                                ),
 330                                (
 331                                    keystroke.modifiers.control,
 332                                    NSEventModifierFlags::NSControlKeyMask,
 333                                ),
 334                                (
 335                                    keystroke.modifiers.alt,
 336                                    NSEventModifierFlags::NSAlternateKeyMask,
 337                                ),
 338                                (
 339                                    keystroke.modifiers.shift,
 340                                    NSEventModifierFlags::NSShiftKeyMask,
 341                                ),
 342                            ] {
 343                                if *modifier {
 344                                    mask |= *flag;
 345                                }
 346                            }
 347
 348                            item = NSMenuItem::alloc(nil)
 349                                .initWithTitle_action_keyEquivalent_(
 350                                    ns_string(&name),
 351                                    selector,
 352                                    ns_string(key_to_native(&keystroke.key).as_ref()),
 353                                )
 354                                .autorelease();
 355                            if MacPlatform::os_version().unwrap() >= SemanticVersion::new(12, 0, 0)
 356                            {
 357                                let _: () = msg_send![item, setAllowsAutomaticKeyEquivalentLocalization: NO];
 358                            }
 359                            item.setKeyEquivalentModifierMask_(mask);
 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                    } else {
 370                        item = NSMenuItem::alloc(nil)
 371                            .initWithTitle_action_keyEquivalent_(
 372                                ns_string(&name),
 373                                selector,
 374                                ns_string(""),
 375                            )
 376                            .autorelease();
 377                    }
 378
 379                    let tag = actions.len() as NSInteger;
 380                    let _: () = msg_send![item, setTag: tag];
 381                    actions.push(action);
 382                    item
 383                }
 384                MenuItem::Submenu(Menu { name, items }) => {
 385                    let item = NSMenuItem::new(nil).autorelease();
 386                    let submenu = NSMenu::new(nil).autorelease();
 387                    submenu.setDelegate_(delegate);
 388                    for item in items {
 389                        submenu.addItem_(Self::create_menu_item(item, delegate, actions, keymap));
 390                    }
 391                    item.setSubmenu_(submenu);
 392                    item.setTitle_(ns_string(&name));
 393                    if name == "Services" {
 394                        let app: id = msg_send![APP_CLASS, sharedApplication];
 395                        app.setServicesMenu_(item);
 396                    }
 397
 398                    item
 399                }
 400            }
 401        }
 402    }
 403
 404    fn os_version() -> Result<SemanticVersion> {
 405        unsafe {
 406            let process_info = NSProcessInfo::processInfo(nil);
 407            let version = process_info.operatingSystemVersion();
 408            Ok(SemanticVersion::new(
 409                version.majorVersion as usize,
 410                version.minorVersion as usize,
 411                version.patchVersion as usize,
 412            ))
 413        }
 414    }
 415}
 416
 417impl Platform for MacPlatform {
 418    fn background_executor(&self) -> BackgroundExecutor {
 419        self.0.lock().background_executor.clone()
 420    }
 421
 422    fn foreground_executor(&self) -> crate::ForegroundExecutor {
 423        self.0.lock().foreground_executor.clone()
 424    }
 425
 426    fn text_system(&self) -> Arc<dyn PlatformTextSystem> {
 427        self.0.lock().text_system.clone()
 428    }
 429
 430    fn run(&self, on_finish_launching: Box<dyn FnOnce()>) {
 431        let mut state = self.0.lock();
 432        if state.headless {
 433            drop(state);
 434            on_finish_launching();
 435            unsafe { CFRunLoopRun() };
 436        } else {
 437            state.finish_launching = Some(on_finish_launching);
 438            drop(state);
 439        }
 440
 441        unsafe {
 442            let app: id = msg_send![APP_CLASS, sharedApplication];
 443            let app_delegate: id = msg_send![APP_DELEGATE_CLASS, new];
 444            app.setDelegate_(app_delegate);
 445
 446            let self_ptr = self as *const Self as *const c_void;
 447            (*app).set_ivar(MAC_PLATFORM_IVAR, self_ptr);
 448            (*app_delegate).set_ivar(MAC_PLATFORM_IVAR, self_ptr);
 449
 450            let pool = NSAutoreleasePool::new(nil);
 451            app.run();
 452            pool.drain();
 453
 454            (*app).set_ivar(MAC_PLATFORM_IVAR, null_mut::<c_void>());
 455            (*NSWindow::delegate(app)).set_ivar(MAC_PLATFORM_IVAR, null_mut::<c_void>());
 456        }
 457    }
 458
 459    fn quit(&self) {
 460        // Quitting the app causes us to close windows, which invokes `Window::on_close` callbacks
 461        // synchronously before this method terminates. If we call `Platform::quit` while holding a
 462        // borrow of the app state (which most of the time we will do), we will end up
 463        // double-borrowing the app state in the `on_close` callbacks for our open windows. To solve
 464        // this, we make quitting the application asynchronous so that we aren't holding borrows to
 465        // the app state on the stack when we actually terminate the app.
 466
 467        use super::dispatcher::{dispatch_get_main_queue, dispatch_sys::dispatch_async_f};
 468
 469        unsafe {
 470            dispatch_async_f(dispatch_get_main_queue(), ptr::null_mut(), Some(quit));
 471        }
 472
 473        unsafe extern "C" fn quit(_: *mut c_void) {
 474            unsafe {
 475                let app = NSApplication::sharedApplication(nil);
 476                let _: () = msg_send![app, terminate: nil];
 477            }
 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            if style == CursorStyle::None {
 908                let _: () = msg_send![class!(NSCursor), setHiddenUntilMouseMoves:YES];
 909                return;
 910            }
 911
 912            let new_cursor: id = match style {
 913                CursorStyle::Arrow => msg_send![class!(NSCursor), arrowCursor],
 914                CursorStyle::IBeam => msg_send![class!(NSCursor), IBeamCursor],
 915                CursorStyle::Crosshair => msg_send![class!(NSCursor), crosshairCursor],
 916                CursorStyle::ClosedHand => msg_send![class!(NSCursor), closedHandCursor],
 917                CursorStyle::OpenHand => msg_send![class!(NSCursor), openHandCursor],
 918                CursorStyle::PointingHand => msg_send![class!(NSCursor), pointingHandCursor],
 919                CursorStyle::ResizeLeftRight => msg_send![class!(NSCursor), resizeLeftRightCursor],
 920                CursorStyle::ResizeUpDown => msg_send![class!(NSCursor), resizeUpDownCursor],
 921                CursorStyle::ResizeLeft => msg_send![class!(NSCursor), resizeLeftCursor],
 922                CursorStyle::ResizeRight => msg_send![class!(NSCursor), resizeRightCursor],
 923                CursorStyle::ResizeColumn => msg_send![class!(NSCursor), resizeLeftRightCursor],
 924                CursorStyle::ResizeRow => msg_send![class!(NSCursor), resizeUpDownCursor],
 925                CursorStyle::ResizeUp => msg_send![class!(NSCursor), resizeUpCursor],
 926                CursorStyle::ResizeDown => msg_send![class!(NSCursor), resizeDownCursor],
 927
 928                // Undocumented, private class methods:
 929                // https://stackoverflow.com/questions/27242353/cocoa-predefined-resize-mouse-cursor
 930                CursorStyle::ResizeUpLeftDownRight => {
 931                    msg_send![class!(NSCursor), _windowResizeNorthWestSouthEastCursor]
 932                }
 933                CursorStyle::ResizeUpRightDownLeft => {
 934                    msg_send![class!(NSCursor), _windowResizeNorthEastSouthWestCursor]
 935                }
 936
 937                CursorStyle::IBeamCursorForVerticalLayout => {
 938                    msg_send![class!(NSCursor), IBeamCursorForVerticalLayout]
 939                }
 940                CursorStyle::OperationNotAllowed => {
 941                    msg_send![class!(NSCursor), operationNotAllowedCursor]
 942                }
 943                CursorStyle::DragLink => msg_send![class!(NSCursor), dragLinkCursor],
 944                CursorStyle::DragCopy => msg_send![class!(NSCursor), dragCopyCursor],
 945                CursorStyle::ContextualMenu => msg_send![class!(NSCursor), contextualMenuCursor],
 946                CursorStyle::None => unreachable!(),
 947            };
 948
 949            let old_cursor: id = msg_send![class!(NSCursor), currentCursor];
 950            if new_cursor != old_cursor {
 951                let _: () = msg_send![new_cursor, set];
 952            }
 953        }
 954    }
 955
 956    fn should_auto_hide_scrollbars(&self) -> bool {
 957        #[allow(non_upper_case_globals)]
 958        const NSScrollerStyleOverlay: NSInteger = 1;
 959
 960        unsafe {
 961            let style: NSInteger = msg_send![class!(NSScroller), preferredScrollerStyle];
 962            style == NSScrollerStyleOverlay
 963        }
 964    }
 965
 966    fn write_to_clipboard(&self, item: ClipboardItem) {
 967        use crate::ClipboardEntry;
 968
 969        unsafe {
 970            // We only want to use NSAttributedString if there are multiple entries to write.
 971            if item.entries.len() <= 1 {
 972                match item.entries.first() {
 973                    Some(entry) => match entry {
 974                        ClipboardEntry::String(string) => {
 975                            self.write_plaintext_to_clipboard(string);
 976                        }
 977                        ClipboardEntry::Image(image) => {
 978                            self.write_image_to_clipboard(image);
 979                        }
 980                    },
 981                    None => {
 982                        // Writing an empty list of entries just clears the clipboard.
 983                        let state = self.0.lock();
 984                        state.pasteboard.clearContents();
 985                    }
 986                }
 987            } else {
 988                let mut any_images = false;
 989                let attributed_string = {
 990                    let mut buf = NSMutableAttributedString::alloc(nil)
 991                        // TODO can we skip this? Or at least part of it?
 992                        .init_attributed_string(NSString::alloc(nil).init_str(""));
 993
 994                    for entry in item.entries {
 995                        if let ClipboardEntry::String(ClipboardString { text, metadata: _ }) = entry
 996                        {
 997                            let to_append = NSAttributedString::alloc(nil)
 998                                .init_attributed_string(NSString::alloc(nil).init_str(&text));
 999
1000                            buf.appendAttributedString_(to_append);
1001                        }
1002                    }
1003
1004                    buf
1005                };
1006
1007                let state = self.0.lock();
1008                state.pasteboard.clearContents();
1009
1010                // Only set rich text clipboard types if we actually have 1+ images to include.
1011                if any_images {
1012                    let rtfd_data = attributed_string.RTFDFromRange_documentAttributes_(
1013                        NSRange::new(0, msg_send![attributed_string, length]),
1014                        nil,
1015                    );
1016                    if rtfd_data != nil {
1017                        state
1018                            .pasteboard
1019                            .setData_forType(rtfd_data, NSPasteboardTypeRTFD);
1020                    }
1021
1022                    let rtf_data = attributed_string.RTFFromRange_documentAttributes_(
1023                        NSRange::new(0, attributed_string.length()),
1024                        nil,
1025                    );
1026                    if rtf_data != nil {
1027                        state
1028                            .pasteboard
1029                            .setData_forType(rtf_data, NSPasteboardTypeRTF);
1030                    }
1031                }
1032
1033                let plain_text = attributed_string.string();
1034                state
1035                    .pasteboard
1036                    .setString_forType(plain_text, NSPasteboardTypeString);
1037            }
1038        }
1039    }
1040
1041    fn read_from_clipboard(&self) -> Option<ClipboardItem> {
1042        let state = self.0.lock();
1043        let pasteboard = state.pasteboard;
1044
1045        // First, see if it's a string.
1046        unsafe {
1047            let types: id = pasteboard.types();
1048            let string_type: id = ns_string("public.utf8-plain-text");
1049
1050            if msg_send![types, containsObject: string_type] {
1051                let data = pasteboard.dataForType(string_type);
1052                if data == nil {
1053                    return None;
1054                } else if data.bytes().is_null() {
1055                    // https://developer.apple.com/documentation/foundation/nsdata/1410616-bytes?language=objc
1056                    // "If the length of the NSData object is 0, this property returns nil."
1057                    return Some(self.read_string_from_clipboard(&state, &[]));
1058                } else {
1059                    let bytes =
1060                        slice::from_raw_parts(data.bytes() as *mut u8, data.length() as usize);
1061
1062                    return Some(self.read_string_from_clipboard(&state, bytes));
1063                }
1064            }
1065
1066            // If it wasn't a string, try the various supported image types.
1067            for format in ImageFormat::iter() {
1068                if let Some(item) = try_clipboard_image(pasteboard, format) {
1069                    return Some(item);
1070                }
1071            }
1072        }
1073
1074        // If it wasn't a string or a supported image type, give up.
1075        None
1076    }
1077
1078    fn write_credentials(&self, url: &str, username: &str, password: &[u8]) -> Task<Result<()>> {
1079        let url = url.to_string();
1080        let username = username.to_string();
1081        let password = password.to_vec();
1082        self.background_executor().spawn(async move {
1083            unsafe {
1084                use security::*;
1085
1086                let url = CFString::from(url.as_str());
1087                let username = CFString::from(username.as_str());
1088                let password = CFData::from_buffer(&password);
1089
1090                // First, check if there are already credentials for the given server. If so, then
1091                // update the username and password.
1092                let mut verb = "updating";
1093                let mut query_attrs = CFMutableDictionary::with_capacity(2);
1094                query_attrs.set(kSecClass as *const _, kSecClassInternetPassword as *const _);
1095                query_attrs.set(kSecAttrServer as *const _, url.as_CFTypeRef());
1096
1097                let mut attrs = CFMutableDictionary::with_capacity(4);
1098                attrs.set(kSecClass as *const _, kSecClassInternetPassword as *const _);
1099                attrs.set(kSecAttrServer as *const _, url.as_CFTypeRef());
1100                attrs.set(kSecAttrAccount as *const _, username.as_CFTypeRef());
1101                attrs.set(kSecValueData as *const _, password.as_CFTypeRef());
1102
1103                let mut status = SecItemUpdate(
1104                    query_attrs.as_concrete_TypeRef(),
1105                    attrs.as_concrete_TypeRef(),
1106                );
1107
1108                // If there were no existing credentials for the given server, then create them.
1109                if status == errSecItemNotFound {
1110                    verb = "creating";
1111                    status = SecItemAdd(attrs.as_concrete_TypeRef(), ptr::null_mut());
1112                }
1113
1114                if status != errSecSuccess {
1115                    return Err(anyhow!("{} password failed: {}", verb, status));
1116                }
1117            }
1118            Ok(())
1119        })
1120    }
1121
1122    fn read_credentials(&self, url: &str) -> Task<Result<Option<(String, Vec<u8>)>>> {
1123        let url = url.to_string();
1124        self.background_executor().spawn(async move {
1125            let url = CFString::from(url.as_str());
1126            let cf_true = CFBoolean::true_value().as_CFTypeRef();
1127
1128            unsafe {
1129                use security::*;
1130
1131                // Find any credentials for the given server URL.
1132                let mut attrs = CFMutableDictionary::with_capacity(5);
1133                attrs.set(kSecClass as *const _, kSecClassInternetPassword as *const _);
1134                attrs.set(kSecAttrServer as *const _, url.as_CFTypeRef());
1135                attrs.set(kSecReturnAttributes as *const _, cf_true);
1136                attrs.set(kSecReturnData as *const _, cf_true);
1137
1138                let mut result = CFTypeRef::from(ptr::null());
1139                let status = SecItemCopyMatching(attrs.as_concrete_TypeRef(), &mut result);
1140                match status {
1141                    security::errSecSuccess => {}
1142                    security::errSecItemNotFound | security::errSecUserCanceled => return Ok(None),
1143                    _ => return Err(anyhow!("reading password failed: {}", status)),
1144                }
1145
1146                let result = CFType::wrap_under_create_rule(result)
1147                    .downcast::<CFDictionary>()
1148                    .ok_or_else(|| anyhow!("keychain item was not a dictionary"))?;
1149                let username = result
1150                    .find(kSecAttrAccount as *const _)
1151                    .ok_or_else(|| anyhow!("account was missing from keychain item"))?;
1152                let username = CFType::wrap_under_get_rule(*username)
1153                    .downcast::<CFString>()
1154                    .ok_or_else(|| anyhow!("account was not a string"))?;
1155                let password = result
1156                    .find(kSecValueData as *const _)
1157                    .ok_or_else(|| anyhow!("password was missing from keychain item"))?;
1158                let password = CFType::wrap_under_get_rule(*password)
1159                    .downcast::<CFData>()
1160                    .ok_or_else(|| anyhow!("password was not a string"))?;
1161
1162                Ok(Some((username.to_string(), password.bytes().to_vec())))
1163            }
1164        })
1165    }
1166
1167    fn delete_credentials(&self, url: &str) -> Task<Result<()>> {
1168        let url = url.to_string();
1169
1170        self.background_executor().spawn(async move {
1171            unsafe {
1172                use security::*;
1173
1174                let url = CFString::from(url.as_str());
1175                let mut query_attrs = CFMutableDictionary::with_capacity(2);
1176                query_attrs.set(kSecClass as *const _, kSecClassInternetPassword as *const _);
1177                query_attrs.set(kSecAttrServer as *const _, url.as_CFTypeRef());
1178
1179                let status = SecItemDelete(query_attrs.as_concrete_TypeRef());
1180
1181                if status != errSecSuccess {
1182                    return Err(anyhow!("delete password failed: {}", status));
1183                }
1184            }
1185            Ok(())
1186        })
1187    }
1188}
1189
1190impl MacPlatform {
1191    unsafe fn read_string_from_clipboard(
1192        &self,
1193        state: &MacPlatformState,
1194        text_bytes: &[u8],
1195    ) -> ClipboardItem {
1196        unsafe {
1197            let text = String::from_utf8_lossy(text_bytes).to_string();
1198            let metadata = self
1199                .read_from_pasteboard(state.pasteboard, state.text_hash_pasteboard_type)
1200                .and_then(|hash_bytes| {
1201                    let hash_bytes = hash_bytes.try_into().ok()?;
1202                    let hash = u64::from_be_bytes(hash_bytes);
1203                    let metadata = self
1204                        .read_from_pasteboard(state.pasteboard, state.metadata_pasteboard_type)?;
1205
1206                    if hash == ClipboardString::text_hash(&text) {
1207                        String::from_utf8(metadata.to_vec()).ok()
1208                    } else {
1209                        None
1210                    }
1211                });
1212
1213            ClipboardItem {
1214                entries: vec![ClipboardEntry::String(ClipboardString { text, metadata })],
1215            }
1216        }
1217    }
1218
1219    unsafe fn write_plaintext_to_clipboard(&self, string: &ClipboardString) {
1220        unsafe {
1221            let state = self.0.lock();
1222            state.pasteboard.clearContents();
1223
1224            let text_bytes = NSData::dataWithBytes_length_(
1225                nil,
1226                string.text.as_ptr() as *const c_void,
1227                string.text.len() as u64,
1228            );
1229            state
1230                .pasteboard
1231                .setData_forType(text_bytes, NSPasteboardTypeString);
1232
1233            if let Some(metadata) = string.metadata.as_ref() {
1234                let hash_bytes = ClipboardString::text_hash(&string.text).to_be_bytes();
1235                let hash_bytes = NSData::dataWithBytes_length_(
1236                    nil,
1237                    hash_bytes.as_ptr() as *const c_void,
1238                    hash_bytes.len() as u64,
1239                );
1240                state
1241                    .pasteboard
1242                    .setData_forType(hash_bytes, state.text_hash_pasteboard_type);
1243
1244                let metadata_bytes = NSData::dataWithBytes_length_(
1245                    nil,
1246                    metadata.as_ptr() as *const c_void,
1247                    metadata.len() as u64,
1248                );
1249                state
1250                    .pasteboard
1251                    .setData_forType(metadata_bytes, state.metadata_pasteboard_type);
1252            }
1253        }
1254    }
1255
1256    unsafe fn write_image_to_clipboard(&self, image: &Image) {
1257        unsafe {
1258            let state = self.0.lock();
1259            state.pasteboard.clearContents();
1260
1261            let bytes = NSData::dataWithBytes_length_(
1262                nil,
1263                image.bytes.as_ptr() as *const c_void,
1264                image.bytes.len() as u64,
1265            );
1266
1267            state
1268                .pasteboard
1269                .setData_forType(bytes, Into::<UTType>::into(image.format).inner_mut());
1270        }
1271    }
1272}
1273
1274fn try_clipboard_image(pasteboard: id, format: ImageFormat) -> Option<ClipboardItem> {
1275    let mut ut_type: UTType = format.into();
1276
1277    unsafe {
1278        let types: id = pasteboard.types();
1279        if msg_send![types, containsObject: ut_type.inner()] {
1280            let data = pasteboard.dataForType(ut_type.inner_mut());
1281            if data == nil {
1282                None
1283            } else {
1284                let bytes = Vec::from(slice::from_raw_parts(
1285                    data.bytes() as *mut u8,
1286                    data.length() as usize,
1287                ));
1288                let id = hash(&bytes);
1289
1290                Some(ClipboardItem {
1291                    entries: vec![ClipboardEntry::Image(Image { format, bytes, id })],
1292                })
1293            }
1294        } else {
1295            None
1296        }
1297    }
1298}
1299
1300unsafe fn path_from_objc(path: id) -> PathBuf {
1301    let len = msg_send![path, lengthOfBytesUsingEncoding: NSUTF8StringEncoding];
1302    let bytes = unsafe { path.UTF8String() as *const u8 };
1303    let path = str::from_utf8(unsafe { slice::from_raw_parts(bytes, len) }).unwrap();
1304    PathBuf::from(path)
1305}
1306
1307unsafe fn get_mac_platform(object: &mut Object) -> &MacPlatform {
1308    unsafe {
1309        let platform_ptr: *mut c_void = *object.get_ivar(MAC_PLATFORM_IVAR);
1310        assert!(!platform_ptr.is_null());
1311        &*(platform_ptr as *const MacPlatform)
1312    }
1313}
1314
1315extern "C" fn did_finish_launching(this: &mut Object, _: Sel, _: id) {
1316    unsafe {
1317        let app: id = msg_send![APP_CLASS, sharedApplication];
1318        app.setActivationPolicy_(NSApplicationActivationPolicyRegular);
1319
1320        let notification_center: *mut Object =
1321            msg_send![class!(NSNotificationCenter), defaultCenter];
1322        let name = ns_string("NSTextInputContextKeyboardSelectionDidChangeNotification");
1323        let _: () = msg_send![notification_center, addObserver: this as id
1324            selector: sel!(onKeyboardLayoutChange:)
1325            name: name
1326            object: nil
1327        ];
1328
1329        let platform = get_mac_platform(this);
1330        let callback = platform.0.lock().finish_launching.take();
1331        if let Some(callback) = callback {
1332            callback();
1333        }
1334    }
1335}
1336
1337extern "C" fn should_handle_reopen(this: &mut Object, _: Sel, _: id, has_open_windows: bool) {
1338    if !has_open_windows {
1339        let platform = unsafe { get_mac_platform(this) };
1340        let mut lock = platform.0.lock();
1341        if let Some(mut callback) = lock.reopen.take() {
1342            drop(lock);
1343            callback();
1344            platform.0.lock().reopen.get_or_insert(callback);
1345        }
1346    }
1347}
1348
1349extern "C" fn will_terminate(this: &mut Object, _: Sel, _: id) {
1350    let platform = unsafe { get_mac_platform(this) };
1351    let mut lock = platform.0.lock();
1352    if let Some(mut callback) = lock.quit.take() {
1353        drop(lock);
1354        callback();
1355        platform.0.lock().quit.get_or_insert(callback);
1356    }
1357}
1358
1359extern "C" fn on_keyboard_layout_change(this: &mut Object, _: Sel, _: id) {
1360    let platform = unsafe { get_mac_platform(this) };
1361    let mut lock = platform.0.lock();
1362    if let Some(mut callback) = lock.on_keyboard_layout_change.take() {
1363        drop(lock);
1364        callback();
1365        platform
1366            .0
1367            .lock()
1368            .on_keyboard_layout_change
1369            .get_or_insert(callback);
1370    }
1371}
1372
1373extern "C" fn open_urls(this: &mut Object, _: Sel, _: id, urls: id) {
1374    let urls = unsafe {
1375        (0..urls.count())
1376            .filter_map(|i| {
1377                let url = urls.objectAtIndex(i);
1378                match CStr::from_ptr(url.absoluteString().UTF8String() as *mut c_char).to_str() {
1379                    Ok(string) => Some(string.to_string()),
1380                    Err(err) => {
1381                        log::error!("error converting path to string: {}", err);
1382                        None
1383                    }
1384                }
1385            })
1386            .collect::<Vec<_>>()
1387    };
1388    let platform = unsafe { get_mac_platform(this) };
1389    let mut lock = platform.0.lock();
1390    if let Some(mut callback) = lock.open_urls.take() {
1391        drop(lock);
1392        callback(urls);
1393        platform.0.lock().open_urls.get_or_insert(callback);
1394    }
1395}
1396
1397extern "C" fn handle_menu_item(this: &mut Object, _: Sel, item: id) {
1398    unsafe {
1399        let platform = get_mac_platform(this);
1400        let mut lock = platform.0.lock();
1401        if let Some(mut callback) = lock.menu_command.take() {
1402            let tag: NSInteger = msg_send![item, tag];
1403            let index = tag as usize;
1404            if let Some(action) = lock.menu_actions.get(index) {
1405                let action = action.boxed_clone();
1406                drop(lock);
1407                callback(&*action);
1408            }
1409            platform.0.lock().menu_command.get_or_insert(callback);
1410        }
1411    }
1412}
1413
1414extern "C" fn validate_menu_item(this: &mut Object, _: Sel, item: id) -> bool {
1415    unsafe {
1416        let mut result = false;
1417        let platform = get_mac_platform(this);
1418        let mut lock = platform.0.lock();
1419        if let Some(mut callback) = lock.validate_menu_command.take() {
1420            let tag: NSInteger = msg_send![item, tag];
1421            let index = tag as usize;
1422            if let Some(action) = lock.menu_actions.get(index) {
1423                let action = action.boxed_clone();
1424                drop(lock);
1425                result = callback(action.as_ref());
1426            }
1427            platform
1428                .0
1429                .lock()
1430                .validate_menu_command
1431                .get_or_insert(callback);
1432        }
1433        result
1434    }
1435}
1436
1437extern "C" fn menu_will_open(this: &mut Object, _: Sel, _: id) {
1438    unsafe {
1439        let platform = get_mac_platform(this);
1440        let mut lock = platform.0.lock();
1441        if let Some(mut callback) = lock.will_open_menu.take() {
1442            drop(lock);
1443            callback();
1444            platform.0.lock().will_open_menu.get_or_insert(callback);
1445        }
1446    }
1447}
1448
1449extern "C" fn handle_dock_menu(this: &mut Object, _: Sel, _: id) -> id {
1450    unsafe {
1451        let platform = get_mac_platform(this);
1452        let mut state = platform.0.lock();
1453        if let Some(id) = state.dock_menu {
1454            id
1455        } else {
1456            nil
1457        }
1458    }
1459}
1460
1461unsafe fn ns_string(string: &str) -> id {
1462    unsafe { NSString::alloc(nil).init_str(string).autorelease() }
1463}
1464
1465unsafe fn ns_url_to_path(url: id) -> Result<PathBuf> {
1466    let path: *mut c_char = msg_send![url, fileSystemRepresentation];
1467    if path.is_null() {
1468        Err(anyhow!("url is not a file path: {}", unsafe {
1469            CStr::from_ptr(url.absoluteString().UTF8String()).to_string_lossy()
1470        }))
1471    } else {
1472        Ok(PathBuf::from(OsStr::from_bytes(unsafe {
1473            CStr::from_ptr(path).to_bytes()
1474        })))
1475    }
1476}
1477
1478#[link(name = "Carbon", kind = "framework")]
1479unsafe extern "C" {
1480    pub(super) fn TISCopyCurrentKeyboardLayoutInputSource() -> *mut Object;
1481    pub(super) fn TISGetInputSourceProperty(
1482        inputSource: *mut Object,
1483        propertyKey: *const c_void,
1484    ) -> *mut Object;
1485
1486    pub(super) fn UCKeyTranslate(
1487        keyLayoutPtr: *const ::std::os::raw::c_void,
1488        virtualKeyCode: u16,
1489        keyAction: u16,
1490        modifierKeyState: u32,
1491        keyboardType: u32,
1492        keyTranslateOptions: u32,
1493        deadKeyState: *mut u32,
1494        maxStringLength: usize,
1495        actualStringLength: *mut usize,
1496        unicodeString: *mut u16,
1497    ) -> u32;
1498    pub(super) fn LMGetKbdType() -> u16;
1499    pub(super) static kTISPropertyUnicodeKeyLayoutData: CFStringRef;
1500    pub(super) static kTISPropertyInputSourceID: CFStringRef;
1501}
1502
1503mod security {
1504    #![allow(non_upper_case_globals)]
1505    use super::*;
1506
1507    #[link(name = "Security", kind = "framework")]
1508    unsafe extern "C" {
1509        pub static kSecClass: CFStringRef;
1510        pub static kSecClassInternetPassword: CFStringRef;
1511        pub static kSecAttrServer: CFStringRef;
1512        pub static kSecAttrAccount: CFStringRef;
1513        pub static kSecValueData: CFStringRef;
1514        pub static kSecReturnAttributes: CFStringRef;
1515        pub static kSecReturnData: CFStringRef;
1516
1517        pub fn SecItemAdd(attributes: CFDictionaryRef, result: *mut CFTypeRef) -> OSStatus;
1518        pub fn SecItemUpdate(query: CFDictionaryRef, attributes: CFDictionaryRef) -> OSStatus;
1519        pub fn SecItemDelete(query: CFDictionaryRef) -> OSStatus;
1520        pub fn SecItemCopyMatching(query: CFDictionaryRef, result: *mut CFTypeRef) -> OSStatus;
1521    }
1522
1523    pub const errSecSuccess: OSStatus = 0;
1524    pub const errSecUserCanceled: OSStatus = -128;
1525    pub const errSecItemNotFound: OSStatus = -25300;
1526}
1527
1528impl From<ImageFormat> for UTType {
1529    fn from(value: ImageFormat) -> Self {
1530        match value {
1531            ImageFormat::Png => Self::png(),
1532            ImageFormat::Jpeg => Self::jpeg(),
1533            ImageFormat::Tiff => Self::tiff(),
1534            ImageFormat::Webp => Self::webp(),
1535            ImageFormat::Gif => Self::gif(),
1536            ImageFormat::Bmp => Self::bmp(),
1537            ImageFormat::Svg => Self::svg(),
1538        }
1539    }
1540}
1541
1542// See https://developer.apple.com/documentation/uniformtypeidentifiers/uttype-swift.struct/
1543struct UTType(id);
1544
1545impl UTType {
1546    pub fn png() -> Self {
1547        // https://developer.apple.com/documentation/uniformtypeidentifiers/uttype-swift.struct/png
1548        Self(unsafe { NSPasteboardTypePNG }) // This is a rare case where there's a built-in NSPasteboardType
1549    }
1550
1551    pub fn jpeg() -> Self {
1552        // https://developer.apple.com/documentation/uniformtypeidentifiers/uttype-swift.struct/jpeg
1553        Self(unsafe { ns_string("public.jpeg") })
1554    }
1555
1556    pub fn gif() -> Self {
1557        // https://developer.apple.com/documentation/uniformtypeidentifiers/uttype-swift.struct/gif
1558        Self(unsafe { ns_string("com.compuserve.gif") })
1559    }
1560
1561    pub fn webp() -> Self {
1562        // https://developer.apple.com/documentation/uniformtypeidentifiers/uttype-swift.struct/webp
1563        Self(unsafe { ns_string("org.webmproject.webp") })
1564    }
1565
1566    pub fn bmp() -> Self {
1567        // https://developer.apple.com/documentation/uniformtypeidentifiers/uttype-swift.struct/bmp
1568        Self(unsafe { ns_string("com.microsoft.bmp") })
1569    }
1570
1571    pub fn svg() -> Self {
1572        // https://developer.apple.com/documentation/uniformtypeidentifiers/uttype-swift.struct/svg
1573        Self(unsafe { ns_string("public.svg-image") })
1574    }
1575
1576    pub fn tiff() -> Self {
1577        // https://developer.apple.com/documentation/uniformtypeidentifiers/uttype-swift.struct/tiff
1578        Self(unsafe { NSPasteboardTypeTIFF }) // This is a rare case where there's a built-in NSPasteboardType
1579    }
1580
1581    fn inner(&self) -> *const Object {
1582        self.0
1583    }
1584
1585    fn inner_mut(&self) -> *mut Object {
1586        self.0 as *mut _
1587    }
1588}
1589
1590#[cfg(test)]
1591mod tests {
1592    use crate::ClipboardItem;
1593
1594    use super::*;
1595
1596    #[test]
1597    fn test_clipboard() {
1598        let platform = build_platform();
1599        assert_eq!(platform.read_from_clipboard(), None);
1600
1601        let item = ClipboardItem::new_string("1".to_string());
1602        platform.write_to_clipboard(item.clone());
1603        assert_eq!(platform.read_from_clipboard(), Some(item));
1604
1605        let item = ClipboardItem {
1606            entries: vec![ClipboardEntry::String(
1607                ClipboardString::new("2".to_string()).with_json_metadata(vec![3, 4]),
1608            )],
1609        };
1610        platform.write_to_clipboard(item.clone());
1611        assert_eq!(platform.read_from_clipboard(), Some(item));
1612
1613        let text_from_other_app = "text from other app";
1614        unsafe {
1615            let bytes = NSData::dataWithBytes_length_(
1616                nil,
1617                text_from_other_app.as_ptr() as *const c_void,
1618                text_from_other_app.len() as u64,
1619            );
1620            platform
1621                .0
1622                .lock()
1623                .pasteboard
1624                .setData_forType(bytes, NSPasteboardTypeString);
1625        }
1626        assert_eq!(
1627            platform.read_from_clipboard(),
1628            Some(ClipboardItem::new_string(text_from_other_app.to_string()))
1629        );
1630    }
1631
1632    fn build_platform() -> MacPlatform {
1633        let platform = MacPlatform::new(false);
1634        platform.0.lock().pasteboard = unsafe { NSPasteboard::pasteboardWithUniqueName(nil) };
1635        platform
1636    }
1637}