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