platform.rs

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