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