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