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