platform.rs

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