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