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