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