Skip to content

Visual Studio Code, rebuilt in Rust

Rust

feat(linux): show message boxes as GTK message dialogs on X11

rokartur0af9fc8797c2
diff --git a/native/crates/app/src/dialog.rs b/native/crates/app/src/dialog.rs
index 27d06e9020f..780f48c4216 100644
--- a/native/crates/app/src/dialog.rs
+++ b/native/crates/app/src/dialog.rs
@@ -1,5 +1,9 @@
//! `nativeHostService.showMessageBox` with a checkbox: Electron's macOS message box is an NSAlert sheet whose
-//! suppression button carries `checkboxLabel`. GPUI's `Window::prompt` has no suppression button.
+//! suppression button carries `checkboxLabel`, its Linux one a GTK message dialog with a check button (linux.rs).
+//! GPUI's `Window::prompt` has neither.
+
+#[cfg(target_os = "linux")]
+mod linux;
use std::cell::Cell;
@@ -69,6 +73,12 @@ pub fn show_message_box_with_checkbox(window: &Window, in_tests: InTests, level:
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 = "linux")]
+ let native_box = x_window.is_some();
+ #[cfg(not(target_os = "linux"))]
+ let native_box = true;
let workbench = crate::workbench::auxiliary_windows::window_workbench(window, cx);
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();
@@ -83,8 +93,8 @@ pub fn show_message_box_with_checkbox(window: &Window, in_tests: InTests, level:
}
return;
}
- // Linux has no native message box yet: the custom dialog stands in for Electron's GTK one.
- if let (true, Some(workbench)) = (custom || cfg!(target_os = "linux"), workbench) {
+ // 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 answer = workbench.update(cx, |workbench, cx| workbench.show_custom_message_box(level, message, detail, buttons, checkbox, cx));
if let Ok(answer) = answer.await {
let _ = sender.send(answer);
@@ -95,6 +105,10 @@ pub fn show_message_box_with_checkbox(window: &Window, in_tests: InTests, level:
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);
+ }
})
.detach();
receiver
diff --git a/native/crates/app/src/dialog/linux.rs b/native/crates/app/src/dialog/linux.rs
new file mode 100644
index 00000000000..5df9de2db77
--- /dev/null
+++ b/native/crates/app/src/dialog/linux.rs
@@ -0,0 +1,158 @@
+//! 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)));
+ }
+}
diff --git a/native/crates/app/src/webview.rs b/native/crates/app/src/webview.rs
index 5377fb94e4e..3bfc2509cdc 100644
--- a/native/crates/app/src/webview.rs
+++ b/native/crates/app/src/webview.rs
@@ -13,7 +13,7 @@ mod linux;
#[cfg(target_os = "macos")]
mod macos;
#[cfg(target_os = "linux")]
-pub use linux::{ClipView, Retained, Webview, pump_gtk, place, supported};
+pub use linux::{ClipView, Retained, Webview, gpui_x_window, pump_gtk, place, supported};
#[cfg(target_os = "macos")]
pub use macos::{ClipView, Retained, Webview, place, supported};
diff --git a/native/crates/app/src/webview/linux.rs b/native/crates/app/src/webview/linux.rs
index 65692d3d712..1861aa9c9e6 100644
--- a/native/crates/app/src/webview/linux.rs
+++ b/native/crates/app/src/webview/linux.rs
@@ -373,7 +373,7 @@ fn embedded_window(parent: xlib::Window) -> gtk::Window {
window
}
-fn gpui_x_window(window: &Window) -> xlib::Window {
+pub fn gpui_x_window(window: &Window) -> xlib::Window {
let handle = HasWindowHandle::window_handle(window).expect("an open window has a handle");
match handle.as_raw() {
RawWindowHandle::Xcb(handle) => handle.window.get().into(),
diff --git a/port/ledger.md b/port/ledger.md
index 4261455291f..88a9b44bbf3 100644
--- a/port/ledger.md
+++ b/port/ledger.md
@@ -46,7 +46,7 @@ Status: `open`, `in progress`, `waiting on Artur`, `later` (postponed), `done`,
| M23 Linux | exthost/src/main_thread_secret_state.rs:46 | done | [linux M] secrets in the Secret Service (libsecret). | `cargo test -p exthost secret` on Linux: `secrets_in_a_keyring` (oo7's file backend); a desktop Secret Service not run |
| M23 Linux | app/src/clipboard.rs:97 | open | [linux M] clipboard file lists, HTML and other custom formats: Chromium offers each as its own MIME target (`code/file-list`, `text/html`) beside the text. Needs gpui_linux vendored, since GPUI's X11 selection owner and Wayland data source offer only text, images and `text/uri-list`, and a second owner would take CLIPBOARD from GPUI's. The find text needs nothing: clipboardService.ts reads and writes it only on macOS. Linux shows now: text only; the other formats read empty. | |
| M23 Linux | app/src/workbench/themes.rs:47 | done | [linux S] host color scheme and high contrast from the xdg-desktop-portal Settings. | GPUI's `window_appearance()`, which gpui_linux reads from the portal's `color-scheme`; high contrast stays off, as Chromium on Linux |
-| M23 Linux | app/src/dialog.rs:63 | open | [linux M] native message box (GTK). Linux shows now: the custom workbench dialog. | |
+| M23 Linux | app/src/dialog.rs:63 | done | [linux M] native message box (GTK) in an X11 session, as Electron's message_box_gtk.cc; the parent window stays enabled (notes.md M23). | `cargo gc test -p app dialog::linux` on Linux under Xvfb: 4 passed, `dialog_is_transient_and_answers_the_callers_index` (GNOME button order, transient hint, checkbox, close answers cancel). |
| M23 Linux | app/src/system_wide_keybindings/linux.rs:171 | done | [linux M] system-wide keybindings through the xdg-desktop-portal GlobalShortcuts in a Wayland session. | `cargo gc test -p app system_wide` on Linux under Xvfb: 13 passed, `x11_grabs_fail_when_taken_and_report_presses` and `portal_binds_the_accelerators_and_reports_activations` (a fake portal on a private bus); GNOME's and KDE's portals not run |
| M23 Linux | app/src/power/linux.rs:8 | done | [linux M] powerMonitor: idle time, lock state, battery, sleep and resume events, power save blockers (logind). | `cargo test -p app power::` on Linux; the D-Bus calls (logind, UPower, ScreenSaver, Mutter) not run on a desktop |
| M23 Linux | app/src/accessibility_signals.rs:119 | done | [linux S] accessibility signal sounds. | `pw-play`, else `paplay`; not run with audio in the container |
diff --git a/port/notes.md b/port/notes.md
index 03dbe345749..d3a24358bfc 100644
--- a/port/notes.md
+++ b/port/notes.md
@@ -1002,6 +1002,7 @@ What to do (milestone 21, in order):
- Accessibility signal sounds run `pw-play`, else `paplay` (both decode mp3 through libsndfile 1.1 or later), one process per sound file, killed when the sound replays.
- The `code` shell command on Linux links `~/.local/bin/<applicationName>` to the archive's `bin/<applicationName>` without a privilege prompt (upstream has the command on macOS only; a Linux package puts it on PATH itself). Proxy `<local>` adds the request's host to `--noproxy` when it has no dot, curl has no such rule. Machine info reads `/proc/cpuinfo`, `/proc/meminfo` and the cpufreq `scaling_cur_freq`.
- System-wide keybindings (`system_wide_keybindings/linux.rs`) follow Chromium 150's listeners, Electron 43's: in GPUI's X11 session X11 key grabs (Ctrl+Alt+F<n> stays with XKB's VT switch), in its Wayland session the xdg-desktop-portal GlobalShortcuts session `GlobalAcceleratorListenerLinux` keeps. A registration there always succeeds; each changed set closes the session, lists the stored shortcuts and binds them with the set when one is missing, with Electron's description (`<nameShort> shortcut: <accelerator>`) and the `preferred_trigger` Electron's `GlobalShortcutsPortalPreferredTrigger` turns on. Differences: the shortcut id is the accelerator (Chromium hashes a per-profile UUID into it), no parent window is passed (Electron passes none either), and an Activated signal is matched by id, not by session path (ashpd keeps the path private). Tested against a fake portal on a private bus (`portal_binds_the_accelerators_and_reports_activations`); not run against GNOME's or KDE's portal.
+- Message boxes (`dialog/linux.rs`) follow Electron 43's message_box_gtk.cc in GPUI's X11 session: a GTK message dialog with GTK's stock Cancel, No, Ok and Yes labels and a check button for `checkboxLabel`, transient for the GPUI window and modal, its buttons in the order dialogs.ts `massageMessageBoxOptions` gives Linux (cancel second, then reversed, the primary last and default). Difference: Electron also disables the parent window (`SetEnabled(false)`); GPUI has no such switch, so the GPUI window still takes input behind the dialog. In a Wayland session, where `webview::supported` has no GTK, the custom workbench dialog shows instead. Tests: `cargo gc test -p app dialog::linux` under Xvfb.
## Accepted platform differences