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