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