platform.rs

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