Skip to content

Visual Studio Code, rebuilt in Rust

Rust
7.6 KB
Raw Blame
//! Electron's GTK message box (shell/browser/ui/message_box_gtk.cc) on the GTK context `webview::pump_gtk` iterates,
//! with the button order dialogs.ts `massageMessageBoxOptions` gives Linux.

use futures::channel::oneshot;
use gpui::PromptLevel;
use gtk::glib;
use gtk::prelude::*;

use super::OpenDialog;

/// Shows the box transient for GPUI's X11 window `parent`; the answer is the pressed button's index in `buttons`.
pub fn show(parent: x11::xlib::Window, level: PromptLevel, message: &str, detail: Option<&str>, buttons: &[String], checkbox: Option<(String, bool)>, sender: oneshot::Sender<(usize, bool)>) {
    let message_type = match level {
        PromptLevel::Info => gtk::MessageType::Info,
        PromptLevel::Warning => gtk::MessageType::Warning,
        PromptLevel::Critical => gtk::MessageType::Error,
    };
    let dialog = gtk::MessageDialog::new(None::<&gtk::Window>, gtk::DialogFlags::empty(), message_type, gtk::ButtonsType::None, message);
    if let Some(detail) = detail {
        dialog.set_secondary_text(Some(detail));
    }
    dialog.set_title(crate::product::name_long());
    let check_button = checkbox.map(|(label, checked)| {
        let check_button = gtk::CheckButton::with_label(&label);
        check_button.set_active(checked);
        let message_area = dialog.message_area().downcast::<gtk::Container>().expect("a message dialog's message area is a box");
        message_area.add(&check_button);
        check_button.show();
        check_button
    });
    let order = ButtonOrder::linux(buttons.len());
    for (response, &index) in order.shown.iter().enumerate() {
        dialog.add_button(&stock_label(&buttons[index]), gtk::ResponseType::Other(response as u16));
    }
    dialog.set_default_response(gtk::ResponseType::Other(order.default as u16));
    dialog.realize();
    let display = dialog.display().downcast::<gdkx11::X11Display>().expect("`webview::supported` holds GTK to X11");
    let parent = gdkx11::X11Window::foreign_new_for_display(&display, parent);
    dialog.window().expect("a realized dialog has a window").set_transient_for(parent.upcast_ref());
    dialog.set_modal(true);
    let sender = std::cell::Cell::new(Some((sender, OpenDialog::new())));
    dialog.connect_response(move |dialog, response| {
        let shown = match response {
            gtk::ResponseType::Other(shown) => shown as usize,
            _ => order.cancel,
        };
        let checked = check_button.as_ref().is_some_and(|check_button| check_button.is_active());
        if let Some((sender, _open)) = sender.take() {
            let _ = sender.send((order.shown[shown], checked));
        }
        // SAFETY: the dialog is ours and nothing uses it after its response.
        unsafe { dialog.destroy() };
    });
    dialog.show();
}

/// The buttons as shown (indices into the caller's buttons, primary first and cancel last), and the shown
/// positions of the default and cancel buttons.
#[derive(Debug, PartialEq)]
struct ButtonOrder {
    shown: Vec<usize>,
    default: usize,
    cancel: usize,
}

impl ButtonOrder {
    /// dialogs.ts `massageMessageBoxOptions` on Linux, GNOME's HIG: the cancel button moves to the second place and the
    /// order reverses, so the primary button is last and the default, cancel just before it.
    fn linux(count: usize) -> Self {
        let mut shown: Vec<usize> = (0..count).collect();
        if count < 2 {
            return ButtonOrder { shown, default: 0, cancel: count.saturating_sub(1) };
        }
        let cancel = shown.remove(count - 1);
        shown.insert(1, cancel);
        shown.reverse();
        ButtonOrder { shown, default: count - 1, cancel: count - 2 }
    }
}

/// labels.ts `mnemonicButtonLabel` on Linux, then message_box_gtk.cc `TranslateToStock`: Cancel, No, OK and Yes take
/// GTK's own translated labels.
fn stock_label(label: &str) -> String {
    let label = label.replace("&&", "_");
    let stock = match label.to_ascii_lowercase().as_str() {
        "cancel" => "_Cancel",
        "no" => "_No",
        "ok" => "_Ok",
        "yes" => "_Yes",
        _ => return label,
    };
    glib::dgettext(Some("gtk30"), stock).into()
}

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

    #[test]
    fn buttons_follow_gnome_order_with_cancel_before_the_primary() {
        assert_eq!(ButtonOrder::linux(1), ButtonOrder { shown: vec![0], default: 0, cancel: 0 });
        // lifecycle.rs's close confirmation: [Close Window, Cancel] shows as Cancel, Close Window.
        assert_eq!(ButtonOrder::linux(2), ButtonOrder { shown: vec![1, 0], default: 1, cancel: 0 });
        // The unsaved changes prompt: [Save, Don't Save, Cancel] shows as Don't Save, Cancel, Save.
        assert_eq!(ButtonOrder::linux(3), ButtonOrder { shown: vec![1, 2, 0], default: 2, cancel: 1 });
    }

    #[test]
    fn labels_take_gtk_mnemonics_and_stock_names() {
        assert_eq!(stock_label("&&Save"), "_Save");
        assert_eq!(stock_label("Don't Save"), "Don't Save");
        assert_eq!(stock_label("Cancel"), glib::dgettext(Some("gtk30"), "_Cancel").as_str());
        assert_eq!(stock_label("OK"), glib::dgettext(Some("gtk30"), "_Ok").as_str());
    }

    /// The unsaved changes prompt under Xvfb: the dialog is transient for its parent, shows its buttons in GNOME order
    /// and answers the caller's index with the checkbox state; closing it answers cancel.
    #[test]
    fn dialog_is_transient_and_answers_the_callers_index() {
        if std::env::var_os("DISPLAY").is_none() {
            return;
        }
        gtk::init().unwrap();
        let parent_window = gtk::Window::new(gtk::WindowType::Toplevel);
        parent_window.realize();
        let parent = parent_window.window().unwrap().downcast::<gdkx11::X11Window>().unwrap().xid();
        let buttons = ["Save".to_string(), "Don't Save".to_string(), "Cancel".to_string()];
        let shown_dialog = |checkbox| {
            let (sender, receiver) = oneshot::channel();
            show(parent, PromptLevel::Warning, "Save changes?", Some("Your changes will be lost."), &buttons, checkbox, sender);
            let dialog = gtk::Window::list_toplevels().into_iter().filter_map(|window| window.downcast::<gtk::MessageDialog>().ok()).find(|dialog| dialog.is_visible()).unwrap();
            (dialog, receiver)
        };

        let (dialog, mut receiver) = shown_dialog(Some(("Do not ask me again".to_string(), false)));
        assert_eq!(dialog.title().unwrap(), crate::product::name_long());
        let labels: Vec<String> = (0..3).map(|response| dialog.widget_for_response(gtk::ResponseType::Other(response)).unwrap().downcast::<gtk::Button>().unwrap().label().unwrap().into()).collect();
        assert_eq!(labels, ["Don't Save", glib::dgettext(Some("gtk30"), "_Cancel").as_str(), "Save"]);
        let xid = dialog.window().unwrap().downcast::<gdkx11::X11Window>().unwrap().xid();
        dialog.display().flush();
        let mut transient_for = 0;
        // SAFETY: a display of our own, closed after the one query.
        unsafe {
            let display = x11::xlib::XOpenDisplay(std::ptr::null());
            assert_ne!(x11::xlib::XGetTransientForHint(display, xid, &mut transient_for), 0);
            x11::xlib::XCloseDisplay(display);
        }
        assert_eq!(transient_for, parent);
        let message_area = dialog.message_area().downcast::<gtk::Container>().unwrap();
        message_area.children().last().unwrap().downcast_ref::<gtk::CheckButton>().unwrap().set_active(true);
        dialog.response(gtk::ResponseType::Other(0));
        assert_eq!(receiver.try_recv().unwrap(), Some((1, true)));

        let (dialog, mut receiver) = shown_dialog(None);
        dialog.response(gtk::ResponseType::DeleteEvent);
        assert_eq!(receiver.try_recv().unwrap(), Some((2, false)));
    }
}