platform.rs

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