platform.rs

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