Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

fix(desktop-gpui): show confirmations and alerts on Linux desktops without zenity (#3158)

Richie McIlroyec15b9840344
diff --git a/.github/workflows/linux-desktop-reliability.yml b/.github/workflows/linux-desktop-reliability.yml
index 7a6f64cf0..4e20876e3 100644
--- a/.github/workflows/linux-desktop-reliability.yml
+++ b/.github/workflows/linux-desktop-reliability.yml
@@ -99,6 +99,12 @@ jobs:
- name: Build cap-gpui
run: cargo +1.95.0 build --manifest-path apps/desktop-gpui/Cargo.toml --locked --bin cap-gpui
+ - name: Confirmation dialog without zenity (X11 input)
+ run: |
+ sudo apt-get install -y -qq xdotool xvfb >/dev/null
+ bash scripts/linux-desktop-harness/dialog-x11.sh \
+ apps/desktop-gpui/target/debug/cap-gpui target/native-deps/lib
+
- name: Fetch the Cap package for desktop integration
run: |
curl --fail --location --retry 3 -o "$RUNNER_TEMP/cap.deb" "$CAP_DEB_URL"
diff --git a/apps/desktop-gpui/src/linux_dialog.rs b/apps/desktop-gpui/src/linux_dialog.rs
new file mode 100644
index 000000000..359d817d3
--- /dev/null
+++ b/apps/desktop-gpui/src/linux_dialog.rs
@@ -0,0 +1,197 @@
+//! Confirmations and alerts on Linux desktops without zenity.
+//!
+//! `rfd`'s portal backend shows every message dialog by running `zenity`, and
+//! answers Cancel when it cannot. Most Arch, NixOS, Hyprland and Niri installs
+//! have no zenity, so every confirmation (delete a recording, run the
+//! diagnostic, discard a recording) silently said no and every alert (export
+//! failed, sign in failed) never appeared.
+//!
+//! Without zenity, the dialog runs in a second copy of this binary started
+//! with [`ARG`]: one small window showing the app's own prompt, whose answer is
+//! the exit status. Callers keep the blocking, zenity-shaped API they already
+//! use, and desktops that have zenity keep it.
+
+use gpui::{
+ App, AppContext as _, Bounds, Context, IntoElement, Render, Styled as _, Window, WindowBounds,
+ WindowOptions, div, point, px, size,
+};
+use serde::{Deserialize, Serialize};
+
+pub const ARG: &str = "--cap-linux-dialog";
+
+const ACCEPTED: i32 = 0;
+const DECLINED: i32 = 1;
+
+#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
+pub struct Request {
+ pub title: String,
+ pub message: String,
+ pub accept: String,
+ /// `None` for an alert with a single button.
+ pub cancel: Option<String>,
+}
+
+pub fn zenity_available() -> bool {
+ std::env::var_os("PATH").is_some_and(|path| zenity_on(&path))
+}
+
+fn zenity_on(path: &std::ffi::OsStr) -> bool {
+ std::env::split_paths(path).any(|dir| {
+ std::fs::metadata(dir.join("zenity"))
+ .is_ok_and(|metadata| metadata.is_file() && is_executable(&metadata))
+ })
+}
+
+fn is_executable(metadata: &std::fs::Metadata) -> bool {
+ use std::os::unix::fs::PermissionsExt as _;
+ metadata.permissions().mode() & 0o111 != 0
+}
+
+/// Shows `request` in a dialog process and blocks until it is answered.
+/// `None` when the process could not run, so the caller can fall back.
+pub fn show(request: &Request) -> Option<bool> {
+ let executable = std::env::current_exe().ok()?;
+ let payload = serde_json::to_string(request).ok()?;
+ let status = std::process::Command::new(executable)
+ .arg(ARG)
+ .arg(payload)
+ .stdin(std::process::Stdio::null())
+ .status()
+ .map_err(|error| tracing::warn!(%error, "could not start the Cap dialog process"))
+ .ok()?;
+ match status.code() {
+ Some(ACCEPTED) => Some(true),
+ Some(DECLINED) => Some(false),
+ _ => {
+ tracing::warn!(%status, "the Cap dialog process ended without an answer");
+ None
+ }
+ }
+}
+
+pub fn run_from_args() -> Option<i32> {
+ let mut args = std::env::args().skip(1);
+ if args.next().as_deref() != Some(ARG) {
+ return None;
+ }
+ let Some(request) = args
+ .next()
+ .and_then(|payload| serde_json::from_str::<Request>(&payload).ok())
+ else {
+ return Some(2);
+ };
+ let app = gpui_platform::application().with_assets(crate::assets::Assets);
+ app.run(move |cx: &mut App| {
+ if let Err(error) = crate::assets::Assets.load_fonts(cx) {
+ eprintln!("Cap dialog: could not load fonts: {error:#}");
+ }
+ open(request, cx);
+ });
+ // The window was closed without an answer.
+ Some(DECLINED)
+}
+
+const WIDTH: f32 = 460.;
+const HEIGHT: f32 = 240.;
+
+struct DialogWindow {
+ theme: crate::theme::Theme,
+}
+
+impl Render for DialogWindow {
+ fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
+ div().size_full().bg(self.theme.gray_1)
+ }
+}
+
+fn open(request: Request, cx: &mut App) {
+ let title = request.title.clone();
+ let opened = cx.open_window(
+ WindowOptions {
+ window_bounds: Some(WindowBounds::Windowed(Bounds {
+ origin: point(px(0.), px(0.)),
+ size: size(px(WIDTH), px(HEIGHT)),
+ })),
+ titlebar: Some(gpui::TitlebarOptions {
+ title: Some(title.into()),
+ ..Default::default()
+ }),
+ app_id: Some(crate::app_windows::APP_ID.into()),
+ focus: true,
+ show: true,
+ is_resizable: false,
+ is_minimizable: false,
+ ..Default::default()
+ },
+ |window, cx| {
+ cx.new(|cx| {
+ crate::theme::bind_window(window, cx);
+ DialogWindow {
+ theme: crate::theme::Theme::for_window(window, cx, false),
+ }
+ })
+ },
+ );
+ let Ok(handle) = opened else {
+ std::process::exit(2);
+ };
+ let _ = handle.update(cx, move |_, window, cx| {
+ let answer: std::pin::Pin<Box<dyn std::future::Future<Output = bool>>> =
+ match &request.cancel {
+ Some(cancel) => Box::pin(crate::editor_modal::confirm_action(
+ &request.title,
+ &request.message,
+ &request.accept,
+ cancel,
+ window,
+ cx,
+ )),
+ None => Box::pin(crate::editor_modal::informational_alert(
+ &request.title,
+ &request.message,
+ window,
+ cx,
+ )),
+ };
+ window
+ .spawn(cx, async move |_| {
+ let accepted = answer.await;
+ std::process::exit(if accepted { ACCEPTED } else { DECLINED });
+ })
+ .detach();
+ });
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn requests_round_trip_through_the_command_line() {
+ let request = Request {
+ title: "Run diagnostic?".into(),
+ message: "Cap will \"take over\" your screen\nfor a while.".into(),
+ accept: "Run Diagnostic".into(),
+ cancel: Some("Cancel".into()),
+ };
+ let payload = serde_json::to_string(&request).unwrap();
+ assert_eq!(serde_json::from_str::<Request>(&payload).unwrap(), request);
+ }
+
+ #[test]
+ fn zenity_lookup_follows_path_and_needs_an_executable() {
+ let dir = tempfile::tempdir().unwrap();
+ let zenity = dir.path().join("zenity");
+ std::fs::write(&zenity, "#!/bin/sh\n").unwrap();
+ let empty = tempfile::tempdir().unwrap();
+ let path = std::env::join_paths([empty.path(), dir.path()]).unwrap();
+ let found = |mode: u32| {
+ use std::os::unix::fs::PermissionsExt as _;
+ std::fs::set_permissions(&zenity, std::fs::Permissions::from_mode(mode)).unwrap();
+ zenity_on(&path)
+ };
+ assert!(found(0o755));
+ assert!(!found(0o644));
+ assert!(!zenity_on(empty.path().as_os_str()));
+ }
+}
diff --git a/apps/desktop-gpui/src/main.rs b/apps/desktop-gpui/src/main.rs
index ad918896d..f4a441758 100644
--- a/apps/desktop-gpui/src/main.rs
+++ b/apps/desktop-gpui/src/main.rs
@@ -47,6 +47,8 @@ mod i18n;
mod import;
mod installer;
mod jpeg_thumbnail;
+#[cfg(not(any(target_os = "macos", target_os = "windows")))]
+mod linux_dialog;
mod library;
mod main_window;
mod media_access;
@@ -289,6 +291,14 @@ fn main() {
std::process::exit(1);
}
+ // A confirmation or alert shown for the running app on a desktop without
+ // zenity (`linux_dialog`): not a second Cap, so before logging and the
+ // single-instance check.
+ #[cfg(not(any(target_os = "macos", target_os = "windows")))]
+ if let Some(status) = linux_dialog::run_from_args() {
+ std::process::exit(status);
+ }
+
let _log_guard = init_logging();
crash_capture::install(&diagnostics::logs_dir());
diff --git a/apps/desktop-gpui/src/platform.rs b/apps/desktop-gpui/src/platform.rs
index d61c2d38b..70368f3bf 100644
--- a/apps/desktop-gpui/src/platform.rs
+++ b/apps/desktop-gpui/src/platform.rs
@@ -2857,6 +2857,16 @@ mod stub {
cancel: &str,
warning: bool,
) -> bool {
+ if !crate::linux_dialog::zenity_available()
+ && let Some(accepted) = crate::linux_dialog::show(&crate::linux_dialog::Request {
+ title: title.to_string(),
+ message: message.to_string(),
+ accept: accept.to_string(),
+ cancel: Some(cancel.to_string()),
+ })
+ {
+ return accepted;
+ }
let level = if warning {
rfd::MessageLevel::Warning
} else {
@@ -2875,6 +2885,17 @@ mod stub {
}
pub fn alert_dialog(title: &str, message: &str) {
+ if !crate::linux_dialog::zenity_available()
+ && crate::linux_dialog::show(&crate::linux_dialog::Request {
+ title: title.to_string(),
+ message: message.to_string(),
+ accept: "OK".to_string(),
+ cancel: None,
+ })
+ .is_some()
+ {
+ return;
+ }
let _ = rfd::MessageDialog::new()
.set_title(title)
.set_description(message)
diff --git a/scripts/linux-desktop-harness/dialog-x11.sh b/scripts/linux-desktop-harness/dialog-x11.sh
new file mode 100755
index 000000000..39fc107a6
--- /dev/null
+++ b/scripts/linux-desktop-harness/dialog-x11.sh
@@ -0,0 +1,49 @@
+#!/usr/bin/env bash
+# The Linux confirmation dialog for desktops without zenity
+# (apps/desktop-gpui/src/linux_dialog.rs), answered with real X input on Xvfb:
+# Escape and Enter on the preselected Cancel decline, Tab then Enter and a
+# click on the accept button accept; an alert closes on its OK button, Enter
+# and Escape. Fails unless every answer is right.
+# Usage: dialog-x11.sh <cap-gpui> <ffmpeg lib dir>
+set -u
+command -v xdotool >/dev/null && command -v Xvfb >/dev/null || { echo "install xdotool and xvfb" >&2; exit 2; }
+bin=$1; libs=$2
+export LD_LIBRARY_PATH=$libs
+unset WAYLAND_DISPLAY
+Xvfb :77 -screen 0 1280x800x24 >/dev/null 2>&1 & xvfb=$!
+export DISPLAY=:77
+sleep 1
+confirm='{"title":"Run diagnostic?","message":"Cap will take over your screen with a flashing pattern and play loud beeps.","accept":"Run Diagnostic","cancel":"Cancel"}'
+alert='{"title":"Export failed","message":"The export could not finish.","accept":"OK","cancel":null}'
+payload=$confirm title="Run diagnostic"
+run() {
+ local name=$1; shift
+ "$bin" --cap-linux-dialog "$payload" >/tmp/dialog-$name.log 2>&1 & local p=$!
+ for _ in $(seq 50); do xdotool search --name "$title" >/dev/null 2>&1 && break; sleep 0.2; done
+ local win; win=$(xdotool search --name "$title" | head -1)
+ sleep 1
+ xdotool windowactivate --sync "$win" >/dev/null 2>&1 || xdotool windowfocus "$win"
+ "$@" "$win"
+ for _ in $(seq 25); do kill -0 $p 2>/dev/null || break; sleep 0.2; done
+ if kill -0 $p 2>/dev/null; then echo "$name: still open"; kill $p; else wait $p; echo "$name: exit=$?"; fi
+}
+keys() { local win=${!#}; set -- "${@:1:$#-1}"; for k in "$@"; do xdotool key --window "$win" "$k"; sleep 0.2; done; }
+click() { local win=$3; eval "$(xdotool getwindowgeometry --shell "$win")"; xdotool mousemove $((X + WIDTH * $1 / 1000)) $((Y + HEIGHT * $2 / 1000)) click 1; }
+failures=0
+expect() {
+ local want=$1 name=$2; shift 2
+ local got; got=$(run "$name" "$@")
+ echo "$got"
+ [[ $got == "$name: exit=$want" ]] || failures=$((failures + 1))
+}
+expect 1 escape keys Escape
+expect 0 tab-enter keys Tab Return
+expect 1 enter-default keys Return
+expect 0 click-accept click 276 683
+expect 1 click-cancel click 722 683
+payload=$alert title="Export failed"
+expect 0 alert-click-ok click 502 641
+expect 0 alert-enter keys Return
+expect 0 alert-escape keys Escape
+kill $xvfb
+exit $failures