platform.rs

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