platform.rs

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