Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

fix(linux): relaunching Cap brings its window to the front on GNOME Wayland (#3245)

Richie McIlroyedaacfa92d62
diff --git a/.github/workflows/linux-desktop-reliability.yml b/.github/workflows/linux-desktop-reliability.yml
index e56634702..41d8ff30c 100644
--- a/.github/workflows/linux-desktop-reliability.yml
+++ b/.github/workflows/linux-desktop-reliability.yml
@@ -162,6 +162,19 @@ jobs:
cat "$RUNNER_TEMP/out/gnome-reopen/result.txt"
grep -qx reopen_forwarded=yes "$RUNNER_TEMP/out/gnome-reopen/result.txt"
+ - name: GNOME 50 relaunch brings Cap to the front over its settings
+ env:
+ DEV_BIN: ${{ github.workspace }}/apps/desktop-gpui/target/debug/cap-gpui
+ DEV_LIBS: ${{ github.workspace }}/target/native-deps/lib
+ SCENARIO: raise
+ run: |
+ for window in main onboarding; do
+ sudo -E bash scripts/linux-desktop-harness/run-desktop.sh gnome "$RUNNER_TEMP/cap.deb" \
+ "$RUNNER_TEMP/out/gnome-raise-$window" GNOME_UNSAFE=1 RAISE_WINDOW=$window
+ cat "$RUNNER_TEMP/out/gnome-raise-$window/result.txt"
+ grep -qx main_raised=yes "$RUNNER_TEMP/out/gnome-raise-$window/result.txt"
+ done
+
- name: Check results
run: |
bash scripts/linux-desktop-harness/check-results.sh \
diff --git a/apps/desktop-gpui/patches/zed-wayland-activation.patch b/apps/desktop-gpui/patches/zed-wayland-activation.patch
new file mode 100644
index 000000000..3ad72f9fb
--- /dev/null
+++ b/apps/desktop-gpui/patches/zed-wayland-activation.patch
@@ -0,0 +1,57 @@
+diff --git a/crates/gpui/src/platform.rs b/crates/gpui/src/platform.rs
+index 7dd2d38..b597e4d 100644
+--- a/crates/gpui/src/platform.rs
++++ b/crates/gpui/src/platform.rs
+@@ -844,6 +844,14 @@ pub trait PlatformWindow: HasWindowHandle + HasDisplayHandle {
+ anyhow::bail!("Retained window visibility is unsupported by this backend")
+ }
+ fn activate(&self);
++ /// Activates the window with a token the compositor issued to another
++ /// client, such as the `XDG_ACTIVATION_TOKEN` a launcher gave a second
++ /// instance of the app. Focus stealing prevention honours it where a
++ /// token the window requests for itself is refused.
++ fn activate_with_token(&self, token: String) {
++ let _ = token;
++ self.activate();
++ }
+ /// Requests that the operating system draw attention to this window.
+ fn request_attention(&self) {}
+ fn is_active(&self) -> bool;
+diff --git a/crates/gpui/src/window.rs b/crates/gpui/src/window.rs
+index 75c3539..c543c6b 100644
+--- a/crates/gpui/src/window.rs
++++ b/crates/gpui/src/window.rs
+@@ -5810,6 +5810,12 @@ impl Window {
+ self.platform_window.activate();
+ }
+
++ /// Activates this window with a token the compositor issued to another
++ /// client. See [`PlatformWindow::activate_with_token`].
++ pub fn activate_window_with_token(&self, token: String) {
++ self.platform_window.activate_with_token(token);
++ }
++
+ /// Requests that the operating system draw attention to this window.
+ pub fn request_attention(&self) {
+ self.platform_window.request_attention();
+diff --git a/crates/gpui_linux/src/linux/wayland/window.rs b/crates/gpui_linux/src/linux/wayland/window.rs
+index 5d8e991..e98c640 100644
+--- a/crates/gpui_linux/src/linux/wayland/window.rs
++++ b/crates/gpui_linux/src/linux/wayland/window.rs
+@@ -2134,6 +2134,16 @@ impl PlatformWindow for WaylandWindow {
+ }
+ }
+
++ fn activate_with_token(&self, token: String) {
++ let state = self.borrow();
++ if let Some(activation) = &state.globals.activation {
++ activation.activate(token, &state.surface);
++ return;
++ }
++ drop(state);
++ self.activate();
++ }
++
+ fn request_attention(&self) {}
+
+ fn is_active(&self) -> bool {
diff --git a/apps/desktop-gpui/src/single_instance.rs b/apps/desktop-gpui/src/single_instance.rs
index 3ecf64b33..f08ded5b6 100644
--- a/apps/desktop-gpui/src/single_instance.rs
+++ b/apps/desktop-gpui/src/single_instance.rs
@@ -635,6 +635,38 @@ fn read_linux_reopen_actions(
reader: &mut impl std::io::Read,
owner: LinuxInstanceIdentity,
) -> std::io::Result<LinuxReopenActions> {
+ read_linux_reopen_request(reader, owner).map(|(actions, _)| actions)
+}
+
+/// The longest activation token a relaunch forwards. Compositors issue short
+/// opaque strings; anything this long is not one.
+#[cfg(target_os = "linux")]
+const MAX_ACTIVATION_TOKEN_BYTES: usize = 4096;
+
+#[cfg(target_os = "linux")]
+fn valid_activation_token(token: &str) -> bool {
+ !token.is_empty()
+ && token.len() <= MAX_ACTIVATION_TOKEN_BYTES
+ && token.chars().all(|c| c.is_ascii_graphic())
+}
+
+/// The relaunch's activation token, from the launcher that started it
+/// (`XDG_ACTIVATION_TOKEN` on Wayland). Focus stealing prevention lets the
+/// running instance raise its window with it.
+#[cfg(target_os = "linux")]
+fn launch_activation_token() -> Option<String> {
+ std::env::var("XDG_ACTIVATION_TOKEN")
+ .ok()
+ .filter(|token| valid_activation_token(token))
+}
+
+/// A forwarded relaunch: its actions, and the activation token it came with
+/// (`CAPACTV1` frames, which carry the token ahead of the actions).
+#[cfg(target_os = "linux")]
+fn read_linux_reopen_request(
+ reader: &mut impl std::io::Read,
+ owner: LinuxInstanceIdentity,
+) -> std::io::Result<(LinuxReopenActions, Option<String>)> {
let invalid = || {
std::io::Error::new(
std::io::ErrorKind::InvalidData,
@@ -645,7 +677,27 @@ fn read_linux_reopen_actions(
reader.read_exact(&mut request)?;
let mut header = linux_reopen_payload(owner);
if request == header {
- return Ok(Vec::new());
+ return Ok((Vec::new(), None));
+ }
+ let mut activation = header;
+ activation[..8].copy_from_slice(b"CAPACTV1");
+ let mut token = None;
+ if request == activation {
+ let mut size = [0; 4];
+ reader.read_exact(&mut size)?;
+ let size = u32::from_be_bytes(size) as usize;
+ if size > MAX_ACTIVATION_TOKEN_BYTES {
+ return Err(invalid());
+ }
+ let mut raw = vec![0; size];
+ reader.read_exact(&mut raw)?;
+ let raw = String::from_utf8(raw).map_err(|_| invalid())?;
+ if !valid_activation_token(&raw) {
+ return Err(invalid());
+ }
+ token = Some(raw);
+ request = header;
+ request[..8].copy_from_slice(b"CAPREOP2");
}
header[..8].copy_from_slice(b"CAPREOP2");
if request != header {
@@ -676,7 +728,42 @@ fn read_linux_reopen_actions(
actions.push(parse_linux_reopen_action(raw)?);
remaining = rest;
}
- Ok(actions)
+ Ok((actions, token))
+}
+
+/// Writes a relaunch for the running instance, with the activation token
+/// when there is one.
+#[cfg(target_os = "linux")]
+fn write_linux_reopen_request(
+ writer: &mut impl std::io::Write,
+ owner: LinuxInstanceIdentity,
+ actions: &[u8],
+ token: Option<&str>,
+) -> std::io::Result<()> {
+ let Some(token) = token.filter(|token| valid_activation_token(token)) else {
+ return write_linux_reopen_actions(writer, owner, actions);
+ };
+ if actions.len() > MAX_FORWARDED_DEEP_LINK_BYTES {
+ return Err(std::io::Error::new(
+ std::io::ErrorKind::InvalidData,
+ "Too many forwarded Cap action bytes",
+ ));
+ }
+ let mut header = linux_reopen_payload(owner);
+ header[..8].copy_from_slice(b"CAPACTV1");
+ writer.write_all(&header)?;
+ writer.write_all(&(token.len() as u32).to_be_bytes())?;
+ writer.write_all(token.as_bytes())?;
+ writer.write_all(&(actions.len() as u32).to_be_bytes())?;
+ writer.write_all(actions)
+}
+
+/// The newest activation token a relaunch brought, until the window it
+/// raises is shown.
+#[cfg(target_os = "linux")]
+fn pending_activation_token() -> &'static std::sync::Mutex<Option<String>> {
+ static TOKEN: std::sync::Mutex<Option<String>> = std::sync::Mutex::new(None);
+ &TOKEN
}
#[cfg(target_os = "linux")]
@@ -730,7 +817,12 @@ fn receive_linux_reopen(
stream.set_read_timeout(Some(std::time::Duration::from_millis(250)))?;
stream.set_write_timeout(Some(std::time::Duration::from_millis(250)))?;
linux_peer(stream)?;
- let actions = read_linux_reopen_actions(stream, owner)?;
+ let (actions, token) = read_linux_reopen_request(stream, owner)?;
+ if let Some(token) = token {
+ *pending_activation_token()
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner) = Some(token);
+ }
match requests.try_send(actions) {
Ok(()) => {}
Err(flume::TrySendError::Full(actions)) if actions.is_empty() => {}
@@ -771,6 +863,16 @@ fn send_linux_reopen(
address: std::os::unix::net::SocketAddr,
owner: LinuxInstanceIdentity,
actions: &[u8],
+) -> std::io::Result<()> {
+ send_linux_reopen_with_token(address, owner, actions, None)
+}
+
+#[cfg(target_os = "linux")]
+fn send_linux_reopen_with_token(
+ address: std::os::unix::net::SocketAddr,
+ owner: LinuxInstanceIdentity,
+ actions: &[u8],
+ token: Option<&str>,
) -> std::io::Result<()> {
use std::io::Read;
let started = std::time::Instant::now();
@@ -799,7 +901,7 @@ fn send_linux_reopen(
"The activation socket belongs to another process",
));
}
- write_linux_reopen_actions(&mut stream, owner, actions)?;
+ write_linux_reopen_request(&mut stream, owner, actions, token)?;
let mut reply = [0];
stream.read_exact(&mut reply)?;
if reply != [1] || linux_instance_identity(owner.pid)? != owner {
@@ -810,6 +912,20 @@ fn send_linux_reopen(
Ok(())
}
+/// Whether the running Cap hung up without acknowledging: how an instance from
+/// before activation tokens rejects their frame, and how a current one fails
+/// before it queues anything. A timeout may come after the actions were
+/// queued, so resending then could run them twice.
+#[cfg(target_os = "linux")]
+fn closed_without_queueing(error: &std::io::Error) -> bool {
+ matches!(
+ error.kind(),
+ std::io::ErrorKind::UnexpectedEof
+ | std::io::ErrorKind::ConnectionReset
+ | std::io::ErrorKind::BrokenPipe
+ )
+}
+
#[cfg(target_os = "linux")]
fn forward_linux_reopen(path: &Path, pid: u32) -> std::io::Result<()> {
let actions = linux_reopen_action_payload(std::env::args().skip(1))?;
@@ -819,7 +935,20 @@ fn forward_linux_reopen(path: &Path, pid: u32) -> std::io::Result<()> {
std::thread::Builder::new()
.name("cap-gpui-reopen-request".into())
.spawn(move || {
- let _ = send.send(send_linux_reopen(address, owner, &actions));
+ // An instance from before activation tokens rejects the frame
+ // that carries one; it still reopens without it.
+ let token = launch_activation_token();
+ if token.is_some() {
+ tracing::info!("forwarding the launcher's activation token");
+ }
+ let result = match send_linux_reopen_with_token(address.clone(), owner, &actions, token.as_deref()) {
+ Err(error) if token.is_some() && closed_without_queueing(&error) => {
+ tracing::info!(%error, "the running Cap refused the activation token; reopening without it");
+ send_linux_reopen(address, owner, &actions)
+ }
+ result => result,
+ };
+ let _ = send.send(result);
})?;
receive.recv_timeout(LINUX_REOPEN_TIMEOUT).map_err(|_| {
std::io::Error::new(
@@ -841,6 +970,35 @@ fn linux_reopen_allowed(
&& mode == Some(crate::recording::RecordingMode::Studio)))
}
+/// A hidden main window maps again a moment after it is shown, and an
+/// activation sent before then has no window to raise; the compositor drops
+/// repeats once the token is used.
+#[cfg(target_os = "linux")]
+fn raise_shown_window_with_token(token: String, cx: &mut gpui::App) {
+ let windows = cx.global::<crate::app_windows::AppWindows>();
+ // The reopen brings onboarding forward in place of the main window, which
+ // stays hidden (and unmapped) until onboarding is done.
+ let target: gpui::AnyWindowHandle = match windows.onboarding {
+ Some(onboarding) => onboarding.into(),
+ None => windows.main.into(),
+ };
+ cx.spawn(async move |cx| {
+ for delay in [0, 150, 400, 1000] {
+ cx.background_executor()
+ .timer(std::time::Duration::from_millis(delay))
+ .await;
+ let token = token.clone();
+ if let Err(error) =
+ target.update(cx, |_, window, _| window.activate_window_with_token(token))
+ {
+ tracing::warn!(%error, "the reopened window was gone before it could be raised");
+ return;
+ }
+ }
+ })
+ .detach();
+}
+
#[cfg(target_os = "linux")]
pub fn init_linux_reopen(cx: &mut gpui::App) {
let requests = linux_reopen_channel().1.clone();
@@ -855,8 +1013,16 @@ pub fn init_linux_reopen(cx: &mut gpui::App) {
}
let session = crate::session::RecordingSession::global(cx);
let current = session.read(cx);
+ let token = pending_activation_token()
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner)
+ .take();
if linux_reopen_allowed(current.phase, current.mode(), current.instant_cleanup_safe()) {
crate::app_windows::show_main_window(cx);
+ if let Some(token) = token {
+ tracing::info!("raising the reopened window with the relaunch's activation token");
+ raise_shown_window_with_token(token, cx);
+ }
} else {
tracing::info!("Cap controls remain hidden while recording is changing state or cannot pause");
}
@@ -2370,6 +2536,91 @@ mod linux_reopen_tests {
payload
}
+ #[cfg(target_os = "linux")]
+ #[test]
+ fn only_a_hang_up_resends_the_request_without_its_token() {
+ use std::io::{Read, Write};
+ let owner = linux_instance_identity(std::process::id()).unwrap();
+ let reply = |server: Box<dyn FnOnce(std::os::unix::net::UnixStream) + Send>| {
+ let (mut client, server_end) = std::os::unix::net::UnixStream::pair().unwrap();
+ client
+ .set_read_timeout(Some(std::time::Duration::from_millis(200)))
+ .unwrap();
+ let serving = std::thread::spawn(move || server(server_end));
+ write_linux_reopen_request(&mut client, owner, &[], Some("token")).unwrap();
+ let mut ack = [0];
+ let error = client.read_exact(&mut ack).unwrap_err();
+ serving.join().unwrap();
+ error
+ };
+
+ // An instance from before activation tokens reads the frame, fails to
+ // parse it and hangs up.
+ let rejected = reply(Box::new(|mut stream| {
+ let mut frame = [0; 8];
+ stream.read_exact(&mut frame).unwrap();
+ drop(stream);
+ }));
+ assert!(closed_without_queueing(&rejected), "{rejected:?}");
+
+ // One that queued the actions but has not acknowledged them yet.
+ let slow = reply(Box::new(|mut stream| {
+ let mut frame = [0; 8];
+ stream.read_exact(&mut frame).unwrap();
+ std::thread::sleep(std::time::Duration::from_millis(400));
+ let _ = stream.write_all(&[1]);
+ }));
+ assert!(!closed_without_queueing(&slow), "{slow:?}");
+ }
+
+ /// A relaunch from a launcher brings an activation token, which the
+ /// running instance needs to raise its window past focus stealing
+ /// prevention. Without one the frame stays the legacy one.
+ #[test]
+ fn a_relaunch_forwards_its_activation_token_with_its_actions() {
+ let owner = linux_instance_identity(std::process::id()).unwrap();
+ let mut plain = Vec::new();
+ write_linux_reopen_request(&mut plain, owner, &[], None).unwrap();
+ assert_eq!(plain, linux_reopen_payload(owner));
+
+ let mut bare = Vec::new();
+ write_linux_reopen_request(&mut bare, owner, &[], Some("gnome-shell/Cap/1234-5-host_TIME7")).unwrap();
+ assert_eq!(&bare[..8], b"CAPACTV1");
+ assert_eq!(
+ read_linux_reopen_request(&mut bare.as_slice(), owner).unwrap(),
+ (Vec::new(), Some("gnome-shell/Cap/1234-5-host_TIME7".to_string()))
+ );
+
+ let payload =
+ linux_reopen_action_payload([action_url(&DeepLinkAction::StopRecording)]).unwrap();
+ let mut with_actions = Vec::new();
+ write_linux_reopen_request(&mut with_actions, owner, &payload, Some("token")).unwrap();
+ assert_eq!(
+ read_linux_reopen_request(&mut with_actions.as_slice(), owner).unwrap(),
+ (vec![DeepLinkAction::StopRecording], Some("token".to_string()))
+ );
+
+ // A token with spaces or control characters is not a compositor's.
+ let mut odd = Vec::new();
+ write_linux_reopen_request(&mut odd, owner, &[], Some("two words")).unwrap();
+ assert_eq!(odd, linux_reopen_payload(owner));
+ let mut forged = linux_reopen_payload(owner).to_vec();
+ forged[..8].copy_from_slice(b"CAPACTV1");
+ forged.extend_from_slice(&3u32.to_be_bytes());
+ forged.extend_from_slice(b"a\nb");
+ forged.extend_from_slice(&0u32.to_be_bytes());
+ assert!(read_linux_reopen_request(&mut forged.as_slice(), owner).is_err());
+
+ // Another instance's frame is refused, token or not.
+ let other = LinuxInstanceIdentity {
+ pid: owner.pid.wrapping_add(1),
+ ..owner
+ };
+ let mut foreign = Vec::new();
+ write_linux_reopen_request(&mut foreign, other, &[], Some("token")).unwrap();
+ assert!(read_linux_reopen_request(&mut foreign.as_slice(), owner).is_err());
+ }
+
#[test]
fn duplicate_launch_during_startup_is_authenticated_and_coalesced() {
let owner = linux_instance_identity(std::process::id()).unwrap();
diff --git a/scripts/finalize-linux-appimage.mjs b/scripts/finalize-linux-appimage.mjs
index 63c836932..b1917414a 100644
--- a/scripts/finalize-linux-appimage.mjs
+++ b/scripts/finalize-linux-appimage.mjs
@@ -119,6 +119,36 @@ export async function preserveAppImageWorkingDirectory(appDir) {
await writeFile(launcher, appRunWrapper, { mode: 0o755, flag: "wx" });
}
+// Desktop launchers (GNOME's app grid among them) only hand an app an
+// XDG_ACTIVATION_TOKEN when its entry asks for startup notification. Without
+// one, Wayland focus stealing prevention keeps Cap's first window, and the
+// running Cap a relaunch raises, behind whatever had focus.
+export function withStartupNotify(entry) {
+ if (/^StartupNotify=/m.test(entry)) {
+ return entry.replace(/^StartupNotify=.*$/m, "StartupNotify=true");
+ }
+ return entry.replace(
+ /^\[Desktop Entry\]\n/m,
+ "[Desktop Entry]\nStartupNotify=true\n",
+ );
+}
+
+export async function notifyStartupInDesktopEntries(root, entries) {
+ const changed = [];
+ for (const entry of entries) {
+ const filename = path.join(root, entry);
+ const stats = await lstat(filename).catch(() => null);
+ if (!stats?.isFile()) continue;
+ const before = await readFile(filename, "utf8");
+ const after = withStartupNotify(before);
+ if (after !== before) {
+ await writeFile(filename, after);
+ changed.push(entry);
+ }
+ }
+ return changed;
+}
+
export function runCommand(command, args, options = {}) {
const result = spawnSync(command, args, { stdio: "inherit", ...options });
if (result.error) throw result.error;
@@ -492,6 +522,12 @@ export async function finalizeLinuxAppImage(
...(await removeWebviewRuntime(appDir, { env: tools, run })),
);
}
+ if (!webview) {
+ await notifyStartupInDesktopEntries(appDir, [
+ "Cap.desktop",
+ "usr/share/applications/Cap.desktop",
+ ]);
+ }
await relativizeDirIcon(appDir);
await preserveAppImageWorkingDirectory(appDir);
const output = path.join(work, path.basename(image));
diff --git a/scripts/finalize-linux-gpui-packages.mjs b/scripts/finalize-linux-gpui-packages.mjs
index f9daf4ffd..5c56d3941 100644
--- a/scripts/finalize-linux-gpui-packages.mjs
+++ b/scripts/finalize-linux-gpui-packages.mjs
@@ -1,3 +1,4 @@
+import { createHash } from "node:crypto";
import {
mkdir,
mkdtemp,
@@ -13,11 +14,26 @@ import {
import path from "node:path";
import { pathToFileURL } from "node:url";
import {
+ notifyStartupInDesktopEntries,
runCommand,
signUpdaterArtifact,
withoutUpdaterSecrets,
} from "./finalize-linux-appimage.mjs";
+const DESKTOP_ENTRY = "usr/share/applications/Cap.desktop";
+
+export async function withUpdatedChecksums(md5sums, root, files) {
+ const lines = md5sums.split("\n");
+ for (const file of files) {
+ const digest = createHash("md5")
+ .update(await readFile(path.join(root, file)))
+ .digest("hex");
+ const index = lines.findIndex((line) => line.endsWith(` ${file}`));
+ if (index >= 0) lines[index] = `${digest} ${file}`;
+ }
+ return lines.join("\n");
+}
+
export const webviewDebPackages = new Set([
"libwebkit2gtk-4.1-0",
"libgtk-3-0",
@@ -315,6 +331,7 @@ export async function finalizeGpuiDeb(
const linked = await linkDuplicateLibraries(
path.join(root, "usr", "lib", "cap"),
);
+ const notified = await notifyStartupInDesktopEntries(root, [DESKTOP_ENTRY]);
const control = path.join(root, "DEBIAN", "control");
await verifyDebGlibc(root, await readFile(control, "utf8"), {
env: tools,
@@ -328,6 +345,16 @@ export async function finalizeGpuiDeb(
),
);
const md5sums = path.join(root, "DEBIAN", "md5sums");
+ if (notified.length > 0 && (await stat(md5sums).catch(() => null))) {
+ await writeFile(
+ md5sums,
+ await withUpdatedChecksums(
+ await readFile(md5sums, "utf8"),
+ root,
+ notified,
+ ),
+ );
+ }
if (linked.length > 0 && (await stat(md5sums).catch(() => null))) {
await writeFile(
md5sums,
@@ -430,6 +457,7 @@ export async function finalizeGpuiRpm(
await mkdir(path.join(top, directory), { recursive: true });
}
await run("bsdtar", ["-xf", rpm, "-C", staging], { env: tools });
+ await notifyStartupInDesktopEntries(staging, [DESKTOP_ENTRY]);
const linked = new Set(
(
await linkDuplicateLibraries(path.join(staging, "usr", "lib", "cap"))
diff --git a/scripts/finalize-linux-gpui-packages.test.mjs b/scripts/finalize-linux-gpui-packages.test.mjs
index eabee5c86..0ff62ad07 100644
--- a/scripts/finalize-linux-gpui-packages.test.mjs
+++ b/scripts/finalize-linux-gpui-packages.test.mjs
@@ -1,5 +1,6 @@
import assert from "node:assert/strict";
import { spawnSync } from "node:child_process";
+import { createHash } from "node:crypto";
import {
lstat,
mkdir,
@@ -12,6 +13,10 @@ import {
import { tmpdir } from "node:os";
import path from "node:path";
import { test } from "node:test";
+import {
+ notifyStartupInDesktopEntries,
+ withStartupNotify,
+} from "./finalize-linux-appimage.mjs";
import {
finalizeGpuiDeb,
finalizeGpuiRpm,
@@ -23,6 +28,7 @@ import {
withoutLinkedFiles,
withoutWebviewDebDependencies,
withoutWebviewRpmRequirements,
+ withUpdatedChecksums,
} from "./finalize-linux-gpui-packages.mjs";
const available = (command) =>
@@ -677,3 +683,42 @@ for (const payload of ["usr/bin/Cap", "usr/lib/cap/libmedia.so"]) {
},
);
}
+
+test("Cap's desktop entries ask for startup notification, once", async (t) => {
+ const shipped = `[Desktop Entry]
+Categories=AudioVideo;Video;
+Exec=Cap
+StartupWMClass=Cap
+Name=Cap
+Type=Application
+`;
+ const notified = withStartupNotify(shipped);
+ assert.match(notified, /^\[Desktop Entry\]\nStartupNotify=true\n/);
+ assert.equal(withStartupNotify(notified), notified);
+ assert.equal(
+ withStartupNotify(
+ shipped.replace("Exec=Cap\n", "Exec=Cap\nStartupNotify=false\n"),
+ ),
+ shipped.replace("Exec=Cap\n", "Exec=Cap\nStartupNotify=true\n"),
+ );
+
+ const root = await mkdtemp(path.join(tmpdir(), "cap-desktop-entry-"));
+ t.after(() => rm(root, { recursive: true, force: true }));
+ const entry = "usr/share/applications/Cap.desktop";
+ await mkdir(path.join(root, "usr/share/applications"), { recursive: true });
+ await writeFile(path.join(root, entry), shipped);
+ assert.deepEqual(
+ await notifyStartupInDesktopEntries(root, [entry, "missing.desktop"]),
+ [entry],
+ );
+ assert.deepEqual(await notifyStartupInDesktopEntries(root, [entry]), []);
+ const sums = await withUpdatedChecksums(
+ `0123 usr/bin/Cap\nffff ${entry}\n`,
+ root,
+ [entry],
+ );
+ const digest = createHash("md5")
+ .update(await readFile(path.join(root, entry)))
+ .digest("hex");
+ assert.equal(sums, `0123 usr/bin/Cap\n${digest} ${entry}\n`);
+});
diff --git a/scripts/linux-desktop-harness/README.md b/scripts/linux-desktop-harness/README.md
index 9438b2a4a..5ce305aa1 100644
--- a/scripts/linux-desktop-harness/README.md
+++ b/scripts/linux-desktop-harness/README.md
@@ -28,7 +28,12 @@ Each run (`run-desktop.sh <desktop> <package> <out-dir> [KEY=VALUE...]`):
4. writes `result.txt`, which `check-results.sh` turns into pass or fail.
`SCENARIO=reopen` launches Cap from a terminal and again from the app grid,
-which must hand over to the running instance. `SCENARIO=settings-close` instead opens Cap's settings and closes it with the
+which must hand over to the running instance. `SCENARIO=raise` (with
+`GNOME_UNSAFE=1`) focuses Cap's settings, then has GNOME Shell launch Cap the
+way the app grid does; the activation token the relaunch hands over must bring
+onboarding, or the main window with `RAISE_WINDOW=main`, to the front.
+`MUTTER_DEBUG=focus,startup` writes mutter's reasoning to
+`compositor.debug.log`. `SCENARIO=settings-close` instead opens Cap's settings and closes it with the
window's own close button (GNOME draws no title bar for it). Clicks go through
`mutter-pointer.py`, one virtual pointer that exists before Cap starts: gpui
binds the seat's pointer once, so a pointer created per click never reaches it.
diff --git a/scripts/linux-desktop-harness/gnome-up.sh b/scripts/linux-desktop-harness/gnome-up.sh
index 82373c111..08e5a6e4b 100644
--- a/scripts/linux-desktop-harness/gnome-up.sh
+++ b/scripts/linux-desktop-harness/gnome-up.sh
@@ -32,6 +32,7 @@ gsettings set org.gnome.desktop.interface toolkit-accessibility true
systemctl --user reset-failed gnome-headless.service >/dev/null 2>&1 || true
systemd-run --user --unit=gnome-headless --collect \
-p StandardOutput=file:"$out/compositor.log" -p StandardError=inherit \
+ ${MUTTER_DEBUG:+-p Environment=MUTTER_DEBUG=$MUTTER_DEBUG -p StandardError=file:"$out/compositor.debug.log"} \
gnome-shell --headless --wayland --no-x11 --virtual-monitor 1920x1080 ${GNOME_UNSAFE:+--unsafe-mode}
for _ in $(seq 600); do
diff --git a/scripts/linux-desktop-harness/scenario-raise.sh b/scripts/linux-desktop-harness/scenario-raise.sh
new file mode 100755
index 000000000..d997e282e
--- /dev/null
+++ b/scripts/linux-desktop-harness/scenario-raise.sh
@@ -0,0 +1,84 @@
+#!/usr/bin/env bash
+# Cap is running with another window focused (its settings); GNOME Shell then
+# launches Cap again the way the app grid launches any app, with an
+# activation token. The relaunch must hand over to the running Cap and bring
+# its main window to the front. Needs GNOME_UNSAFE=1 (Shell.Eval).
+# Prints key=value results to $HARNESS_OUT/result.txt.
+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)=" | sed 's/^/export /')"
+
+: >"$out/result.txt"
+result() { printf '%s=%s\n' "$1" "$2" >>"$out/result.txt"; }
+shell() {
+ gdbus call --session --dest org.gnome.Shell --object-path /org/gnome/Shell \
+ --method org.gnome.Shell.Eval "$1" 2>/dev/null
+}
+focused() { shell "global.display.focus_window ? global.display.focus_window.get_title() : ''" | sed -n "s/^(true, '\"\\(.*\\)\"')$/\\1/p"; }
+wait_log() {
+ for _ in $(seq $(($3 * 4))); do
+ grep -q -- "$2" "$out/$1.log" 2>/dev/null && return 0
+ sleep 0.25
+ done
+ return 1
+}
+
+# RAISE_WINDOW=main reopens a Cap that finished setup; the default reopens one
+# still showing onboarding, which the reopen brings forward instead.
+expected="Welcome to Cap"
+if [[ ${RAISE_WINDOW:-onboarding} == main ]]; then
+ expected=Cap
+ mkdir -p "$out/profile"
+ cat >"$out/profile/store" <<'JSON'
+{
+ "general_settings": {
+ "hasCompletedStartup": true,
+ "hasCompletedOnboarding": true,
+ "enableNotifications": false,
+ "enableTelemetry": false,
+ "recordingCountdown": 0
+ }
+}
+JSON
+fi
+result window "$expected"
+
+CAP_ARGS='cap-desktop://action?value=%7B%22open_settings%22%3A%7B%22page%22%3Anull%7D%7D' \
+ bash "$here/launch-cap.sh" cap >/dev/null
+if ! wait_log cap "settings window opened" 30; then
+ result first_ready no
+ exit 0
+fi
+shell 'Main.overview.hide()' >/dev/null
+sleep 2
+shell "global.display.list_all_windows().find(w => w.get_title() === 'Cap Settings').activate(global.display.get_current_time_roundtrip())" >/dev/null
+sleep 1
+before=$(focused)
+result focused_before "${before:-none}"
+
+# The same build and profile the running Cap uses, as an app GNOME launches.
+profile="$out/profile"
+mkdir -p "$HOME/.local/share/applications"
+cat >"$HOME/.local/share/applications/cap-under-test.desktop" <<DESKTOP
+[Desktop Entry]
+Type=Application
+Name=Cap under test
+StartupNotify=true
+Exec=env CAP_GPUI_APP_DATA_DIR=$profile CAP_GPUI_RECORDINGS_DIR=$profile/recordings CAP_GPUI_LOG_DIR=$profile/logs LD_LIBRARY_PATH=${LD_LIBRARY_PATH:-} RUST_LOG=info sh -c 'echo "launch token: \${XDG_ACTIVATION_TOKEN:-none}" >"$out/second.log"; exec "\$0" >>"$out/second.log" 2>&1' ${CAP_BIN:-/usr/bin/Cap}
+DESKTOP
+shell "imports.gi.Gio.DesktopAppInfo.new_from_filename('$HOME/.local/share/applications/cap-under-test.desktop').launch([], global.create_app_launch_context(global.display.get_current_time_roundtrip(), -1))" >>"$out/actions.log"
+wait_log second "Requested the existing Cap GPUI controls" 20 && result reopen_forwarded yes || result reopen_forwarded no
+grep -q "forwarding the launcher's activation token" "$out/second.log" && result relaunch_had_token yes || result relaunch_had_token no
+sleep 3
+after=$(focused)
+shell "global.display.list_all_windows().map(w => [w.get_title(), w.get_wm_class(), w.minimized, w.showing_on_its_workspace(), w.is_hidden ? w.is_hidden() : '', w.get_frame_rect().width + 'x' + w.get_frame_rect().height].join(':')).join(' | ')" >>"$out/actions.log"
+result focused_after "${after:-none}"
+if [[ $before == "Cap Settings" && $after == "$expected" ]]; then
+ result main_raised yes
+else
+ result main_raised no
+fi
+cat "$out/result.txt"
diff --git a/scripts/prepare-gpui-dependency.sh b/scripts/prepare-gpui-dependency.sh
index af6575d31..e02b1e995 100755
--- a/scripts/prepare-gpui-dependency.sh
+++ b/scripts/prepare-gpui-dependency.sh
@@ -10,6 +10,7 @@ patch_paths=(
"apps/desktop-gpui/patches/zed-idle-frames.patch"
"apps/desktop-gpui/patches/zed-streaming-image.patch"
"apps/desktop-gpui/patches/zed-wayland-visibility.patch"
+ "apps/desktop-gpui/patches/zed-wayland-activation.patch"
)
patch_files=("${patch_paths[@]/#/$repo_root/}")
base_revision="5d1f83d9f27a19bec1fb241dc33b42238af9cf8d"
diff --git a/scripts/prepare-gpui-dependency.test.mjs b/scripts/prepare-gpui-dependency.test.mjs
index 090cc9ba2..e06587c8c 100644
--- a/scripts/prepare-gpui-dependency.test.mjs
+++ b/scripts/prepare-gpui-dependency.test.mjs
@@ -148,6 +148,8 @@ test("dependency verification handles overlapping patches without changing the c
patch("zed-streaming-image.patch");
writeFileSync(path.join(upstream, "visibility.rs"), "withheld first map\n");
patch("zed-wayland-visibility.patch");
+ writeFileSync(path.join(upstream, "activation.rs"), "launcher tokens\n");
+ patch("zed-wayland-activation.patch");
const script = path.join(cap, "scripts/prepare-gpui-dependency.sh");
writeFileSync(
script,