Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

fix(linux): ask for the Wayland screenshot permission while Cap has focus (#3293)

Richie McIlroy3bea07756089
diff --git a/.github/workflows/linux-desktop-reliability.yml b/.github/workflows/linux-desktop-reliability.yml
index 775063a4c..3122784b9 100644
--- a/.github/workflows/linux-desktop-reliability.yml
+++ b/.github/workflows/linux-desktop-reliability.yml
@@ -253,6 +253,21 @@ jobs:
grep -qx "$line" "$RUNNER_TEMP/out/gnome-wallpaper/result.txt"
done
+ # GNOME asks once whether Cap may take screenshots, and only while Cap
+ # has focus.
+ - name: GNOME 50 screenshot, allowed when the portal asks
+ env:
+ DEV_BIN: ${{ github.workspace }}/apps/desktop-gpui/target/debug/cap-gpui
+ DEV_LIBS: ${{ github.workspace }}/target/native-deps/lib
+ SCENARIO: screenshot
+ run: |
+ sudo -E bash scripts/linux-desktop-harness/run-desktop.sh gnome "$RUNNER_TEMP/cap.deb" \
+ "$RUNNER_TEMP/out/gnome-screenshot" LAUNCH=dock GNOME_UNSAFE=1
+ cat "$RUNNER_TEMP/out/gnome-screenshot/result.txt" "$RUNNER_TEMP/out/gnome-screenshot/actions.log"
+ for line in screenshot_taken=yes screenshot_size=yes capture_failed=0 cap_alive=yes panics=0; do
+ grep -qx "$line" "$RUNNER_TEMP/out/gnome-screenshot/result.txt"
+ done
+
- name: Check results
run: |
bash scripts/linux-desktop-harness/check-results.sh \
@@ -319,6 +334,18 @@ jobs:
"$RUNNER_TEMP/out/hyprland-gl" LAUNCH=dock VK_ICD_FILENAMES=/nonexistent.json
grep -q 'Selected GPU adapter: .*(Gl)' "$RUNNER_TEMP/out/hyprland-gl/cap.log"
+ - name: Hyprland screenshot
+ env:
+ SCENARIO: screenshot
+ run: |
+ sudo -E env DEV_BIN="$RUNNER_TEMP/build/cap-gpui" DEV_LIBS="$RUNNER_TEMP/build/libs" \
+ bash scripts/linux-desktop-harness/run-desktop.sh hyprland "$RUNNER_TEMP/build/cap-gpui" \
+ "$RUNNER_TEMP/out/hyprland-screenshot" LAUNCH=dock
+ cat "$RUNNER_TEMP/out/hyprland-screenshot/result.txt"
+ for line in screenshot_taken=yes screenshot_size=yes capture_failed=0 cap_alive=yes panics=0; do
+ grep -qx "$line" "$RUNNER_TEMP/out/hyprland-screenshot/result.txt"
+ done
+
- name: Hyprland clipboard (Ctrl+V into and Ctrl+C out of a text field)
env:
SCENARIO: clipboard
diff --git a/apps/desktop-gpui/src/screenshot.rs b/apps/desktop-gpui/src/screenshot.rs
index b01af4894..af88148f5 100644
--- a/apps/desktop-gpui/src/screenshot.rs
+++ b/apps/desktop-gpui/src/screenshot.rs
@@ -29,6 +29,43 @@ pub fn take_screenshot(target: ScreenCaptureTarget, cx: &mut App) {
}
tracing::info!(kind = target.kind_str(), "taking a screenshot");
+ #[cfg(target_os = "linux")]
+ if cap_recording::screenshot::uses_wayland_portal()
+ && matches!(
+ target,
+ ScreenCaptureTarget::Display { .. } | ScreenCaptureTarget::Area { .. }
+ )
+ && !WAYLAND_SCREENSHOTS_ALLOWED.load(std::sync::atomic::Ordering::Acquire)
+ {
+ // Asked while the picker still has focus: GNOME Shell shows the
+ // permission question only for the focused app, and the capture below
+ // hides the picker first.
+ let request = gpui_tokio::Tokio::spawn_result(
+ cx,
+ cap_recording::screenshot::request_wayland_screenshot_permission(),
+ );
+ cx.spawn(async move |cx| match request.await {
+ Ok(()) => {
+ WAYLAND_SCREENSHOTS_ALLOWED.store(true, std::sync::atomic::Ordering::Release);
+ tracing::info!("the desktop allows Cap's screenshots");
+ cx.update(|cx| capture(target, cx));
+ }
+ // The picker is still up, so the user can try again.
+ Err(error) => tracing::error!("screenshot capture failed: {error:#}"),
+ })
+ .detach();
+ return;
+ }
+ capture(target, cx);
+}
+
+/// Set once the screenshot portal has answered a request: the permission it
+/// may have asked for is granted for the rest of the session.
+#[cfg(target_os = "linux")]
+static WAYLAND_SCREENSHOTS_ALLOWED: std::sync::atomic::AtomicBool =
+ std::sync::atomic::AtomicBool::new(false);
+
+fn capture(target: ScreenCaptureTarget, cx: &mut App) {
let settle = app_windows::prepare_for_screenshot_capture(cx);
let task = gpui_tokio::Tokio::spawn_result(cx, async move {
diff --git a/crates/recording/src/screenshot.rs b/crates/recording/src/screenshot.rs
index fa88ec9f3..5cee43a30 100644
--- a/crates/recording/src/screenshot.rs
+++ b/crates/recording/src/screenshot.rs
@@ -1174,6 +1174,31 @@ pub fn uses_wayland_portal() -> bool {
prefers_wayland_portal()
}
+/// Asks the screenshot portal for one screenshot and throws it away. Before
+/// an app's first non-interactive screenshot the portal asks the user whether
+/// to allow it, and GNOME Shell only shows that question for the focused app,
+/// so this runs while Cap's picker still has focus, before it hides for the
+/// real capture.
+#[cfg(target_os = "linux")]
+pub async fn request_wayland_screenshot_permission() -> anyhow::Result<()> {
+ let screenshot = ashpd::desktop::screenshot::Screenshot::request()
+ .interactive(false)
+ .send()
+ .await
+ .context("Request Wayland screenshot from desktop portal")?
+ .response()
+ .context("The desktop did not allow Cap to take screenshots")?;
+ let uri = screenshot.uri();
+ if is_local_wayland_screenshot_uri(uri.scheme(), uri.host_str())
+ && let Ok(path) = uri.to_file_path()
+ && std::fs::symlink_metadata(&path).is_ok_and(|metadata| metadata.file_type().is_file())
+ && let Err(error) = std::fs::remove_file(&path)
+ {
+ tracing::warn!(path = %path.display(), %error, "Could not remove the permission screenshot");
+ }
+ Ok(())
+}
+
#[cfg(target_os = "linux")]
async fn capture_screenshot_wayland(target: &ScreenCaptureTarget) -> anyhow::Result<RgbImage> {
let display_id = wayland_screenshot_display_id(target)?;
diff --git a/scripts/linux-desktop-harness/README.md b/scripts/linux-desktop-harness/README.md
index 8f3ce8cf1..971b86217 100644
--- a/scripts/linux-desktop-harness/README.md
+++ b/scripts/linux-desktop-harness/README.md
@@ -51,6 +51,11 @@ the editor and presses the Image background's picker
portal's file chooser through `mutter-keys.py --type` and presses Select.
Mutter's RemoteDesktop drops the first key of each session, so `mutter-keys.py`
leads every session with a Shift tap.
+`SCENARIO=screenshot` takes a screenshot of the display the way the
+screenshot mode does, with Cap focused as after a click, and allows it when
+the portal asks (GNOME Shell's question is answered from the Shell, so it needs
+`GNOME_UNSAFE=1`; elsewhere the permission is granted up front because the GTK
+portal's dialog aborts in the container). It checks a PNG of the display's size (`SCREEN`, 1920x1080) was saved.
`SCENARIO=wallpaper` records a clip, opens it in the editor and imports the
desktop's wallpaper as its background (`CAP_GPUI_AUTO_DESKTOP_BACKGROUND=1`).
GNOME keeps its default JPEG XL wallpaper; `WALLPAPER=swaybg` starts swaybg
diff --git a/scripts/linux-desktop-harness/scenario-screenshot.sh b/scripts/linux-desktop-harness/scenario-screenshot.sh
new file mode 100755
index 000000000..14bce51ce
--- /dev/null
+++ b/scripts/linux-desktop-harness/scenario-screenshot.sh
@@ -0,0 +1,83 @@
+#!/usr/bin/env bash
+set -uo pipefail
+here=$(cd "$(dirname "$0")" && pwd)
+export XDG_RUNTIME_DIR=/run/user/$(id -u)
+export DBUS_SESSION_BUS_ADDRESS=unix:path=$XDG_RUNTIME_DIR/bus
+out=${HARNESS_OUT:-/out}
+eval "$(systemctl --user show-environment | grep -E "^(WAYLAND_DISPLAY|XDG_SESSION_TYPE|XDG_CURRENT_DESKTOP|XDG_SESSION_DESKTOP|LIBGL_ALWAYS_SOFTWARE|HYPRLAND_INSTANCE_SIGNATURE|NIRI_SOCKET)=" | sed 's/^/export /')"
+: >"$out/result.txt"
+result() { printf '%s=%s\n' "$1" "$2" >>"$out/result.txt"; }
+
+# Outside GNOME the question comes from the GTK portal, which aborts in this
+# container (its image loader sandbox cannot start), so the permission is
+# granted up front there; GNOME Shell asks for real.
+if [[ $XDG_CURRENT_DESKTOP != *GNOME* ]]; then
+ for app in Cap so.cap.Cap ""; do
+ gdbus call --session --dest org.freedesktop.impl.portal.PermissionStore \
+ --object-path /org/freedesktop/impl/portal/PermissionStore \
+ --method org.freedesktop.impl.portal.PermissionStore.SetPermission \
+ screenshot true screenshot "$app" "['yes']" >/dev/null 2>&1
+ done
+fi
+
+# LAUNCH=dock starts Cap in the unit GNOME's app grid gives it, as
+# scenario-start-stop.sh does; LAUNCH=terminal from a shell.
+if [[ ${LAUNCH:-dock} == dock ]]; then
+ export CAP_LAUNCH_PREFIX="systemd-run --user --scope --quiet --unit=app-gnome-Cap-$$.scope"
+fi
+pid=$(bash "$here/launch-cap.sh" cap CAP_GPUI_AUTO_RECORD=screenshot CAP_GPUI_AUTO_OVERLAY=display)
+
+# A person starts a screenshot by clicking Cap, so Cap has focus when the
+# portal asks; the automated start does not click.
+focus_cap() {
+ if [[ $XDG_CURRENT_DESKTOP == *GNOME* ]]; then
+ gdbus call --session --dest org.gnome.Shell --object-path /org/gnome/Shell --method org.gnome.Shell.Eval \
+ "global.display.list_all_windows().filter(w => w.get_wm_class() === 'Cap' && w.showing_on_its_workspace()).forEach(w => w.activate(global.display.get_current_time_roundtrip()))" \
+ >/dev/null 2>&1
+ elif [[ -n ${HYPRLAND_INSTANCE_SIGNATURE:-} ]]; then
+ hyprctl dispatch focuswindow class:Cap >/dev/null 2>&1
+ fi
+}
+for _ in $(seq 60); do
+ grep -aq "taking a screenshot" "$out/cap.log" 2>/dev/null && break
+ focus_cap
+ sleep 0.1
+done
+if [[ $XDG_CURRENT_DESKTOP == *GNOME* ]]; then
+ gdbus call --session --dest org.gnome.Shell --object-path /org/gnome/Shell --method org.gnome.Shell.Eval \
+ "(imports.gi.Shell.WindowTracker.get_default().focus_app || {get_id: () => 'none'}).get_id()" \
+ 2>&1 | sed 's/^/focused app: /' >>"$out/actions.log"
+fi
+shot=""
+for _ in $(seq 120); do
+ shot=$(find "$out/profile" -path "*screenshots/*.cap/original.png" 2>/dev/null | head -1)
+ [[ -n $shot ]] && break
+ # The portal's one-time question, "Allow Cap to Take Screenshots?": GNOME
+ # Shell draws it (no accessibility tree here, so its button is clicked from
+ # the Shell), elsewhere the GTK portal does.
+ if [[ $XDG_CURRENT_DESKTOP == *GNOME* ]]; then
+ gdbus call --session --dest org.gnome.Shell --object-path /org/gnome/Shell --method org.gnome.Shell.Eval \
+ "(() => { const find = a => { if (a instanceof imports.gi.St.Button && a.label === 'Allow') return a; for (const c of a.get_children()) { const f = find(c); if (f) return f; } return null; }; const b = find(global.stage); if (!b) return 'none'; b.emit('clicked', 1); return 'clicked Allow'; })()" \
+ 2>&1 | grep -o "clicked Allow" >>"$out/actions.log"
+ else
+ python3 "$here/atspi-press.py" "xdg-desktop-portal-gtk|xdg-desktop-portal-gnome" "^Allow$" 1 >>"$out/actions.log" 2>&1
+ fi
+ sleep 0.5
+done
+sleep 1
+size=""
+[[ -n $shot ]] && size=$(python3 -c 'import struct, sys
+data = open(sys.argv[1], "rb").read(24)
+if data[:8] == b"\x89PNG\r\n\x1a\n":
+ print(*struct.unpack(">II", data[16:24]))' "$shot")
+echo "screenshot: ${shot:-none} ${size:-}" >>"$out/actions.log"
+result screenshot_taken "$([[ -n $size ]] && echo yes || echo no)"
+result screenshot_size "$([[ ${size// /x} == "${SCREEN:-1920x1080}" ]] && echo yes || echo "${size// /x}")"
+result capture_failed "$(grep -ac 'screenshot capture failed' "$out/cap.log")"
+if [[ -z $shot ]]; then
+ find "$HOME" /tmp -newer "$out/profile/store" -iname "Screenshot*.png" -printf "portal file: %s bytes %p\n" 2>/dev/null >>"$out/actions.log"
+ journalctl --user --no-pager -n 300 2>/dev/null | grep -iE "access dialog|screenshot|portal-(gtk|hyprland|gnome)\[" | tail -8 >>"$out/actions.log"
+fi
+result cap_alive "$(kill -0 "$pid" 2>/dev/null && echo yes || echo no)"
+result panics "$(grep -ac 'panicked at' "$out/cap.log")"
+cat "$out/result.txt"