platform.rs

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