platform.rs

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