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