platform.rs

   1use super::{
   2    BoolExt,
   3    attributed_string::{NSAttributedString, NSMutableAttributedString},
   4    events::key_to_native,
   5    is_macos_version_at_least, 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, NSOperatingSystemVersion,
  26        NSProcessInfo, NSRange, NSString, 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 Self::os_version() >= SemanticVersion::new(12, 0, 0) {
 357                                let _: () = msg_send![item, setAllowsAutomaticKeyEquivalentLocalization: NO];
 358                            }
 359                            item.setKeyEquivalentModifierMask_(mask);
 360                        } else {
 361                            item = NSMenuItem::alloc(nil)
 362                                .initWithTitle_action_keyEquivalent_(
 363                                    ns_string(&name),
 364                                    selector,
 365                                    ns_string(""),
 366                                )
 367                                .autorelease();
 368                        }
 369                    } else {
 370                        item = NSMenuItem::alloc(nil)
 371                            .initWithTitle_action_keyEquivalent_(
 372                                ns_string(&name),
 373                                selector,
 374                                ns_string(""),
 375                            )
 376                            .autorelease();
 377                    }
 378
 379                    let tag = actions.len() as NSInteger;
 380                    let _: () = msg_send![item, setTag: tag];
 381                    actions.push(action);
 382                    item
 383                }
 384                MenuItem::Submenu(Menu { name, items }) => {
 385                    let item = NSMenuItem::new(nil).autorelease();
 386                    let submenu = NSMenu::new(nil).autorelease();
 387                    submenu.setDelegate_(delegate);
 388                    for item in items {
 389                        submenu.addItem_(Self::create_menu_item(item, delegate, actions, keymap));
 390                    }
 391                    item.setSubmenu_(submenu);
 392                    item.setTitle_(ns_string(&name));
 393                    if name == "Services" {
 394                        let app: id = msg_send![APP_CLASS, sharedApplication];
 395                        app.setServicesMenu_(item);
 396                    }
 397
 398                    item
 399                }
 400            }
 401        }
 402    }
 403
 404    fn os_version() -> SemanticVersion {
 405        let version = unsafe {
 406            let process_info = NSProcessInfo::processInfo(nil);
 407            process_info.operatingSystemVersion()
 408        };
 409        SemanticVersion::new(
 410            version.majorVersion as usize,
 411            version.minorVersion as usize,
 412            version.patchVersion as usize,
 413        )
 414    }
 415}
 416
 417impl Platform for MacPlatform {
 418    fn background_executor(&self) -> BackgroundExecutor {
 419        self.0.lock().background_executor.clone()
 420    }
 421
 422    fn foreground_executor(&self) -> crate::ForegroundExecutor {
 423        self.0.lock().foreground_executor.clone()
 424    }
 425
 426    fn text_system(&self) -> Arc<dyn PlatformTextSystem> {
 427        self.0.lock().text_system.clone()
 428    }
 429
 430    fn run(&self, on_finish_launching: Box<dyn FnOnce()>) {
 431        let mut state = self.0.lock();
 432        if state.headless {
 433            drop(state);
 434            on_finish_launching();
 435            unsafe { CFRunLoopRun() };
 436        } else {
 437            state.finish_launching = Some(on_finish_launching);
 438            drop(state);
 439        }
 440
 441        unsafe {
 442            let app: id = msg_send![APP_CLASS, sharedApplication];
 443            let app_delegate: id = msg_send![APP_DELEGATE_CLASS, new];
 444            app.setDelegate_(app_delegate);
 445
 446            let self_ptr = self as *const Self as *const c_void;
 447            (*app).set_ivar(MAC_PLATFORM_IVAR, self_ptr);
 448            (*app_delegate).set_ivar(MAC_PLATFORM_IVAR, self_ptr);
 449
 450            let pool = NSAutoreleasePool::new(nil);
 451            app.run();
 452            pool.drain();
 453
 454            (*app).set_ivar(MAC_PLATFORM_IVAR, null_mut::<c_void>());
 455            (*NSWindow::delegate(app)).set_ivar(MAC_PLATFORM_IVAR, null_mut::<c_void>());
 456        }
 457    }
 458
 459    fn quit(&self) {
 460        // Quitting the app causes us to close windows, which invokes `Window::on_close` callbacks
 461        // synchronously before this method terminates. If we call `Platform::quit` while holding a
 462        // borrow of the app state (which most of the time we will do), we will end up
 463        // double-borrowing the app state in the `on_close` callbacks for our open windows. To solve
 464        // this, we make quitting the application asynchronous so that we aren't holding borrows to
 465        // the app state on the stack when we actually terminate the app.
 466
 467        use super::dispatcher::{dispatch_get_main_queue, dispatch_sys::dispatch_async_f};
 468
 469        unsafe {
 470            dispatch_async_f(dispatch_get_main_queue(), ptr::null_mut(), Some(quit));
 471        }
 472
 473        unsafe extern "C" fn quit(_: *mut c_void) {
 474            unsafe {
 475                let app = NSApplication::sharedApplication(nil);
 476                let _: () = msg_send![app, terminate: nil];
 477            }
 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 is_screen_capture_supported(&self) -> bool {
 555        let min_version = NSOperatingSystemVersion::new(12, 3, 0);
 556        is_macos_version_at_least(min_version)
 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() < 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() >= SemanticVersion::new(15, 0, 0) {
 739                                            let new_filename = OsStr::from_bytes(
 740                                                &filename.as_bytes()
 741                                                    [..chunks[0].len() + 1 + chunks[1].len()],
 742                                            )
 743                                            .to_owned();
 744                                            result.set_file_name(&new_filename);
 745                                        }
 746                                    }
 747                                    return result;
 748                                })
 749                            }
 750                        }
 751
 752                        if let Some(done_tx) = done_tx.take() {
 753                            let _ = done_tx.send(Ok(result));
 754                        }
 755                    });
 756                    let block = block.copy();
 757                    let _: () = msg_send![panel, beginWithCompletionHandler: block];
 758                }
 759            })
 760            .detach();
 761
 762        done_rx
 763    }
 764
 765    fn can_select_mixed_files_and_dirs(&self) -> bool {
 766        true
 767    }
 768
 769    fn reveal_path(&self, path: &Path) {
 770        unsafe {
 771            let path = path.to_path_buf();
 772            self.0
 773                .lock()
 774                .background_executor
 775                .spawn(async move {
 776                    let full_path = ns_string(path.to_str().unwrap_or(""));
 777                    let root_full_path = ns_string("");
 778                    let workspace: id = msg_send![class!(NSWorkspace), sharedWorkspace];
 779                    let _: BOOL = msg_send![
 780                        workspace,
 781                        selectFile: full_path
 782                        inFileViewerRootedAtPath: root_full_path
 783                    ];
 784                })
 785                .detach();
 786        }
 787    }
 788
 789    fn open_with_system(&self, path: &Path) {
 790        let path = path.to_owned();
 791        self.0
 792            .lock()
 793            .background_executor
 794            .spawn(async move {
 795                let _ = std::process::Command::new("open")
 796                    .arg(path)
 797                    .spawn()
 798                    .context("invoking open command")
 799                    .log_err();
 800            })
 801            .detach();
 802    }
 803
 804    fn on_quit(&self, callback: Box<dyn FnMut()>) {
 805        self.0.lock().quit = Some(callback);
 806    }
 807
 808    fn on_reopen(&self, callback: Box<dyn FnMut()>) {
 809        self.0.lock().reopen = Some(callback);
 810    }
 811
 812    fn on_keyboard_layout_change(&self, callback: Box<dyn FnMut()>) {
 813        self.0.lock().on_keyboard_layout_change = Some(callback);
 814    }
 815
 816    fn on_app_menu_action(&self, callback: Box<dyn FnMut(&dyn Action)>) {
 817        self.0.lock().menu_command = Some(callback);
 818    }
 819
 820    fn on_will_open_app_menu(&self, callback: Box<dyn FnMut()>) {
 821        self.0.lock().will_open_menu = Some(callback);
 822    }
 823
 824    fn on_validate_app_menu_command(&self, callback: Box<dyn FnMut(&dyn Action) -> bool>) {
 825        self.0.lock().validate_menu_command = Some(callback);
 826    }
 827
 828    fn keyboard_layout(&self) -> String {
 829        unsafe {
 830            let current_keyboard = TISCopyCurrentKeyboardLayoutInputSource();
 831
 832            let input_source_id: *mut Object = TISGetInputSourceProperty(
 833                current_keyboard,
 834                kTISPropertyInputSourceID as *const c_void,
 835            );
 836            let input_source_id: *const std::os::raw::c_char =
 837                msg_send![input_source_id, UTF8String];
 838            let input_source_id = CStr::from_ptr(input_source_id).to_str().unwrap();
 839
 840            input_source_id.to_string()
 841        }
 842    }
 843
 844    fn app_path(&self) -> Result<PathBuf> {
 845        unsafe {
 846            let bundle: id = NSBundle::mainBundle();
 847            if bundle.is_null() {
 848                Err(anyhow!("app is not running inside a bundle"))
 849            } else {
 850                Ok(path_from_objc(msg_send![bundle, bundlePath]))
 851            }
 852        }
 853    }
 854
 855    fn set_menus(&self, menus: Vec<Menu>, keymap: &Keymap) {
 856        unsafe {
 857            let app: id = msg_send![APP_CLASS, sharedApplication];
 858            let mut state = self.0.lock();
 859            let actions = &mut state.menu_actions;
 860            let menu = self.create_menu_bar(menus, NSWindow::delegate(app), actions, keymap);
 861            drop(state);
 862            app.setMainMenu_(menu);
 863        }
 864    }
 865
 866    fn set_dock_menu(&self, menu: Vec<MenuItem>, keymap: &Keymap) {
 867        unsafe {
 868            let app: id = msg_send![APP_CLASS, sharedApplication];
 869            let mut state = self.0.lock();
 870            let actions = &mut state.menu_actions;
 871            let new = self.create_dock_menu(menu, NSWindow::delegate(app), actions, keymap);
 872            if let Some(old) = state.dock_menu.replace(new) {
 873                CFRelease(old as _)
 874            }
 875        }
 876    }
 877
 878    fn add_recent_document(&self, path: &Path) {
 879        if let Some(path_str) = path.to_str() {
 880            unsafe {
 881                let document_controller: id =
 882                    msg_send![class!(NSDocumentController), sharedDocumentController];
 883                let url: id = NSURL::fileURLWithPath_(nil, ns_string(path_str));
 884                let _: () = msg_send![document_controller, noteNewRecentDocumentURL:url];
 885            }
 886        }
 887    }
 888
 889    fn path_for_auxiliary_executable(&self, name: &str) -> Result<PathBuf> {
 890        unsafe {
 891            let bundle: id = NSBundle::mainBundle();
 892            if bundle.is_null() {
 893                Err(anyhow!("app is not running inside a bundle"))
 894            } else {
 895                let name = ns_string(name);
 896                let url: id = msg_send![bundle, URLForAuxiliaryExecutable: name];
 897                if url.is_null() {
 898                    Err(anyhow!("resource not found"))
 899                } else {
 900                    ns_url_to_path(url)
 901                }
 902            }
 903        }
 904    }
 905
 906    /// Match cursor style to one of the styles available
 907    /// in macOS's [NSCursor](https://developer.apple.com/documentation/appkit/nscursor).
 908    fn set_cursor_style(&self, style: CursorStyle) {
 909        unsafe {
 910            if style == CursorStyle::None {
 911                let _: () = msg_send![class!(NSCursor), setHiddenUntilMouseMoves:YES];
 912                return;
 913            }
 914
 915            let new_cursor: id = match style {
 916                CursorStyle::Arrow => msg_send![class!(NSCursor), arrowCursor],
 917                CursorStyle::IBeam => msg_send![class!(NSCursor), IBeamCursor],
 918                CursorStyle::Crosshair => msg_send![class!(NSCursor), crosshairCursor],
 919                CursorStyle::ClosedHand => msg_send![class!(NSCursor), closedHandCursor],
 920                CursorStyle::OpenHand => msg_send![class!(NSCursor), openHandCursor],
 921                CursorStyle::PointingHand => msg_send![class!(NSCursor), pointingHandCursor],
 922                CursorStyle::ResizeLeftRight => msg_send![class!(NSCursor), resizeLeftRightCursor],
 923                CursorStyle::ResizeUpDown => msg_send![class!(NSCursor), resizeUpDownCursor],
 924                CursorStyle::ResizeLeft => msg_send![class!(NSCursor), resizeLeftCursor],
 925                CursorStyle::ResizeRight => msg_send![class!(NSCursor), resizeRightCursor],
 926                CursorStyle::ResizeColumn => msg_send![class!(NSCursor), resizeLeftRightCursor],
 927                CursorStyle::ResizeRow => msg_send![class!(NSCursor), resizeUpDownCursor],
 928                CursorStyle::ResizeUp => msg_send![class!(NSCursor), resizeUpCursor],
 929                CursorStyle::ResizeDown => msg_send![class!(NSCursor), resizeDownCursor],
 930
 931                // Undocumented, private class methods:
 932                // https://stackoverflow.com/questions/27242353/cocoa-predefined-resize-mouse-cursor
 933                CursorStyle::ResizeUpLeftDownRight => {
 934                    msg_send![class!(NSCursor), _windowResizeNorthWestSouthEastCursor]
 935                }
 936                CursorStyle::ResizeUpRightDownLeft => {
 937                    msg_send![class!(NSCursor), _windowResizeNorthEastSouthWestCursor]
 938                }
 939
 940                CursorStyle::IBeamCursorForVerticalLayout => {
 941                    msg_send![class!(NSCursor), IBeamCursorForVerticalLayout]
 942                }
 943                CursorStyle::OperationNotAllowed => {
 944                    msg_send![class!(NSCursor), operationNotAllowedCursor]
 945                }
 946                CursorStyle::DragLink => msg_send![class!(NSCursor), dragLinkCursor],
 947                CursorStyle::DragCopy => msg_send![class!(NSCursor), dragCopyCursor],
 948                CursorStyle::ContextualMenu => msg_send![class!(NSCursor), contextualMenuCursor],
 949                CursorStyle::None => unreachable!(),
 950            };
 951
 952            let old_cursor: id = msg_send![class!(NSCursor), currentCursor];
 953            if new_cursor != old_cursor {
 954                let _: () = msg_send![new_cursor, set];
 955            }
 956        }
 957    }
 958
 959    fn should_auto_hide_scrollbars(&self) -> bool {
 960        #[allow(non_upper_case_globals)]
 961        const NSScrollerStyleOverlay: NSInteger = 1;
 962
 963        unsafe {
 964            let style: NSInteger = msg_send![class!(NSScroller), preferredScrollerStyle];
 965            style == NSScrollerStyleOverlay
 966        }
 967    }
 968
 969    fn write_to_clipboard(&self, item: ClipboardItem) {
 970        use crate::ClipboardEntry;
 971
 972        unsafe {
 973            // We only want to use NSAttributedString if there are multiple entries to write.
 974            if item.entries.len() <= 1 {
 975                match item.entries.first() {
 976                    Some(entry) => match entry {
 977                        ClipboardEntry::String(string) => {
 978                            self.write_plaintext_to_clipboard(string);
 979                        }
 980                        ClipboardEntry::Image(image) => {
 981                            self.write_image_to_clipboard(image);
 982                        }
 983                    },
 984                    None => {
 985                        // Writing an empty list of entries just clears the clipboard.
 986                        let state = self.0.lock();
 987                        state.pasteboard.clearContents();
 988                    }
 989                }
 990            } else {
 991                let mut any_images = false;
 992                let attributed_string = {
 993                    let mut buf = NSMutableAttributedString::alloc(nil)
 994                        // TODO can we skip this? Or at least part of it?
 995                        .init_attributed_string(NSString::alloc(nil).init_str(""));
 996
 997                    for entry in item.entries {
 998                        if let ClipboardEntry::String(ClipboardString { text, metadata: _ }) = entry
 999                        {
1000                            let to_append = NSAttributedString::alloc(nil)
1001                                .init_attributed_string(NSString::alloc(nil).init_str(&text));
1002
1003                            buf.appendAttributedString_(to_append);
1004                        }
1005                    }
1006
1007                    buf
1008                };
1009
1010                let state = self.0.lock();
1011                state.pasteboard.clearContents();
1012
1013                // Only set rich text clipboard types if we actually have 1+ images to include.
1014                if any_images {
1015                    let rtfd_data = attributed_string.RTFDFromRange_documentAttributes_(
1016                        NSRange::new(0, msg_send![attributed_string, length]),
1017                        nil,
1018                    );
1019                    if rtfd_data != nil {
1020                        state
1021                            .pasteboard
1022                            .setData_forType(rtfd_data, NSPasteboardTypeRTFD);
1023                    }
1024
1025                    let rtf_data = attributed_string.RTFFromRange_documentAttributes_(
1026                        NSRange::new(0, attributed_string.length()),
1027                        nil,
1028                    );
1029                    if rtf_data != nil {
1030                        state
1031                            .pasteboard
1032                            .setData_forType(rtf_data, NSPasteboardTypeRTF);
1033                    }
1034                }
1035
1036                let plain_text = attributed_string.string();
1037                state
1038                    .pasteboard
1039                    .setString_forType(plain_text, NSPasteboardTypeString);
1040            }
1041        }
1042    }
1043
1044    fn read_from_clipboard(&self) -> Option<ClipboardItem> {
1045        let state = self.0.lock();
1046        let pasteboard = state.pasteboard;
1047
1048        // First, see if it's a string.
1049        unsafe {
1050            let types: id = pasteboard.types();
1051            let string_type: id = ns_string("public.utf8-plain-text");
1052
1053            if msg_send![types, containsObject: string_type] {
1054                let data = pasteboard.dataForType(string_type);
1055                if data == nil {
1056                    return None;
1057                } else if data.bytes().is_null() {
1058                    // https://developer.apple.com/documentation/foundation/nsdata/1410616-bytes?language=objc
1059                    // "If the length of the NSData object is 0, this property returns nil."
1060                    return Some(self.read_string_from_clipboard(&state, &[]));
1061                } else {
1062                    let bytes =
1063                        slice::from_raw_parts(data.bytes() as *mut u8, data.length() as usize);
1064
1065                    return Some(self.read_string_from_clipboard(&state, bytes));
1066                }
1067            }
1068
1069            // If it wasn't a string, try the various supported image types.
1070            for format in ImageFormat::iter() {
1071                if let Some(item) = try_clipboard_image(pasteboard, format) {
1072                    return Some(item);
1073                }
1074            }
1075        }
1076
1077        // If it wasn't a string or a supported image type, give up.
1078        None
1079    }
1080
1081    fn write_credentials(&self, url: &str, username: &str, password: &[u8]) -> Task<Result<()>> {
1082        let url = url.to_string();
1083        let username = username.to_string();
1084        let password = password.to_vec();
1085        self.background_executor().spawn(async move {
1086            unsafe {
1087                use security::*;
1088
1089                let url = CFString::from(url.as_str());
1090                let username = CFString::from(username.as_str());
1091                let password = CFData::from_buffer(&password);
1092
1093                // First, check if there are already credentials for the given server. If so, then
1094                // update the username and password.
1095                let mut verb = "updating";
1096                let mut query_attrs = CFMutableDictionary::with_capacity(2);
1097                query_attrs.set(kSecClass as *const _, kSecClassInternetPassword as *const _);
1098                query_attrs.set(kSecAttrServer as *const _, url.as_CFTypeRef());
1099
1100                let mut attrs = CFMutableDictionary::with_capacity(4);
1101                attrs.set(kSecClass as *const _, kSecClassInternetPassword as *const _);
1102                attrs.set(kSecAttrServer as *const _, url.as_CFTypeRef());
1103                attrs.set(kSecAttrAccount as *const _, username.as_CFTypeRef());
1104                attrs.set(kSecValueData as *const _, password.as_CFTypeRef());
1105
1106                let mut status = SecItemUpdate(
1107                    query_attrs.as_concrete_TypeRef(),
1108                    attrs.as_concrete_TypeRef(),
1109                );
1110
1111                // If there were no existing credentials for the given server, then create them.
1112                if status == errSecItemNotFound {
1113                    verb = "creating";
1114                    status = SecItemAdd(attrs.as_concrete_TypeRef(), ptr::null_mut());
1115                }
1116
1117                if status != errSecSuccess {
1118                    return Err(anyhow!("{} password failed: {}", verb, status));
1119                }
1120            }
1121            Ok(())
1122        })
1123    }
1124
1125    fn read_credentials(&self, url: &str) -> Task<Result<Option<(String, Vec<u8>)>>> {
1126        let url = url.to_string();
1127        self.background_executor().spawn(async move {
1128            let url = CFString::from(url.as_str());
1129            let cf_true = CFBoolean::true_value().as_CFTypeRef();
1130
1131            unsafe {
1132                use security::*;
1133
1134                // Find any credentials for the given server URL.
1135                let mut attrs = CFMutableDictionary::with_capacity(5);
1136                attrs.set(kSecClass as *const _, kSecClassInternetPassword as *const _);
1137                attrs.set(kSecAttrServer as *const _, url.as_CFTypeRef());
1138                attrs.set(kSecReturnAttributes as *const _, cf_true);
1139                attrs.set(kSecReturnData as *const _, cf_true);
1140
1141                let mut result = CFTypeRef::from(ptr::null());
1142                let status = SecItemCopyMatching(attrs.as_concrete_TypeRef(), &mut result);
1143                match status {
1144                    security::errSecSuccess => {}
1145                    security::errSecItemNotFound | security::errSecUserCanceled => return Ok(None),
1146                    _ => return Err(anyhow!("reading password failed: {}", status)),
1147                }
1148
1149                let result = CFType::wrap_under_create_rule(result)
1150                    .downcast::<CFDictionary>()
1151                    .ok_or_else(|| anyhow!("keychain item was not a dictionary"))?;
1152                let username = result
1153                    .find(kSecAttrAccount as *const _)
1154                    .ok_or_else(|| anyhow!("account was missing from keychain item"))?;
1155                let username = CFType::wrap_under_get_rule(*username)
1156                    .downcast::<CFString>()
1157                    .ok_or_else(|| anyhow!("account was not a string"))?;
1158                let password = result
1159                    .find(kSecValueData as *const _)
1160                    .ok_or_else(|| anyhow!("password was missing from keychain item"))?;
1161                let password = CFType::wrap_under_get_rule(*password)
1162                    .downcast::<CFData>()
1163                    .ok_or_else(|| anyhow!("password was not a string"))?;
1164
1165                Ok(Some((username.to_string(), password.bytes().to_vec())))
1166            }
1167        })
1168    }
1169
1170    fn delete_credentials(&self, url: &str) -> Task<Result<()>> {
1171        let url = url.to_string();
1172
1173        self.background_executor().spawn(async move {
1174            unsafe {
1175                use security::*;
1176
1177                let url = CFString::from(url.as_str());
1178                let mut query_attrs = CFMutableDictionary::with_capacity(2);
1179                query_attrs.set(kSecClass as *const _, kSecClassInternetPassword as *const _);
1180                query_attrs.set(kSecAttrServer as *const _, url.as_CFTypeRef());
1181
1182                let status = SecItemDelete(query_attrs.as_concrete_TypeRef());
1183
1184                if status != errSecSuccess {
1185                    return Err(anyhow!("delete password failed: {}", status));
1186                }
1187            }
1188            Ok(())
1189        })
1190    }
1191}
1192
1193impl MacPlatform {
1194    unsafe fn read_string_from_clipboard(
1195        &self,
1196        state: &MacPlatformState,
1197        text_bytes: &[u8],
1198    ) -> ClipboardItem {
1199        unsafe {
1200            let text = String::from_utf8_lossy(text_bytes).to_string();
1201            let metadata = self
1202                .read_from_pasteboard(state.pasteboard, state.text_hash_pasteboard_type)
1203                .and_then(|hash_bytes| {
1204                    let hash_bytes = hash_bytes.try_into().ok()?;
1205                    let hash = u64::from_be_bytes(hash_bytes);
1206                    let metadata = self
1207                        .read_from_pasteboard(state.pasteboard, state.metadata_pasteboard_type)?;
1208
1209                    if hash == ClipboardString::text_hash(&text) {
1210                        String::from_utf8(metadata.to_vec()).ok()
1211                    } else {
1212                        None
1213                    }
1214                });
1215
1216            ClipboardItem {
1217                entries: vec![ClipboardEntry::String(ClipboardString { text, metadata })],
1218            }
1219        }
1220    }
1221
1222    unsafe fn write_plaintext_to_clipboard(&self, string: &ClipboardString) {
1223        unsafe {
1224            let state = self.0.lock();
1225            state.pasteboard.clearContents();
1226
1227            let text_bytes = NSData::dataWithBytes_length_(
1228                nil,
1229                string.text.as_ptr() as *const c_void,
1230                string.text.len() as u64,
1231            );
1232            state
1233                .pasteboard
1234                .setData_forType(text_bytes, NSPasteboardTypeString);
1235
1236            if let Some(metadata) = string.metadata.as_ref() {
1237                let hash_bytes = ClipboardString::text_hash(&string.text).to_be_bytes();
1238                let hash_bytes = NSData::dataWithBytes_length_(
1239                    nil,
1240                    hash_bytes.as_ptr() as *const c_void,
1241                    hash_bytes.len() as u64,
1242                );
1243                state
1244                    .pasteboard
1245                    .setData_forType(hash_bytes, state.text_hash_pasteboard_type);
1246
1247                let metadata_bytes = NSData::dataWithBytes_length_(
1248                    nil,
1249                    metadata.as_ptr() as *const c_void,
1250                    metadata.len() as u64,
1251                );
1252                state
1253                    .pasteboard
1254                    .setData_forType(metadata_bytes, state.metadata_pasteboard_type);
1255            }
1256        }
1257    }
1258
1259    unsafe fn write_image_to_clipboard(&self, image: &Image) {
1260        unsafe {
1261            let state = self.0.lock();
1262            state.pasteboard.clearContents();
1263
1264            let bytes = NSData::dataWithBytes_length_(
1265                nil,
1266                image.bytes.as_ptr() as *const c_void,
1267                image.bytes.len() as u64,
1268            );
1269
1270            state
1271                .pasteboard
1272                .setData_forType(bytes, Into::<UTType>::into(image.format).inner_mut());
1273        }
1274    }
1275}
1276
1277fn try_clipboard_image(pasteboard: id, format: ImageFormat) -> Option<ClipboardItem> {
1278    let mut ut_type: UTType = format.into();
1279
1280    unsafe {
1281        let types: id = pasteboard.types();
1282        if msg_send![types, containsObject: ut_type.inner()] {
1283            let data = pasteboard.dataForType(ut_type.inner_mut());
1284            if data == nil {
1285                None
1286            } else {
1287                let bytes = Vec::from(slice::from_raw_parts(
1288                    data.bytes() as *mut u8,
1289                    data.length() as usize,
1290                ));
1291                let id = hash(&bytes);
1292
1293                Some(ClipboardItem {
1294                    entries: vec![ClipboardEntry::Image(Image { format, bytes, id })],
1295                })
1296            }
1297        } else {
1298            None
1299        }
1300    }
1301}
1302
1303unsafe fn path_from_objc(path: id) -> PathBuf {
1304    let len = msg_send![path, lengthOfBytesUsingEncoding: NSUTF8StringEncoding];
1305    let bytes = unsafe { path.UTF8String() as *const u8 };
1306    let path = str::from_utf8(unsafe { slice::from_raw_parts(bytes, len) }).unwrap();
1307    PathBuf::from(path)
1308}
1309
1310unsafe fn get_mac_platform(object: &mut Object) -> &MacPlatform {
1311    unsafe {
1312        let platform_ptr: *mut c_void = *object.get_ivar(MAC_PLATFORM_IVAR);
1313        assert!(!platform_ptr.is_null());
1314        &*(platform_ptr as *const MacPlatform)
1315    }
1316}
1317
1318extern "C" fn did_finish_launching(this: &mut Object, _: Sel, _: id) {
1319    unsafe {
1320        let app: id = msg_send![APP_CLASS, sharedApplication];
1321        app.setActivationPolicy_(NSApplicationActivationPolicyRegular);
1322
1323        let notification_center: *mut Object =
1324            msg_send![class!(NSNotificationCenter), defaultCenter];
1325        let name = ns_string("NSTextInputContextKeyboardSelectionDidChangeNotification");
1326        let _: () = msg_send![notification_center, addObserver: this as id
1327            selector: sel!(onKeyboardLayoutChange:)
1328            name: name
1329            object: nil
1330        ];
1331
1332        let platform = get_mac_platform(this);
1333        let callback = platform.0.lock().finish_launching.take();
1334        if let Some(callback) = callback {
1335            callback();
1336        }
1337    }
1338}
1339
1340extern "C" fn should_handle_reopen(this: &mut Object, _: Sel, _: id, has_open_windows: bool) {
1341    if !has_open_windows {
1342        let platform = unsafe { get_mac_platform(this) };
1343        let mut lock = platform.0.lock();
1344        if let Some(mut callback) = lock.reopen.take() {
1345            drop(lock);
1346            callback();
1347            platform.0.lock().reopen.get_or_insert(callback);
1348        }
1349    }
1350}
1351
1352extern "C" fn will_terminate(this: &mut Object, _: Sel, _: id) {
1353    let platform = unsafe { get_mac_platform(this) };
1354    let mut lock = platform.0.lock();
1355    if let Some(mut callback) = lock.quit.take() {
1356        drop(lock);
1357        callback();
1358        platform.0.lock().quit.get_or_insert(callback);
1359    }
1360}
1361
1362extern "C" fn on_keyboard_layout_change(this: &mut Object, _: Sel, _: id) {
1363    let platform = unsafe { get_mac_platform(this) };
1364    let mut lock = platform.0.lock();
1365    if let Some(mut callback) = lock.on_keyboard_layout_change.take() {
1366        drop(lock);
1367        callback();
1368        platform
1369            .0
1370            .lock()
1371            .on_keyboard_layout_change
1372            .get_or_insert(callback);
1373    }
1374}
1375
1376extern "C" fn open_urls(this: &mut Object, _: Sel, _: id, urls: id) {
1377    let urls = unsafe {
1378        (0..urls.count())
1379            .filter_map(|i| {
1380                let url = urls.objectAtIndex(i);
1381                match CStr::from_ptr(url.absoluteString().UTF8String() as *mut c_char).to_str() {
1382                    Ok(string) => Some(string.to_string()),
1383                    Err(err) => {
1384                        log::error!("error converting path to string: {}", err);
1385                        None
1386                    }
1387                }
1388            })
1389            .collect::<Vec<_>>()
1390    };
1391    let platform = unsafe { get_mac_platform(this) };
1392    let mut lock = platform.0.lock();
1393    if let Some(mut callback) = lock.open_urls.take() {
1394        drop(lock);
1395        callback(urls);
1396        platform.0.lock().open_urls.get_or_insert(callback);
1397    }
1398}
1399
1400extern "C" fn handle_menu_item(this: &mut Object, _: Sel, item: id) {
1401    unsafe {
1402        let platform = get_mac_platform(this);
1403        let mut lock = platform.0.lock();
1404        if let Some(mut callback) = lock.menu_command.take() {
1405            let tag: NSInteger = msg_send![item, tag];
1406            let index = tag as usize;
1407            if let Some(action) = lock.menu_actions.get(index) {
1408                let action = action.boxed_clone();
1409                drop(lock);
1410                callback(&*action);
1411            }
1412            platform.0.lock().menu_command.get_or_insert(callback);
1413        }
1414    }
1415}
1416
1417extern "C" fn validate_menu_item(this: &mut Object, _: Sel, item: id) -> bool {
1418    unsafe {
1419        let mut result = false;
1420        let platform = get_mac_platform(this);
1421        let mut lock = platform.0.lock();
1422        if let Some(mut callback) = lock.validate_menu_command.take() {
1423            let tag: NSInteger = msg_send![item, tag];
1424            let index = tag as usize;
1425            if let Some(action) = lock.menu_actions.get(index) {
1426                let action = action.boxed_clone();
1427                drop(lock);
1428                result = callback(action.as_ref());
1429            }
1430            platform
1431                .0
1432                .lock()
1433                .validate_menu_command
1434                .get_or_insert(callback);
1435        }
1436        result
1437    }
1438}
1439
1440extern "C" fn menu_will_open(this: &mut Object, _: Sel, _: id) {
1441    unsafe {
1442        let platform = get_mac_platform(this);
1443        let mut lock = platform.0.lock();
1444        if let Some(mut callback) = lock.will_open_menu.take() {
1445            drop(lock);
1446            callback();
1447            platform.0.lock().will_open_menu.get_or_insert(callback);
1448        }
1449    }
1450}
1451
1452extern "C" fn handle_dock_menu(this: &mut Object, _: Sel, _: id) -> id {
1453    unsafe {
1454        let platform = get_mac_platform(this);
1455        let mut state = platform.0.lock();
1456        if let Some(id) = state.dock_menu {
1457            id
1458        } else {
1459            nil
1460        }
1461    }
1462}
1463
1464unsafe fn ns_string(string: &str) -> id {
1465    unsafe { NSString::alloc(nil).init_str(string).autorelease() }
1466}
1467
1468unsafe fn ns_url_to_path(url: id) -> Result<PathBuf> {
1469    let path: *mut c_char = msg_send![url, fileSystemRepresentation];
1470    if path.is_null() {
1471        Err(anyhow!("url is not a file path: {}", unsafe {
1472            CStr::from_ptr(url.absoluteString().UTF8String()).to_string_lossy()
1473        }))
1474    } else {
1475        Ok(PathBuf::from(OsStr::from_bytes(unsafe {
1476            CStr::from_ptr(path).to_bytes()
1477        })))
1478    }
1479}
1480
1481#[link(name = "Carbon", kind = "framework")]
1482unsafe extern "C" {
1483    pub(super) fn TISCopyCurrentKeyboardLayoutInputSource() -> *mut Object;
1484    pub(super) fn TISGetInputSourceProperty(
1485        inputSource: *mut Object,
1486        propertyKey: *const c_void,
1487    ) -> *mut Object;
1488
1489    pub(super) fn UCKeyTranslate(
1490        keyLayoutPtr: *const ::std::os::raw::c_void,
1491        virtualKeyCode: u16,
1492        keyAction: u16,
1493        modifierKeyState: u32,
1494        keyboardType: u32,
1495        keyTranslateOptions: u32,
1496        deadKeyState: *mut u32,
1497        maxStringLength: usize,
1498        actualStringLength: *mut usize,
1499        unicodeString: *mut u16,
1500    ) -> u32;
1501    pub(super) fn LMGetKbdType() -> u16;
1502    pub(super) static kTISPropertyUnicodeKeyLayoutData: CFStringRef;
1503    pub(super) static kTISPropertyInputSourceID: CFStringRef;
1504}
1505
1506mod security {
1507    #![allow(non_upper_case_globals)]
1508    use super::*;
1509
1510    #[link(name = "Security", kind = "framework")]
1511    unsafe extern "C" {
1512        pub static kSecClass: CFStringRef;
1513        pub static kSecClassInternetPassword: CFStringRef;
1514        pub static kSecAttrServer: CFStringRef;
1515        pub static kSecAttrAccount: CFStringRef;
1516        pub static kSecValueData: CFStringRef;
1517        pub static kSecReturnAttributes: CFStringRef;
1518        pub static kSecReturnData: CFStringRef;
1519
1520        pub fn SecItemAdd(attributes: CFDictionaryRef, result: *mut CFTypeRef) -> OSStatus;
1521        pub fn SecItemUpdate(query: CFDictionaryRef, attributes: CFDictionaryRef) -> OSStatus;
1522        pub fn SecItemDelete(query: CFDictionaryRef) -> OSStatus;
1523        pub fn SecItemCopyMatching(query: CFDictionaryRef, result: *mut CFTypeRef) -> OSStatus;
1524    }
1525
1526    pub const errSecSuccess: OSStatus = 0;
1527    pub const errSecUserCanceled: OSStatus = -128;
1528    pub const errSecItemNotFound: OSStatus = -25300;
1529}
1530
1531impl From<ImageFormat> for UTType {
1532    fn from(value: ImageFormat) -> Self {
1533        match value {
1534            ImageFormat::Png => Self::png(),
1535            ImageFormat::Jpeg => Self::jpeg(),
1536            ImageFormat::Tiff => Self::tiff(),
1537            ImageFormat::Webp => Self::webp(),
1538            ImageFormat::Gif => Self::gif(),
1539            ImageFormat::Bmp => Self::bmp(),
1540            ImageFormat::Svg => Self::svg(),
1541        }
1542    }
1543}
1544
1545// See https://developer.apple.com/documentation/uniformtypeidentifiers/uttype-swift.struct/
1546struct UTType(id);
1547
1548impl UTType {
1549    pub fn png() -> Self {
1550        // https://developer.apple.com/documentation/uniformtypeidentifiers/uttype-swift.struct/png
1551        Self(unsafe { NSPasteboardTypePNG }) // This is a rare case where there's a built-in NSPasteboardType
1552    }
1553
1554    pub fn jpeg() -> Self {
1555        // https://developer.apple.com/documentation/uniformtypeidentifiers/uttype-swift.struct/jpeg
1556        Self(unsafe { ns_string("public.jpeg") })
1557    }
1558
1559    pub fn gif() -> Self {
1560        // https://developer.apple.com/documentation/uniformtypeidentifiers/uttype-swift.struct/gif
1561        Self(unsafe { ns_string("com.compuserve.gif") })
1562    }
1563
1564    pub fn webp() -> Self {
1565        // https://developer.apple.com/documentation/uniformtypeidentifiers/uttype-swift.struct/webp
1566        Self(unsafe { ns_string("org.webmproject.webp") })
1567    }
1568
1569    pub fn bmp() -> Self {
1570        // https://developer.apple.com/documentation/uniformtypeidentifiers/uttype-swift.struct/bmp
1571        Self(unsafe { ns_string("com.microsoft.bmp") })
1572    }
1573
1574    pub fn svg() -> Self {
1575        // https://developer.apple.com/documentation/uniformtypeidentifiers/uttype-swift.struct/svg
1576        Self(unsafe { ns_string("public.svg-image") })
1577    }
1578
1579    pub fn tiff() -> Self {
1580        // https://developer.apple.com/documentation/uniformtypeidentifiers/uttype-swift.struct/tiff
1581        Self(unsafe { NSPasteboardTypeTIFF }) // This is a rare case where there's a built-in NSPasteboardType
1582    }
1583
1584    fn inner(&self) -> *const Object {
1585        self.0
1586    }
1587
1588    fn inner_mut(&self) -> *mut Object {
1589        self.0 as *mut _
1590    }
1591}
1592
1593#[cfg(test)]
1594mod tests {
1595    use crate::ClipboardItem;
1596
1597    use super::*;
1598
1599    #[test]
1600    fn test_clipboard() {
1601        let platform = build_platform();
1602        assert_eq!(platform.read_from_clipboard(), None);
1603
1604        let item = ClipboardItem::new_string("1".to_string());
1605        platform.write_to_clipboard(item.clone());
1606        assert_eq!(platform.read_from_clipboard(), Some(item));
1607
1608        let item = ClipboardItem {
1609            entries: vec![ClipboardEntry::String(
1610                ClipboardString::new("2".to_string()).with_json_metadata(vec![3, 4]),
1611            )],
1612        };
1613        platform.write_to_clipboard(item.clone());
1614        assert_eq!(platform.read_from_clipboard(), Some(item));
1615
1616        let text_from_other_app = "text from other app";
1617        unsafe {
1618            let bytes = NSData::dataWithBytes_length_(
1619                nil,
1620                text_from_other_app.as_ptr() as *const c_void,
1621                text_from_other_app.len() as u64,
1622            );
1623            platform
1624                .0
1625                .lock()
1626                .pasteboard
1627                .setData_forType(bytes, NSPasteboardTypeString);
1628        }
1629        assert_eq!(
1630            platform.read_from_clipboard(),
1631            Some(ClipboardItem::new_string(text_from_other_app.to_string()))
1632        );
1633    }
1634
1635    fn build_platform() -> MacPlatform {
1636        let platform = MacPlatform::new(false);
1637        platform.0.lock().pasteboard = unsafe { NSPasteboard::pasteboardWithUniqueName(nil) };
1638        platform
1639    }
1640}