platform.rs

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