platform.rs

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