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