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