platform.rs

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