platform.rs

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