platform.rs

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