platform.rs

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