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