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