platform.rs

   1use super::{events::key_to_native, BoolExt};
   2use crate::{
   3    Action, AnyWindowHandle, BackgroundExecutor, ClipboardItem, CursorStyle, ForegroundExecutor,
   4    Keymap, MacDispatcher, MacDisplay, MacTextSystem, MacWindow, Menu, MenuItem, PathPromptOptions,
   5    Platform, PlatformDisplay, PlatformTextSystem, PlatformWindow, Result, SemanticVersion, Task,
   6    WindowAppearance, WindowParams,
   7};
   8use anyhow::anyhow;
   9use block::ConcreteBlock;
  10use cocoa::{
  11    appkit::{
  12        NSApplication, NSApplicationActivationPolicy::NSApplicationActivationPolicyRegular,
  13        NSEventModifierFlags, NSMenu, NSMenuItem, NSModalResponse, NSOpenPanel, NSPasteboard,
  14        NSPasteboardTypeString, NSSavePanel, NSWindow,
  15    },
  16    base::{id, nil, selector, BOOL, YES},
  17    foundation::{
  18        NSArray, NSAutoreleasePool, NSBundle, NSData, NSInteger, NSProcessInfo, NSString,
  19        NSUInteger, NSURL,
  20    },
  21};
  22use core_foundation::{
  23    base::{CFRelease, CFType, CFTypeRef, OSStatus, TCFType as _},
  24    boolean::CFBoolean,
  25    data::CFData,
  26    dictionary::{CFDictionary, CFDictionaryRef, CFMutableDictionary},
  27    string::{CFString, CFStringRef},
  28};
  29use ctor::ctor;
  30use futures::channel::oneshot;
  31use objc::{
  32    class,
  33    declare::ClassDecl,
  34    msg_send,
  35    runtime::{Class, Object, Sel},
  36    sel, sel_impl,
  37};
  38use parking_lot::Mutex;
  39use ptr::null_mut;
  40use std::{
  41    cell::Cell,
  42    convert::TryInto,
  43    ffi::{c_void, CStr, OsStr},
  44    os::{raw::c_char, unix::ffi::OsStrExt},
  45    path::{Path, PathBuf},
  46    process::Command,
  47    ptr,
  48    rc::Rc,
  49    slice, str,
  50    sync::Arc,
  51};
  52
  53use super::renderer;
  54
  55#[allow(non_upper_case_globals)]
  56const NSUTF8StringEncoding: NSUInteger = 4;
  57
  58const MAC_PLATFORM_IVAR: &str = "platform";
  59static mut APP_CLASS: *const Class = ptr::null();
  60static mut APP_DELEGATE_CLASS: *const Class = ptr::null();
  61
  62#[ctor]
  63unsafe fn build_classes() {
  64    APP_CLASS = {
  65        let mut decl = ClassDecl::new("GPUIApplication", class!(NSApplication)).unwrap();
  66        decl.add_ivar::<*mut c_void>(MAC_PLATFORM_IVAR);
  67        decl.register()
  68    };
  69
  70    APP_DELEGATE_CLASS = {
  71        let mut decl = ClassDecl::new("GPUIApplicationDelegate", class!(NSResponder)).unwrap();
  72        decl.add_ivar::<*mut c_void>(MAC_PLATFORM_IVAR);
  73        decl.add_method(
  74            sel!(applicationDidFinishLaunching:),
  75            did_finish_launching as extern "C" fn(&mut Object, Sel, id),
  76        );
  77        decl.add_method(
  78            sel!(applicationShouldHandleReopen:hasVisibleWindows:),
  79            should_handle_reopen as extern "C" fn(&mut Object, Sel, id, bool),
  80        );
  81        decl.add_method(
  82            sel!(applicationWillTerminate:),
  83            will_terminate as extern "C" fn(&mut Object, Sel, id),
  84        );
  85        decl.add_method(
  86            sel!(handleGPUIMenuItem:),
  87            handle_menu_item as extern "C" fn(&mut Object, Sel, id),
  88        );
  89        // Add menu item handlers so that OS save panels have the correct key commands
  90        decl.add_method(
  91            sel!(cut:),
  92            handle_menu_item as extern "C" fn(&mut Object, Sel, id),
  93        );
  94        decl.add_method(
  95            sel!(copy:),
  96            handle_menu_item as extern "C" fn(&mut Object, Sel, id),
  97        );
  98        decl.add_method(
  99            sel!(paste:),
 100            handle_menu_item as extern "C" fn(&mut Object, Sel, id),
 101        );
 102        decl.add_method(
 103            sel!(selectAll:),
 104            handle_menu_item as extern "C" fn(&mut Object, Sel, id),
 105        );
 106        decl.add_method(
 107            sel!(undo:),
 108            handle_menu_item as extern "C" fn(&mut Object, Sel, id),
 109        );
 110        decl.add_method(
 111            sel!(redo:),
 112            handle_menu_item as extern "C" fn(&mut Object, Sel, id),
 113        );
 114        decl.add_method(
 115            sel!(validateMenuItem:),
 116            validate_menu_item as extern "C" fn(&mut Object, Sel, id) -> bool,
 117        );
 118        decl.add_method(
 119            sel!(menuWillOpen:),
 120            menu_will_open as extern "C" fn(&mut Object, Sel, id),
 121        );
 122        decl.add_method(
 123            sel!(applicationDockMenu:),
 124            handle_dock_menu as extern "C" fn(&mut Object, Sel, id) -> id,
 125        );
 126        decl.add_method(
 127            sel!(application:openURLs:),
 128            open_urls as extern "C" fn(&mut Object, Sel, id, id),
 129        );
 130
 131        decl.register()
 132    }
 133}
 134
 135pub(crate) struct MacPlatform(Mutex<MacPlatformState>);
 136
 137pub(crate) struct MacPlatformState {
 138    background_executor: BackgroundExecutor,
 139    foreground_executor: ForegroundExecutor,
 140    text_system: Arc<MacTextSystem>,
 141    renderer_context: renderer::Context,
 142    pasteboard: id,
 143    text_hash_pasteboard_type: id,
 144    metadata_pasteboard_type: id,
 145    reopen: Option<Box<dyn FnMut()>>,
 146    quit: Option<Box<dyn FnMut()>>,
 147    menu_command: Option<Box<dyn FnMut(&dyn Action)>>,
 148    validate_menu_command: Option<Box<dyn FnMut(&dyn Action) -> bool>>,
 149    will_open_menu: Option<Box<dyn FnMut()>>,
 150    menu_actions: Vec<Box<dyn Action>>,
 151    open_urls: Option<Box<dyn FnMut(Vec<String>)>>,
 152    finish_launching: Option<Box<dyn FnOnce()>>,
 153    dock_menu: Option<id>,
 154}
 155
 156impl Default for MacPlatform {
 157    fn default() -> Self {
 158        Self::new()
 159    }
 160}
 161
 162impl MacPlatform {
 163    pub(crate) fn new() -> Self {
 164        let dispatcher = Arc::new(MacDispatcher::new());
 165        Self(Mutex::new(MacPlatformState {
 166            background_executor: BackgroundExecutor::new(dispatcher.clone()),
 167            foreground_executor: ForegroundExecutor::new(dispatcher),
 168            text_system: Arc::new(MacTextSystem::new()),
 169            renderer_context: renderer::Context::default(),
 170            pasteboard: unsafe { NSPasteboard::generalPasteboard(nil) },
 171            text_hash_pasteboard_type: unsafe { ns_string("zed-text-hash") },
 172            metadata_pasteboard_type: unsafe { ns_string("zed-metadata") },
 173            reopen: None,
 174            quit: None,
 175            menu_command: None,
 176            validate_menu_command: None,
 177            will_open_menu: None,
 178            menu_actions: Default::default(),
 179            open_urls: None,
 180            finish_launching: None,
 181            dock_menu: None,
 182        }))
 183    }
 184
 185    unsafe fn read_from_pasteboard(&self, pasteboard: *mut Object, kind: id) -> Option<&[u8]> {
 186        let data = pasteboard.dataForType(kind);
 187        if data == nil {
 188            None
 189        } else {
 190            Some(slice::from_raw_parts(
 191                data.bytes() as *mut u8,
 192                data.length() as usize,
 193            ))
 194        }
 195    }
 196
 197    unsafe fn create_menu_bar(
 198        &self,
 199        menus: Vec<Menu>,
 200        delegate: id,
 201        actions: &mut Vec<Box<dyn Action>>,
 202        keymap: &Keymap,
 203    ) -> id {
 204        let application_menu = NSMenu::new(nil).autorelease();
 205        application_menu.setDelegate_(delegate);
 206
 207        for menu_config in menus {
 208            let menu = NSMenu::new(nil).autorelease();
 209            menu.setTitle_(ns_string(menu_config.name));
 210            menu.setDelegate_(delegate);
 211
 212            for item_config in menu_config.items {
 213                menu.addItem_(Self::create_menu_item(
 214                    item_config,
 215                    delegate,
 216                    actions,
 217                    keymap,
 218                ));
 219            }
 220
 221            let menu_item = NSMenuItem::new(nil).autorelease();
 222            menu_item.setSubmenu_(menu);
 223            application_menu.addItem_(menu_item);
 224
 225            if menu_config.name == "Window" {
 226                let app: id = msg_send![APP_CLASS, sharedApplication];
 227                app.setWindowsMenu_(menu);
 228            }
 229        }
 230
 231        application_menu
 232    }
 233
 234    unsafe fn create_dock_menu(
 235        &self,
 236        menu_items: Vec<MenuItem>,
 237        delegate: id,
 238        actions: &mut Vec<Box<dyn Action>>,
 239        keymap: &Keymap,
 240    ) -> id {
 241        let dock_menu = NSMenu::new(nil);
 242        dock_menu.setDelegate_(delegate);
 243        for item_config in menu_items {
 244            dock_menu.addItem_(Self::create_menu_item(
 245                item_config,
 246                delegate,
 247                actions,
 248                keymap,
 249            ));
 250        }
 251
 252        dock_menu
 253    }
 254
 255    unsafe fn create_menu_item(
 256        item: MenuItem,
 257        delegate: id,
 258        actions: &mut Vec<Box<dyn Action>>,
 259        keymap: &Keymap,
 260    ) -> id {
 261        match item {
 262            MenuItem::Separator => NSMenuItem::separatorItem(nil),
 263            MenuItem::Action {
 264                name,
 265                action,
 266                os_action,
 267            } => {
 268                let keystrokes = keymap
 269                    .bindings_for_action(action.as_ref())
 270                    .next()
 271                    .map(|binding| binding.keystrokes());
 272
 273                let selector = match os_action {
 274                    Some(crate::OsAction::Cut) => selector("cut:"),
 275                    Some(crate::OsAction::Copy) => selector("copy:"),
 276                    Some(crate::OsAction::Paste) => selector("paste:"),
 277                    Some(crate::OsAction::SelectAll) => selector("selectAll:"),
 278                    Some(crate::OsAction::Undo) => selector("undo:"),
 279                    Some(crate::OsAction::Redo) => selector("redo:"),
 280                    None => selector("handleGPUIMenuItem:"),
 281                };
 282
 283                let item;
 284                if let Some(keystrokes) = keystrokes {
 285                    if keystrokes.len() == 1 {
 286                        let keystroke = &keystrokes[0];
 287                        let mut mask = NSEventModifierFlags::empty();
 288                        for (modifier, flag) in &[
 289                            (
 290                                keystroke.modifiers.platform,
 291                                NSEventModifierFlags::NSCommandKeyMask,
 292                            ),
 293                            (
 294                                keystroke.modifiers.control,
 295                                NSEventModifierFlags::NSControlKeyMask,
 296                            ),
 297                            (
 298                                keystroke.modifiers.alt,
 299                                NSEventModifierFlags::NSAlternateKeyMask,
 300                            ),
 301                            (
 302                                keystroke.modifiers.shift,
 303                                NSEventModifierFlags::NSShiftKeyMask,
 304                            ),
 305                        ] {
 306                            if *modifier {
 307                                mask |= *flag;
 308                            }
 309                        }
 310
 311                        item = NSMenuItem::alloc(nil)
 312                            .initWithTitle_action_keyEquivalent_(
 313                                ns_string(name),
 314                                selector,
 315                                ns_string(key_to_native(&keystroke.key).as_ref()),
 316                            )
 317                            .autorelease();
 318                        item.setKeyEquivalentModifierMask_(mask);
 319                    }
 320                    // For multi-keystroke bindings, render the keystroke as part of the title.
 321                    else {
 322                        use std::fmt::Write;
 323
 324                        let mut name = format!("{name} [");
 325                        for (i, keystroke) in keystrokes.iter().enumerate() {
 326                            if i > 0 {
 327                                name.push(' ');
 328                            }
 329                            write!(&mut name, "{}", keystroke).unwrap();
 330                        }
 331                        name.push(']');
 332
 333                        item = NSMenuItem::alloc(nil)
 334                            .initWithTitle_action_keyEquivalent_(
 335                                ns_string(&name),
 336                                selector,
 337                                ns_string(""),
 338                            )
 339                            .autorelease();
 340                    }
 341                } else {
 342                    item = NSMenuItem::alloc(nil)
 343                        .initWithTitle_action_keyEquivalent_(
 344                            ns_string(name),
 345                            selector,
 346                            ns_string(""),
 347                        )
 348                        .autorelease();
 349                }
 350
 351                let tag = actions.len() as NSInteger;
 352                let _: () = msg_send![item, setTag: tag];
 353                actions.push(action);
 354                item
 355            }
 356            MenuItem::Submenu(Menu { name, items }) => {
 357                let item = NSMenuItem::new(nil).autorelease();
 358                let submenu = NSMenu::new(nil).autorelease();
 359                submenu.setDelegate_(delegate);
 360                for item in items {
 361                    submenu.addItem_(Self::create_menu_item(item, delegate, actions, keymap));
 362                }
 363                item.setSubmenu_(submenu);
 364                item.setTitle_(ns_string(name));
 365                item
 366            }
 367        }
 368    }
 369
 370    fn os_version(&self) -> Result<SemanticVersion> {
 371        unsafe {
 372            let process_info = NSProcessInfo::processInfo(nil);
 373            let version = process_info.operatingSystemVersion();
 374            Ok(SemanticVersion::new(
 375                version.majorVersion as usize,
 376                version.minorVersion as usize,
 377                version.patchVersion as usize,
 378            ))
 379        }
 380    }
 381}
 382
 383impl Platform for MacPlatform {
 384    fn background_executor(&self) -> BackgroundExecutor {
 385        self.0.lock().background_executor.clone()
 386    }
 387
 388    fn foreground_executor(&self) -> crate::ForegroundExecutor {
 389        self.0.lock().foreground_executor.clone()
 390    }
 391
 392    fn text_system(&self) -> Arc<dyn PlatformTextSystem> {
 393        self.0.lock().text_system.clone()
 394    }
 395
 396    fn run(&self, on_finish_launching: Box<dyn FnOnce()>) {
 397        self.0.lock().finish_launching = Some(on_finish_launching);
 398
 399        unsafe {
 400            let app: id = msg_send![APP_CLASS, sharedApplication];
 401            let app_delegate: id = msg_send![APP_DELEGATE_CLASS, new];
 402            app.setDelegate_(app_delegate);
 403
 404            let self_ptr = self as *const Self as *const c_void;
 405            (*app).set_ivar(MAC_PLATFORM_IVAR, self_ptr);
 406            (*app_delegate).set_ivar(MAC_PLATFORM_IVAR, self_ptr);
 407
 408            let pool = NSAutoreleasePool::new(nil);
 409            app.run();
 410            pool.drain();
 411
 412            (*app).set_ivar(MAC_PLATFORM_IVAR, null_mut::<c_void>());
 413            (*app.delegate()).set_ivar(MAC_PLATFORM_IVAR, null_mut::<c_void>());
 414        }
 415    }
 416
 417    fn quit(&self) {
 418        // Quitting the app causes us to close windows, which invokes `Window::on_close` callbacks
 419        // synchronously before this method terminates. If we call `Platform::quit` while holding a
 420        // borrow of the app state (which most of the time we will do), we will end up
 421        // double-borrowing the app state in the `on_close` callbacks for our open windows. To solve
 422        // this, we make quitting the application asynchronous so that we aren't holding borrows to
 423        // the app state on the stack when we actually terminate the app.
 424
 425        use super::dispatcher::{dispatch_get_main_queue, dispatch_sys::dispatch_async_f};
 426
 427        unsafe {
 428            dispatch_async_f(dispatch_get_main_queue(), ptr::null_mut(), Some(quit));
 429        }
 430
 431        unsafe extern "C" fn quit(_: *mut c_void) {
 432            let app = NSApplication::sharedApplication(nil);
 433            let _: () = msg_send![app, terminate: nil];
 434        }
 435    }
 436
 437    fn restart(&self, _binary_path: Option<PathBuf>) {
 438        use std::os::unix::process::CommandExt as _;
 439
 440        let app_pid = std::process::id().to_string();
 441        let app_path = self
 442            .app_path()
 443            .ok()
 444            // When the app is not bundled, `app_path` returns the
 445            // directory containing the executable. Disregard this
 446            // and get the path to the executable itself.
 447            .and_then(|path| (path.extension()?.to_str()? == "app").then_some(path))
 448            .unwrap_or_else(|| std::env::current_exe().unwrap());
 449
 450        // Wait until this process has exited and then re-open this path.
 451        let script = r#"
 452            while kill -0 $0 2> /dev/null; do
 453                sleep 0.1
 454            done
 455            open "$1"
 456        "#;
 457
 458        let restart_process = Command::new("/bin/bash")
 459            .arg("-c")
 460            .arg(script)
 461            .arg(app_pid)
 462            .arg(app_path)
 463            .process_group(0)
 464            .spawn();
 465
 466        match restart_process {
 467            Ok(_) => self.quit(),
 468            Err(e) => log::error!("failed to spawn restart script: {:?}", e),
 469        }
 470    }
 471
 472    fn activate(&self, ignoring_other_apps: bool) {
 473        unsafe {
 474            let app = NSApplication::sharedApplication(nil);
 475            app.activateIgnoringOtherApps_(ignoring_other_apps.to_objc());
 476        }
 477    }
 478
 479    fn hide(&self) {
 480        unsafe {
 481            let app = NSApplication::sharedApplication(nil);
 482            let _: () = msg_send![app, hide: nil];
 483        }
 484    }
 485
 486    fn hide_other_apps(&self) {
 487        unsafe {
 488            let app = NSApplication::sharedApplication(nil);
 489            let _: () = msg_send![app, hideOtherApplications: nil];
 490        }
 491    }
 492
 493    fn unhide_other_apps(&self) {
 494        unsafe {
 495            let app = NSApplication::sharedApplication(nil);
 496            let _: () = msg_send![app, unhideAllApplications: nil];
 497        }
 498    }
 499
 500    fn primary_display(&self) -> Option<Rc<dyn PlatformDisplay>> {
 501        Some(Rc::new(MacDisplay::primary()))
 502    }
 503
 504    fn displays(&self) -> Vec<Rc<dyn PlatformDisplay>> {
 505        MacDisplay::all()
 506            .map(|screen| Rc::new(screen) as Rc<_>)
 507            .collect()
 508    }
 509
 510    fn active_window(&self) -> Option<AnyWindowHandle> {
 511        MacWindow::active_window()
 512    }
 513
 514    fn open_window(
 515        &self,
 516        handle: AnyWindowHandle,
 517        options: WindowParams,
 518    ) -> Result<Box<dyn PlatformWindow>> {
 519        // Clippy thinks that this evaluates to `()`, for some reason.
 520        #[allow(clippy::unit_arg, clippy::clone_on_copy)]
 521        let renderer_context = self.0.lock().renderer_context.clone();
 522        Ok(Box::new(MacWindow::open(
 523            handle,
 524            options,
 525            self.foreground_executor(),
 526            renderer_context,
 527        )))
 528    }
 529
 530    fn window_appearance(&self) -> WindowAppearance {
 531        unsafe {
 532            let app = NSApplication::sharedApplication(nil);
 533            let appearance: id = msg_send![app, effectiveAppearance];
 534            WindowAppearance::from_native(appearance)
 535        }
 536    }
 537
 538    fn open_url(&self, url: &str) {
 539        unsafe {
 540            let url = NSURL::alloc(nil)
 541                .initWithString_(ns_string(url))
 542                .autorelease();
 543            let workspace: id = msg_send![class!(NSWorkspace), sharedWorkspace];
 544            msg_send![workspace, openURL: url]
 545        }
 546    }
 547
 548    fn register_url_scheme(&self, scheme: &str) -> Task<anyhow::Result<()>> {
 549        // API only available post Monterey
 550        // https://developer.apple.com/documentation/appkit/nsworkspace/3753004-setdefaultapplicationaturl
 551        let (done_tx, done_rx) = oneshot::channel();
 552        if self.os_version().ok() < Some(SemanticVersion::new(12, 0, 0)) {
 553            return Task::ready(Err(anyhow!(
 554                "macOS 12.0 or later is required to register URL schemes"
 555            )));
 556        }
 557
 558        let bundle_id = unsafe {
 559            let bundle: id = msg_send![class!(NSBundle), mainBundle];
 560            let bundle_id: id = msg_send![bundle, bundleIdentifier];
 561            if bundle_id == nil {
 562                return Task::ready(Err(anyhow!("Can only register URL scheme in bundled apps")));
 563            }
 564            bundle_id
 565        };
 566
 567        unsafe {
 568            let workspace: id = msg_send![class!(NSWorkspace), sharedWorkspace];
 569            let scheme: id = ns_string(scheme);
 570            let app: id = msg_send![workspace, URLForApplicationWithBundleIdentifier: bundle_id];
 571            if app == nil {
 572                return Task::ready(Err(anyhow!(
 573                    "Cannot register URL scheme until app is installed"
 574                )));
 575            }
 576            let done_tx = Cell::new(Some(done_tx));
 577            let block = ConcreteBlock::new(move |error: id| {
 578                let result = if error == nil {
 579                    Ok(())
 580                } else {
 581                    let msg: id = msg_send![error, localizedDescription];
 582                    Err(anyhow!("Failed to register: {:?}", msg))
 583                };
 584
 585                if let Some(done_tx) = done_tx.take() {
 586                    let _ = done_tx.send(result);
 587                }
 588            });
 589            let block = block.copy();
 590            let _: () = msg_send![workspace, setDefaultApplicationAtURL: app toOpenURLsWithScheme: scheme completionHandler: block];
 591        }
 592
 593        self.background_executor()
 594            .spawn(async { crate::Flatten::flatten(done_rx.await.map_err(|e| anyhow!(e))) })
 595    }
 596
 597    fn on_open_urls(&self, callback: Box<dyn FnMut(Vec<String>)>) {
 598        self.0.lock().open_urls = Some(callback);
 599    }
 600
 601    fn prompt_for_paths(
 602        &self,
 603        options: PathPromptOptions,
 604    ) -> oneshot::Receiver<Result<Option<Vec<PathBuf>>>> {
 605        let (done_tx, done_rx) = oneshot::channel();
 606        self.foreground_executor()
 607            .spawn(async move {
 608                unsafe {
 609                    let panel = NSOpenPanel::openPanel(nil);
 610                    panel.setCanChooseDirectories_(options.directories.to_objc());
 611                    panel.setCanChooseFiles_(options.files.to_objc());
 612                    panel.setAllowsMultipleSelection_(options.multiple.to_objc());
 613                    panel.setCanCreateDirectories(true.to_objc());
 614                    panel.setResolvesAliases_(false.to_objc());
 615                    let done_tx = Cell::new(Some(done_tx));
 616                    let block = ConcreteBlock::new(move |response: NSModalResponse| {
 617                        let result = if response == NSModalResponse::NSModalResponseOk {
 618                            let mut result = Vec::new();
 619                            let urls = panel.URLs();
 620                            for i in 0..urls.count() {
 621                                let url = urls.objectAtIndex(i);
 622                                if url.isFileURL() == YES {
 623                                    if let Ok(path) = ns_url_to_path(url) {
 624                                        result.push(path)
 625                                    }
 626                                }
 627                            }
 628                            Some(result)
 629                        } else {
 630                            None
 631                        };
 632
 633                        if let Some(done_tx) = done_tx.take() {
 634                            let _ = done_tx.send(Ok(result));
 635                        }
 636                    });
 637                    let block = block.copy();
 638                    let _: () = msg_send![panel, beginWithCompletionHandler: block];
 639                }
 640            })
 641            .detach();
 642        done_rx
 643    }
 644
 645    fn prompt_for_new_path(&self, directory: &Path) -> oneshot::Receiver<Result<Option<PathBuf>>> {
 646        let directory = directory.to_owned();
 647        let (done_tx, done_rx) = oneshot::channel();
 648        self.foreground_executor()
 649            .spawn(async move {
 650                unsafe {
 651                    let panel = NSSavePanel::savePanel(nil);
 652                    let path = ns_string(directory.to_string_lossy().as_ref());
 653                    let url = NSURL::fileURLWithPath_isDirectory_(nil, path, true.to_objc());
 654                    panel.setDirectoryURL(url);
 655
 656                    let done_tx = Cell::new(Some(done_tx));
 657                    let block = ConcreteBlock::new(move |response: NSModalResponse| {
 658                        let mut result = None;
 659                        if response == NSModalResponse::NSModalResponseOk {
 660                            let url = panel.URL();
 661                            if url.isFileURL() == YES {
 662                                result = ns_url_to_path(panel.URL()).ok()
 663                            }
 664                        }
 665
 666                        if let Some(done_tx) = done_tx.take() {
 667                            let _ = done_tx.send(Ok(result));
 668                        }
 669                    });
 670                    let block = block.copy();
 671                    let _: () = msg_send![panel, beginWithCompletionHandler: block];
 672                }
 673            })
 674            .detach();
 675
 676        done_rx
 677    }
 678
 679    fn reveal_path(&self, path: &Path) {
 680        unsafe {
 681            let path = path.to_path_buf();
 682            self.0
 683                .lock()
 684                .background_executor
 685                .spawn(async move {
 686                    let full_path = ns_string(path.to_str().unwrap_or(""));
 687                    let root_full_path = ns_string("");
 688                    let workspace: id = msg_send![class!(NSWorkspace), sharedWorkspace];
 689                    let _: BOOL = msg_send![
 690                        workspace,
 691                        selectFile: full_path
 692                        inFileViewerRootedAtPath: root_full_path
 693                    ];
 694                })
 695                .detach();
 696        }
 697    }
 698
 699    fn on_quit(&self, callback: Box<dyn FnMut()>) {
 700        self.0.lock().quit = Some(callback);
 701    }
 702
 703    fn on_reopen(&self, callback: Box<dyn FnMut()>) {
 704        self.0.lock().reopen = Some(callback);
 705    }
 706
 707    fn on_app_menu_action(&self, callback: Box<dyn FnMut(&dyn Action)>) {
 708        self.0.lock().menu_command = Some(callback);
 709    }
 710
 711    fn on_will_open_app_menu(&self, callback: Box<dyn FnMut()>) {
 712        self.0.lock().will_open_menu = Some(callback);
 713    }
 714
 715    fn on_validate_app_menu_command(&self, callback: Box<dyn FnMut(&dyn Action) -> bool>) {
 716        self.0.lock().validate_menu_command = Some(callback);
 717    }
 718
 719    fn app_path(&self) -> Result<PathBuf> {
 720        unsafe {
 721            let bundle: id = NSBundle::mainBundle();
 722            if bundle.is_null() {
 723                Err(anyhow!("app is not running inside a bundle"))
 724            } else {
 725                Ok(path_from_objc(msg_send![bundle, bundlePath]))
 726            }
 727        }
 728    }
 729
 730    fn set_menus(&self, menus: Vec<Menu>, keymap: &Keymap) {
 731        unsafe {
 732            let app: id = msg_send![APP_CLASS, sharedApplication];
 733            let mut state = self.0.lock();
 734            let actions = &mut state.menu_actions;
 735            app.setMainMenu_(self.create_menu_bar(menus, app.delegate(), actions, keymap));
 736        }
 737    }
 738
 739    fn set_dock_menu(&self, menu: Vec<MenuItem>, keymap: &Keymap) {
 740        unsafe {
 741            let app: id = msg_send![APP_CLASS, sharedApplication];
 742            let mut state = self.0.lock();
 743            let actions = &mut state.menu_actions;
 744            let new = self.create_dock_menu(menu, app.delegate(), actions, keymap);
 745            if let Some(old) = state.dock_menu.replace(new) {
 746                CFRelease(old as _)
 747            }
 748        }
 749    }
 750
 751    fn add_recent_document(&self, path: &Path) {
 752        if let Some(path_str) = path.to_str() {
 753            unsafe {
 754                let document_controller: id =
 755                    msg_send![class!(NSDocumentController), sharedDocumentController];
 756                let url: id = NSURL::fileURLWithPath_(nil, ns_string(path_str));
 757                let _: () = msg_send![document_controller, noteNewRecentDocumentURL:url];
 758            }
 759        }
 760    }
 761
 762    fn path_for_auxiliary_executable(&self, name: &str) -> Result<PathBuf> {
 763        unsafe {
 764            let bundle: id = NSBundle::mainBundle();
 765            if bundle.is_null() {
 766                Err(anyhow!("app is not running inside a bundle"))
 767            } else {
 768                let name = ns_string(name);
 769                let url: id = msg_send![bundle, URLForAuxiliaryExecutable: name];
 770                if url.is_null() {
 771                    Err(anyhow!("resource not found"))
 772                } else {
 773                    ns_url_to_path(url)
 774                }
 775            }
 776        }
 777    }
 778
 779    /// Match cursor style to one of the styles available
 780    /// in macOS's [NSCursor](https://developer.apple.com/documentation/appkit/nscursor).
 781    fn set_cursor_style(&self, style: CursorStyle) {
 782        unsafe {
 783            let new_cursor: id = match style {
 784                CursorStyle::Arrow => msg_send![class!(NSCursor), arrowCursor],
 785                CursorStyle::IBeam => msg_send![class!(NSCursor), IBeamCursor],
 786                CursorStyle::Crosshair => msg_send![class!(NSCursor), crosshairCursor],
 787                CursorStyle::ClosedHand => msg_send![class!(NSCursor), closedHandCursor],
 788                CursorStyle::OpenHand => msg_send![class!(NSCursor), openHandCursor],
 789                CursorStyle::PointingHand => msg_send![class!(NSCursor), pointingHandCursor],
 790                CursorStyle::ResizeLeftRight => msg_send![class!(NSCursor), resizeLeftRightCursor],
 791                CursorStyle::ResizeUpDown => msg_send![class!(NSCursor), resizeUpDownCursor],
 792                CursorStyle::ResizeLeft => msg_send![class!(NSCursor), resizeLeftCursor],
 793                CursorStyle::ResizeRight => msg_send![class!(NSCursor), resizeRightCursor],
 794                CursorStyle::ResizeColumn => msg_send![class!(NSCursor), resizeLeftRightCursor],
 795                CursorStyle::ResizeRow => msg_send![class!(NSCursor), resizeUpDownCursor],
 796                CursorStyle::ResizeUp => msg_send![class!(NSCursor), resizeUpCursor],
 797                CursorStyle::ResizeDown => msg_send![class!(NSCursor), resizeDownCursor],
 798
 799                // Undocumented, private class methods:
 800                // https://stackoverflow.com/questions/27242353/cocoa-predefined-resize-mouse-cursor
 801                CursorStyle::ResizeUpLeftDownRight => {
 802                    msg_send![class!(NSCursor), _windowResizeNorthWestSouthEastCursor]
 803                }
 804                CursorStyle::ResizeUpRightDownLeft => {
 805                    msg_send![class!(NSCursor), _windowResizeNorthEastSouthWestCursor]
 806                }
 807
 808                CursorStyle::IBeamCursorForVerticalLayout => {
 809                    msg_send![class!(NSCursor), IBeamCursorForVerticalLayout]
 810                }
 811                CursorStyle::OperationNotAllowed => {
 812                    msg_send![class!(NSCursor), operationNotAllowedCursor]
 813                }
 814                CursorStyle::DragLink => msg_send![class!(NSCursor), dragLinkCursor],
 815                CursorStyle::DragCopy => msg_send![class!(NSCursor), dragCopyCursor],
 816                CursorStyle::ContextualMenu => msg_send![class!(NSCursor), contextualMenuCursor],
 817            };
 818
 819            let old_cursor: id = msg_send![class!(NSCursor), currentCursor];
 820            if new_cursor != old_cursor {
 821                let _: () = msg_send![new_cursor, set];
 822            }
 823        }
 824    }
 825
 826    fn should_auto_hide_scrollbars(&self) -> bool {
 827        #[allow(non_upper_case_globals)]
 828        const NSScrollerStyleOverlay: NSInteger = 1;
 829
 830        unsafe {
 831            let style: NSInteger = msg_send![class!(NSScroller), preferredScrollerStyle];
 832            style == NSScrollerStyleOverlay
 833        }
 834    }
 835
 836    fn write_to_clipboard(&self, item: ClipboardItem) {
 837        let state = self.0.lock();
 838        unsafe {
 839            state.pasteboard.clearContents();
 840
 841            let text_bytes = NSData::dataWithBytes_length_(
 842                nil,
 843                item.text.as_ptr() as *const c_void,
 844                item.text.len() as u64,
 845            );
 846            state
 847                .pasteboard
 848                .setData_forType(text_bytes, NSPasteboardTypeString);
 849
 850            if let Some(metadata) = item.metadata.as_ref() {
 851                let hash_bytes = ClipboardItem::text_hash(&item.text).to_be_bytes();
 852                let hash_bytes = NSData::dataWithBytes_length_(
 853                    nil,
 854                    hash_bytes.as_ptr() as *const c_void,
 855                    hash_bytes.len() as u64,
 856                );
 857                state
 858                    .pasteboard
 859                    .setData_forType(hash_bytes, state.text_hash_pasteboard_type);
 860
 861                let metadata_bytes = NSData::dataWithBytes_length_(
 862                    nil,
 863                    metadata.as_ptr() as *const c_void,
 864                    metadata.len() as u64,
 865                );
 866                state
 867                    .pasteboard
 868                    .setData_forType(metadata_bytes, state.metadata_pasteboard_type);
 869            }
 870        }
 871    }
 872
 873    fn read_from_clipboard(&self) -> Option<ClipboardItem> {
 874        let state = self.0.lock();
 875        unsafe {
 876            if let Some(text_bytes) =
 877                self.read_from_pasteboard(state.pasteboard, NSPasteboardTypeString)
 878            {
 879                let text = String::from_utf8_lossy(text_bytes).to_string();
 880                let hash_bytes = self
 881                    .read_from_pasteboard(state.pasteboard, state.text_hash_pasteboard_type)
 882                    .and_then(|bytes| bytes.try_into().ok())
 883                    .map(u64::from_be_bytes);
 884                let metadata_bytes = self
 885                    .read_from_pasteboard(state.pasteboard, state.metadata_pasteboard_type)
 886                    .and_then(|bytes| String::from_utf8(bytes.to_vec()).ok());
 887
 888                if let Some((hash, metadata)) = hash_bytes.zip(metadata_bytes) {
 889                    if hash == ClipboardItem::text_hash(&text) {
 890                        Some(ClipboardItem {
 891                            text,
 892                            metadata: Some(metadata),
 893                        })
 894                    } else {
 895                        Some(ClipboardItem {
 896                            text,
 897                            metadata: None,
 898                        })
 899                    }
 900                } else {
 901                    Some(ClipboardItem {
 902                        text,
 903                        metadata: None,
 904                    })
 905                }
 906            } else {
 907                None
 908            }
 909        }
 910    }
 911
 912    fn write_credentials(&self, url: &str, username: &str, password: &[u8]) -> Task<Result<()>> {
 913        let url = url.to_string();
 914        let username = username.to_string();
 915        let password = password.to_vec();
 916        self.background_executor().spawn(async move {
 917            unsafe {
 918                use security::*;
 919
 920                let url = CFString::from(url.as_str());
 921                let username = CFString::from(username.as_str());
 922                let password = CFData::from_buffer(&password);
 923
 924                // First, check if there are already credentials for the given server. If so, then
 925                // update the username and password.
 926                let mut verb = "updating";
 927                let mut query_attrs = CFMutableDictionary::with_capacity(2);
 928                query_attrs.set(kSecClass as *const _, kSecClassInternetPassword as *const _);
 929                query_attrs.set(kSecAttrServer as *const _, url.as_CFTypeRef());
 930
 931                let mut attrs = CFMutableDictionary::with_capacity(4);
 932                attrs.set(kSecClass as *const _, kSecClassInternetPassword as *const _);
 933                attrs.set(kSecAttrServer as *const _, url.as_CFTypeRef());
 934                attrs.set(kSecAttrAccount as *const _, username.as_CFTypeRef());
 935                attrs.set(kSecValueData as *const _, password.as_CFTypeRef());
 936
 937                let mut status = SecItemUpdate(
 938                    query_attrs.as_concrete_TypeRef(),
 939                    attrs.as_concrete_TypeRef(),
 940                );
 941
 942                // If there were no existing credentials for the given server, then create them.
 943                if status == errSecItemNotFound {
 944                    verb = "creating";
 945                    status = SecItemAdd(attrs.as_concrete_TypeRef(), ptr::null_mut());
 946                }
 947
 948                if status != errSecSuccess {
 949                    return Err(anyhow!("{} password failed: {}", verb, status));
 950                }
 951            }
 952            Ok(())
 953        })
 954    }
 955
 956    fn read_credentials(&self, url: &str) -> Task<Result<Option<(String, Vec<u8>)>>> {
 957        let url = url.to_string();
 958        self.background_executor().spawn(async move {
 959            let url = CFString::from(url.as_str());
 960            let cf_true = CFBoolean::true_value().as_CFTypeRef();
 961
 962            unsafe {
 963                use security::*;
 964
 965                // Find any credentials for the given server URL.
 966                let mut attrs = CFMutableDictionary::with_capacity(5);
 967                attrs.set(kSecClass as *const _, kSecClassInternetPassword as *const _);
 968                attrs.set(kSecAttrServer as *const _, url.as_CFTypeRef());
 969                attrs.set(kSecReturnAttributes as *const _, cf_true);
 970                attrs.set(kSecReturnData as *const _, cf_true);
 971
 972                let mut result = CFTypeRef::from(ptr::null());
 973                let status = SecItemCopyMatching(attrs.as_concrete_TypeRef(), &mut result);
 974                match status {
 975                    security::errSecSuccess => {}
 976                    security::errSecItemNotFound | security::errSecUserCanceled => return Ok(None),
 977                    _ => return Err(anyhow!("reading password failed: {}", status)),
 978                }
 979
 980                let result = CFType::wrap_under_create_rule(result)
 981                    .downcast::<CFDictionary>()
 982                    .ok_or_else(|| anyhow!("keychain item was not a dictionary"))?;
 983                let username = result
 984                    .find(kSecAttrAccount as *const _)
 985                    .ok_or_else(|| anyhow!("account was missing from keychain item"))?;
 986                let username = CFType::wrap_under_get_rule(*username)
 987                    .downcast::<CFString>()
 988                    .ok_or_else(|| anyhow!("account was not a string"))?;
 989                let password = result
 990                    .find(kSecValueData as *const _)
 991                    .ok_or_else(|| anyhow!("password was missing from keychain item"))?;
 992                let password = CFType::wrap_under_get_rule(*password)
 993                    .downcast::<CFData>()
 994                    .ok_or_else(|| anyhow!("password was not a string"))?;
 995
 996                Ok(Some((username.to_string(), password.bytes().to_vec())))
 997            }
 998        })
 999    }
1000
1001    fn delete_credentials(&self, url: &str) -> Task<Result<()>> {
1002        let url = url.to_string();
1003
1004        self.background_executor().spawn(async move {
1005            unsafe {
1006                use security::*;
1007
1008                let url = CFString::from(url.as_str());
1009                let mut query_attrs = CFMutableDictionary::with_capacity(2);
1010                query_attrs.set(kSecClass as *const _, kSecClassInternetPassword as *const _);
1011                query_attrs.set(kSecAttrServer as *const _, url.as_CFTypeRef());
1012
1013                let status = SecItemDelete(query_attrs.as_concrete_TypeRef());
1014
1015                if status != errSecSuccess {
1016                    return Err(anyhow!("delete password failed: {}", status));
1017                }
1018            }
1019            Ok(())
1020        })
1021    }
1022}
1023
1024unsafe fn path_from_objc(path: id) -> PathBuf {
1025    let len = msg_send![path, lengthOfBytesUsingEncoding: NSUTF8StringEncoding];
1026    let bytes = path.UTF8String() as *const u8;
1027    let path = str::from_utf8(slice::from_raw_parts(bytes, len)).unwrap();
1028    PathBuf::from(path)
1029}
1030
1031unsafe fn get_mac_platform(object: &mut Object) -> &MacPlatform {
1032    let platform_ptr: *mut c_void = *object.get_ivar(MAC_PLATFORM_IVAR);
1033    assert!(!platform_ptr.is_null());
1034    &*(platform_ptr as *const MacPlatform)
1035}
1036
1037extern "C" fn did_finish_launching(this: &mut Object, _: Sel, _: id) {
1038    unsafe {
1039        let app: id = msg_send![APP_CLASS, sharedApplication];
1040        app.setActivationPolicy_(NSApplicationActivationPolicyRegular);
1041        let platform = get_mac_platform(this);
1042        let callback = platform.0.lock().finish_launching.take();
1043        if let Some(callback) = callback {
1044            callback();
1045        }
1046    }
1047}
1048
1049extern "C" fn should_handle_reopen(this: &mut Object, _: Sel, _: id, has_open_windows: bool) {
1050    if !has_open_windows {
1051        let platform = unsafe { get_mac_platform(this) };
1052        let mut lock = platform.0.lock();
1053        if let Some(mut callback) = lock.reopen.take() {
1054            drop(lock);
1055            callback();
1056            platform.0.lock().reopen.get_or_insert(callback);
1057        }
1058    }
1059}
1060
1061extern "C" fn will_terminate(this: &mut Object, _: Sel, _: id) {
1062    let platform = unsafe { get_mac_platform(this) };
1063    let mut lock = platform.0.lock();
1064    if let Some(mut callback) = lock.quit.take() {
1065        drop(lock);
1066        callback();
1067        platform.0.lock().quit.get_or_insert(callback);
1068    }
1069}
1070
1071extern "C" fn open_urls(this: &mut Object, _: Sel, _: id, urls: id) {
1072    let urls = unsafe {
1073        (0..urls.count())
1074            .filter_map(|i| {
1075                let url = urls.objectAtIndex(i);
1076                match CStr::from_ptr(url.absoluteString().UTF8String() as *mut c_char).to_str() {
1077                    Ok(string) => Some(string.to_string()),
1078                    Err(err) => {
1079                        log::error!("error converting path to string: {}", err);
1080                        None
1081                    }
1082                }
1083            })
1084            .collect::<Vec<_>>()
1085    };
1086    let platform = unsafe { get_mac_platform(this) };
1087    let mut lock = platform.0.lock();
1088    if let Some(mut callback) = lock.open_urls.take() {
1089        drop(lock);
1090        callback(urls);
1091        platform.0.lock().open_urls.get_or_insert(callback);
1092    }
1093}
1094
1095extern "C" fn handle_menu_item(this: &mut Object, _: Sel, item: id) {
1096    unsafe {
1097        let platform = get_mac_platform(this);
1098        let mut lock = platform.0.lock();
1099        if let Some(mut callback) = lock.menu_command.take() {
1100            let tag: NSInteger = msg_send![item, tag];
1101            let index = tag as usize;
1102            if let Some(action) = lock.menu_actions.get(index) {
1103                let action = action.boxed_clone();
1104                drop(lock);
1105                callback(&*action);
1106            }
1107            platform.0.lock().menu_command.get_or_insert(callback);
1108        }
1109    }
1110}
1111
1112extern "C" fn validate_menu_item(this: &mut Object, _: Sel, item: id) -> bool {
1113    unsafe {
1114        let mut result = false;
1115        let platform = get_mac_platform(this);
1116        let mut lock = platform.0.lock();
1117        if let Some(mut callback) = lock.validate_menu_command.take() {
1118            let tag: NSInteger = msg_send![item, tag];
1119            let index = tag as usize;
1120            if let Some(action) = lock.menu_actions.get(index) {
1121                let action = action.boxed_clone();
1122                drop(lock);
1123                result = callback(action.as_ref());
1124            }
1125            platform
1126                .0
1127                .lock()
1128                .validate_menu_command
1129                .get_or_insert(callback);
1130        }
1131        result
1132    }
1133}
1134
1135extern "C" fn menu_will_open(this: &mut Object, _: Sel, _: id) {
1136    unsafe {
1137        let platform = get_mac_platform(this);
1138        let mut lock = platform.0.lock();
1139        if let Some(mut callback) = lock.will_open_menu.take() {
1140            drop(lock);
1141            callback();
1142            platform.0.lock().will_open_menu.get_or_insert(callback);
1143        }
1144    }
1145}
1146
1147extern "C" fn handle_dock_menu(this: &mut Object, _: Sel, _: id) -> id {
1148    unsafe {
1149        let platform = get_mac_platform(this);
1150        let mut state = platform.0.lock();
1151        if let Some(id) = state.dock_menu {
1152            id
1153        } else {
1154            nil
1155        }
1156    }
1157}
1158
1159unsafe fn ns_string(string: &str) -> id {
1160    NSString::alloc(nil).init_str(string).autorelease()
1161}
1162
1163unsafe fn ns_url_to_path(url: id) -> Result<PathBuf> {
1164    let path: *mut c_char = msg_send![url, fileSystemRepresentation];
1165    if path.is_null() {
1166        Err(anyhow!(
1167            "url is not a file path: {}",
1168            CStr::from_ptr(url.absoluteString().UTF8String()).to_string_lossy()
1169        ))
1170    } else {
1171        Ok(PathBuf::from(OsStr::from_bytes(
1172            CStr::from_ptr(path).to_bytes(),
1173        )))
1174    }
1175}
1176
1177mod security {
1178    #![allow(non_upper_case_globals)]
1179    use super::*;
1180
1181    #[link(name = "Security", kind = "framework")]
1182    extern "C" {
1183        pub static kSecClass: CFStringRef;
1184        pub static kSecClassInternetPassword: CFStringRef;
1185        pub static kSecAttrServer: CFStringRef;
1186        pub static kSecAttrAccount: CFStringRef;
1187        pub static kSecValueData: CFStringRef;
1188        pub static kSecReturnAttributes: CFStringRef;
1189        pub static kSecReturnData: CFStringRef;
1190
1191        pub fn SecItemAdd(attributes: CFDictionaryRef, result: *mut CFTypeRef) -> OSStatus;
1192        pub fn SecItemUpdate(query: CFDictionaryRef, attributes: CFDictionaryRef) -> OSStatus;
1193        pub fn SecItemDelete(query: CFDictionaryRef) -> OSStatus;
1194        pub fn SecItemCopyMatching(query: CFDictionaryRef, result: *mut CFTypeRef) -> OSStatus;
1195    }
1196
1197    pub const errSecSuccess: OSStatus = 0;
1198    pub const errSecUserCanceled: OSStatus = -128;
1199    pub const errSecItemNotFound: OSStatus = -25300;
1200}
1201
1202#[cfg(test)]
1203mod tests {
1204    use crate::ClipboardItem;
1205
1206    use super::*;
1207
1208    #[test]
1209    fn test_clipboard() {
1210        let platform = build_platform();
1211        assert_eq!(platform.read_from_clipboard(), None);
1212
1213        let item = ClipboardItem::new("1".to_string());
1214        platform.write_to_clipboard(item.clone());
1215        assert_eq!(platform.read_from_clipboard(), Some(item));
1216
1217        let item = ClipboardItem::new("2".to_string()).with_metadata(vec![3, 4]);
1218        platform.write_to_clipboard(item.clone());
1219        assert_eq!(platform.read_from_clipboard(), Some(item));
1220
1221        let text_from_other_app = "text from other app";
1222        unsafe {
1223            let bytes = NSData::dataWithBytes_length_(
1224                nil,
1225                text_from_other_app.as_ptr() as *const c_void,
1226                text_from_other_app.len() as u64,
1227            );
1228            platform
1229                .0
1230                .lock()
1231                .pasteboard
1232                .setData_forType(bytes, NSPasteboardTypeString);
1233        }
1234        assert_eq!(
1235            platform.read_from_clipboard(),
1236            Some(ClipboardItem::new(text_from_other_app.to_string()))
1237        );
1238    }
1239
1240    fn build_platform() -> MacPlatform {
1241        let platform = MacPlatform::new();
1242        platform.0.lock().pasteboard = unsafe { NSPasteboard::pasteboardWithUniqueName(nil) };
1243        platform
1244    }
1245}