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