platform.rs

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