platform.rs

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