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, WindowOptions,
   7};
   8use anyhow::anyhow;
   9use block::ConcreteBlock;
  10use cocoa::{
  11    appkit::{
  12        NSApplication, NSApplicationActivationPolicy::NSApplicationActivationPolicyRegular,
  13        NSEventModifierFlags, NSMenu, NSMenuItem, NSModalResponse, NSOpenPanel, NSPasteboard,
  14        NSPasteboardTypeString, NSSavePanel, NSWindow,
  15    },
  16    base::{id, nil, selector, BOOL, YES},
  17    foundation::{
  18        NSArray, NSAutoreleasePool, NSBundle, NSData, NSInteger, NSProcessInfo, NSString,
  19        NSUInteger, NSURL,
  20    },
  21};
  22use core_foundation::{
  23    base::{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
  55#[allow(non_upper_case_globals)]
  56const NSUTF8StringEncoding: NSUInteger = 4;
  57
  58const MAC_PLATFORM_IVAR: &str = "platform";
  59static mut APP_CLASS: *const Class = ptr::null();
  60static mut APP_DELEGATE_CLASS: *const Class = ptr::null();
  61
  62#[ctor]
  63unsafe fn build_classes() {
  64    APP_CLASS = {
  65        let mut decl = ClassDecl::new("GPUIApplication", class!(NSApplication)).unwrap();
  66        decl.add_ivar::<*mut c_void>(MAC_PLATFORM_IVAR);
  67        decl.add_method(
  68            sel!(sendEvent:),
  69            send_event as extern "C" fn(&mut Object, Sel, id),
  70        );
  71        decl.register()
  72    };
  73
  74    APP_DELEGATE_CLASS = {
  75        let mut decl = ClassDecl::new("GPUIApplicationDelegate", class!(NSResponder)).unwrap();
  76        decl.add_ivar::<*mut c_void>(MAC_PLATFORM_IVAR);
  77        decl.add_method(
  78            sel!(applicationDidFinishLaunching:),
  79            did_finish_launching as extern "C" fn(&mut Object, Sel, id),
  80        );
  81        decl.add_method(
  82            sel!(applicationShouldHandleReopen:hasVisibleWindows:),
  83            should_handle_reopen as extern "C" fn(&mut Object, Sel, id, bool),
  84        );
  85        decl.add_method(
  86            sel!(applicationDidBecomeActive:),
  87            did_become_active as extern "C" fn(&mut Object, Sel, id),
  88        );
  89        decl.add_method(
  90            sel!(applicationDidResignActive:),
  91            did_resign_active as extern "C" fn(&mut Object, Sel, id),
  92        );
  93        decl.add_method(
  94            sel!(applicationWillTerminate:),
  95            will_terminate as extern "C" fn(&mut Object, Sel, id),
  96        );
  97        decl.add_method(
  98            sel!(handleGPUIMenuItem:),
  99            handle_menu_item as extern "C" fn(&mut Object, Sel, id),
 100        );
 101        // Add menu item handlers so that OS save panels have the correct key commands
 102        decl.add_method(
 103            sel!(cut:),
 104            handle_menu_item as extern "C" fn(&mut Object, Sel, id),
 105        );
 106        decl.add_method(
 107            sel!(copy:),
 108            handle_menu_item as extern "C" fn(&mut Object, Sel, id),
 109        );
 110        decl.add_method(
 111            sel!(paste:),
 112            handle_menu_item as extern "C" fn(&mut Object, Sel, id),
 113        );
 114        decl.add_method(
 115            sel!(selectAll:),
 116            handle_menu_item as extern "C" fn(&mut Object, Sel, id),
 117        );
 118        decl.add_method(
 119            sel!(undo:),
 120            handle_menu_item as extern "C" fn(&mut Object, Sel, id),
 121        );
 122        decl.add_method(
 123            sel!(redo:),
 124            handle_menu_item as extern "C" fn(&mut Object, Sel, id),
 125        );
 126        decl.add_method(
 127            sel!(validateMenuItem:),
 128            validate_menu_item as extern "C" fn(&mut Object, Sel, id) -> bool,
 129        );
 130        decl.add_method(
 131            sel!(menuWillOpen:),
 132            menu_will_open as extern "C" fn(&mut Object, Sel, id),
 133        );
 134        decl.add_method(
 135            sel!(application:openURLs:),
 136            open_urls as extern "C" fn(&mut Object, Sel, id, id),
 137        );
 138        decl.register()
 139    }
 140}
 141
 142pub(crate) struct MacPlatform(Mutex<MacPlatformState>);
 143
 144pub(crate) struct MacPlatformState {
 145    background_executor: BackgroundExecutor,
 146    foreground_executor: ForegroundExecutor,
 147    text_system: Arc<MacTextSystem>,
 148    instance_buffer_pool: Arc<Mutex<Vec<metal::Buffer>>>,
 149    pasteboard: id,
 150    text_hash_pasteboard_type: id,
 151    metadata_pasteboard_type: id,
 152    become_active: Option<Box<dyn FnMut()>>,
 153    resign_active: Option<Box<dyn FnMut()>>,
 154    reopen: Option<Box<dyn FnMut()>>,
 155    quit: Option<Box<dyn FnMut()>>,
 156    event: Option<Box<dyn FnMut(PlatformInput) -> bool>>,
 157    menu_command: Option<Box<dyn FnMut(&dyn Action)>>,
 158    validate_menu_command: Option<Box<dyn FnMut(&dyn Action) -> bool>>,
 159    will_open_menu: Option<Box<dyn FnMut()>>,
 160    menu_actions: Vec<Box<dyn Action>>,
 161    open_urls: Option<Box<dyn FnMut(Vec<String>)>>,
 162    finish_launching: Option<Box<dyn FnOnce()>>,
 163}
 164
 165impl Default for MacPlatform {
 166    fn default() -> Self {
 167        Self::new()
 168    }
 169}
 170
 171impl MacPlatform {
 172    pub(crate) fn new() -> Self {
 173        let dispatcher = Arc::new(MacDispatcher::new());
 174        Self(Mutex::new(MacPlatformState {
 175            background_executor: BackgroundExecutor::new(dispatcher.clone()),
 176            foreground_executor: ForegroundExecutor::new(dispatcher),
 177            text_system: Arc::new(MacTextSystem::new()),
 178            instance_buffer_pool: Arc::default(),
 179            pasteboard: unsafe { NSPasteboard::generalPasteboard(nil) },
 180            text_hash_pasteboard_type: unsafe { ns_string("zed-text-hash") },
 181            metadata_pasteboard_type: unsafe { ns_string("zed-metadata") },
 182            become_active: None,
 183            resign_active: None,
 184            reopen: None,
 185            quit: None,
 186            event: None,
 187            menu_command: None,
 188            validate_menu_command: None,
 189            will_open_menu: None,
 190            menu_actions: Default::default(),
 191            open_urls: None,
 192            finish_launching: None,
 193        }))
 194    }
 195
 196    unsafe fn read_from_pasteboard(&self, pasteboard: *mut Object, kind: id) -> Option<&[u8]> {
 197        let data = pasteboard.dataForType(kind);
 198        if data == nil {
 199            None
 200        } else {
 201            Some(slice::from_raw_parts(
 202                data.bytes() as *mut u8,
 203                data.length() as usize,
 204            ))
 205        }
 206    }
 207
 208    unsafe fn create_menu_bar(
 209        &self,
 210        menus: Vec<Menu>,
 211        delegate: id,
 212        actions: &mut Vec<Box<dyn Action>>,
 213        keymap: &Keymap,
 214    ) -> id {
 215        let application_menu = NSMenu::new(nil).autorelease();
 216        application_menu.setDelegate_(delegate);
 217
 218        for menu_config in menus {
 219            let menu = NSMenu::new(nil).autorelease();
 220            menu.setTitle_(ns_string(menu_config.name));
 221            menu.setDelegate_(delegate);
 222
 223            for item_config in menu_config.items {
 224                menu.addItem_(Self::create_menu_item(
 225                    item_config,
 226                    delegate,
 227                    actions,
 228                    keymap,
 229                ));
 230            }
 231
 232            let menu_item = NSMenuItem::new(nil).autorelease();
 233            menu_item.setSubmenu_(menu);
 234            application_menu.addItem_(menu_item);
 235
 236            if menu_config.name == "Window" {
 237                let app: id = msg_send![APP_CLASS, sharedApplication];
 238                app.setWindowsMenu_(menu);
 239            }
 240        }
 241
 242        application_menu
 243    }
 244
 245    unsafe fn create_menu_item(
 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.as_ref())
 260                    .next()
 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_get_main_queue, dispatch_sys::dispatch_async_f};
 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 displays(&self) -> Vec<Rc<dyn PlatformDisplay>> {
 479        MacDisplay::all()
 480            .map(|screen| Rc::new(screen) as Rc<_>)
 481            .collect()
 482    }
 483
 484    fn display(&self, id: DisplayId) -> Option<Rc<dyn PlatformDisplay>> {
 485        MacDisplay::find_by_id(id).map(|screen| Rc::new(screen) as Rc<_>)
 486    }
 487
 488    fn active_window(&self) -> Option<AnyWindowHandle> {
 489        MacWindow::active_window()
 490    }
 491
 492    fn open_window(
 493        &self,
 494        handle: AnyWindowHandle,
 495        options: WindowOptions,
 496    ) -> Box<dyn PlatformWindow> {
 497        let instance_buffer_pool = self.0.lock().instance_buffer_pool.clone();
 498        Box::new(MacWindow::open(
 499            handle,
 500            options,
 501            self.foreground_executor(),
 502            instance_buffer_pool,
 503        ))
 504    }
 505
 506    fn open_url(&self, url: &str) {
 507        unsafe {
 508            let url = NSURL::alloc(nil)
 509                .initWithString_(ns_string(url))
 510                .autorelease();
 511            let workspace: id = msg_send![class!(NSWorkspace), sharedWorkspace];
 512            msg_send![workspace, openURL: url]
 513        }
 514    }
 515
 516    fn on_open_urls(&self, callback: Box<dyn FnMut(Vec<String>)>) {
 517        self.0.lock().open_urls = Some(callback);
 518    }
 519
 520    fn prompt_for_paths(
 521        &self,
 522        options: PathPromptOptions,
 523    ) -> oneshot::Receiver<Option<Vec<PathBuf>>> {
 524        let (done_tx, done_rx) = oneshot::channel();
 525        self.foreground_executor()
 526            .spawn(async move {
 527                unsafe {
 528                    let panel = NSOpenPanel::openPanel(nil);
 529                    panel.setCanChooseDirectories_(options.directories.to_objc());
 530                    panel.setCanChooseFiles_(options.files.to_objc());
 531                    panel.setAllowsMultipleSelection_(options.multiple.to_objc());
 532                    panel.setResolvesAliases_(false.to_objc());
 533                    let done_tx = Cell::new(Some(done_tx));
 534                    let block = ConcreteBlock::new(move |response: NSModalResponse| {
 535                        let result = if response == NSModalResponse::NSModalResponseOk {
 536                            let mut result = Vec::new();
 537                            let urls = panel.URLs();
 538                            for i in 0..urls.count() {
 539                                let url = urls.objectAtIndex(i);
 540                                if url.isFileURL() == YES {
 541                                    if let Ok(path) = ns_url_to_path(url) {
 542                                        result.push(path)
 543                                    }
 544                                }
 545                            }
 546                            Some(result)
 547                        } else {
 548                            None
 549                        };
 550
 551                        if let Some(done_tx) = done_tx.take() {
 552                            let _ = done_tx.send(result);
 553                        }
 554                    });
 555                    let block = block.copy();
 556                    let _: () = msg_send![panel, beginWithCompletionHandler: block];
 557                }
 558            })
 559            .detach();
 560        done_rx
 561    }
 562
 563    fn prompt_for_new_path(&self, directory: &Path) -> oneshot::Receiver<Option<PathBuf>> {
 564        let directory = directory.to_owned();
 565        let (done_tx, done_rx) = oneshot::channel();
 566        self.foreground_executor()
 567            .spawn(async move {
 568                unsafe {
 569                    let panel = NSSavePanel::savePanel(nil);
 570                    let path = ns_string(directory.to_string_lossy().as_ref());
 571                    let url = NSURL::fileURLWithPath_isDirectory_(nil, path, true.to_objc());
 572                    panel.setDirectoryURL(url);
 573
 574                    let done_tx = Cell::new(Some(done_tx));
 575                    let block = ConcreteBlock::new(move |response: NSModalResponse| {
 576                        let mut result = None;
 577                        if response == NSModalResponse::NSModalResponseOk {
 578                            let url = panel.URL();
 579                            if url.isFileURL() == YES {
 580                                result = ns_url_to_path(panel.URL()).ok()
 581                            }
 582                        }
 583
 584                        if let Some(done_tx) = done_tx.take() {
 585                            let _ = done_tx.send(result);
 586                        }
 587                    });
 588                    let block = block.copy();
 589                    let _: () = msg_send![panel, beginWithCompletionHandler: block];
 590                }
 591            })
 592            .detach();
 593
 594        done_rx
 595    }
 596
 597    fn reveal_path(&self, path: &Path) {
 598        unsafe {
 599            let path = path.to_path_buf();
 600            self.0
 601                .lock()
 602                .background_executor
 603                .spawn(async move {
 604                    let full_path = ns_string(path.to_str().unwrap_or(""));
 605                    let root_full_path = ns_string("");
 606                    let workspace: id = msg_send![class!(NSWorkspace), sharedWorkspace];
 607                    let _: BOOL = msg_send![
 608                        workspace,
 609                        selectFile: full_path
 610                        inFileViewerRootedAtPath: root_full_path
 611                    ];
 612                })
 613                .detach();
 614        }
 615    }
 616
 617    fn on_become_active(&self, callback: Box<dyn FnMut()>) {
 618        self.0.lock().become_active = Some(callback);
 619    }
 620
 621    fn on_resign_active(&self, callback: Box<dyn FnMut()>) {
 622        self.0.lock().resign_active = Some(callback);
 623    }
 624
 625    fn on_quit(&self, callback: Box<dyn FnMut()>) {
 626        self.0.lock().quit = Some(callback);
 627    }
 628
 629    fn on_reopen(&self, callback: Box<dyn FnMut()>) {
 630        self.0.lock().reopen = Some(callback);
 631    }
 632
 633    fn on_event(&self, callback: Box<dyn FnMut(PlatformInput) -> bool>) {
 634        self.0.lock().event = Some(callback);
 635    }
 636
 637    fn on_app_menu_action(&self, callback: Box<dyn FnMut(&dyn Action)>) {
 638        self.0.lock().menu_command = Some(callback);
 639    }
 640
 641    fn on_will_open_app_menu(&self, callback: Box<dyn FnMut()>) {
 642        self.0.lock().will_open_menu = Some(callback);
 643    }
 644
 645    fn on_validate_app_menu_command(&self, callback: Box<dyn FnMut(&dyn Action) -> bool>) {
 646        self.0.lock().validate_menu_command = Some(callback);
 647    }
 648
 649    fn os_name(&self) -> &'static str {
 650        "macOS"
 651    }
 652
 653    fn double_click_interval(&self) -> Duration {
 654        unsafe {
 655            let double_click_interval: f64 = msg_send![class!(NSEvent), doubleClickInterval];
 656            Duration::from_secs_f64(double_click_interval)
 657        }
 658    }
 659
 660    fn os_version(&self) -> Result<SemanticVersion> {
 661        unsafe {
 662            let process_info = NSProcessInfo::processInfo(nil);
 663            let version = process_info.operatingSystemVersion();
 664            Ok(SemanticVersion {
 665                major: version.majorVersion as usize,
 666                minor: version.minorVersion as usize,
 667                patch: version.patchVersion as usize,
 668            })
 669        }
 670    }
 671
 672    fn app_version(&self) -> Result<SemanticVersion> {
 673        unsafe {
 674            let bundle: id = NSBundle::mainBundle();
 675            if bundle.is_null() {
 676                Err(anyhow!("app is not running inside a bundle"))
 677            } else {
 678                let version: id = msg_send![bundle, objectForInfoDictionaryKey: ns_string("CFBundleShortVersionString")];
 679                let len = msg_send![version, lengthOfBytesUsingEncoding: NSUTF8StringEncoding];
 680                let bytes = version.UTF8String() as *const u8;
 681                let version = str::from_utf8(slice::from_raw_parts(bytes, len)).unwrap();
 682                version.parse()
 683            }
 684        }
 685    }
 686
 687    fn app_path(&self) -> Result<PathBuf> {
 688        unsafe {
 689            let bundle: id = NSBundle::mainBundle();
 690            if bundle.is_null() {
 691                Err(anyhow!("app is not running inside a bundle"))
 692            } else {
 693                Ok(path_from_objc(msg_send![bundle, bundlePath]))
 694            }
 695        }
 696    }
 697
 698    fn set_menus(&self, menus: Vec<Menu>, keymap: &Keymap) {
 699        unsafe {
 700            let app: id = msg_send![APP_CLASS, sharedApplication];
 701            let mut state = self.0.lock();
 702            let actions = &mut state.menu_actions;
 703            app.setMainMenu_(self.create_menu_bar(menus, app.delegate(), actions, keymap));
 704        }
 705    }
 706
 707    fn local_timezone(&self) -> UtcOffset {
 708        unsafe {
 709            let local_timezone: id = msg_send![class!(NSTimeZone), localTimeZone];
 710            let seconds_from_gmt: NSInteger = msg_send![local_timezone, secondsFromGMT];
 711            UtcOffset::from_whole_seconds(seconds_from_gmt.try_into().unwrap()).unwrap()
 712        }
 713    }
 714
 715    fn path_for_auxiliary_executable(&self, name: &str) -> Result<PathBuf> {
 716        unsafe {
 717            let bundle: id = NSBundle::mainBundle();
 718            if bundle.is_null() {
 719                Err(anyhow!("app is not running inside a bundle"))
 720            } else {
 721                let name = ns_string(name);
 722                let url: id = msg_send![bundle, URLForAuxiliaryExecutable: name];
 723                if url.is_null() {
 724                    Err(anyhow!("resource not found"))
 725                } else {
 726                    ns_url_to_path(url)
 727                }
 728            }
 729        }
 730    }
 731
 732    /// Match cursor style to one of the styles available
 733    /// in macOS's [NSCursor](https://developer.apple.com/documentation/appkit/nscursor).
 734    fn set_cursor_style(&self, style: CursorStyle) {
 735        unsafe {
 736            let new_cursor: id = match style {
 737                CursorStyle::Arrow => msg_send![class!(NSCursor), arrowCursor],
 738                CursorStyle::IBeam => msg_send![class!(NSCursor), IBeamCursor],
 739                CursorStyle::Crosshair => msg_send![class!(NSCursor), crosshairCursor],
 740                CursorStyle::ClosedHand => msg_send![class!(NSCursor), closedHandCursor],
 741                CursorStyle::OpenHand => msg_send![class!(NSCursor), openHandCursor],
 742                CursorStyle::PointingHand => msg_send![class!(NSCursor), pointingHandCursor],
 743                CursorStyle::ResizeLeft => msg_send![class!(NSCursor), resizeLeftCursor],
 744                CursorStyle::ResizeRight => msg_send![class!(NSCursor), resizeRightCursor],
 745                CursorStyle::ResizeLeftRight => msg_send![class!(NSCursor), resizeLeftRightCursor],
 746                CursorStyle::ResizeUp => msg_send![class!(NSCursor), resizeUpCursor],
 747                CursorStyle::ResizeDown => msg_send![class!(NSCursor), resizeDownCursor],
 748                CursorStyle::ResizeUpDown => msg_send![class!(NSCursor), resizeUpDownCursor],
 749                CursorStyle::DisappearingItem => {
 750                    msg_send![class!(NSCursor), disappearingItemCursor]
 751                }
 752                CursorStyle::IBeamCursorForVerticalLayout => {
 753                    msg_send![class!(NSCursor), IBeamCursorForVerticalLayout]
 754                }
 755                CursorStyle::OperationNotAllowed => {
 756                    msg_send![class!(NSCursor), operationNotAllowedCursor]
 757                }
 758                CursorStyle::DragLink => msg_send![class!(NSCursor), dragLinkCursor],
 759                CursorStyle::DragCopy => msg_send![class!(NSCursor), dragCopyCursor],
 760                CursorStyle::ContextualMenu => msg_send![class!(NSCursor), contextualMenuCursor],
 761            };
 762
 763            let old_cursor: id = msg_send![class!(NSCursor), currentCursor];
 764            if new_cursor != old_cursor {
 765                let _: () = msg_send![new_cursor, set];
 766            }
 767        }
 768    }
 769
 770    fn should_auto_hide_scrollbars(&self) -> bool {
 771        #[allow(non_upper_case_globals)]
 772        const NSScrollerStyleOverlay: NSInteger = 1;
 773
 774        unsafe {
 775            let style: NSInteger = msg_send![class!(NSScroller), preferredScrollerStyle];
 776            style == NSScrollerStyleOverlay
 777        }
 778    }
 779
 780    fn write_to_clipboard(&self, item: ClipboardItem) {
 781        let state = self.0.lock();
 782        unsafe {
 783            state.pasteboard.clearContents();
 784
 785            let text_bytes = NSData::dataWithBytes_length_(
 786                nil,
 787                item.text.as_ptr() as *const c_void,
 788                item.text.len() as u64,
 789            );
 790            state
 791                .pasteboard
 792                .setData_forType(text_bytes, NSPasteboardTypeString);
 793
 794            if let Some(metadata) = item.metadata.as_ref() {
 795                let hash_bytes = ClipboardItem::text_hash(&item.text).to_be_bytes();
 796                let hash_bytes = NSData::dataWithBytes_length_(
 797                    nil,
 798                    hash_bytes.as_ptr() as *const c_void,
 799                    hash_bytes.len() as u64,
 800                );
 801                state
 802                    .pasteboard
 803                    .setData_forType(hash_bytes, state.text_hash_pasteboard_type);
 804
 805                let metadata_bytes = NSData::dataWithBytes_length_(
 806                    nil,
 807                    metadata.as_ptr() as *const c_void,
 808                    metadata.len() as u64,
 809                );
 810                state
 811                    .pasteboard
 812                    .setData_forType(metadata_bytes, state.metadata_pasteboard_type);
 813            }
 814        }
 815    }
 816
 817    fn read_from_clipboard(&self) -> Option<ClipboardItem> {
 818        let state = self.0.lock();
 819        unsafe {
 820            if let Some(text_bytes) =
 821                self.read_from_pasteboard(state.pasteboard, NSPasteboardTypeString)
 822            {
 823                let text = String::from_utf8_lossy(text_bytes).to_string();
 824                let hash_bytes = self
 825                    .read_from_pasteboard(state.pasteboard, state.text_hash_pasteboard_type)
 826                    .and_then(|bytes| bytes.try_into().ok())
 827                    .map(u64::from_be_bytes);
 828                let metadata_bytes = self
 829                    .read_from_pasteboard(state.pasteboard, state.metadata_pasteboard_type)
 830                    .and_then(|bytes| String::from_utf8(bytes.to_vec()).ok());
 831
 832                if let Some((hash, metadata)) = hash_bytes.zip(metadata_bytes) {
 833                    if hash == ClipboardItem::text_hash(&text) {
 834                        Some(ClipboardItem {
 835                            text,
 836                            metadata: Some(metadata),
 837                        })
 838                    } else {
 839                        Some(ClipboardItem {
 840                            text,
 841                            metadata: None,
 842                        })
 843                    }
 844                } else {
 845                    Some(ClipboardItem {
 846                        text,
 847                        metadata: None,
 848                    })
 849                }
 850            } else {
 851                None
 852            }
 853        }
 854    }
 855
 856    fn write_credentials(&self, url: &str, username: &str, password: &[u8]) -> Task<Result<()>> {
 857        let url = url.to_string();
 858        let username = username.to_string();
 859        let password = password.to_vec();
 860        self.background_executor().spawn(async move {
 861            unsafe {
 862                use security::*;
 863
 864                let url = CFString::from(url.as_str());
 865                let username = CFString::from(username.as_str());
 866                let password = CFData::from_buffer(&password);
 867
 868                // First, check if there are already credentials for the given server. If so, then
 869                // update the username and password.
 870                let mut verb = "updating";
 871                let mut query_attrs = CFMutableDictionary::with_capacity(2);
 872                query_attrs.set(kSecClass as *const _, kSecClassInternetPassword as *const _);
 873                query_attrs.set(kSecAttrServer as *const _, url.as_CFTypeRef());
 874
 875                let mut attrs = CFMutableDictionary::with_capacity(4);
 876                attrs.set(kSecClass as *const _, kSecClassInternetPassword as *const _);
 877                attrs.set(kSecAttrServer as *const _, url.as_CFTypeRef());
 878                attrs.set(kSecAttrAccount as *const _, username.as_CFTypeRef());
 879                attrs.set(kSecValueData as *const _, password.as_CFTypeRef());
 880
 881                let mut status = SecItemUpdate(
 882                    query_attrs.as_concrete_TypeRef(),
 883                    attrs.as_concrete_TypeRef(),
 884                );
 885
 886                // If there were no existing credentials for the given server, then create them.
 887                if status == errSecItemNotFound {
 888                    verb = "creating";
 889                    status = SecItemAdd(attrs.as_concrete_TypeRef(), ptr::null_mut());
 890                }
 891
 892                if status != errSecSuccess {
 893                    return Err(anyhow!("{} password failed: {}", verb, status));
 894                }
 895            }
 896            Ok(())
 897        })
 898    }
 899
 900    fn read_credentials(&self, url: &str) -> Task<Result<Option<(String, Vec<u8>)>>> {
 901        let url = url.to_string();
 902        self.background_executor().spawn(async move {
 903            let url = CFString::from(url.as_str());
 904            let cf_true = CFBoolean::true_value().as_CFTypeRef();
 905
 906            unsafe {
 907                use security::*;
 908
 909                // Find any credentials for the given server URL.
 910                let mut attrs = CFMutableDictionary::with_capacity(5);
 911                attrs.set(kSecClass as *const _, kSecClassInternetPassword as *const _);
 912                attrs.set(kSecAttrServer as *const _, url.as_CFTypeRef());
 913                attrs.set(kSecReturnAttributes as *const _, cf_true);
 914                attrs.set(kSecReturnData as *const _, cf_true);
 915
 916                let mut result = CFTypeRef::from(ptr::null());
 917                let status = SecItemCopyMatching(attrs.as_concrete_TypeRef(), &mut result);
 918                match status {
 919                    security::errSecSuccess => {}
 920                    security::errSecItemNotFound | security::errSecUserCanceled => return Ok(None),
 921                    _ => return Err(anyhow!("reading password failed: {}", status)),
 922                }
 923
 924                let result = CFType::wrap_under_create_rule(result)
 925                    .downcast::<CFDictionary>()
 926                    .ok_or_else(|| anyhow!("keychain item was not a dictionary"))?;
 927                let username = result
 928                    .find(kSecAttrAccount as *const _)
 929                    .ok_or_else(|| anyhow!("account was missing from keychain item"))?;
 930                let username = CFType::wrap_under_get_rule(*username)
 931                    .downcast::<CFString>()
 932                    .ok_or_else(|| anyhow!("account was not a string"))?;
 933                let password = result
 934                    .find(kSecValueData as *const _)
 935                    .ok_or_else(|| anyhow!("password was missing from keychain item"))?;
 936                let password = CFType::wrap_under_get_rule(*password)
 937                    .downcast::<CFData>()
 938                    .ok_or_else(|| anyhow!("password was not a string"))?;
 939
 940                Ok(Some((username.to_string(), password.bytes().to_vec())))
 941            }
 942        })
 943    }
 944
 945    fn delete_credentials(&self, url: &str) -> Task<Result<()>> {
 946        let url = url.to_string();
 947
 948        self.background_executor().spawn(async move {
 949            unsafe {
 950                use security::*;
 951
 952                let url = CFString::from(url.as_str());
 953                let mut query_attrs = CFMutableDictionary::with_capacity(2);
 954                query_attrs.set(kSecClass as *const _, kSecClassInternetPassword as *const _);
 955                query_attrs.set(kSecAttrServer as *const _, url.as_CFTypeRef());
 956
 957                let status = SecItemDelete(query_attrs.as_concrete_TypeRef());
 958
 959                if status != errSecSuccess {
 960                    return Err(anyhow!("delete password failed: {}", status));
 961                }
 962            }
 963            Ok(())
 964        })
 965    }
 966}
 967
 968unsafe fn path_from_objc(path: id) -> PathBuf {
 969    let len = msg_send![path, lengthOfBytesUsingEncoding: NSUTF8StringEncoding];
 970    let bytes = path.UTF8String() as *const u8;
 971    let path = str::from_utf8(slice::from_raw_parts(bytes, len)).unwrap();
 972    PathBuf::from(path)
 973}
 974
 975unsafe fn get_mac_platform(object: &mut Object) -> &MacPlatform {
 976    let platform_ptr: *mut c_void = *object.get_ivar(MAC_PLATFORM_IVAR);
 977    assert!(!platform_ptr.is_null());
 978    &*(platform_ptr as *const MacPlatform)
 979}
 980
 981extern "C" fn send_event(this: &mut Object, _sel: Sel, native_event: id) {
 982    unsafe {
 983        if let Some(event) = PlatformInput::from_native(native_event, None) {
 984            let platform = get_mac_platform(this);
 985            let mut lock = platform.0.lock();
 986            if let Some(mut callback) = lock.event.take() {
 987                drop(lock);
 988                let result = callback(event);
 989                platform.0.lock().event.get_or_insert(callback);
 990                if !result {
 991                    return;
 992                }
 993            }
 994        }
 995        msg_send![super(this, class!(NSApplication)), sendEvent: native_event]
 996    }
 997}
 998
 999extern "C" fn did_finish_launching(this: &mut Object, _: Sel, _: id) {
1000    unsafe {
1001        let app: id = msg_send![APP_CLASS, sharedApplication];
1002        app.setActivationPolicy_(NSApplicationActivationPolicyRegular);
1003
1004        let platform = get_mac_platform(this);
1005        let callback = platform.0.lock().finish_launching.take();
1006        if let Some(callback) = callback {
1007            callback();
1008        }
1009    }
1010}
1011
1012extern "C" fn should_handle_reopen(this: &mut Object, _: Sel, _: id, has_open_windows: bool) {
1013    if !has_open_windows {
1014        let platform = unsafe { get_mac_platform(this) };
1015        let mut lock = platform.0.lock();
1016        if let Some(mut callback) = lock.reopen.take() {
1017            drop(lock);
1018            callback();
1019            platform.0.lock().reopen.get_or_insert(callback);
1020        }
1021    }
1022}
1023
1024extern "C" fn did_become_active(this: &mut Object, _: Sel, _: id) {
1025    let platform = unsafe { get_mac_platform(this) };
1026    let mut lock = platform.0.lock();
1027    if let Some(mut callback) = lock.become_active.take() {
1028        drop(lock);
1029        callback();
1030        platform.0.lock().become_active.get_or_insert(callback);
1031    }
1032}
1033
1034extern "C" fn did_resign_active(this: &mut Object, _: Sel, _: id) {
1035    let platform = unsafe { get_mac_platform(this) };
1036    let mut lock = platform.0.lock();
1037    if let Some(mut callback) = lock.resign_active.take() {
1038        drop(lock);
1039        callback();
1040        platform.0.lock().resign_active.get_or_insert(callback);
1041    }
1042}
1043
1044extern "C" fn will_terminate(this: &mut Object, _: Sel, _: id) {
1045    let platform = unsafe { get_mac_platform(this) };
1046    let mut lock = platform.0.lock();
1047    if let Some(mut callback) = lock.quit.take() {
1048        drop(lock);
1049        callback();
1050        platform.0.lock().quit.get_or_insert(callback);
1051    }
1052}
1053
1054extern "C" fn open_urls(this: &mut Object, _: Sel, _: id, urls: id) {
1055    let urls = unsafe {
1056        (0..urls.count())
1057            .filter_map(|i| {
1058                let url = urls.objectAtIndex(i);
1059                match CStr::from_ptr(url.absoluteString().UTF8String() as *mut c_char).to_str() {
1060                    Ok(string) => Some(string.to_string()),
1061                    Err(err) => {
1062                        log::error!("error converting path to string: {}", err);
1063                        None
1064                    }
1065                }
1066            })
1067            .collect::<Vec<_>>()
1068    };
1069    let platform = unsafe { get_mac_platform(this) };
1070    let mut lock = platform.0.lock();
1071    if let Some(mut callback) = lock.open_urls.take() {
1072        drop(lock);
1073        callback(urls);
1074        platform.0.lock().open_urls.get_or_insert(callback);
1075    }
1076}
1077
1078extern "C" fn handle_menu_item(this: &mut Object, _: Sel, item: id) {
1079    unsafe {
1080        let platform = get_mac_platform(this);
1081        let mut lock = platform.0.lock();
1082        if let Some(mut callback) = lock.menu_command.take() {
1083            let tag: NSInteger = msg_send![item, tag];
1084            let index = tag as usize;
1085            if let Some(action) = lock.menu_actions.get(index) {
1086                let action = action.boxed_clone();
1087                drop(lock);
1088                callback(&*action);
1089            }
1090            platform.0.lock().menu_command.get_or_insert(callback);
1091        }
1092    }
1093}
1094
1095extern "C" fn validate_menu_item(this: &mut Object, _: Sel, item: id) -> bool {
1096    unsafe {
1097        let mut result = false;
1098        let platform = get_mac_platform(this);
1099        let mut lock = platform.0.lock();
1100        if let Some(mut callback) = lock.validate_menu_command.take() {
1101            let tag: NSInteger = msg_send![item, tag];
1102            let index = tag as usize;
1103            if let Some(action) = lock.menu_actions.get(index) {
1104                let action = action.boxed_clone();
1105                drop(lock);
1106                result = callback(action.as_ref());
1107            }
1108            platform
1109                .0
1110                .lock()
1111                .validate_menu_command
1112                .get_or_insert(callback);
1113        }
1114        result
1115    }
1116}
1117
1118extern "C" fn menu_will_open(this: &mut Object, _: Sel, _: id) {
1119    unsafe {
1120        let platform = get_mac_platform(this);
1121        let mut lock = platform.0.lock();
1122        if let Some(mut callback) = lock.will_open_menu.take() {
1123            drop(lock);
1124            callback();
1125            platform.0.lock().will_open_menu.get_or_insert(callback);
1126        }
1127    }
1128}
1129
1130unsafe fn ns_string(string: &str) -> id {
1131    NSString::alloc(nil).init_str(string).autorelease()
1132}
1133
1134unsafe fn ns_url_to_path(url: id) -> Result<PathBuf> {
1135    let path: *mut c_char = msg_send![url, fileSystemRepresentation];
1136    if path.is_null() {
1137        Err(anyhow!(
1138            "url is not a file path: {}",
1139            CStr::from_ptr(url.absoluteString().UTF8String()).to_string_lossy()
1140        ))
1141    } else {
1142        Ok(PathBuf::from(OsStr::from_bytes(
1143            CStr::from_ptr(path).to_bytes(),
1144        )))
1145    }
1146}
1147
1148mod security {
1149    #![allow(non_upper_case_globals)]
1150    use super::*;
1151
1152    #[link(name = "Security", kind = "framework")]
1153    extern "C" {
1154        pub static kSecClass: CFStringRef;
1155        pub static kSecClassInternetPassword: CFStringRef;
1156        pub static kSecAttrServer: CFStringRef;
1157        pub static kSecAttrAccount: CFStringRef;
1158        pub static kSecValueData: CFStringRef;
1159        pub static kSecReturnAttributes: CFStringRef;
1160        pub static kSecReturnData: CFStringRef;
1161
1162        pub fn SecItemAdd(attributes: CFDictionaryRef, result: *mut CFTypeRef) -> OSStatus;
1163        pub fn SecItemUpdate(query: CFDictionaryRef, attributes: CFDictionaryRef) -> OSStatus;
1164        pub fn SecItemDelete(query: CFDictionaryRef) -> OSStatus;
1165        pub fn SecItemCopyMatching(query: CFDictionaryRef, result: *mut CFTypeRef) -> OSStatus;
1166    }
1167
1168    pub const errSecSuccess: OSStatus = 0;
1169    pub const errSecUserCanceled: OSStatus = -128;
1170    pub const errSecItemNotFound: OSStatus = -25300;
1171}
1172
1173#[cfg(test)]
1174mod tests {
1175    use crate::ClipboardItem;
1176
1177    use super::*;
1178
1179    #[test]
1180    fn test_clipboard() {
1181        let platform = build_platform();
1182        assert_eq!(platform.read_from_clipboard(), None);
1183
1184        let item = ClipboardItem::new("1".to_string());
1185        platform.write_to_clipboard(item.clone());
1186        assert_eq!(platform.read_from_clipboard(), Some(item));
1187
1188        let item = ClipboardItem::new("2".to_string()).with_metadata(vec![3, 4]);
1189        platform.write_to_clipboard(item.clone());
1190        assert_eq!(platform.read_from_clipboard(), Some(item));
1191
1192        let text_from_other_app = "text from other app";
1193        unsafe {
1194            let bytes = NSData::dataWithBytes_length_(
1195                nil,
1196                text_from_other_app.as_ptr() as *const c_void,
1197                text_from_other_app.len() as u64,
1198            );
1199            platform
1200                .0
1201                .lock()
1202                .pasteboard
1203                .setData_forType(bytes, NSPasteboardTypeString);
1204        }
1205        assert_eq!(
1206            platform.read_from_clipboard(),
1207            Some(ClipboardItem::new(text_from_other_app.to_string()))
1208        );
1209    }
1210
1211    fn build_platform() -> MacPlatform {
1212        let platform = MacPlatform::new();
1213        platform.0.lock().pasteboard = unsafe { NSPasteboard::pasteboardWithUniqueName(nil) };
1214        platform
1215    }
1216}