Skip to content

Visual Studio Code, rebuilt in Rust

Rust

feat(linux): keep the window always on top through _NET_WM_STATE_ABOVE

rokarturdb1e451ceb9a
diff --git a/native/Cargo.lock b/native/Cargo.lock
index 7b1e6329197..1433fa94546 100644
--- a/native/Cargo.lock
+++ b/native/Cargo.lock
@@ -272,6 +272,7 @@ dependencies = [
"webkit2gtk",
"wuff",
"x11",
+ "x11rb",
"zbus 5.19.0",
]
diff --git a/native/crates/app/Cargo.toml b/native/crates/app/Cargo.toml
index 982ef070e70..00a58e7037d 100644
--- a/native/crates/app/Cargo.toml
+++ b/native/crates/app/Cargo.toml
@@ -60,6 +60,8 @@ openssl = "0.10"
rcgen = { version = "0.14", default-features = false, features = ["crypto", "pem", "ring"] }
webkit2gtk = { version = "2.0", features = ["v2_40"] }
x11 = { version = "2", features = ["xlib"] }
+# The x11rb gpui_linux's X11 backend uses.
+x11rb = "0.13"
[build-dependencies]
regex = "1"
diff --git a/native/crates/app/src/main.rs b/native/crates/app/src/main.rs
index ce72bc9cab8..f1d6179f697 100644
--- a/native/crates/app/src/main.rs
+++ b/native/crates/app/src/main.rs
@@ -129,6 +129,8 @@ mod user_data_profile;
mod windows_state;
mod workbench;
mod workspace_trust;
+#[cfg(target_os = "linux")]
+mod x11;
use std::path::{Path, PathBuf};
use std::sync::mpsc::{Receiver, channel};
diff --git a/native/crates/app/src/workbench/host.rs b/native/crates/app/src/workbench/host.rs
index 15978fafc29..0a92991db41 100644
--- a/native/crates/app/src/workbench/host.rs
+++ b/native/crates/app/src/workbench/host.rs
@@ -411,14 +411,30 @@ fn set_always_on_top(window: &Window, on_top: bool) {
crate::dialog::ns_window(window).setLevel(if on_top { NSFloatingWindowLevel } else { NSNormalWindowLevel });
}
-/// GPUI has no always-on-top window state on Linux yet.
#[cfg(target_os = "linux")]
-pub(super) fn is_always_on_top(_window: &Window) -> bool {
- false
+thread_local! {
+ /// The windows set always on top: Chromium's X11 and Wayland windows keep the z-order level they were given and
+ /// report that one, Wayland having no protocol to apply it.
+ static ALWAYS_ON_TOP: std::cell::RefCell<std::collections::HashSet<gpui::WindowId>> = Default::default();
}
#[cfg(target_os = "linux")]
-fn set_always_on_top(_window: &Window, _on_top: bool) {}
+pub(super) fn is_always_on_top(window: &Window) -> bool {
+ ALWAYS_ON_TOP.with_borrow(|windows| windows.contains(&window.window_handle().window_id()))
+}
+
+/// Chromium's X11Window `SetZOrderLevel`: the `_NET_WM_STATE_ABOVE` state through the window manager.
+#[cfg(target_os = "linux")]
+fn set_always_on_top(window: &Window, on_top: bool) {
+ ALWAYS_ON_TOP.with_borrow_mut(|windows| match on_top {
+ true => windows.insert(window.window_handle().window_id()),
+ false => windows.remove(&window.window_handle().window_id()),
+ });
+ let Some(xid) = crate::x11::window_xid(window) else { return };
+ if let Err(error) = crate::x11::set_wm_state(xid, "_NET_WM_STATE_ABOVE", on_top) {
+ eprintln!("[window] always on top: {error}");
+ }
+}
#[cfg(test)]
mod tests;
diff --git a/native/crates/app/src/workbench/host/tests.rs b/native/crates/app/src/workbench/host/tests.rs
index 2ac7659fc73..5a5ac8a9266 100644
--- a/native/crates/app/src/workbench/host/tests.rs
+++ b/native/crates/app/src/workbench/host/tests.rs
@@ -188,3 +188,17 @@ fn a_file_opens_in_the_window_whose_folder_holds_it(cx: &mut TestAppContext) {
assert_eq!(opened, [(None, None), (Some(dir.join("project")), Some("top.txt".into())), (Some(dir.join("project/sub")), Some("deep.txt".into()))]);
std::fs::remove_dir_all(dir).unwrap();
}
+
+/// Chromium keeps a Linux window's z-order level: the toggle sets `isWindowAlwaysOnTop` and toggles it back.
+#[cfg(target_os = "linux")]
+#[gpui::test]
+fn always_on_top_toggles_the_context_key_on_linux(cx: &mut TestAppContext) {
+ let (workbench, window) = empty_window(cx);
+ let on_top = |cx: &mut TestAppContext| window.update(cx, |_, window, _| super::is_always_on_top(window)).unwrap();
+ let toggle = |cx: &mut TestAppContext| window.update(cx, |_, window, cx| workbench.update(cx, |workbench, cx| _ = workbench.execute_command("workbench.action.toggleWindowAlwaysOnTop", vec![], window, cx))).unwrap();
+ assert!(!on_top(cx));
+ toggle(cx);
+ assert!(on_top(cx));
+ toggle(cx);
+ assert!(!on_top(cx));
+}
diff --git a/native/crates/app/src/x11.rs b/native/crates/app/src/x11.rs
new file mode 100644
index 00000000000..7edf0320fb7
--- /dev/null
+++ b/native/crates/app/src/x11.rs
@@ -0,0 +1,30 @@
+//! The X server calls the Linux build makes beside GPUI's own connection, as Chromium's X11 code does them: window
+//! manager states, key grabs and the keyboard layout. On Wayland they reach XWayland, or nothing without `DISPLAY`.
+
+use anyhow::Context as _;
+use gpui::Window;
+use raw_window_handle::{HasWindowHandle, RawWindowHandle};
+use x11rb::connection::Connection;
+use x11rb::protocol::xproto::{ClientMessageEvent, ConnectionExt, EventMask};
+
+/// The window's X11 id; none for a Wayland window.
+pub fn window_xid(window: &Window) -> Option<u32> {
+ match HasWindowHandle::window_handle(window).ok()?.as_raw() {
+ RawWindowHandle::Xcb(handle) => Some(handle.window.get()),
+ RawWindowHandle::Xlib(handle) => u32::try_from(handle.window).ok(),
+ _ => None,
+ }
+}
+
+/// ui/base/x/x11_util.cc `SetWMSpecState`: a `_NET_WM_STATE` add or remove message to the root window.
+pub fn set_wm_state(xid: u32, state: &str, enabled: bool) -> anyhow::Result<()> {
+ let (connection, screen) = x11rb::connect(None).context("connecting to the X server")?;
+ let root = connection.setup().roots[screen].root;
+ let wm_state = connection.intern_atom(false, b"_NET_WM_STATE")?.reply()?.atom;
+ let state = connection.intern_atom(false, state.as_bytes())?.reply()?.atom;
+ // _NET_WM_STATE_ADD and _NET_WM_STATE_REMOVE; source 1 is a normal application.
+ let event = ClientMessageEvent::new(32, xid, wm_state, [u32::from(enabled), state, 0, 1, 0]);
+ connection.send_event(false, root, EventMask::SUBSTRUCTURE_NOTIFY | EventMask::SUBSTRUCTURE_REDIRECT, event)?;
+ connection.flush()?;
+ Ok(())
+}
diff --git a/port/ledger.md b/port/ledger.md
index 83ce2e9b11d..73bf4a3093e 100644
--- a/port/ledger.md
+++ b/port/ledger.md
@@ -52,7 +52,7 @@ Status: `open`, `in progress`, `waiting on Artur`, `later` (postponed), `done`,
| 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 |
| M23 Linux | app/src/metered_connection.rs:57 | done | [linux S] metered connection (NetworkManager). | NetworkManager `Metered` over D-Bus; not run on a desktop |
| M23 Linux | app/src/keyboard_layout/linux.rs:8 | open | [linux M] keyboard layout info and raw mapping (xkbcommon). Linux shows now: empty layout, US scan code fallback. | |
-| M23 Linux | app/src/workbench/host.rs:330 | open | [linux S] always on top. Linux shows now: the commands do nothing, the context key stays false. | |
+| M23 Linux | app/src/workbench/host.rs:330 | done | [linux S] always on top. | `cargo test -p app always_on_top` on Linux: `always_on_top_toggles_the_context_key_on_linux`; the `_NET_WM_STATE_ABOVE` request (Chromium's X11Window `SetZOrderLevel`) not run under a window manager, Wayland keeps only the state as Chromium |
| M23 Linux | app/src/workbench/accessibility.rs:531 | done | [linux S] screen reader and reduced motion detection (AT-SPI, portal). | AT-SPI `ScreenReaderEnabled` and the portal's `enable-animations` over D-Bus; not run on a desktop |
| M23 Linux | app/src/file_dialog.rs:28 | open | [linux S] dialog title, filters and the open dialog's default folder in the portal file chooser (GPUI's `PathPromptOptions` carries only the button label, which it now gets). Linux shows now: the portal chooser's title, no filters, its last folder. | |
| M23 Linux | exthost/src/request/linux.rs:24 | done | [linux S] the `<local>` proxy bypass rule. | `cargo test -p exthost request::linux` on Linux: `local_bypasses_hosts_without_a_dot` |