platform.rs

   1use super::{
   2    attributed_string::{NSAttributedString, NSMutableAttributedString},
   3    events::key_to_native,
   4    renderer, screen_capture, BoolExt,
   5};
   6use crate::{
   7    hash, Action, AnyWindowHandle, BackgroundExecutor, ClipboardEntry, ClipboardItem,
   8    ClipboardString, CursorStyle, ForegroundExecutor, Image, ImageFormat, Keymap, MacDispatcher,
   9    MacDisplay, MacWindow, Menu, MenuItem, PathPromptOptions, Platform, PlatformDisplay,
  10    PlatformTextSystem, PlatformWindow, Result, ScreenCaptureSource, SemanticVersion, Task,
  11    WindowAppearance, WindowParams,
  12};
  13use anyhow::{anyhow, Context as _};
  14use block::ConcreteBlock;
  15use cocoa::{
  16    appkit::{
  17        NSApplication, NSApplicationActivationPolicy::NSApplicationActivationPolicyRegular,
  18        NSEventModifierFlags, NSMenu, NSMenuItem, NSModalResponse, NSOpenPanel, NSPasteboard,
  19        NSPasteboardTypePNG, NSPasteboardTypeRTF, NSPasteboardTypeRTFD, NSPasteboardTypeString,
  20        NSPasteboardTypeTIFF, NSSavePanel, NSWindow,
  21    },
  22    base::{id, nil, selector, BOOL, NO, YES},
  23    foundation::{
  24        NSArray, NSAutoreleasePool, NSBundle, NSData, NSInteger, NSProcessInfo, NSRange, NSString,
  25        NSUInteger, NSURL,
  26    },
  27};
  28use core_foundation::{
  29    base::{CFRelease, CFType, CFTypeRef, OSStatus, TCFType},
  30    boolean::CFBoolean,
  31    data::CFData,
  32    dictionary::{CFDictionary, CFDictionaryRef, CFMutableDictionary},
  33    runloop::CFRunLoopRun,
  34    string::{CFString, CFStringRef},
  35};
  36use ctor::ctor;
  37use futures::channel::oneshot;
  38use objc::{
  39    class,
  40    declare::ClassDecl,
  41    msg_send,
  42    runtime::{Class, Object, Sel},
  43    sel, sel_impl,
  44};
  45use parking_lot::Mutex;
  46use ptr::null_mut;
  47use std::{
  48    cell::Cell,
  49    convert::TryInto,
  50    ffi::{c_void, CStr, OsStr},
  51    os::{raw::c_char, unix::ffi::OsStrExt},
  52    path::{Path, PathBuf},
  53    process::Command,
  54    ptr,
  55    rc::Rc,
  56    slice, str,
  57    sync::Arc,
  58};
  59use strum::IntoEnumIterator;
  60use util::ResultExt;
  61
  62#[allow(non_upper_case_globals)]
  63const NSUTF8StringEncoding: NSUInteger = 4;
  64
  65const MAC_PLATFORM_IVAR: &str = "platform";
  66static mut APP_CLASS: *const Class = ptr::null();
  67static mut APP_DELEGATE_CLASS: *const Class = ptr::null();
  68
  69#[ctor]
  70unsafe fn build_classes() {
  71    APP_CLASS = {
  72        let mut decl = ClassDecl::new("GPUIApplication", class!(NSApplication)).unwrap();
  73        decl.add_ivar::<*mut c_void>(MAC_PLATFORM_IVAR);
  74        decl.register()
  75    };
  76
  77    APP_DELEGATE_CLASS = {
  78        let mut decl = ClassDecl::new("GPUIApplicationDelegate", class!(NSResponder)).unwrap();
  79        decl.add_ivar::<*mut c_void>(MAC_PLATFORM_IVAR);
  80        decl.add_method(
  81            sel!(applicationDidFinishLaunching:),
  82            did_finish_launching as extern "C" fn(&mut Object, Sel, id),
  83        );
  84        decl.add_method(
  85            sel!(applicationShouldHandleReopen:hasVisibleWindows:),
  86            should_handle_reopen as extern "C" fn(&mut Object, Sel, id, bool),
  87        );
  88        decl.add_method(
  89            sel!(applicationWillTerminate:),
  90            will_terminate as extern "C" fn(&mut Object, Sel, id),
  91        );
  92        decl.add_method(
  93            sel!(handleGPUIMenuItem:),
  94            handle_menu_item as extern "C" fn(&mut Object, Sel, id),
  95        );
  96        // Add menu item handlers so that OS save panels have the correct key commands
  97        decl.add_method(
  98            sel!(cut:),
  99            handle_menu_item as extern "C" fn(&mut Object, Sel, id),
 100        );
 101        decl.add_method(
 102            sel!(copy:),
 103            handle_menu_item as extern "C" fn(&mut Object, Sel, id),
 104        );
 105        decl.add_method(
 106            sel!(paste:),
 107            handle_menu_item as extern "C" fn(&mut Object, Sel, id),
 108        );
 109        decl.add_method(
 110            sel!(selectAll:),
 111            handle_menu_item as extern "C" fn(&mut Object, Sel, id),
 112        );
 113        decl.add_method(
 114            sel!(undo:),
 115            handle_menu_item as extern "C" fn(&mut Object, Sel, id),
 116        );
 117        decl.add_method(
 118            sel!(redo:),
 119            handle_menu_item as extern "C" fn(&mut Object, Sel, id),
 120        );
 121        decl.add_method(
 122            sel!(validateMenuItem:),
 123            validate_menu_item as extern "C" fn(&mut Object, Sel, id) -> bool,
 124        );
 125        decl.add_method(
 126            sel!(menuWillOpen:),
 127            menu_will_open as extern "C" fn(&mut Object, Sel, id),
 128        );
 129        decl.add_method(
 130            sel!(applicationDockMenu:),
 131            handle_dock_menu as extern "C" fn(&mut Object, Sel, id) -> id,
 132        );
 133        decl.add_method(
 134            sel!(application:openURLs:),
 135            open_urls as extern "C" fn(&mut Object, Sel, id, id),
 136        );
 137
 138        decl.add_method(
 139            sel!(onKeyboardLayoutChange:),
 140            on_keyboard_layout_change as extern "C" fn(&mut Object, Sel, id),
 141        );
 142
 143        decl.register()
 144    }
 145}
 146
 147pub(crate) struct MacPlatform(Mutex<MacPlatformState>);
 148
 149pub(crate) struct MacPlatformState {
 150    background_executor: BackgroundExecutor,
 151    foreground_executor: ForegroundExecutor,
 152    text_system: Arc<dyn PlatformTextSystem>,
 153    renderer_context: renderer::Context,
 154    headless: bool,
 155    pasteboard: id,
 156    text_hash_pasteboard_type: id,
 157    metadata_pasteboard_type: id,
 158    reopen: Option<Box<dyn FnMut()>>,
 159    on_keyboard_layout_change: Option<Box<dyn FnMut()>>,
 160    quit: Option<Box<dyn FnMut()>>,
 161    menu_command: Option<Box<dyn FnMut(&dyn Action)>>,
 162    validate_menu_command: Option<Box<dyn FnMut(&dyn Action) -> bool>>,
 163    will_open_menu: Option<Box<dyn FnMut()>>,
 164    menu_actions: Vec<Box<dyn Action>>,
 165    open_urls: Option<Box<dyn FnMut(Vec<String>)>>,
 166    finish_launching: Option<Box<dyn FnOnce()>>,
 167    dock_menu: Option<id>,
 168}
 169
 170impl Default for MacPlatform {
 171    fn default() -> Self {
 172        Self::new(false)
 173    }
 174}
 175
 176impl MacPlatform {
 177    pub(crate) fn new(headless: bool) -> Self {
 178        let dispatcher = Arc::new(MacDispatcher::new());
 179
 180        #[cfg(feature = "font-kit")]
 181        let text_system = Arc::new(crate::MacTextSystem::new());
 182
 183        #[cfg(not(feature = "font-kit"))]
 184        let text_system = Arc::new(crate::NoopTextSystem::new());
 185
 186        Self(Mutex::new(MacPlatformState {
 187            headless,
 188            text_system,
 189            background_executor: BackgroundExecutor::new(dispatcher.clone()),
 190            foreground_executor: ForegroundExecutor::new(dispatcher),
 191            renderer_context: renderer::Context::default(),
 192            pasteboard: unsafe { NSPasteboard::generalPasteboard(nil) },
 193            text_hash_pasteboard_type: unsafe { ns_string("zed-text-hash") },
 194            metadata_pasteboard_type: unsafe { ns_string("zed-metadata") },
 195            reopen: None,
 196            quit: None,
 197            menu_command: None,
 198            validate_menu_command: None,
 199            will_open_menu: None,
 200            menu_actions: Default::default(),
 201            open_urls: None,
 202            finish_launching: None,
 203            dock_menu: None,
 204            on_keyboard_layout_change: None,
 205        }))
 206    }
 207
 208    unsafe fn read_from_pasteboard(&self, pasteboard: *mut Object, kind: id) -> Option<&[u8]> {
 209        let data = pasteboard.dataForType(kind);
 210        if data == nil {
 211            None
 212        } else {
 213            Some(slice::from_raw_parts(
 214                data.bytes() as *mut u8,
 215                data.length() as usize,
 216            ))
 217        }
 218    }
 219
 220    unsafe fn create_menu_bar(
 221        &self,
 222        menus: Vec<Menu>,
 223        delegate: id,
 224        actions: &mut Vec<Box<dyn Action>>,
 225        keymap: &Keymap,
 226    ) -> id {
 227        let application_menu = NSMenu::new(nil).autorelease();
 228        application_menu.setDelegate_(delegate);
 229
 230        for menu_config in menus {
 231            let menu = NSMenu::new(nil).autorelease();
 232            let menu_title = ns_string(&menu_config.name);
 233            menu.setTitle_(menu_title);
 234            menu.setDelegate_(delegate);
 235
 236            for item_config in menu_config.items {
 237                menu.addItem_(Self::create_menu_item(
 238                    item_config,
 239                    delegate,
 240                    actions,
 241                    keymap,
 242                ));
 243            }
 244
 245            let menu_item = NSMenuItem::new(nil).autorelease();
 246            menu_item.setTitle_(menu_title);
 247            menu_item.setSubmenu_(menu);
 248            application_menu.addItem_(menu_item);
 249
 250            if menu_config.name == "Window" {
 251                let app: id = msg_send![APP_CLASS, sharedApplication];
 252                app.setWindowsMenu_(menu);
 253            }
 254        }
 255
 256        application_menu
 257    }
 258
 259    unsafe fn create_dock_menu(
 260        &self,
 261        menu_items: Vec<MenuItem>,
 262        delegate: id,
 263        actions: &mut Vec<Box<dyn Action>>,
 264        keymap: &Keymap,
 265    ) -> id {
 266        let dock_menu = NSMenu::new(nil);
 267        dock_menu.setDelegate_(delegate);
 268        for item_config in menu_items {
 269            dock_menu.addItem_(Self::create_menu_item(
 270                item_config,
 271                delegate,
 272                actions,
 273                keymap,
 274            ));
 275        }
 276
 277        dock_menu
 278    }
 279
 280    unsafe fn create_menu_item(
 281        item: MenuItem,
 282        delegate: id,
 283        actions: &mut Vec<Box<dyn Action>>,
 284        keymap: &Keymap,
 285    ) -> id {
 286        match item {
 287            MenuItem::Separator => NSMenuItem::separatorItem(nil),
 288            MenuItem::Action {
 289                name,
 290                action,
 291                os_action,
 292            } => {
 293                // Note that this is not the standard logic for selecting which keybinding to
 294                // display. Typically the last binding takes precedence for display. However, in
 295                // this case the menus are not updated on context changes. To make these bindings
 296                // more likely to be correct, the first binding instead takes precedence (typically
 297                // from the base keymap).
 298                let keystrokes = keymap
 299                    .bindings_for_action(action.as_ref())
 300                    .next()
 301                    .map(|binding| binding.keystrokes());
 302
 303                let selector = match os_action {
 304                    Some(crate::OsAction::Cut) => selector("cut:"),
 305                    Some(crate::OsAction::Copy) => selector("copy:"),
 306                    Some(crate::OsAction::Paste) => selector("paste:"),
 307                    Some(crate::OsAction::SelectAll) => selector("selectAll:"),
 308                    // "undo:" and "redo:" are always disabled in our case, as
 309                    // we don't have a NSTextView/NSTextField to enable them on.
 310                    Some(crate::OsAction::Undo) => selector("handleGPUIMenuItem:"),
 311                    Some(crate::OsAction::Redo) => selector("handleGPUIMenuItem:"),
 312                    None => selector("handleGPUIMenuItem:"),
 313                };
 314
 315                let item;
 316                if let Some(keystrokes) = keystrokes {
 317                    if keystrokes.len() == 1 {
 318                        let keystroke = &keystrokes[0];
 319                        let mut mask = NSEventModifierFlags::empty();
 320                        for (modifier, flag) in &[
 321                            (
 322                                keystroke.modifiers.platform,
 323                                NSEventModifierFlags::NSCommandKeyMask,
 324                            ),
 325                            (
 326                                keystroke.modifiers.control,
 327                                NSEventModifierFlags::NSControlKeyMask,
 328                            ),
 329                            (
 330                                keystroke.modifiers.alt,
 331                                NSEventModifierFlags::NSAlternateKeyMask,
 332                            ),
 333                            (
 334                                keystroke.modifiers.shift,
 335                                NSEventModifierFlags::NSShiftKeyMask,
 336                            ),
 337                        ] {
 338                            if *modifier {
 339                                mask |= *flag;
 340                            }
 341                        }
 342
 343                        item = NSMenuItem::alloc(nil)
 344                            .initWithTitle_action_keyEquivalent_(
 345                                ns_string(&name),
 346                                selector,
 347                                ns_string(key_to_native(&keystroke.key).as_ref()),
 348                            )
 349                            .autorelease();
 350                        if MacPlatform::os_version().unwrap() >= SemanticVersion::new(12, 0, 0) {
 351                            let _: () =
 352                                msg_send![item, setAllowsAutomaticKeyEquivalentLocalization: NO];
 353                        }
 354                        item.setKeyEquivalentModifierMask_(mask);
 355                    }
 356                    // For multi-keystroke bindings, render the keystroke as part of the title.
 357                    else {
 358                        use std::fmt::Write;
 359
 360                        let mut name = format!("{name} [");
 361                        for (i, keystroke) in keystrokes.iter().enumerate() {
 362                            if i > 0 {
 363                                name.push(' ');
 364                            }
 365                            write!(&mut name, "{}", keystroke).unwrap();
 366                        }
 367                        name.push(']');
 368
 369                        item = NSMenuItem::alloc(nil)
 370                            .initWithTitle_action_keyEquivalent_(
 371                                ns_string(&name),
 372                                selector,
 373                                ns_string(""),
 374                            )
 375                            .autorelease();
 376                    }
 377                } else {
 378                    item = NSMenuItem::alloc(nil)
 379                        .initWithTitle_action_keyEquivalent_(
 380                            ns_string(&name),
 381                            selector,
 382                            ns_string(""),
 383                        )
 384                        .autorelease();
 385                }
 386
 387                let tag = actions.len() as NSInteger;
 388                let _: () = msg_send![item, setTag: tag];
 389                actions.push(action);
 390                item
 391            }
 392            MenuItem::Submenu(Menu { name, items }) => {
 393                let item = NSMenuItem::new(nil).autorelease();
 394                let submenu = NSMenu::new(nil).autorelease();
 395                submenu.setDelegate_(delegate);
 396                for item in items {
 397                    submenu.addItem_(Self::create_menu_item(item, delegate, actions, keymap));
 398                }
 399                item.setSubmenu_(submenu);
 400                item.setTitle_(ns_string(&name));
 401                if name == "Services" {
 402                    let app: id = msg_send![APP_CLASS, sharedApplication];
 403                    app.setServicesMenu_(item);
 404                }
 405
 406                item
 407            }
 408        }
 409    }
 410
 411    fn os_version() -> Result<SemanticVersion> {
 412        unsafe {
 413            let process_info = NSProcessInfo::processInfo(nil);
 414            let version = process_info.operatingSystemVersion();
 415            Ok(SemanticVersion::new(
 416                version.majorVersion as usize,
 417                version.minorVersion as usize,
 418                version.patchVersion as usize,
 419            ))
 420        }
 421    }
 422}
 423
 424impl Platform for MacPlatform {
 425    fn background_executor(&self) -> BackgroundExecutor {
 426        self.0.lock().background_executor.clone()
 427    }
 428
 429    fn foreground_executor(&self) -> crate::ForegroundExecutor {
 430        self.0.lock().foreground_executor.clone()
 431    }
 432
 433    fn text_system(&self) -> Arc<dyn PlatformTextSystem> {
 434        self.0.lock().text_system.clone()
 435    }
 436
 437    fn run(&self, on_finish_launching: Box<dyn FnOnce()>) {
 438        let mut state = self.0.lock();
 439        if state.headless {
 440            drop(state);
 441            on_finish_launching();
 442            unsafe { CFRunLoopRun() };
 443        } else {
 444            state.finish_launching = Some(on_finish_launching);
 445            drop(state);
 446        }
 447
 448        unsafe {
 449            let app: id = msg_send![APP_CLASS, sharedApplication];
 450            let app_delegate: id = msg_send![APP_DELEGATE_CLASS, new];
 451            app.setDelegate_(app_delegate);
 452
 453            let self_ptr = self as *const Self as *const c_void;
 454            (*app).set_ivar(MAC_PLATFORM_IVAR, self_ptr);
 455            (*app_delegate).set_ivar(MAC_PLATFORM_IVAR, self_ptr);
 456
 457            let pool = NSAutoreleasePool::new(nil);
 458            app.run();
 459            pool.drain();
 460
 461            (*app).set_ivar(MAC_PLATFORM_IVAR, null_mut::<c_void>());
 462            (*NSWindow::delegate(app)).set_ivar(MAC_PLATFORM_IVAR, null_mut::<c_void>());
 463        }
 464    }
 465
 466    fn quit(&self) {
 467        // Quitting the app causes us to close windows, which invokes `Window::on_close` callbacks
 468        // synchronously before this method terminates. If we call `Platform::quit` while holding a
 469        // borrow of the app state (which most of the time we will do), we will end up
 470        // double-borrowing the app state in the `on_close` callbacks for our open windows. To solve
 471        // this, we make quitting the application asynchronous so that we aren't holding borrows to
 472        // the app state on the stack when we actually terminate the app.
 473
 474        use super::dispatcher::{dispatch_get_main_queue, dispatch_sys::dispatch_async_f};
 475
 476        unsafe {
 477            dispatch_async_f(dispatch_get_main_queue(), ptr::null_mut(), Some(quit));
 478        }
 479
 480        unsafe extern "C" fn quit(_: *mut c_void) {
 481            let app = NSApplication::sharedApplication(nil);
 482            let _: () = msg_send![app, terminate: nil];
 483        }
 484    }
 485
 486    fn restart(&self, _binary_path: Option<PathBuf>) {
 487        use std::os::unix::process::CommandExt as _;
 488
 489        let app_pid = std::process::id().to_string();
 490        let app_path = self
 491            .app_path()
 492            .ok()
 493            // When the app is not bundled, `app_path` returns the
 494            // directory containing the executable. Disregard this
 495            // and get the path to the executable itself.
 496            .and_then(|path| (path.extension()?.to_str()? == "app").then_some(path))
 497            .unwrap_or_else(|| std::env::current_exe().unwrap());
 498
 499        // Wait until this process has exited and then re-open this path.
 500        let script = r#"
 501            while kill -0 $0 2> /dev/null; do
 502                sleep 0.1
 503            done
 504            open "$1"
 505        "#;
 506
 507        let restart_process = Command::new("/bin/bash")
 508            .arg("-c")
 509            .arg(script)
 510            .arg(app_pid)
 511            .arg(app_path)
 512            .process_group(0)
 513            .spawn();
 514
 515        match restart_process {
 516            Ok(_) => self.quit(),
 517            Err(e) => log::error!("failed to spawn restart script: {:?}", e),
 518        }
 519    }
 520
 521    fn activate(&self, ignoring_other_apps: bool) {
 522        unsafe {
 523            let app = NSApplication::sharedApplication(nil);
 524            app.activateIgnoringOtherApps_(ignoring_other_apps.to_objc());
 525        }
 526    }
 527
 528    fn hide(&self) {
 529        unsafe {
 530            let app = NSApplication::sharedApplication(nil);
 531            let _: () = msg_send![app, hide: nil];
 532        }
 533    }
 534
 535    fn hide_other_apps(&self) {
 536        unsafe {
 537            let app = NSApplication::sharedApplication(nil);
 538            let _: () = msg_send![app, hideOtherApplications: nil];
 539        }
 540    }
 541
 542    fn unhide_other_apps(&self) {
 543        unsafe {
 544            let app = NSApplication::sharedApplication(nil);
 545            let _: () = msg_send![app, unhideAllApplications: nil];
 546        }
 547    }
 548
 549    fn primary_display(&self) -> Option<Rc<dyn PlatformDisplay>> {
 550        Some(Rc::new(MacDisplay::primary()))
 551    }
 552
 553    fn displays(&self) -> Vec<Rc<dyn PlatformDisplay>> {
 554        MacDisplay::all()
 555            .map(|screen| Rc::new(screen) as Rc<_>)
 556            .collect()
 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            let new_cursor: id = match style {
 913                CursorStyle::Arrow => msg_send![class!(NSCursor), arrowCursor],
 914                CursorStyle::IBeam => msg_send![class!(NSCursor), IBeamCursor],
 915                CursorStyle::Crosshair => msg_send![class!(NSCursor), crosshairCursor],
 916                CursorStyle::ClosedHand => msg_send![class!(NSCursor), closedHandCursor],
 917                CursorStyle::OpenHand => msg_send![class!(NSCursor), openHandCursor],
 918                CursorStyle::PointingHand => msg_send![class!(NSCursor), pointingHandCursor],
 919                CursorStyle::ResizeLeftRight => msg_send![class!(NSCursor), resizeLeftRightCursor],
 920                CursorStyle::ResizeUpDown => msg_send![class!(NSCursor), resizeUpDownCursor],
 921                CursorStyle::ResizeLeft => msg_send![class!(NSCursor), resizeLeftCursor],
 922                CursorStyle::ResizeRight => msg_send![class!(NSCursor), resizeRightCursor],
 923                CursorStyle::ResizeColumn => msg_send![class!(NSCursor), resizeLeftRightCursor],
 924                CursorStyle::ResizeRow => msg_send![class!(NSCursor), resizeUpDownCursor],
 925                CursorStyle::ResizeUp => msg_send![class!(NSCursor), resizeUpCursor],
 926                CursorStyle::ResizeDown => msg_send![class!(NSCursor), resizeDownCursor],
 927
 928                // Undocumented, private class methods:
 929                // https://stackoverflow.com/questions/27242353/cocoa-predefined-resize-mouse-cursor
 930                CursorStyle::ResizeUpLeftDownRight => {
 931                    msg_send![class!(NSCursor), _windowResizeNorthWestSouthEastCursor]
 932                }
 933                CursorStyle::ResizeUpRightDownLeft => {
 934                    msg_send![class!(NSCursor), _windowResizeNorthEastSouthWestCursor]
 935                }
 936
 937                CursorStyle::IBeamCursorForVerticalLayout => {
 938                    msg_send![class!(NSCursor), IBeamCursorForVerticalLayout]
 939                }
 940                CursorStyle::OperationNotAllowed => {
 941                    msg_send![class!(NSCursor), operationNotAllowedCursor]
 942                }
 943                CursorStyle::DragLink => msg_send![class!(NSCursor), dragLinkCursor],
 944                CursorStyle::DragCopy => msg_send![class!(NSCursor), dragCopyCursor],
 945                CursorStyle::ContextualMenu => msg_send![class!(NSCursor), contextualMenuCursor],
 946            };
 947
 948            let old_cursor: id = msg_send![class!(NSCursor), currentCursor];
 949            if new_cursor != old_cursor {
 950                let _: () = msg_send![new_cursor, set];
 951            }
 952        }
 953    }
 954
 955    fn should_auto_hide_scrollbars(&self) -> bool {
 956        #[allow(non_upper_case_globals)]
 957        const NSScrollerStyleOverlay: NSInteger = 1;
 958
 959        unsafe {
 960            let style: NSInteger = msg_send![class!(NSScroller), preferredScrollerStyle];
 961            style == NSScrollerStyleOverlay
 962        }
 963    }
 964
 965    fn write_to_clipboard(&self, item: ClipboardItem) {
 966        use crate::ClipboardEntry;
 967
 968        unsafe {
 969            // We only want to use NSAttributedString if there are multiple entries to write.
 970            if item.entries.len() <= 1 {
 971                match item.entries.first() {
 972                    Some(entry) => match entry {
 973                        ClipboardEntry::String(string) => {
 974                            self.write_plaintext_to_clipboard(string);
 975                        }
 976                        ClipboardEntry::Image(image) => {
 977                            self.write_image_to_clipboard(image);
 978                        }
 979                    },
 980                    None => {
 981                        // Writing an empty list of entries just clears the clipboard.
 982                        let state = self.0.lock();
 983                        state.pasteboard.clearContents();
 984                    }
 985                }
 986            } else {
 987                let mut any_images = false;
 988                let attributed_string = {
 989                    let mut buf = NSMutableAttributedString::alloc(nil)
 990                        // TODO can we skip this? Or at least part of it?
 991                        .init_attributed_string(NSString::alloc(nil).init_str(""));
 992
 993                    for entry in item.entries {
 994                        if let ClipboardEntry::String(ClipboardString { text, metadata: _ }) = entry
 995                        {
 996                            let to_append = NSAttributedString::alloc(nil)
 997                                .init_attributed_string(NSString::alloc(nil).init_str(&text));
 998
 999                            buf.appendAttributedString_(to_append);
1000                        }
1001                    }
1002
1003                    buf
1004                };
1005
1006                let state = self.0.lock();
1007                state.pasteboard.clearContents();
1008
1009                // Only set rich text clipboard types if we actually have 1+ images to include.
1010                if any_images {
1011                    let rtfd_data = attributed_string.RTFDFromRange_documentAttributes_(
1012                        NSRange::new(0, msg_send![attributed_string, length]),
1013                        nil,
1014                    );
1015                    if rtfd_data != nil {
1016                        state
1017                            .pasteboard
1018                            .setData_forType(rtfd_data, NSPasteboardTypeRTFD);
1019                    }
1020
1021                    let rtf_data = attributed_string.RTFFromRange_documentAttributes_(
1022                        NSRange::new(0, attributed_string.length()),
1023                        nil,
1024                    );
1025                    if rtf_data != nil {
1026                        state
1027                            .pasteboard
1028                            .setData_forType(rtf_data, NSPasteboardTypeRTF);
1029                    }
1030                }
1031
1032                let plain_text = attributed_string.string();
1033                state
1034                    .pasteboard
1035                    .setString_forType(plain_text, NSPasteboardTypeString);
1036            }
1037        }
1038    }
1039
1040    fn read_from_clipboard(&self) -> Option<ClipboardItem> {
1041        let state = self.0.lock();
1042        let pasteboard = state.pasteboard;
1043
1044        // First, see if it's a string.
1045        unsafe {
1046            let types: id = pasteboard.types();
1047            let string_type: id = ns_string("public.utf8-plain-text");
1048
1049            if msg_send![types, containsObject: string_type] {
1050                let data = pasteboard.dataForType(string_type);
1051                if data == nil {
1052                    return None;
1053                } else if data.bytes().is_null() {
1054                    // https://developer.apple.com/documentation/foundation/nsdata/1410616-bytes?language=objc
1055                    // "If the length of the NSData object is 0, this property returns nil."
1056                    return Some(self.read_string_from_clipboard(&state, &[]));
1057                } else {
1058                    let bytes =
1059                        slice::from_raw_parts(data.bytes() as *mut u8, data.length() as usize);
1060
1061                    return Some(self.read_string_from_clipboard(&state, bytes));
1062                }
1063            }
1064
1065            // If it wasn't a string, try the various supported image types.
1066            for format in ImageFormat::iter() {
1067                if let Some(item) = try_clipboard_image(pasteboard, format) {
1068                    return Some(item);
1069                }
1070            }
1071        }
1072
1073        // If it wasn't a string or a supported image type, give up.
1074        None
1075    }
1076
1077    fn write_credentials(&self, url: &str, username: &str, password: &[u8]) -> Task<Result<()>> {
1078        let url = url.to_string();
1079        let username = username.to_string();
1080        let password = password.to_vec();
1081        self.background_executor().spawn(async move {
1082            unsafe {
1083                use security::*;
1084
1085                let url = CFString::from(url.as_str());
1086                let username = CFString::from(username.as_str());
1087                let password = CFData::from_buffer(&password);
1088
1089                // First, check if there are already credentials for the given server. If so, then
1090                // update the username and password.
1091                let mut verb = "updating";
1092                let mut query_attrs = CFMutableDictionary::with_capacity(2);
1093                query_attrs.set(kSecClass as *const _, kSecClassInternetPassword as *const _);
1094                query_attrs.set(kSecAttrServer as *const _, url.as_CFTypeRef());
1095
1096                let mut attrs = CFMutableDictionary::with_capacity(4);
1097                attrs.set(kSecClass as *const _, kSecClassInternetPassword as *const _);
1098                attrs.set(kSecAttrServer as *const _, url.as_CFTypeRef());
1099                attrs.set(kSecAttrAccount as *const _, username.as_CFTypeRef());
1100                attrs.set(kSecValueData as *const _, password.as_CFTypeRef());
1101
1102                let mut status = SecItemUpdate(
1103                    query_attrs.as_concrete_TypeRef(),
1104                    attrs.as_concrete_TypeRef(),
1105                );
1106
1107                // If there were no existing credentials for the given server, then create them.
1108                if status == errSecItemNotFound {
1109                    verb = "creating";
1110                    status = SecItemAdd(attrs.as_concrete_TypeRef(), ptr::null_mut());
1111                }
1112
1113                if status != errSecSuccess {
1114                    return Err(anyhow!("{} password failed: {}", verb, status));
1115                }
1116            }
1117            Ok(())
1118        })
1119    }
1120
1121    fn read_credentials(&self, url: &str) -> Task<Result<Option<(String, Vec<u8>)>>> {
1122        let url = url.to_string();
1123        self.background_executor().spawn(async move {
1124            let url = CFString::from(url.as_str());
1125            let cf_true = CFBoolean::true_value().as_CFTypeRef();
1126
1127            unsafe {
1128                use security::*;
1129
1130                // Find any credentials for the given server URL.
1131                let mut attrs = CFMutableDictionary::with_capacity(5);
1132                attrs.set(kSecClass as *const _, kSecClassInternetPassword as *const _);
1133                attrs.set(kSecAttrServer as *const _, url.as_CFTypeRef());
1134                attrs.set(kSecReturnAttributes as *const _, cf_true);
1135                attrs.set(kSecReturnData as *const _, cf_true);
1136
1137                let mut result = CFTypeRef::from(ptr::null());
1138                let status = SecItemCopyMatching(attrs.as_concrete_TypeRef(), &mut result);
1139                match status {
1140                    security::errSecSuccess => {}
1141                    security::errSecItemNotFound | security::errSecUserCanceled => return Ok(None),
1142                    _ => return Err(anyhow!("reading password failed: {}", status)),
1143                }
1144
1145                let result = CFType::wrap_under_create_rule(result)
1146                    .downcast::<CFDictionary>()
1147                    .ok_or_else(|| anyhow!("keychain item was not a dictionary"))?;
1148                let username = result
1149                    .find(kSecAttrAccount as *const _)
1150                    .ok_or_else(|| anyhow!("account was missing from keychain item"))?;
1151                let username = CFType::wrap_under_get_rule(*username)
1152                    .downcast::<CFString>()
1153                    .ok_or_else(|| anyhow!("account was not a string"))?;
1154                let password = result
1155                    .find(kSecValueData as *const _)
1156                    .ok_or_else(|| anyhow!("password was missing from keychain item"))?;
1157                let password = CFType::wrap_under_get_rule(*password)
1158                    .downcast::<CFData>()
1159                    .ok_or_else(|| anyhow!("password was not a string"))?;
1160
1161                Ok(Some((username.to_string(), password.bytes().to_vec())))
1162            }
1163        })
1164    }
1165
1166    fn delete_credentials(&self, url: &str) -> Task<Result<()>> {
1167        let url = url.to_string();
1168
1169        self.background_executor().spawn(async move {
1170            unsafe {
1171                use security::*;
1172
1173                let url = CFString::from(url.as_str());
1174                let mut query_attrs = CFMutableDictionary::with_capacity(2);
1175                query_attrs.set(kSecClass as *const _, kSecClassInternetPassword as *const _);
1176                query_attrs.set(kSecAttrServer as *const _, url.as_CFTypeRef());
1177
1178                let status = SecItemDelete(query_attrs.as_concrete_TypeRef());
1179
1180                if status != errSecSuccess {
1181                    return Err(anyhow!("delete password failed: {}", status));
1182                }
1183            }
1184            Ok(())
1185        })
1186    }
1187}
1188
1189impl MacPlatform {
1190    unsafe fn read_string_from_clipboard(
1191        &self,
1192        state: &MacPlatformState,
1193        text_bytes: &[u8],
1194    ) -> ClipboardItem {
1195        let text = String::from_utf8_lossy(text_bytes).to_string();
1196        let metadata = self
1197            .read_from_pasteboard(state.pasteboard, state.text_hash_pasteboard_type)
1198            .and_then(|hash_bytes| {
1199                let hash_bytes = hash_bytes.try_into().ok()?;
1200                let hash = u64::from_be_bytes(hash_bytes);
1201                let metadata =
1202                    self.read_from_pasteboard(state.pasteboard, state.metadata_pasteboard_type)?;
1203
1204                if hash == ClipboardString::text_hash(&text) {
1205                    String::from_utf8(metadata.to_vec()).ok()
1206                } else {
1207                    None
1208                }
1209            });
1210
1211        ClipboardItem {
1212            entries: vec![ClipboardEntry::String(ClipboardString { text, metadata })],
1213        }
1214    }
1215
1216    unsafe fn write_plaintext_to_clipboard(&self, string: &ClipboardString) {
1217        let state = self.0.lock();
1218        state.pasteboard.clearContents();
1219
1220        let text_bytes = NSData::dataWithBytes_length_(
1221            nil,
1222            string.text.as_ptr() as *const c_void,
1223            string.text.len() as u64,
1224        );
1225        state
1226            .pasteboard
1227            .setData_forType(text_bytes, NSPasteboardTypeString);
1228
1229        if let Some(metadata) = string.metadata.as_ref() {
1230            let hash_bytes = ClipboardString::text_hash(&string.text).to_be_bytes();
1231            let hash_bytes = NSData::dataWithBytes_length_(
1232                nil,
1233                hash_bytes.as_ptr() as *const c_void,
1234                hash_bytes.len() as u64,
1235            );
1236            state
1237                .pasteboard
1238                .setData_forType(hash_bytes, state.text_hash_pasteboard_type);
1239
1240            let metadata_bytes = NSData::dataWithBytes_length_(
1241                nil,
1242                metadata.as_ptr() as *const c_void,
1243                metadata.len() as u64,
1244            );
1245            state
1246                .pasteboard
1247                .setData_forType(metadata_bytes, state.metadata_pasteboard_type);
1248        }
1249    }
1250
1251    unsafe fn write_image_to_clipboard(&self, image: &Image) {
1252        let state = self.0.lock();
1253        state.pasteboard.clearContents();
1254
1255        let bytes = NSData::dataWithBytes_length_(
1256            nil,
1257            image.bytes.as_ptr() as *const c_void,
1258            image.bytes.len() as u64,
1259        );
1260
1261        state
1262            .pasteboard
1263            .setData_forType(bytes, Into::<UTType>::into(image.format).inner_mut());
1264    }
1265}
1266
1267fn try_clipboard_image(pasteboard: id, format: ImageFormat) -> Option<ClipboardItem> {
1268    let mut ut_type: UTType = format.into();
1269
1270    unsafe {
1271        let types: id = pasteboard.types();
1272        if msg_send![types, containsObject: ut_type.inner()] {
1273            let data = pasteboard.dataForType(ut_type.inner_mut());
1274            if data == nil {
1275                None
1276            } else {
1277                let bytes = Vec::from(slice::from_raw_parts(
1278                    data.bytes() as *mut u8,
1279                    data.length() as usize,
1280                ));
1281                let id = hash(&bytes);
1282
1283                Some(ClipboardItem {
1284                    entries: vec![ClipboardEntry::Image(Image { format, bytes, id })],
1285                })
1286            }
1287        } else {
1288            None
1289        }
1290    }
1291}
1292
1293unsafe fn path_from_objc(path: id) -> PathBuf {
1294    let len = msg_send![path, lengthOfBytesUsingEncoding: NSUTF8StringEncoding];
1295    let bytes = path.UTF8String() as *const u8;
1296    let path = str::from_utf8(slice::from_raw_parts(bytes, len)).unwrap();
1297    PathBuf::from(path)
1298}
1299
1300unsafe fn get_mac_platform(object: &mut Object) -> &MacPlatform {
1301    let platform_ptr: *mut c_void = *object.get_ivar(MAC_PLATFORM_IVAR);
1302    assert!(!platform_ptr.is_null());
1303    &*(platform_ptr as *const MacPlatform)
1304}
1305
1306extern "C" fn did_finish_launching(this: &mut Object, _: Sel, _: id) {
1307    unsafe {
1308        let app: id = msg_send![APP_CLASS, sharedApplication];
1309        app.setActivationPolicy_(NSApplicationActivationPolicyRegular);
1310
1311        let notification_center: *mut Object =
1312            msg_send![class!(NSNotificationCenter), defaultCenter];
1313        let name = ns_string("NSTextInputContextKeyboardSelectionDidChangeNotification");
1314        let _: () = msg_send![notification_center, addObserver: this as id
1315            selector: sel!(onKeyboardLayoutChange:)
1316            name: name
1317            object: nil
1318        ];
1319
1320        let platform = get_mac_platform(this);
1321        let callback = platform.0.lock().finish_launching.take();
1322        if let Some(callback) = callback {
1323            callback();
1324        }
1325    }
1326}
1327
1328extern "C" fn should_handle_reopen(this: &mut Object, _: Sel, _: id, has_open_windows: bool) {
1329    if !has_open_windows {
1330        let platform = unsafe { get_mac_platform(this) };
1331        let mut lock = platform.0.lock();
1332        if let Some(mut callback) = lock.reopen.take() {
1333            drop(lock);
1334            callback();
1335            platform.0.lock().reopen.get_or_insert(callback);
1336        }
1337    }
1338}
1339
1340extern "C" fn will_terminate(this: &mut Object, _: Sel, _: id) {
1341    let platform = unsafe { get_mac_platform(this) };
1342    let mut lock = platform.0.lock();
1343    if let Some(mut callback) = lock.quit.take() {
1344        drop(lock);
1345        callback();
1346        platform.0.lock().quit.get_or_insert(callback);
1347    }
1348}
1349
1350extern "C" fn on_keyboard_layout_change(this: &mut Object, _: Sel, _: id) {
1351    let platform = unsafe { get_mac_platform(this) };
1352    let mut lock = platform.0.lock();
1353    if let Some(mut callback) = lock.on_keyboard_layout_change.take() {
1354        drop(lock);
1355        callback();
1356        platform
1357            .0
1358            .lock()
1359            .on_keyboard_layout_change
1360            .get_or_insert(callback);
1361    }
1362}
1363
1364extern "C" fn open_urls(this: &mut Object, _: Sel, _: id, urls: id) {
1365    let urls = unsafe {
1366        (0..urls.count())
1367            .filter_map(|i| {
1368                let url = urls.objectAtIndex(i);
1369                match CStr::from_ptr(url.absoluteString().UTF8String() as *mut c_char).to_str() {
1370                    Ok(string) => Some(string.to_string()),
1371                    Err(err) => {
1372                        log::error!("error converting path to string: {}", err);
1373                        None
1374                    }
1375                }
1376            })
1377            .collect::<Vec<_>>()
1378    };
1379    let platform = unsafe { get_mac_platform(this) };
1380    let mut lock = platform.0.lock();
1381    if let Some(mut callback) = lock.open_urls.take() {
1382        drop(lock);
1383        callback(urls);
1384        platform.0.lock().open_urls.get_or_insert(callback);
1385    }
1386}
1387
1388extern "C" fn handle_menu_item(this: &mut Object, _: Sel, item: id) {
1389    unsafe {
1390        let platform = get_mac_platform(this);
1391        let mut lock = platform.0.lock();
1392        if let Some(mut callback) = lock.menu_command.take() {
1393            let tag: NSInteger = msg_send![item, tag];
1394            let index = tag as usize;
1395            if let Some(action) = lock.menu_actions.get(index) {
1396                let action = action.boxed_clone();
1397                drop(lock);
1398                callback(&*action);
1399            }
1400            platform.0.lock().menu_command.get_or_insert(callback);
1401        }
1402    }
1403}
1404
1405extern "C" fn validate_menu_item(this: &mut Object, _: Sel, item: id) -> bool {
1406    unsafe {
1407        let mut result = false;
1408        let platform = get_mac_platform(this);
1409        let mut lock = platform.0.lock();
1410        if let Some(mut callback) = lock.validate_menu_command.take() {
1411            let tag: NSInteger = msg_send![item, tag];
1412            let index = tag as usize;
1413            if let Some(action) = lock.menu_actions.get(index) {
1414                let action = action.boxed_clone();
1415                drop(lock);
1416                result = callback(action.as_ref());
1417            }
1418            platform
1419                .0
1420                .lock()
1421                .validate_menu_command
1422                .get_or_insert(callback);
1423        }
1424        result
1425    }
1426}
1427
1428extern "C" fn menu_will_open(this: &mut Object, _: Sel, _: id) {
1429    unsafe {
1430        let platform = get_mac_platform(this);
1431        let mut lock = platform.0.lock();
1432        if let Some(mut callback) = lock.will_open_menu.take() {
1433            drop(lock);
1434            callback();
1435            platform.0.lock().will_open_menu.get_or_insert(callback);
1436        }
1437    }
1438}
1439
1440extern "C" fn handle_dock_menu(this: &mut Object, _: Sel, _: id) -> id {
1441    unsafe {
1442        let platform = get_mac_platform(this);
1443        let mut state = platform.0.lock();
1444        if let Some(id) = state.dock_menu {
1445            id
1446        } else {
1447            nil
1448        }
1449    }
1450}
1451
1452unsafe fn ns_string(string: &str) -> id {
1453    NSString::alloc(nil).init_str(string).autorelease()
1454}
1455
1456unsafe fn ns_url_to_path(url: id) -> Result<PathBuf> {
1457    let path: *mut c_char = msg_send![url, fileSystemRepresentation];
1458    if path.is_null() {
1459        Err(anyhow!(
1460            "url is not a file path: {}",
1461            CStr::from_ptr(url.absoluteString().UTF8String()).to_string_lossy()
1462        ))
1463    } else {
1464        Ok(PathBuf::from(OsStr::from_bytes(
1465            CStr::from_ptr(path).to_bytes(),
1466        )))
1467    }
1468}
1469
1470#[link(name = "Carbon", kind = "framework")]
1471extern "C" {
1472    pub(super) fn TISCopyCurrentKeyboardLayoutInputSource() -> *mut Object;
1473    pub(super) fn TISGetInputSourceProperty(
1474        inputSource: *mut Object,
1475        propertyKey: *const c_void,
1476    ) -> *mut Object;
1477
1478    pub(super) fn UCKeyTranslate(
1479        keyLayoutPtr: *const ::std::os::raw::c_void,
1480        virtualKeyCode: u16,
1481        keyAction: u16,
1482        modifierKeyState: u32,
1483        keyboardType: u32,
1484        keyTranslateOptions: u32,
1485        deadKeyState: *mut u32,
1486        maxStringLength: usize,
1487        actualStringLength: *mut usize,
1488        unicodeString: *mut u16,
1489    ) -> u32;
1490    pub(super) fn LMGetKbdType() -> u16;
1491    pub(super) static kTISPropertyUnicodeKeyLayoutData: CFStringRef;
1492    pub(super) static kTISPropertyInputSourceID: CFStringRef;
1493}
1494
1495mod security {
1496    #![allow(non_upper_case_globals)]
1497    use super::*;
1498
1499    #[link(name = "Security", kind = "framework")]
1500    extern "C" {
1501        pub static kSecClass: CFStringRef;
1502        pub static kSecClassInternetPassword: CFStringRef;
1503        pub static kSecAttrServer: CFStringRef;
1504        pub static kSecAttrAccount: CFStringRef;
1505        pub static kSecValueData: CFStringRef;
1506        pub static kSecReturnAttributes: CFStringRef;
1507        pub static kSecReturnData: CFStringRef;
1508
1509        pub fn SecItemAdd(attributes: CFDictionaryRef, result: *mut CFTypeRef) -> OSStatus;
1510        pub fn SecItemUpdate(query: CFDictionaryRef, attributes: CFDictionaryRef) -> OSStatus;
1511        pub fn SecItemDelete(query: CFDictionaryRef) -> OSStatus;
1512        pub fn SecItemCopyMatching(query: CFDictionaryRef, result: *mut CFTypeRef) -> OSStatus;
1513    }
1514
1515    pub const errSecSuccess: OSStatus = 0;
1516    pub const errSecUserCanceled: OSStatus = -128;
1517    pub const errSecItemNotFound: OSStatus = -25300;
1518}
1519
1520impl From<ImageFormat> for UTType {
1521    fn from(value: ImageFormat) -> Self {
1522        match value {
1523            ImageFormat::Png => Self::png(),
1524            ImageFormat::Jpeg => Self::jpeg(),
1525            ImageFormat::Tiff => Self::tiff(),
1526            ImageFormat::Webp => Self::webp(),
1527            ImageFormat::Gif => Self::gif(),
1528            ImageFormat::Bmp => Self::bmp(),
1529            ImageFormat::Svg => Self::svg(),
1530        }
1531    }
1532}
1533
1534// See https://developer.apple.com/documentation/uniformtypeidentifiers/uttype-swift.struct/
1535struct UTType(id);
1536
1537impl UTType {
1538    pub fn png() -> Self {
1539        // https://developer.apple.com/documentation/uniformtypeidentifiers/uttype-swift.struct/png
1540        Self(unsafe { NSPasteboardTypePNG }) // This is a rare case where there's a built-in NSPasteboardType
1541    }
1542
1543    pub fn jpeg() -> Self {
1544        // https://developer.apple.com/documentation/uniformtypeidentifiers/uttype-swift.struct/jpeg
1545        Self(unsafe { ns_string("public.jpeg") })
1546    }
1547
1548    pub fn gif() -> Self {
1549        // https://developer.apple.com/documentation/uniformtypeidentifiers/uttype-swift.struct/gif
1550        Self(unsafe { ns_string("com.compuserve.gif") })
1551    }
1552
1553    pub fn webp() -> Self {
1554        // https://developer.apple.com/documentation/uniformtypeidentifiers/uttype-swift.struct/webp
1555        Self(unsafe { ns_string("org.webmproject.webp") })
1556    }
1557
1558    pub fn bmp() -> Self {
1559        // https://developer.apple.com/documentation/uniformtypeidentifiers/uttype-swift.struct/bmp
1560        Self(unsafe { ns_string("com.microsoft.bmp") })
1561    }
1562
1563    pub fn svg() -> Self {
1564        // https://developer.apple.com/documentation/uniformtypeidentifiers/uttype-swift.struct/svg
1565        Self(unsafe { ns_string("public.svg-image") })
1566    }
1567
1568    pub fn tiff() -> Self {
1569        // https://developer.apple.com/documentation/uniformtypeidentifiers/uttype-swift.struct/tiff
1570        Self(unsafe { NSPasteboardTypeTIFF }) // This is a rare case where there's a built-in NSPasteboardType
1571    }
1572
1573    fn inner(&self) -> *const Object {
1574        self.0
1575    }
1576
1577    fn inner_mut(&self) -> *mut Object {
1578        self.0 as *mut _
1579    }
1580}
1581
1582#[cfg(test)]
1583mod tests {
1584    use crate::ClipboardItem;
1585
1586    use super::*;
1587
1588    #[test]
1589    fn test_clipboard() {
1590        let platform = build_platform();
1591        assert_eq!(platform.read_from_clipboard(), None);
1592
1593        let item = ClipboardItem::new_string("1".to_string());
1594        platform.write_to_clipboard(item.clone());
1595        assert_eq!(platform.read_from_clipboard(), Some(item));
1596
1597        let item = ClipboardItem {
1598            entries: vec![ClipboardEntry::String(
1599                ClipboardString::new("2".to_string()).with_json_metadata(vec![3, 4]),
1600            )],
1601        };
1602        platform.write_to_clipboard(item.clone());
1603        assert_eq!(platform.read_from_clipboard(), Some(item));
1604
1605        let text_from_other_app = "text from other app";
1606        unsafe {
1607            let bytes = NSData::dataWithBytes_length_(
1608                nil,
1609                text_from_other_app.as_ptr() as *const c_void,
1610                text_from_other_app.len() as u64,
1611            );
1612            platform
1613                .0
1614                .lock()
1615                .pasteboard
1616                .setData_forType(bytes, NSPasteboardTypeString);
1617        }
1618        assert_eq!(
1619            platform.read_from_clipboard(),
1620            Some(ClipboardItem::new_string(text_from_other_app.to_string()))
1621        );
1622    }
1623
1624    fn build_platform() -> MacPlatform {
1625        let platform = MacPlatform::new(false);
1626        platform.0.lock().pasteboard = unsafe { NSPasteboard::pasteboardWithUniqueName(nil) };
1627        platform
1628    }
1629}