platform.rs

   1use super::{
   2    BoolExt, MacKeyboardLayout,
   3    attributed_string::{NSAttributedString, NSMutableAttributedString},
   4    events::key_to_native,
   5    is_macos_version_at_least, renderer, screen_capture,
   6};
   7use crate::{
   8    Action, AnyWindowHandle, BackgroundExecutor, ClipboardEntry, ClipboardItem, ClipboardString,
   9    CursorStyle, ForegroundExecutor, Image, ImageFormat, KeyContext, Keymap, MacDispatcher,
  10    MacDisplay, MacWindow, Menu, MenuItem, PathPromptOptions, Platform, PlatformDisplay,
  11    PlatformKeyboardLayout, PlatformTextSystem, PlatformWindow, Result, ScreenCaptureSource,
  12    SemanticVersion, Task, 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, NSOperatingSystemVersion,
  26        NSProcessInfo, NSRange, NSString, 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}
 174
 175impl Default for MacPlatform {
 176    fn default() -> Self {
 177        Self::new(false)
 178    }
 179}
 180
 181impl MacPlatform {
 182    pub(crate) fn new(headless: bool) -> Self {
 183        let dispatcher = Arc::new(MacDispatcher::new());
 184
 185        #[cfg(feature = "font-kit")]
 186        let text_system = Arc::new(crate::MacTextSystem::new());
 187
 188        #[cfg(not(feature = "font-kit"))]
 189        let text_system = Arc::new(crate::NoopTextSystem::new());
 190
 191        Self(Mutex::new(MacPlatformState {
 192            headless,
 193            text_system,
 194            background_executor: BackgroundExecutor::new(dispatcher.clone()),
 195            foreground_executor: ForegroundExecutor::new(dispatcher),
 196            renderer_context: renderer::Context::default(),
 197            pasteboard: unsafe { NSPasteboard::generalPasteboard(nil) },
 198            text_hash_pasteboard_type: unsafe { ns_string("zed-text-hash") },
 199            metadata_pasteboard_type: unsafe { ns_string("zed-metadata") },
 200            reopen: None,
 201            quit: None,
 202            menu_command: None,
 203            validate_menu_command: None,
 204            will_open_menu: None,
 205            menu_actions: Default::default(),
 206            open_urls: None,
 207            finish_launching: None,
 208            dock_menu: None,
 209            on_keyboard_layout_change: None,
 210        }))
 211    }
 212
 213    unsafe fn read_from_pasteboard(&self, pasteboard: *mut Object, kind: id) -> Option<&[u8]> {
 214        unsafe {
 215            let data = pasteboard.dataForType(kind);
 216            if data == nil {
 217                None
 218            } else {
 219                Some(slice::from_raw_parts(
 220                    data.bytes() as *mut u8,
 221                    data.length() as usize,
 222                ))
 223            }
 224        }
 225    }
 226
 227    unsafe fn create_menu_bar(
 228        &self,
 229        menus: Vec<Menu>,
 230        delegate: id,
 231        actions: &mut Vec<Box<dyn Action>>,
 232        keymap: &Keymap,
 233    ) -> id {
 234        unsafe {
 235            let application_menu = NSMenu::new(nil).autorelease();
 236            application_menu.setDelegate_(delegate);
 237
 238            for menu_config in menus {
 239                let menu = NSMenu::new(nil).autorelease();
 240                let menu_title = ns_string(&menu_config.name);
 241                menu.setTitle_(menu_title);
 242                menu.setDelegate_(delegate);
 243
 244                for item_config in menu_config.items {
 245                    menu.addItem_(Self::create_menu_item(
 246                        item_config,
 247                        delegate,
 248                        actions,
 249                        keymap,
 250                    ));
 251                }
 252
 253                let menu_item = NSMenuItem::new(nil).autorelease();
 254                menu_item.setTitle_(menu_title);
 255                menu_item.setSubmenu_(menu);
 256                application_menu.addItem_(menu_item);
 257
 258                if menu_config.name == "Window" {
 259                    let app: id = msg_send![APP_CLASS, sharedApplication];
 260                    app.setWindowsMenu_(menu);
 261                }
 262            }
 263
 264            application_menu
 265        }
 266    }
 267
 268    unsafe fn create_dock_menu(
 269        &self,
 270        menu_items: Vec<MenuItem>,
 271        delegate: id,
 272        actions: &mut Vec<Box<dyn Action>>,
 273        keymap: &Keymap,
 274    ) -> id {
 275        unsafe {
 276            let dock_menu = NSMenu::new(nil);
 277            dock_menu.setDelegate_(delegate);
 278            for item_config in menu_items {
 279                dock_menu.addItem_(Self::create_menu_item(
 280                    item_config,
 281                    delegate,
 282                    actions,
 283                    keymap,
 284                ));
 285            }
 286
 287            dock_menu
 288        }
 289    }
 290
 291    unsafe fn create_menu_item(
 292        item: MenuItem,
 293        delegate: id,
 294        actions: &mut Vec<Box<dyn Action>>,
 295        keymap: &Keymap,
 296    ) -> id {
 297        const DEFAULT_CONTEXT: LazyCell<Vec<KeyContext>> = LazyCell::new(|| {
 298            let mut workspace_context = KeyContext::new_with_defaults();
 299            workspace_context.add("Workspace");
 300            let mut pane_context = KeyContext::new_with_defaults();
 301            pane_context.add("Pane");
 302            let mut editor_context = KeyContext::new_with_defaults();
 303            editor_context.add("Editor");
 304
 305            pane_context.extend(&editor_context);
 306            workspace_context.extend(&pane_context);
 307            vec![workspace_context]
 308        });
 309
 310        unsafe {
 311            match item {
 312                MenuItem::Separator => NSMenuItem::separatorItem(nil),
 313                MenuItem::Action {
 314                    name,
 315                    action,
 316                    os_action,
 317                } => {
 318                    let keystrokes = keymap
 319                        .bindings_for_action(action.as_ref())
 320                        .find_or_first(|binding| {
 321                            binding
 322                                .predicate()
 323                                .is_none_or(|predicate| predicate.eval(&DEFAULT_CONTEXT))
 324                        })
 325                        .map(|binding| binding.keystrokes());
 326
 327                    let selector = match os_action {
 328                        Some(crate::OsAction::Cut) => selector("cut:"),
 329                        Some(crate::OsAction::Copy) => selector("copy:"),
 330                        Some(crate::OsAction::Paste) => selector("paste:"),
 331                        Some(crate::OsAction::SelectAll) => selector("selectAll:"),
 332                        // "undo:" and "redo:" are always disabled in our case, as
 333                        // we don't have a NSTextView/NSTextField to enable them on.
 334                        Some(crate::OsAction::Undo) => selector("handleGPUIMenuItem:"),
 335                        Some(crate::OsAction::Redo) => selector("handleGPUIMenuItem:"),
 336                        None => selector("handleGPUIMenuItem:"),
 337                    };
 338
 339                    let item;
 340                    if let Some(keystrokes) = keystrokes {
 341                        if keystrokes.len() == 1 {
 342                            let keystroke = &keystrokes[0];
 343                            let mut mask = NSEventModifierFlags::empty();
 344                            for (modifier, flag) in &[
 345                                (
 346                                    keystroke.modifiers.platform,
 347                                    NSEventModifierFlags::NSCommandKeyMask,
 348                                ),
 349                                (
 350                                    keystroke.modifiers.control,
 351                                    NSEventModifierFlags::NSControlKeyMask,
 352                                ),
 353                                (
 354                                    keystroke.modifiers.alt,
 355                                    NSEventModifierFlags::NSAlternateKeyMask,
 356                                ),
 357                                (
 358                                    keystroke.modifiers.shift,
 359                                    NSEventModifierFlags::NSShiftKeyMask,
 360                                ),
 361                            ] {
 362                                if *modifier {
 363                                    mask |= *flag;
 364                                }
 365                            }
 366
 367                            item = NSMenuItem::alloc(nil)
 368                                .initWithTitle_action_keyEquivalent_(
 369                                    ns_string(&name),
 370                                    selector,
 371                                    ns_string(key_to_native(&keystroke.key).as_ref()),
 372                                )
 373                                .autorelease();
 374                            if Self::os_version() >= SemanticVersion::new(12, 0, 0) {
 375                                let _: () = msg_send![item, setAllowsAutomaticKeyEquivalentLocalization: NO];
 376                            }
 377                            item.setKeyEquivalentModifierMask_(mask);
 378                        } else {
 379                            item = NSMenuItem::alloc(nil)
 380                                .initWithTitle_action_keyEquivalent_(
 381                                    ns_string(&name),
 382                                    selector,
 383                                    ns_string(""),
 384                                )
 385                                .autorelease();
 386                        }
 387                    } else {
 388                        item = NSMenuItem::alloc(nil)
 389                            .initWithTitle_action_keyEquivalent_(
 390                                ns_string(&name),
 391                                selector,
 392                                ns_string(""),
 393                            )
 394                            .autorelease();
 395                    }
 396
 397                    let tag = actions.len() as NSInteger;
 398                    let _: () = msg_send![item, setTag: tag];
 399                    actions.push(action);
 400                    item
 401                }
 402                MenuItem::Submenu(Menu { name, items }) => {
 403                    let item = NSMenuItem::new(nil).autorelease();
 404                    let submenu = NSMenu::new(nil).autorelease();
 405                    submenu.setDelegate_(delegate);
 406                    for item in items {
 407                        submenu.addItem_(Self::create_menu_item(item, delegate, actions, keymap));
 408                    }
 409                    item.setSubmenu_(submenu);
 410                    item.setTitle_(ns_string(&name));
 411                    if name == "Services" {
 412                        let app: id = msg_send![APP_CLASS, sharedApplication];
 413                        app.setServicesMenu_(item);
 414                    }
 415
 416                    item
 417                }
 418            }
 419        }
 420    }
 421
 422    fn os_version() -> SemanticVersion {
 423        let version = unsafe {
 424            let process_info = NSProcessInfo::processInfo(nil);
 425            process_info.operatingSystemVersion()
 426        };
 427        SemanticVersion::new(
 428            version.majorVersion as usize,
 429            version.minorVersion as usize,
 430            version.patchVersion as usize,
 431        )
 432    }
 433}
 434
 435impl Platform for MacPlatform {
 436    fn background_executor(&self) -> BackgroundExecutor {
 437        self.0.lock().background_executor.clone()
 438    }
 439
 440    fn foreground_executor(&self) -> crate::ForegroundExecutor {
 441        self.0.lock().foreground_executor.clone()
 442    }
 443
 444    fn text_system(&self) -> Arc<dyn PlatformTextSystem> {
 445        self.0.lock().text_system.clone()
 446    }
 447
 448    fn run(&self, on_finish_launching: Box<dyn FnOnce()>) {
 449        let mut state = self.0.lock();
 450        if state.headless {
 451            drop(state);
 452            on_finish_launching();
 453            unsafe { CFRunLoopRun() };
 454        } else {
 455            state.finish_launching = Some(on_finish_launching);
 456            drop(state);
 457        }
 458
 459        unsafe {
 460            let app: id = msg_send![APP_CLASS, sharedApplication];
 461            let app_delegate: id = msg_send![APP_DELEGATE_CLASS, new];
 462            app.setDelegate_(app_delegate);
 463
 464            let self_ptr = self as *const Self as *const c_void;
 465            (*app).set_ivar(MAC_PLATFORM_IVAR, self_ptr);
 466            (*app_delegate).set_ivar(MAC_PLATFORM_IVAR, self_ptr);
 467
 468            let pool = NSAutoreleasePool::new(nil);
 469            app.run();
 470            pool.drain();
 471
 472            (*app).set_ivar(MAC_PLATFORM_IVAR, null_mut::<c_void>());
 473            (*NSWindow::delegate(app)).set_ivar(MAC_PLATFORM_IVAR, null_mut::<c_void>());
 474        }
 475    }
 476
 477    fn quit(&self) {
 478        // Quitting the app causes us to close windows, which invokes `Window::on_close` callbacks
 479        // synchronously before this method terminates. If we call `Platform::quit` while holding a
 480        // borrow of the app state (which most of the time we will do), we will end up
 481        // double-borrowing the app state in the `on_close` callbacks for our open windows. To solve
 482        // this, we make quitting the application asynchronous so that we aren't holding borrows to
 483        // the app state on the stack when we actually terminate the app.
 484
 485        use super::dispatcher::{dispatch_get_main_queue, dispatch_sys::dispatch_async_f};
 486
 487        unsafe {
 488            dispatch_async_f(dispatch_get_main_queue(), ptr::null_mut(), Some(quit));
 489        }
 490
 491        unsafe extern "C" fn quit(_: *mut c_void) {
 492            unsafe {
 493                let app = NSApplication::sharedApplication(nil);
 494                let _: () = msg_send![app, terminate: nil];
 495            }
 496        }
 497    }
 498
 499    fn restart(&self, _binary_path: Option<PathBuf>) {
 500        use std::os::unix::process::CommandExt as _;
 501
 502        let app_pid = std::process::id().to_string();
 503        let app_path = self
 504            .app_path()
 505            .ok()
 506            // When the app is not bundled, `app_path` returns the
 507            // directory containing the executable. Disregard this
 508            // and get the path to the executable itself.
 509            .and_then(|path| (path.extension()?.to_str()? == "app").then_some(path))
 510            .unwrap_or_else(|| std::env::current_exe().unwrap());
 511
 512        // Wait until this process has exited and then re-open this path.
 513        let script = r#"
 514            while kill -0 $0 2> /dev/null; do
 515                sleep 0.1
 516            done
 517            open "$1"
 518        "#;
 519
 520        let restart_process = Command::new("/bin/bash")
 521            .arg("-c")
 522            .arg(script)
 523            .arg(app_pid)
 524            .arg(app_path)
 525            .process_group(0)
 526            .spawn();
 527
 528        match restart_process {
 529            Ok(_) => self.quit(),
 530            Err(e) => log::error!("failed to spawn restart script: {:?}", e),
 531        }
 532    }
 533
 534    fn activate(&self, ignoring_other_apps: bool) {
 535        unsafe {
 536            let app = NSApplication::sharedApplication(nil);
 537            app.activateIgnoringOtherApps_(ignoring_other_apps.to_objc());
 538        }
 539    }
 540
 541    fn hide(&self) {
 542        unsafe {
 543            let app = NSApplication::sharedApplication(nil);
 544            let _: () = msg_send![app, hide: nil];
 545        }
 546    }
 547
 548    fn hide_other_apps(&self) {
 549        unsafe {
 550            let app = NSApplication::sharedApplication(nil);
 551            let _: () = msg_send![app, hideOtherApplications: nil];
 552        }
 553    }
 554
 555    fn unhide_other_apps(&self) {
 556        unsafe {
 557            let app = NSApplication::sharedApplication(nil);
 558            let _: () = msg_send![app, unhideAllApplications: nil];
 559        }
 560    }
 561
 562    fn primary_display(&self) -> Option<Rc<dyn PlatformDisplay>> {
 563        Some(Rc::new(MacDisplay::primary()))
 564    }
 565
 566    fn displays(&self) -> Vec<Rc<dyn PlatformDisplay>> {
 567        MacDisplay::all()
 568            .map(|screen| Rc::new(screen) as Rc<_>)
 569            .collect()
 570    }
 571
 572    fn is_screen_capture_supported(&self) -> bool {
 573        let min_version = NSOperatingSystemVersion::new(12, 3, 0);
 574        is_macos_version_at_least(min_version)
 575    }
 576
 577    fn screen_capture_sources(
 578        &self,
 579    ) -> oneshot::Receiver<Result<Vec<Box<dyn ScreenCaptureSource>>>> {
 580        screen_capture::get_sources()
 581    }
 582
 583    fn active_window(&self) -> Option<AnyWindowHandle> {
 584        MacWindow::active_window()
 585    }
 586
 587    // Returns the windows ordered front-to-back, meaning that the active
 588    // window is the first one in the returned vec.
 589    fn window_stack(&self) -> Option<Vec<AnyWindowHandle>> {
 590        Some(MacWindow::ordered_windows())
 591    }
 592
 593    fn open_window(
 594        &self,
 595        handle: AnyWindowHandle,
 596        options: WindowParams,
 597    ) -> Result<Box<dyn PlatformWindow>> {
 598        let renderer_context = self.0.lock().renderer_context.clone();
 599        Ok(Box::new(MacWindow::open(
 600            handle,
 601            options,
 602            self.foreground_executor(),
 603            renderer_context,
 604        )))
 605    }
 606
 607    fn window_appearance(&self) -> WindowAppearance {
 608        unsafe {
 609            let app = NSApplication::sharedApplication(nil);
 610            let appearance: id = msg_send![app, effectiveAppearance];
 611            WindowAppearance::from_native(appearance)
 612        }
 613    }
 614
 615    fn open_url(&self, url: &str) {
 616        unsafe {
 617            let url = NSURL::alloc(nil)
 618                .initWithString_(ns_string(url))
 619                .autorelease();
 620            let workspace: id = msg_send![class!(NSWorkspace), sharedWorkspace];
 621            msg_send![workspace, openURL: url]
 622        }
 623    }
 624
 625    fn register_url_scheme(&self, scheme: &str) -> Task<anyhow::Result<()>> {
 626        // API only available post Monterey
 627        // https://developer.apple.com/documentation/appkit/nsworkspace/3753004-setdefaultapplicationaturl
 628        let (done_tx, done_rx) = oneshot::channel();
 629        if Self::os_version() < SemanticVersion::new(12, 0, 0) {
 630            return Task::ready(Err(anyhow!(
 631                "macOS 12.0 or later is required to register URL schemes"
 632            )));
 633        }
 634
 635        let bundle_id = unsafe {
 636            let bundle: id = msg_send![class!(NSBundle), mainBundle];
 637            let bundle_id: id = msg_send![bundle, bundleIdentifier];
 638            if bundle_id == nil {
 639                return Task::ready(Err(anyhow!("Can only register URL scheme in bundled apps")));
 640            }
 641            bundle_id
 642        };
 643
 644        unsafe {
 645            let workspace: id = msg_send![class!(NSWorkspace), sharedWorkspace];
 646            let scheme: id = ns_string(scheme);
 647            let app: id = msg_send![workspace, URLForApplicationWithBundleIdentifier: bundle_id];
 648            if app == nil {
 649                return Task::ready(Err(anyhow!(
 650                    "Cannot register URL scheme until app is installed"
 651                )));
 652            }
 653            let done_tx = Cell::new(Some(done_tx));
 654            let block = ConcreteBlock::new(move |error: id| {
 655                let result = if error == nil {
 656                    Ok(())
 657                } else {
 658                    let msg: id = msg_send![error, localizedDescription];
 659                    Err(anyhow!("Failed to register: {msg:?}"))
 660                };
 661
 662                if let Some(done_tx) = done_tx.take() {
 663                    let _ = done_tx.send(result);
 664                }
 665            });
 666            let block = block.copy();
 667            let _: () = msg_send![workspace, setDefaultApplicationAtURL: app toOpenURLsWithScheme: scheme completionHandler: block];
 668        }
 669
 670        self.background_executor()
 671            .spawn(async { crate::Flatten::flatten(done_rx.await.map_err(|e| anyhow!(e))) })
 672    }
 673
 674    fn on_open_urls(&self, callback: Box<dyn FnMut(Vec<String>)>) {
 675        self.0.lock().open_urls = Some(callback);
 676    }
 677
 678    fn prompt_for_paths(
 679        &self,
 680        options: PathPromptOptions,
 681    ) -> oneshot::Receiver<Result<Option<Vec<PathBuf>>>> {
 682        let (done_tx, done_rx) = oneshot::channel();
 683        self.foreground_executor()
 684            .spawn(async move {
 685                unsafe {
 686                    let panel = NSOpenPanel::openPanel(nil);
 687                    panel.setCanChooseDirectories_(options.directories.to_objc());
 688                    panel.setCanChooseFiles_(options.files.to_objc());
 689                    panel.setAllowsMultipleSelection_(options.multiple.to_objc());
 690                    panel.setCanCreateDirectories(true.to_objc());
 691                    panel.setResolvesAliases_(false.to_objc());
 692                    let done_tx = Cell::new(Some(done_tx));
 693                    let block = ConcreteBlock::new(move |response: NSModalResponse| {
 694                        let result = if response == NSModalResponse::NSModalResponseOk {
 695                            let mut result = Vec::new();
 696                            let urls = panel.URLs();
 697                            for i in 0..urls.count() {
 698                                let url = urls.objectAtIndex(i);
 699                                if url.isFileURL() == YES {
 700                                    if let Ok(path) = ns_url_to_path(url) {
 701                                        result.push(path)
 702                                    }
 703                                }
 704                            }
 705                            Some(result)
 706                        } else {
 707                            None
 708                        };
 709
 710                        if let Some(done_tx) = done_tx.take() {
 711                            let _ = done_tx.send(Ok(result));
 712                        }
 713                    });
 714                    let block = block.copy();
 715                    let _: () = msg_send![panel, beginWithCompletionHandler: block];
 716                }
 717            })
 718            .detach();
 719        done_rx
 720    }
 721
 722    fn prompt_for_new_path(&self, directory: &Path) -> oneshot::Receiver<Result<Option<PathBuf>>> {
 723        let directory = directory.to_owned();
 724        let (done_tx, done_rx) = oneshot::channel();
 725        self.foreground_executor()
 726            .spawn(async move {
 727                unsafe {
 728                    let panel = NSSavePanel::savePanel(nil);
 729                    let path = ns_string(directory.to_string_lossy().as_ref());
 730                    let url = NSURL::fileURLWithPath_isDirectory_(nil, path, true.to_objc());
 731                    panel.setDirectoryURL(url);
 732
 733                    let done_tx = Cell::new(Some(done_tx));
 734                    let block = ConcreteBlock::new(move |response: NSModalResponse| {
 735                        let mut result = None;
 736                        if response == NSModalResponse::NSModalResponseOk {
 737                            let url = panel.URL();
 738                            if url.isFileURL() == YES {
 739                                result = ns_url_to_path(panel.URL()).ok().map(|mut result| {
 740                                    let Some(filename) = result.file_name() else {
 741                                        return result;
 742                                    };
 743                                    let chunks = filename
 744                                        .as_bytes()
 745                                        .split(|&b| b == b'.')
 746                                        .collect::<Vec<_>>();
 747
 748                                    // https://github.com/zed-industries/zed/issues/16969
 749                                    // Workaround a bug in macOS Sequoia that adds an extra file-extension
 750                                    // sometimes. e.g. `a.sql` becomes `a.sql.s` or `a.txtx` becomes `a.txtx.txt`
 751                                    //
 752                                    // This is conditional on OS version because I'd like to get rid of it, so that
 753                                    // you can manually create a file called `a.sql.s`. That said it seems better
 754                                    // to break that use-case than breaking `a.sql`.
 755                                    if chunks.len() == 3 && chunks[1].starts_with(chunks[2]) {
 756                                        if Self::os_version() >= SemanticVersion::new(15, 0, 0) {
 757                                            let new_filename = OsStr::from_bytes(
 758                                                &filename.as_bytes()
 759                                                    [..chunks[0].len() + 1 + chunks[1].len()],
 760                                            )
 761                                            .to_owned();
 762                                            result.set_file_name(&new_filename);
 763                                        }
 764                                    }
 765                                    return result;
 766                                })
 767                            }
 768                        }
 769
 770                        if let Some(done_tx) = done_tx.take() {
 771                            let _ = done_tx.send(Ok(result));
 772                        }
 773                    });
 774                    let block = block.copy();
 775                    let _: () = msg_send![panel, beginWithCompletionHandler: block];
 776                }
 777            })
 778            .detach();
 779
 780        done_rx
 781    }
 782
 783    fn can_select_mixed_files_and_dirs(&self) -> bool {
 784        true
 785    }
 786
 787    fn reveal_path(&self, path: &Path) {
 788        unsafe {
 789            let path = path.to_path_buf();
 790            self.0
 791                .lock()
 792                .background_executor
 793                .spawn(async move {
 794                    let full_path = ns_string(path.to_str().unwrap_or(""));
 795                    let root_full_path = ns_string("");
 796                    let workspace: id = msg_send![class!(NSWorkspace), sharedWorkspace];
 797                    let _: BOOL = msg_send![
 798                        workspace,
 799                        selectFile: full_path
 800                        inFileViewerRootedAtPath: root_full_path
 801                    ];
 802                })
 803                .detach();
 804        }
 805    }
 806
 807    fn open_with_system(&self, path: &Path) {
 808        let path = path.to_owned();
 809        self.0
 810            .lock()
 811            .background_executor
 812            .spawn(async move {
 813                let _ = std::process::Command::new("open")
 814                    .arg(path)
 815                    .spawn()
 816                    .context("invoking open command")
 817                    .log_err();
 818            })
 819            .detach();
 820    }
 821
 822    fn on_quit(&self, callback: Box<dyn FnMut()>) {
 823        self.0.lock().quit = Some(callback);
 824    }
 825
 826    fn on_reopen(&self, callback: Box<dyn FnMut()>) {
 827        self.0.lock().reopen = Some(callback);
 828    }
 829
 830    fn on_keyboard_layout_change(&self, callback: Box<dyn FnMut()>) {
 831        self.0.lock().on_keyboard_layout_change = Some(callback);
 832    }
 833
 834    fn on_app_menu_action(&self, callback: Box<dyn FnMut(&dyn Action)>) {
 835        self.0.lock().menu_command = Some(callback);
 836    }
 837
 838    fn on_will_open_app_menu(&self, callback: Box<dyn FnMut()>) {
 839        self.0.lock().will_open_menu = Some(callback);
 840    }
 841
 842    fn on_validate_app_menu_command(&self, callback: Box<dyn FnMut(&dyn Action) -> bool>) {
 843        self.0.lock().validate_menu_command = Some(callback);
 844    }
 845
 846    fn keyboard_layout(&self) -> Box<dyn PlatformKeyboardLayout> {
 847        Box::new(MacKeyboardLayout::new())
 848    }
 849
 850    fn app_path(&self) -> Result<PathBuf> {
 851        unsafe {
 852            let bundle: id = NSBundle::mainBundle();
 853            anyhow::ensure!(!bundle.is_null(), "app is not running inside a bundle");
 854            Ok(path_from_objc(msg_send![bundle, bundlePath]))
 855        }
 856    }
 857
 858    fn set_menus(&self, menus: Vec<Menu>, keymap: &Keymap) {
 859        unsafe {
 860            let app: id = msg_send![APP_CLASS, sharedApplication];
 861            let mut state = self.0.lock();
 862            let actions = &mut state.menu_actions;
 863            let menu = self.create_menu_bar(menus, NSWindow::delegate(app), actions, keymap);
 864            drop(state);
 865            app.setMainMenu_(menu);
 866        }
 867    }
 868
 869    fn set_dock_menu(&self, menu: Vec<MenuItem>, keymap: &Keymap) {
 870        unsafe {
 871            let app: id = msg_send![APP_CLASS, sharedApplication];
 872            let mut state = self.0.lock();
 873            let actions = &mut state.menu_actions;
 874            let new = self.create_dock_menu(menu, NSWindow::delegate(app), actions, keymap);
 875            if let Some(old) = state.dock_menu.replace(new) {
 876                CFRelease(old as _)
 877            }
 878        }
 879    }
 880
 881    fn add_recent_document(&self, path: &Path) {
 882        if let Some(path_str) = path.to_str() {
 883            unsafe {
 884                let document_controller: id =
 885                    msg_send![class!(NSDocumentController), sharedDocumentController];
 886                let url: id = NSURL::fileURLWithPath_(nil, ns_string(path_str));
 887                let _: () = msg_send![document_controller, noteNewRecentDocumentURL:url];
 888            }
 889        }
 890    }
 891
 892    fn path_for_auxiliary_executable(&self, name: &str) -> Result<PathBuf> {
 893        unsafe {
 894            let bundle: id = NSBundle::mainBundle();
 895            anyhow::ensure!(!bundle.is_null(), "app is not running inside a bundle");
 896            let name = ns_string(name);
 897            let url: id = msg_send![bundle, URLForAuxiliaryExecutable: name];
 898            anyhow::ensure!(!url.is_null(), "resource not found");
 899            ns_url_to_path(url)
 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                anyhow::ensure!(status == errSecSuccess, "{verb} password failed: {status}");
1114            }
1115            Ok(())
1116        })
1117    }
1118
1119    fn read_credentials(&self, url: &str) -> Task<Result<Option<(String, Vec<u8>)>>> {
1120        let url = url.to_string();
1121        self.background_executor().spawn(async move {
1122            let url = CFString::from(url.as_str());
1123            let cf_true = CFBoolean::true_value().as_CFTypeRef();
1124
1125            unsafe {
1126                use security::*;
1127
1128                // Find any credentials for the given server URL.
1129                let mut attrs = CFMutableDictionary::with_capacity(5);
1130                attrs.set(kSecClass as *const _, kSecClassInternetPassword as *const _);
1131                attrs.set(kSecAttrServer as *const _, url.as_CFTypeRef());
1132                attrs.set(kSecReturnAttributes as *const _, cf_true);
1133                attrs.set(kSecReturnData as *const _, cf_true);
1134
1135                let mut result = CFTypeRef::from(ptr::null());
1136                let status = SecItemCopyMatching(attrs.as_concrete_TypeRef(), &mut result);
1137                match status {
1138                    security::errSecSuccess => {}
1139                    security::errSecItemNotFound | security::errSecUserCanceled => return Ok(None),
1140                    _ => anyhow::bail!("reading password failed: {status}"),
1141                }
1142
1143                let result = CFType::wrap_under_create_rule(result)
1144                    .downcast::<CFDictionary>()
1145                    .context("keychain item was not a dictionary")?;
1146                let username = result
1147                    .find(kSecAttrAccount as *const _)
1148                    .context("account was missing from keychain item")?;
1149                let username = CFType::wrap_under_get_rule(*username)
1150                    .downcast::<CFString>()
1151                    .context("account was not a string")?;
1152                let password = result
1153                    .find(kSecValueData as *const _)
1154                    .context("password was missing from keychain item")?;
1155                let password = CFType::wrap_under_get_rule(*password)
1156                    .downcast::<CFData>()
1157                    .context("password was not a string")?;
1158
1159                Ok(Some((username.to_string(), password.bytes().to_vec())))
1160            }
1161        })
1162    }
1163
1164    fn delete_credentials(&self, url: &str) -> Task<Result<()>> {
1165        let url = url.to_string();
1166
1167        self.background_executor().spawn(async move {
1168            unsafe {
1169                use security::*;
1170
1171                let url = CFString::from(url.as_str());
1172                let mut query_attrs = CFMutableDictionary::with_capacity(2);
1173                query_attrs.set(kSecClass as *const _, kSecClassInternetPassword as *const _);
1174                query_attrs.set(kSecAttrServer as *const _, url.as_CFTypeRef());
1175
1176                let status = SecItemDelete(query_attrs.as_concrete_TypeRef());
1177                anyhow::ensure!(status == errSecSuccess, "delete password failed: {status}");
1178            }
1179            Ok(())
1180        })
1181    }
1182}
1183
1184impl MacPlatform {
1185    unsafe fn read_string_from_clipboard(
1186        &self,
1187        state: &MacPlatformState,
1188        text_bytes: &[u8],
1189    ) -> ClipboardItem {
1190        unsafe {
1191            let text = String::from_utf8_lossy(text_bytes).to_string();
1192            let metadata = self
1193                .read_from_pasteboard(state.pasteboard, state.text_hash_pasteboard_type)
1194                .and_then(|hash_bytes| {
1195                    let hash_bytes = hash_bytes.try_into().ok()?;
1196                    let hash = u64::from_be_bytes(hash_bytes);
1197                    let metadata = self
1198                        .read_from_pasteboard(state.pasteboard, state.metadata_pasteboard_type)?;
1199
1200                    if hash == ClipboardString::text_hash(&text) {
1201                        String::from_utf8(metadata.to_vec()).ok()
1202                    } else {
1203                        None
1204                    }
1205                });
1206
1207            ClipboardItem {
1208                entries: vec![ClipboardEntry::String(ClipboardString { text, metadata })],
1209            }
1210        }
1211    }
1212
1213    unsafe fn write_plaintext_to_clipboard(&self, string: &ClipboardString) {
1214        unsafe {
1215            let state = self.0.lock();
1216            state.pasteboard.clearContents();
1217
1218            let text_bytes = NSData::dataWithBytes_length_(
1219                nil,
1220                string.text.as_ptr() as *const c_void,
1221                string.text.len() as u64,
1222            );
1223            state
1224                .pasteboard
1225                .setData_forType(text_bytes, NSPasteboardTypeString);
1226
1227            if let Some(metadata) = string.metadata.as_ref() {
1228                let hash_bytes = ClipboardString::text_hash(&string.text).to_be_bytes();
1229                let hash_bytes = NSData::dataWithBytes_length_(
1230                    nil,
1231                    hash_bytes.as_ptr() as *const c_void,
1232                    hash_bytes.len() as u64,
1233                );
1234                state
1235                    .pasteboard
1236                    .setData_forType(hash_bytes, state.text_hash_pasteboard_type);
1237
1238                let metadata_bytes = NSData::dataWithBytes_length_(
1239                    nil,
1240                    metadata.as_ptr() as *const c_void,
1241                    metadata.len() as u64,
1242                );
1243                state
1244                    .pasteboard
1245                    .setData_forType(metadata_bytes, state.metadata_pasteboard_type);
1246            }
1247        }
1248    }
1249
1250    unsafe fn write_image_to_clipboard(&self, image: &Image) {
1251        unsafe {
1252            let state = self.0.lock();
1253            state.pasteboard.clearContents();
1254
1255            let bytes = NSData::dataWithBytes_length_(
1256                nil,
1257                image.bytes.as_ptr() as *const c_void,
1258                image.bytes.len() as u64,
1259            );
1260
1261            state
1262                .pasteboard
1263                .setData_forType(bytes, Into::<UTType>::into(image.format).inner_mut());
1264        }
1265    }
1266}
1267
1268fn try_clipboard_image(pasteboard: id, format: ImageFormat) -> Option<ClipboardItem> {
1269    let mut ut_type: UTType = format.into();
1270
1271    unsafe {
1272        let types: id = pasteboard.types();
1273        if msg_send![types, containsObject: ut_type.inner()] {
1274            let data = pasteboard.dataForType(ut_type.inner_mut());
1275            if data == nil {
1276                None
1277            } else {
1278                let bytes = Vec::from(slice::from_raw_parts(
1279                    data.bytes() as *mut u8,
1280                    data.length() as usize,
1281                ));
1282                let id = hash(&bytes);
1283
1284                Some(ClipboardItem {
1285                    entries: vec![ClipboardEntry::Image(Image { format, bytes, id })],
1286                })
1287            }
1288        } else {
1289            None
1290        }
1291    }
1292}
1293
1294unsafe fn path_from_objc(path: id) -> PathBuf {
1295    let len = msg_send![path, lengthOfBytesUsingEncoding: NSUTF8StringEncoding];
1296    let bytes = unsafe { path.UTF8String() as *const u8 };
1297    let path = str::from_utf8(unsafe { slice::from_raw_parts(bytes, len) }).unwrap();
1298    PathBuf::from(path)
1299}
1300
1301unsafe fn get_mac_platform(object: &mut Object) -> &MacPlatform {
1302    unsafe {
1303        let platform_ptr: *mut c_void = *object.get_ivar(MAC_PLATFORM_IVAR);
1304        assert!(!platform_ptr.is_null());
1305        &*(platform_ptr as *const MacPlatform)
1306    }
1307}
1308
1309extern "C" fn did_finish_launching(this: &mut Object, _: Sel, _: id) {
1310    unsafe {
1311        let app: id = msg_send![APP_CLASS, sharedApplication];
1312        app.setActivationPolicy_(NSApplicationActivationPolicyRegular);
1313
1314        let notification_center: *mut Object =
1315            msg_send![class!(NSNotificationCenter), defaultCenter];
1316        let name = ns_string("NSTextInputContextKeyboardSelectionDidChangeNotification");
1317        let _: () = msg_send![notification_center, addObserver: this as id
1318            selector: sel!(onKeyboardLayoutChange:)
1319            name: name
1320            object: nil
1321        ];
1322
1323        let platform = get_mac_platform(this);
1324        let callback = platform.0.lock().finish_launching.take();
1325        if let Some(callback) = callback {
1326            callback();
1327        }
1328    }
1329}
1330
1331extern "C" fn should_handle_reopen(this: &mut Object, _: Sel, _: id, has_open_windows: bool) {
1332    if !has_open_windows {
1333        let platform = unsafe { get_mac_platform(this) };
1334        let mut lock = platform.0.lock();
1335        if let Some(mut callback) = lock.reopen.take() {
1336            drop(lock);
1337            callback();
1338            platform.0.lock().reopen.get_or_insert(callback);
1339        }
1340    }
1341}
1342
1343extern "C" fn will_terminate(this: &mut Object, _: Sel, _: id) {
1344    let platform = unsafe { get_mac_platform(this) };
1345    let mut lock = platform.0.lock();
1346    if let Some(mut callback) = lock.quit.take() {
1347        drop(lock);
1348        callback();
1349        platform.0.lock().quit.get_or_insert(callback);
1350    }
1351}
1352
1353extern "C" fn on_keyboard_layout_change(this: &mut Object, _: Sel, _: id) {
1354    let platform = unsafe { get_mac_platform(this) };
1355    let mut lock = platform.0.lock();
1356    if let Some(mut callback) = lock.on_keyboard_layout_change.take() {
1357        drop(lock);
1358        callback();
1359        platform
1360            .0
1361            .lock()
1362            .on_keyboard_layout_change
1363            .get_or_insert(callback);
1364    }
1365}
1366
1367extern "C" fn open_urls(this: &mut Object, _: Sel, _: id, urls: id) {
1368    let urls = unsafe {
1369        (0..urls.count())
1370            .filter_map(|i| {
1371                let url = urls.objectAtIndex(i);
1372                match CStr::from_ptr(url.absoluteString().UTF8String() as *mut c_char).to_str() {
1373                    Ok(string) => Some(string.to_string()),
1374                    Err(err) => {
1375                        log::error!("error converting path to string: {}", err);
1376                        None
1377                    }
1378                }
1379            })
1380            .collect::<Vec<_>>()
1381    };
1382    let platform = unsafe { get_mac_platform(this) };
1383    let mut lock = platform.0.lock();
1384    if let Some(mut callback) = lock.open_urls.take() {
1385        drop(lock);
1386        callback(urls);
1387        platform.0.lock().open_urls.get_or_insert(callback);
1388    }
1389}
1390
1391extern "C" fn handle_menu_item(this: &mut Object, _: Sel, item: id) {
1392    unsafe {
1393        let platform = get_mac_platform(this);
1394        let mut lock = platform.0.lock();
1395        if let Some(mut callback) = lock.menu_command.take() {
1396            let tag: NSInteger = msg_send![item, tag];
1397            let index = tag as usize;
1398            if let Some(action) = lock.menu_actions.get(index) {
1399                let action = action.boxed_clone();
1400                drop(lock);
1401                callback(&*action);
1402            }
1403            platform.0.lock().menu_command.get_or_insert(callback);
1404        }
1405    }
1406}
1407
1408extern "C" fn validate_menu_item(this: &mut Object, _: Sel, item: id) -> bool {
1409    unsafe {
1410        let mut result = false;
1411        let platform = get_mac_platform(this);
1412        let mut lock = platform.0.lock();
1413        if let Some(mut callback) = lock.validate_menu_command.take() {
1414            let tag: NSInteger = msg_send![item, tag];
1415            let index = tag as usize;
1416            if let Some(action) = lock.menu_actions.get(index) {
1417                let action = action.boxed_clone();
1418                drop(lock);
1419                result = callback(action.as_ref());
1420            }
1421            platform
1422                .0
1423                .lock()
1424                .validate_menu_command
1425                .get_or_insert(callback);
1426        }
1427        result
1428    }
1429}
1430
1431extern "C" fn menu_will_open(this: &mut Object, _: Sel, _: id) {
1432    unsafe {
1433        let platform = get_mac_platform(this);
1434        let mut lock = platform.0.lock();
1435        if let Some(mut callback) = lock.will_open_menu.take() {
1436            drop(lock);
1437            callback();
1438            platform.0.lock().will_open_menu.get_or_insert(callback);
1439        }
1440    }
1441}
1442
1443extern "C" fn handle_dock_menu(this: &mut Object, _: Sel, _: id) -> id {
1444    unsafe {
1445        let platform = get_mac_platform(this);
1446        let mut state = platform.0.lock();
1447        if let Some(id) = state.dock_menu {
1448            id
1449        } else {
1450            nil
1451        }
1452    }
1453}
1454
1455unsafe fn ns_string(string: &str) -> id {
1456    unsafe { NSString::alloc(nil).init_str(string).autorelease() }
1457}
1458
1459unsafe fn ns_url_to_path(url: id) -> Result<PathBuf> {
1460    let path: *mut c_char = msg_send![url, fileSystemRepresentation];
1461    anyhow::ensure!(!path.is_null(), "url is not a file path: {}", unsafe {
1462        CStr::from_ptr(url.absoluteString().UTF8String()).to_string_lossy()
1463    });
1464    Ok(PathBuf::from(OsStr::from_bytes(unsafe {
1465        CStr::from_ptr(path).to_bytes()
1466    })))
1467}
1468
1469#[link(name = "Carbon", kind = "framework")]
1470unsafe extern "C" {
1471    pub(super) fn TISCopyCurrentKeyboardLayoutInputSource() -> *mut Object;
1472    pub(super) fn TISGetInputSourceProperty(
1473        inputSource: *mut Object,
1474        propertyKey: *const c_void,
1475    ) -> *mut Object;
1476
1477    pub(super) fn UCKeyTranslate(
1478        keyLayoutPtr: *const ::std::os::raw::c_void,
1479        virtualKeyCode: u16,
1480        keyAction: u16,
1481        modifierKeyState: u32,
1482        keyboardType: u32,
1483        keyTranslateOptions: u32,
1484        deadKeyState: *mut u32,
1485        maxStringLength: usize,
1486        actualStringLength: *mut usize,
1487        unicodeString: *mut u16,
1488    ) -> u32;
1489    pub(super) fn LMGetKbdType() -> u16;
1490    pub(super) static kTISPropertyUnicodeKeyLayoutData: CFStringRef;
1491    pub(super) static kTISPropertyInputSourceID: CFStringRef;
1492    pub(super) static kTISPropertyLocalizedName: CFStringRef;
1493}
1494
1495mod security {
1496    #![allow(non_upper_case_globals)]
1497    use super::*;
1498
1499    #[link(name = "Security", kind = "framework")]
1500    unsafe extern "C" {
1501        pub static kSecClass: CFStringRef;
1502        pub static kSecClassInternetPassword: CFStringRef;
1503        pub static kSecAttrServer: CFStringRef;
1504        pub static kSecAttrAccount: CFStringRef;
1505        pub static kSecValueData: CFStringRef;
1506        pub static kSecReturnAttributes: CFStringRef;
1507        pub static kSecReturnData: CFStringRef;
1508
1509        pub fn SecItemAdd(attributes: CFDictionaryRef, result: *mut CFTypeRef) -> OSStatus;
1510        pub fn SecItemUpdate(query: CFDictionaryRef, attributes: CFDictionaryRef) -> OSStatus;
1511        pub fn SecItemDelete(query: CFDictionaryRef) -> OSStatus;
1512        pub fn SecItemCopyMatching(query: CFDictionaryRef, result: *mut CFTypeRef) -> OSStatus;
1513    }
1514
1515    pub const errSecSuccess: OSStatus = 0;
1516    pub const errSecUserCanceled: OSStatus = -128;
1517    pub const errSecItemNotFound: OSStatus = -25300;
1518}
1519
1520impl From<ImageFormat> for UTType {
1521    fn from(value: ImageFormat) -> Self {
1522        match value {
1523            ImageFormat::Png => Self::png(),
1524            ImageFormat::Jpeg => Self::jpeg(),
1525            ImageFormat::Tiff => Self::tiff(),
1526            ImageFormat::Webp => Self::webp(),
1527            ImageFormat::Gif => Self::gif(),
1528            ImageFormat::Bmp => Self::bmp(),
1529            ImageFormat::Svg => Self::svg(),
1530        }
1531    }
1532}
1533
1534// See https://developer.apple.com/documentation/uniformtypeidentifiers/uttype-swift.struct/
1535struct UTType(id);
1536
1537impl UTType {
1538    pub fn png() -> Self {
1539        // https://developer.apple.com/documentation/uniformtypeidentifiers/uttype-swift.struct/png
1540        Self(unsafe { NSPasteboardTypePNG }) // This is a rare case where there's a built-in NSPasteboardType
1541    }
1542
1543    pub fn jpeg() -> Self {
1544        // https://developer.apple.com/documentation/uniformtypeidentifiers/uttype-swift.struct/jpeg
1545        Self(unsafe { ns_string("public.jpeg") })
1546    }
1547
1548    pub fn gif() -> Self {
1549        // https://developer.apple.com/documentation/uniformtypeidentifiers/uttype-swift.struct/gif
1550        Self(unsafe { ns_string("com.compuserve.gif") })
1551    }
1552
1553    pub fn webp() -> Self {
1554        // https://developer.apple.com/documentation/uniformtypeidentifiers/uttype-swift.struct/webp
1555        Self(unsafe { ns_string("org.webmproject.webp") })
1556    }
1557
1558    pub fn bmp() -> Self {
1559        // https://developer.apple.com/documentation/uniformtypeidentifiers/uttype-swift.struct/bmp
1560        Self(unsafe { ns_string("com.microsoft.bmp") })
1561    }
1562
1563    pub fn svg() -> Self {
1564        // https://developer.apple.com/documentation/uniformtypeidentifiers/uttype-swift.struct/svg
1565        Self(unsafe { ns_string("public.svg-image") })
1566    }
1567
1568    pub fn tiff() -> Self {
1569        // https://developer.apple.com/documentation/uniformtypeidentifiers/uttype-swift.struct/tiff
1570        Self(unsafe { NSPasteboardTypeTIFF }) // This is a rare case where there's a built-in NSPasteboardType
1571    }
1572
1573    fn inner(&self) -> *const Object {
1574        self.0
1575    }
1576
1577    fn inner_mut(&self) -> *mut Object {
1578        self.0 as *mut _
1579    }
1580}
1581
1582#[cfg(test)]
1583mod tests {
1584    use crate::ClipboardItem;
1585
1586    use super::*;
1587
1588    #[test]
1589    fn test_clipboard() {
1590        let platform = build_platform();
1591        assert_eq!(platform.read_from_clipboard(), None);
1592
1593        let item = ClipboardItem::new_string("1".to_string());
1594        platform.write_to_clipboard(item.clone());
1595        assert_eq!(platform.read_from_clipboard(), Some(item));
1596
1597        let item = ClipboardItem {
1598            entries: vec![ClipboardEntry::String(
1599                ClipboardString::new("2".to_string()).with_json_metadata(vec![3, 4]),
1600            )],
1601        };
1602        platform.write_to_clipboard(item.clone());
1603        assert_eq!(platform.read_from_clipboard(), Some(item));
1604
1605        let text_from_other_app = "text from other app";
1606        unsafe {
1607            let bytes = NSData::dataWithBytes_length_(
1608                nil,
1609                text_from_other_app.as_ptr() as *const c_void,
1610                text_from_other_app.len() as u64,
1611            );
1612            platform
1613                .0
1614                .lock()
1615                .pasteboard
1616                .setData_forType(bytes, NSPasteboardTypeString);
1617        }
1618        assert_eq!(
1619            platform.read_from_clipboard(),
1620            Some(ClipboardItem::new_string(text_from_other_app.to_string()))
1621        );
1622    }
1623
1624    fn build_platform() -> MacPlatform {
1625        let platform = MacPlatform::new(false);
1626        platform.0.lock().pasteboard = unsafe { NSPasteboard::pasteboardWithUniqueName(nil) };
1627        platform
1628    }
1629}