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