platform.rs

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