platform.rs

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