Skip to content

Visual Studio Code, rebuilt in Rust

Rust
11.7 KB
Raw Blame
//! `nativeHostService.showMessageBox` with a checkbox: Electron's macOS message box is an NSAlert sheet whose
//! suppression button carries `checkboxLabel`, its Linux one a GTK message dialog with a check button (linux.rs), its
//! Windows one a task dialog with verification text (windows.rs). GPUI's `Window::prompt` has neither.

#[cfg(target_os = "linux")]
mod linux;
#[cfg(target_os = "windows")]
mod windows;

use std::cell::Cell;

#[cfg(target_os = "macos")]
use block2::RcBlock;
use futures::channel::oneshot;
use gpui::{App, PromptLevel, Window};
#[cfg(target_os = "macos")]
use objc2::MainThreadMarker;
#[cfg(target_os = "macos")]
use objc2::rc::Retained;
#[cfg(target_os = "macos")]
use objc2_app_kit::{NSAlert, NSAlertStyle, NSControlStateValueOn, NSModalResponse, NSView, NSWindow};
#[cfg(target_os = "macos")]
use objc2_foundation::NSString;
#[cfg(target_os = "macos")]
use raw_window_handle::{HasWindowHandle, RawWindowHandle};

thread_local! {
    /// dialogMainService.ts's dialog queues: the native message boxes and file panels showing, all on the main thread.
    static OPEN_DIALOGS: Cell<usize> = const { Cell::new(0) };
}

/// A native dialog that `has_open_dialogs` counts until it is dropped.
pub struct OpenDialog(());

impl OpenDialog {
    pub fn new() -> Self {
        OPEN_DIALOGS.set(OPEN_DIALOGS.get() + 1);
        OpenDialog(())
    }
}

impl Drop for OpenDialog {
    fn drop(&mut self) {
        OPEN_DIALOGS.set(OPEN_DIALOGS.get() - 1);
    }
}

/// dialogMainService.ts `hasOpenDialogs`, the unattended restart's `app.dialogOpen`.
pub fn has_open_dialogs() -> bool {
    OPEN_DIALOGS.get() > 0
}

/// How a dialog answers while extension tests run (dialogService.ts `skipDialogs`).
#[derive(Clone, Copy, PartialEq, Debug)]
pub enum InTests {
    /// `confirm`: confirmed without showing, the first button.
    Confirm,
    /// `prompt`, `input`, `info`, `warn`, `error`: refused, the receiver is cancelled.
    Refuse,
    /// A main process dialog, which upstream's skipDialogs does not reach.
    Show,
}

/// The pressed button's index (buttons in `massageMessageBoxOptions` order: primary first, cancel last) and
/// whether the checkbox, if any, was checked.
/// With `window.dialogStyle: custom` the workbench's custom dialog shows it instead (dialog.contribution.ts).
#[allow(clippy::too_many_arguments)]
pub fn show_message_box(window: &Window, in_tests: InTests, level: PromptLevel, message: &str, detail: Option<&str>, buttons: &[&str], checkbox: Option<&str>, cx: &App) -> oneshot::Receiver<(usize, bool)> {
    show_message_box_with_checkbox(window, in_tests, level, message, detail, buttons, checkbox.map(|label| (label, false)), cx)
}

/// `show_message_box` with the checkbox's label and its state when the box opens.
#[allow(clippy::too_many_arguments)]
pub fn show_message_box_with_checkbox(window: &Window, in_tests: InTests, level: PromptLevel, message: &str, detail: Option<&str>, buttons: &[&str], checkbox: Option<(&str, bool)>, cx: &App) -> oneshot::Receiver<(usize, bool)> {
    let (sender, receiver) = oneshot::channel();
    #[cfg(target_os = "macos")]
    let ns_window = app_kit_window(window);
    #[cfg(target_os = "linux")]
    let x_window = crate::webview::supported().then(|| crate::webview::gpui_x_window(window));
    #[cfg(target_os = "windows")]
    let owner = windows::owner(window);
    #[cfg(target_os = "linux")]
    let native_box = x_window.is_some();
    #[cfg(not(target_os = "linux"))]
    let native_box = true;
    // Weak: the task waits on the custom dialog's answer, whose sender the workbench holds while the dialog is open.
    let workbench = crate::workbench::auxiliary_windows::window_workbench(window, cx).map(|workbench| workbench.downgrade());
    let (message, detail, checkbox) = (message.to_owned(), detail.map(str::to_owned), checkbox.map(|(label, checked)| (label.to_owned(), checked)));
    let buttons: Vec<String> = buttons.iter().map(|button| button.to_string()).collect();
    // Begun after this update returns: the sheet takes the key window and GPUI's handlers must not run re-entrantly,
    // and the workbench the caller updates can be read for its dialog style only then.
    cx.spawn(async move |cx| {
        let style = workbench.as_ref().and_then(|workbench| workbench.read_with(cx, |workbench, _| (workbench.skip_dialogs, workbench.uses_custom_dialogs())).ok());
        let (skip_dialogs, custom) = style.unwrap_or_default();
        if skip_dialogs && in_tests != InTests::Show {
            if in_tests == InTests::Confirm {
                let _ = sender.send((0, false));
            }
            return;
        }
        // Without GTK on X11 (a Wayland session) the custom dialog stands in for Electron's GTK message box.
        if let (true, Some(workbench)) = (custom || !native_box, workbench) {
            let Ok(answer) = workbench.update(cx, |workbench, cx| workbench.show_custom_message_box(level, message, detail, buttons, checkbox, cx)) else { return };
            if let Ok(answer) = answer.await {
                let _ = sender.send(answer);
            }
            return;
        }
        #[cfg(target_os = "macos")]
        if let Some(ns_window) = ns_window {
            begin_alert_sheet(&ns_window, level, &message, detail.as_deref(), &buttons, checkbox, sender);
        }
        #[cfg(target_os = "linux")]
        if let Some(x_window) = x_window {
            linux::show(x_window, level, &message, detail.as_deref(), &buttons, checkbox, sender);
        }
        #[cfg(target_os = "windows")]
        if let Some(owner) = owner {
            windows::show(owner, level, &message, detail.as_deref(), &buttons, checkbox, sender);
        }
    })
    .detach();
    receiver
}

/// labels.ts `mnemonicButtonLabel` on Windows: `&&` marks the mnemonic as `&`, a lone `&` is escaped as `&&`.
#[cfg(any(target_os = "windows", test))]
pub(crate) fn windows_mnemonic(label: &str) -> String {
    let parts: Vec<String> = label.split("&&").map(|part| part.replace('&', "&&")).collect();
    parts.join("&")
}

/// message_box_win.cc `kIDStart`: the id of the first custom button.
#[cfg(any(target_os = "windows", test))]
const TASK_DIALOG_FIRST_ID: i32 = 100;

/// The task dialog's custom buttons as `(id, label)`, in the caller's order: `massageMessageBoxOptions` on Windows only
/// moves the cancel button last, where the caller's buttons already have it, and `noLink` keeps them buttons.
#[cfg(any(target_os = "windows", test))]
fn task_dialog_buttons(buttons: &[String]) -> Vec<(i32, String)> {
    let mut shown = Vec::new();
    for (index, label) in buttons.iter().enumerate() {
        shown.push((TASK_DIALOG_FIRST_ID + index as i32, windows_mnemonic(label)));
    }
    shown
}

/// message_box_win.cc: a custom button answers its index; Esc, the close button or a failed dialog the cancel
/// button, the last one.
#[cfg(any(target_os = "windows", test))]
fn task_dialog_answer(id: i32, count: usize) -> usize {
    usize::try_from(id - TASK_DIALOG_FIRST_ID).ok().filter(|index| *index < count).unwrap_or(count.saturating_sub(1))
}

/// message_box_win.cc: with a detail the message is the main instruction above it, else the content alone.
#[cfg(any(target_os = "windows", test))]
fn task_dialog_texts<'a>(message: &'a str, detail: Option<&'a str>) -> (Option<&'a str>, &'a str) {
    match detail.filter(|detail| !detail.is_empty()) {
        Some(detail) => (Some(message), detail),
        None => (None, message),
    }
}

#[cfg(target_os = "macos")]
fn begin_alert_sheet(ns_window: &NSWindow, level: PromptLevel, message: &str, detail: Option<&str>, buttons: &[String], checkbox: Option<(String, bool)>, sender: oneshot::Sender<(usize, bool)>) {
    let sender = Cell::new(Some((sender, OpenDialog::new())));
    let mtm = MainThreadMarker::new().expect("dialogs open on the main thread");
    let alert = NSAlert::new(mtm);
    // Electron's message_box_mac.mm: warning and error types take the critical style, the caution icon with an app
    // icon badge (the warning style draws the app icon alone); the others informational.
    alert.setAlertStyle(match level {
        PromptLevel::Info => NSAlertStyle::Informational,
        PromptLevel::Warning | PromptLevel::Critical => NSAlertStyle::Critical,
    });
    alert.setMessageText(&NSString::from_str(message));
    if let Some(detail) = detail {
        alert.setInformativeText(&NSString::from_str(detail));
    }
    for (index, title) in buttons.iter().enumerate() {
        let button = alert.addButtonWithTitle(&NSString::from_str(title));
        button.setTag(index as isize);
        if index == buttons.len() - 1 && index > 0 {
            button.setKeyEquivalent(&NSString::from_str("\u{1b}"));
        }
    }
    let suppression = checkbox.map(|(label, checked)| {
        alert.setShowsSuppressionButton(true);
        let suppression = alert.suppressionButton().expect("an alert showing its suppression button has one");
        suppression.setTitle(&NSString::from_str(&label));
        if checked {
            suppression.setState(NSControlStateValueOn);
        }
        suppression
    });
    let count = buttons.len();
    let handler = RcBlock::new(move |response: NSModalResponse| {
        let checked = suppression.as_ref().is_some_and(|suppression| suppression.state() == NSControlStateValueOn);
        // A negative response (NSModalResponseAbort) is a sheet closed without a button: cancel.
        let index = usize::try_from(response).ok().filter(|index| *index < count).unwrap_or(count - 1);
        if let Some((sender, _open)) = sender.take() {
            let _ = sender.send((index, checked));
        }
    });
    alert.beginSheetModalForWindow_completionHandler(ns_window, Some(&handler));
}

#[cfg(target_os = "macos")]
pub(crate) fn ns_window(window: &Window) -> Retained<NSWindow> {
    app_kit_window(window).expect("macOS windows are AppKit windows")
}

/// The window's NSWindow; none on GPUI's test platform.
#[cfg(target_os = "macos")]
pub(crate) fn app_kit_window(window: &Window) -> Option<Retained<NSWindow>> {
    let handle = HasWindowHandle::window_handle(window).ok()?;
    let RawWindowHandle::AppKit(handle) = handle.as_raw() else { return None };
    // SAFETY: GPUI's AppKit handle points at the window's content NSView, alive while the window is.
    let view: &NSView = unsafe { handle.ns_view.cast().as_ref() };
    view.window()
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn windows_labels_take_ampersand_mnemonics() {
        assert_eq!(windows_mnemonic("&&Save"), "&Save");
        assert_eq!(windows_mnemonic("Save && Close"), "Save & Close");
        assert_eq!(windows_mnemonic("Tom & Jerry"), "Tom && Jerry");
        assert_eq!(windows_mnemonic("Don't Save"), "Don't Save");
    }

    #[test]
    fn windows_task_dialog_keeps_the_callers_button_order_with_cancel_last() {
        // The unsaved changes prompt: [Save, Don't Save, Cancel] shows as Save, Don't Save, Cancel.
        let buttons = ["&&Save".to_owned(), "Do&&n't Save".to_owned(), "Cancel".to_owned()];
        assert_eq!(task_dialog_buttons(&buttons), vec![(100, "&Save".to_owned()), (101, "Do&n't Save".to_owned()), (102, "Cancel".to_owned())]);
        assert_eq!(task_dialog_answer(101, 3), 1);
        // IDCANCEL (Esc, the close button) and 0 (TaskDialogIndirect failed) answer cancel.
        assert_eq!(task_dialog_answer(2, 3), 2);
        assert_eq!(task_dialog_answer(0, 3), 2);
        assert_eq!(task_dialog_answer(0, 0), 0);
    }

    #[test]
    fn windows_task_dialog_message_is_the_main_instruction_only_with_a_detail() {
        assert_eq!(task_dialog_texts("Save changes?", Some("Your changes will be lost.")), (Some("Save changes?"), "Your changes will be lost."));
        assert_eq!(task_dialog_texts("Saved.", None), (None, "Saved."));
        assert_eq!(task_dialog_texts("Saved.", Some("")), (None, "Saved."));
    }
}