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