platform.rs

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