platform.rs

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