From 61c97492efc335233bc81b83e6985cf5e9ef26f6 Mon Sep 17 00:00:00 2001 From: bmh129 Date: Mon, 26 Oct 2026 17:00:22 -0500 Subject: [PATCH 1/3] W30: Linux: hand the launcher's activation token back from the first window eframe never gives winit an activation token, so with StartupNotify=true GNOME kept its busy cursor for 15 seconds after the window appeared, and a Wayland window opened without focus. The first window created without a token now takes the one the launcher put in the environment (XDG_ACTIVATION_TOKEN on Wayland, DESKTOP_STARTUP_ID on X11) and hands it back as a token given through with_activation_token would be. Later windows don't reuse the spent token, and an empty or oversized (over 1,024 bytes) token is ignored. The variable is left in the environment, unlike reset_activation_token_env: changing the environment while other threads may read it is unsound. Port of PdfCraft's vendored winit patch (14), from storytold/cadcraft#2030. Co-Authored-By: Claude Opus 5.5 --- PATCHES.md | 1 + src/platform/startup_notify.rs | 4 +- src/platform_impl/linux/mod.rs | 15 ++- src/platform_impl/linux/startup_token.rs | 115 +++++++++++++++++++++++ 4 files changed, 130 insertions(+), 5 deletions(-) create mode 100644 src/platform_impl/linux/startup_token.rs diff --git a/PATCHES.md b/PATCHES.md index c100c83d..6a54a854 100644 --- a/PATCHES.md +++ b/PATCHES.md @@ -34,6 +34,7 @@ input lives in `craft-tablet`). | W25 | `eb4007da` | X11/Wayland: `platform::latin_layout::KeyEventExtLatinLayout`, the key on the first Latin layout group for shortcuts on non-Latin layouts | none; to be proposed | upstream release with an equivalent | storytold/winit PR #5; craft-libs#198 (K2) | | W26 | `2b9cd1cf` | macOS: replaced text is deleted by UTF-8 byte count with the commit (`WindowExtMacOS::take_ime_delete_surrounding`, same shape as W27) | master: `Ime::DeleteSurrounding` (a new `Ime` variant breaks 0.30 matchers) | the egui → 0.31 move | storytold/winit PR #6 (`d103edae`) | | W27 | `f40c76a2` | Wayland: text-input-v3 surrounding text (`WindowExtWayland::set_ime_surrounding_text`, `set_ime_surrounding_text_with_change_cause`, `clear_ime_surrounding_text`), delete-surrounding attached to the commit (`take_ime_delete_surrounding` → `ImeDeleteSurrounding { before_bytes, after_bytes }`), per-seat preedit ownership and outgoing state waiting for a matching `done` (E21b) | master has both as core API (`Ime::DeleteSurrounding`) | the egui → 0.31 move | storytold/winit PR #7; craft-libs#198 (I7) | +| W30 | this commit | Linux: the first window created without an activation token takes the launcher's (`XDG_ACTIVATION_TOKEN` on Wayland, `DESKTOP_STARTUP_ID` on X11) and hands it back as one given through `with_activation_token` would be (`platform_impl/linux/startup_token.rs`), so GNOME drops the busy cursor and a Wayland window opens focused; later windows don't reuse the spent token, an empty or oversized (over 1,024 bytes) token is ignored, and the variable stays in the environment (changing it while other threads may read it is unsound) | none; to be proposed | upstream release that hands the launcher's token to the first window | pdfcraft vendor patch (14); cadcraft#2030 (`tests/winit_startup_token.rs`) | Conflict resolved by hand: `wayland/seat/mod.rs` `remove_seat` keeps all three cleanups — cancel a file drag (W15), remove the seat from winit's clipboard (W15), destroy the seat's text input (W2). diff --git a/src/platform/startup_notify.rs b/src/platform/startup_notify.rs index 6fab284e..e8f4287f 100644 --- a/src/platform/startup_notify.rs +++ b/src/platform/startup_notify.rs @@ -28,10 +28,10 @@ use crate::event_loop::{ActiveEventLoop, AsyncRequestSerial}; use crate::window::{ActivationToken, Window, WindowAttributes}; /// The variable which is used mostly on X11. -const X11_VAR: &str = "DESKTOP_STARTUP_ID"; +pub(crate) const X11_VAR: &str = "DESKTOP_STARTUP_ID"; /// The variable which is used mostly on Wayland. -const WAYLAND_VAR: &str = "XDG_ACTIVATION_TOKEN"; +pub(crate) const WAYLAND_VAR: &str = "XDG_ACTIVATION_TOKEN"; pub trait EventLoopExtStartupNotify { /// Read the token from the environment. diff --git a/src/platform_impl/linux/mod.rs b/src/platform_impl/linux/mod.rs index 1d6262ac..a45b86ee 100644 --- a/src/platform_impl/linux/mod.rs +++ b/src/platform_impl/linux/mod.rs @@ -25,6 +25,7 @@ use crate::event_loop::{ use crate::icon::Icon; use crate::keyboard::Key; use crate::platform::pump_events::PumpStatus; +use crate::platform::startup_notify; #[cfg(x11_platform)] use crate::platform::x11::{WindowType as XWindowType, XlibErrorHook}; use crate::window::{ @@ -38,6 +39,7 @@ pub(crate) use crate::icon::RgbaIcon as PlatformIcon; pub(crate) use crate::platform_impl::Fullscreen; pub(crate) mod common; +mod startup_token; #[cfg(wayland_platform)] pub(crate) mod wayland; #[cfg(x11_platform)] @@ -290,16 +292,23 @@ impl Window { #[inline] pub(crate) fn new( window_target: &ActiveEventLoop, - attribs: WindowAttributes, + mut attribs: WindowAttributes, ) -> Result { + let given = attribs.platform_specific.activation_token.take(); match *window_target { #[cfg(wayland_platform)] ActiveEventLoop::Wayland(ref window_target) => { - wayland::Window::new(window_target, attribs).map(Window::Wayland) + startup_token::with_token(given, startup_notify::WAYLAND_VAR, |token| { + attribs.platform_specific.activation_token = token; + wayland::Window::new(window_target, attribs).map(Window::Wayland) + }) }, #[cfg(x11_platform)] ActiveEventLoop::X(ref window_target) => { - x11::Window::new(window_target, attribs).map(Window::X) + startup_token::with_token(given, startup_notify::X11_VAR, |token| { + attribs.platform_specific.activation_token = token; + x11::Window::new(window_target, attribs).map(Window::X) + }) }, } } diff --git a/src/platform_impl/linux/startup_token.rs b/src/platform_impl/linux/startup_token.rs new file mode 100644 index 00000000..726c9f98 --- /dev/null +++ b/src/platform_impl/linux/startup_token.rs @@ -0,0 +1,115 @@ +//! The launcher's activation token for the first window (CADCraft patch, from PdfCraft). +//! +//! A launcher with `StartupNotify=true` passes an activation token in the environment +//! (`XDG_ACTIVATION_TOKEN` on Wayland, `DESKTOP_STARTUP_ID` on X11) and shows a busy cursor +//! until a window hands it back. winit hands back only a token given through +//! `WindowAttributesExtStartupNotify::with_activation_token`, and eframe never gives one, so +//! GNOME kept the busy cursor until its 15-second timeout and the window opened without focus. +//! +//! The first window the process creates without a token now takes the one in the environment. +//! Later windows never do: the token is spent once a window has been created with it. A window +//! that fails to be created leaves it unspent, so a retry still hands it back. The variable is +//! left in the environment, unlike `reset_activation_token_env`, because changing the +//! environment while other threads may read it is unsound, and an application can start +//! threads before its first window. + +use std::sync::atomic::{AtomicBool, Ordering}; + +use crate::window::ActivationToken; + +/// Longer tokens are ignored. Launchers make tokens of a few dozen bytes; on X11 the token is +/// written to a window property and sent to the window manager, and an oversized one would +/// fail window creation. +const MAX_TOKEN_LEN: usize = 1024; + +static TAKEN: AtomicBool = AtomicBool::new(false); + +/// Creates a window with `given` if there is one, else, for the process's first window, the +/// environment's value of `var`. The launcher's token is spent only when `create` succeeds. +pub(crate) fn with_token( + given: Option, + var: &str, + create: impl FnOnce(Option) -> Result, +) -> Result { + create_with(given, &TAKEN, || std::env::var(var).ok(), create) +} + +fn create_with( + given: Option, + taken: &AtomicBool, + read: impl FnOnce() -> Option, + create: impl FnOnce(Option) -> Result, +) -> Result { + let first = !taken.load(Ordering::Relaxed); + let token = if given.is_some() || !first { + given + } else { + read().filter(|token| !token.is_empty() && token.len() <= MAX_TOKEN_LEN).map(ActivationToken::from_raw) + }; + let window = create(token)?; + // The first window spends the launcher's token, whether or not it was given one. + taken.store(true, Ordering::Relaxed); + Ok(window) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn token(raw: &str) -> Option { + Some(ActivationToken::from_raw(raw.to_owned())) + } + + /// The token a successfully created window received. + fn choose(given: Option, taken: &AtomicBool, read: impl FnOnce() -> Option) -> Option { + create_with(given, taken, read, Ok::<_, ()>).ok().flatten() + } + + #[test] + fn the_first_window_takes_the_launchers_token() { + let taken = AtomicBool::new(false); + assert_eq!(choose(None, &taken, || Some("gnome-shell/PdfCraft/1234".into())), token("gnome-shell/PdfCraft/1234")); + } + + #[test] + fn a_later_window_does_not_reuse_the_spent_token() { + let taken = AtomicBool::new(false); + assert!(choose(None, &taken, || Some("t".into())).is_some()); + assert_eq!(choose(None, &taken, || Some("t".into())), None); + } + + #[test] + fn a_given_token_wins_and_still_spends_the_launchers() { + let taken = AtomicBool::new(false); + assert_eq!(choose(token("mine"), &taken, || Some("env".into())), token("mine")); + assert_eq!(choose(None, &taken, || Some("env".into())), None); + assert_eq!(choose(token("again"), &taken, || Some("env".into())), token("again")); + } + + #[test] + fn a_missing_empty_or_oversized_token_is_ignored() { + assert_eq!(choose(None, &AtomicBool::new(false), || None), None); + assert_eq!(choose(None, &AtomicBool::new(false), || Some(String::new())), None); + let long = "x".repeat(MAX_TOKEN_LEN + 1); + assert_eq!(choose(None, &AtomicBool::new(false), || Some(long)), None); + let limit = "x".repeat(MAX_TOKEN_LEN); + assert!(choose(None, &AtomicBool::new(false), || Some(limit)).is_some()); + } + + #[test] + fn a_failed_window_leaves_the_token_for_a_retry() { + let taken = AtomicBool::new(false); + let failed = create_with( + None, + &taken, + || Some("t".into()), + |received| { + assert_eq!(received, token("t")); + Err::<(), _>("no window") + }, + ); + assert_eq!(failed, Err("no window")); + assert_eq!(choose(None, &taken, || Some("t".into())), token("t")); + assert_eq!(choose(None, &taken, || Some("t".into())), None); + } +} From b452532426f26c00ef5f9104d72484b70d797623 Mon Sep 17 00:00:00 2001 From: bmh129 <11478682+bmh129@users.noreply.github.com> Date: Sun, 1 Nov 2026 09:27:57 -0600 Subject: [PATCH 2/3] W30: test the launcher's token read from a variable that is set, then cleared The policy tests gave the token through a closure; this one reads it from a real environment variable (one no other test uses, so setting it races nothing): set, the first window takes it; cleared, it takes none. Also rustfmt startup_token.rs, which had four lines over 100 columns. Co-Authored-By: Claude Opus 5.5 --- src/platform_impl/linux/startup_token.rs | 35 +++++++++++++++++++++--- 1 file changed, 31 insertions(+), 4 deletions(-) diff --git a/src/platform_impl/linux/startup_token.rs b/src/platform_impl/linux/startup_token.rs index 726c9f98..031b4b7f 100644 --- a/src/platform_impl/linux/startup_token.rs +++ b/src/platform_impl/linux/startup_token.rs @@ -31,7 +31,12 @@ pub(crate) fn with_token( var: &str, create: impl FnOnce(Option) -> Result, ) -> Result { - create_with(given, &TAKEN, || std::env::var(var).ok(), create) + create_with(given, &TAKEN, from_env(var), create) +} + +/// Reads the launcher's token from the environment variable `var`. +fn from_env(var: &str) -> impl FnOnce() -> Option + '_ { + move || std::env::var(var).ok() } fn create_with( @@ -44,7 +49,9 @@ fn create_with( let token = if given.is_some() || !first { given } else { - read().filter(|token| !token.is_empty() && token.len() <= MAX_TOKEN_LEN).map(ActivationToken::from_raw) + read() + .filter(|token| !token.is_empty() && token.len() <= MAX_TOKEN_LEN) + .map(ActivationToken::from_raw) }; let window = create(token)?; // The first window spends the launcher's token, whether or not it was given one. @@ -61,14 +68,21 @@ mod tests { } /// The token a successfully created window received. - fn choose(given: Option, taken: &AtomicBool, read: impl FnOnce() -> Option) -> Option { + fn choose( + given: Option, + taken: &AtomicBool, + read: impl FnOnce() -> Option, + ) -> Option { create_with(given, taken, read, Ok::<_, ()>).ok().flatten() } #[test] fn the_first_window_takes_the_launchers_token() { let taken = AtomicBool::new(false); - assert_eq!(choose(None, &taken, || Some("gnome-shell/PdfCraft/1234".into())), token("gnome-shell/PdfCraft/1234")); + assert_eq!( + choose(None, &taken, || Some("gnome-shell/PdfCraft/1234".into())), + token("gnome-shell/PdfCraft/1234") + ); } #[test] @@ -96,6 +110,19 @@ mod tests { assert!(choose(None, &AtomicBool::new(false), || Some(limit)).is_some()); } + #[test] + fn the_token_is_read_from_the_variable_when_set_and_not_when_cleared() { + // A variable no other test reads, so setting it while tests run in parallel races nothing. + const VAR: &str = "WINIT_W30_TEST_ACTIVATION_TOKEN"; + std::env::set_var(VAR, "gnome-shell/CADCraft/42"); + assert_eq!( + choose(None, &AtomicBool::new(false), from_env(VAR)), + token("gnome-shell/CADCraft/42") + ); + std::env::remove_var(VAR); + assert_eq!(choose(None, &AtomicBool::new(false), from_env(VAR)), None); + } + #[test] fn a_failed_window_leaves_the_token_for_a_retry() { let taken = AtomicBool::new(false); From 78df1155809d1def666e0f31bd786f9b14732cf9 Mon Sep 17 00:00:00 2001 From: bmh129 <11478682+bmh129@users.noreply.github.com> Date: Sun, 1 Nov 2026 09:33:18 -0600 Subject: [PATCH 3/3] W30: give the environment test its variable through a child process b452532's test called set_var and remove_var while other test threads ran, which is the unsoundness W30 avoids by leaving the launcher's variable alone; a variable no other test reads doesn't make it sound, since any thread reading any variable races the write. The test now runs itself in a child process with the variable set, then removed, and checks the child ran its one test; this process's environment never changes. Co-Authored-By: Claude Opus 5.5 --- src/platform_impl/linux/startup_token.rs | 42 +++++++++++++++++++----- 1 file changed, 33 insertions(+), 9 deletions(-) diff --git a/src/platform_impl/linux/startup_token.rs b/src/platform_impl/linux/startup_token.rs index 031b4b7f..8f68c943 100644 --- a/src/platform_impl/linux/startup_token.rs +++ b/src/platform_impl/linux/startup_token.rs @@ -110,17 +110,41 @@ mod tests { assert!(choose(None, &AtomicBool::new(false), || Some(limit)).is_some()); } + /// The variable the child below reads its token from. + const VAR: &str = "WINIT_W30_TEST_ACTIVATION_TOKEN"; + /// Set only in the child: the token it must take, or empty for none. + const EXPECT: &str = "WINIT_W30_TEST_EXPECT"; + #[test] fn the_token_is_read_from_the_variable_when_set_and_not_when_cleared() { - // A variable no other test reads, so setting it while tests run in parallel races nothing. - const VAR: &str = "WINIT_W30_TEST_ACTIVATION_TOKEN"; - std::env::set_var(VAR, "gnome-shell/CADCraft/42"); - assert_eq!( - choose(None, &AtomicBool::new(false), from_env(VAR)), - token("gnome-shell/CADCraft/42") - ); - std::env::remove_var(VAR); - assert_eq!(choose(None, &AtomicBool::new(false), from_env(VAR)), None); + // The environment is given to a child process rather than changed here: `set_var` while + // other test threads run is the unsoundness this module avoids by leaving the variable. + let name = concat!(module_path!(), "::the_first_window_reads_the_variable_in_a_child"); + let name = name.split_once("::").unwrap().1; + for value in [Some("gnome-shell/CADCraft/42"), None] { + let mut child = std::process::Command::new(std::env::current_exe().unwrap()); + child.args([name, "--exact", "--test-threads=1"]).env(EXPECT, value.unwrap_or("")); + match value { + Some(value) => child.env(VAR, value), + None => child.env_remove(VAR), + }; + let out = child.output().unwrap(); + let stdout = String::from_utf8_lossy(&out.stdout); + assert!( + out.status.success(), + "{value:?}: {stdout}{}", + String::from_utf8_lossy(&out.stderr) + ); + assert!(stdout.contains("1 passed"), "{value:?}: the child ran no test: {stdout}"); + } + } + + #[test] + fn the_first_window_reads_the_variable_in_a_child() { + let Some(expect) = std::env::var_os(EXPECT) else { return }; + let expect = Some(expect.into_string().unwrap()).filter(|e| !e.is_empty()); + let received = choose(None, &AtomicBool::new(false), from_env(VAR)); + assert_eq!(received, expect.as_deref().and_then(token)); } #[test]