forge
Explore
Log in

Don't you dare go Hollow

Implement xwayland-satellite integration

Browse files at this commit

f918eabe6a144e78c62c3fc0cfa7fe32e4623e5aIvan MolodetskikhParent: 0698f16
niri-config/src/lib.rsmodified+23 -0
@@ -65,6 +65,8 @@ pub struct Config {
65 pub overview: Overview,65 pub overview: Overview,
66 #[knuffel(child, default)]66 #[knuffel(child, default)]
67 pub environment: Environment,67 pub environment: Environment,
68+ #[knuffel(child, default)]
69+ pub xwayland_satellite: XwaylandSatellite,
68 #[knuffel(children(name = "window-rule"))]70 #[knuffel(children(name = "window-rule"))]
69 pub window_rules: Vec<WindowRule>,71 pub window_rules: Vec<WindowRule>,
70 #[knuffel(children(name = "layer-rule"))]72 #[knuffel(children(name = "layer-rule"))]
@@ -1364,6 +1366,23 @@ pub struct EnvironmentVariable {
1364 pub value: Option<String>,1366 pub value: Option<String>,
1365 }1367 }
1366 1368
1369+#[derive(knuffel::Decode, Debug, Clone, PartialEq, Eq)]
1370+pub struct XwaylandSatellite {
1371+ #[knuffel(child)]
1372+ pub off: bool,
1373+ #[knuffel(child, unwrap(argument), default = Self::default().path)]
1374+ pub path: String,
1375+}
1376+
1377+impl Default for XwaylandSatellite {
1378+ fn default() -> Self {
1379+ Self {
1380+ off: false,
1381+ path: String::from("xwayland-satellite"),
1382+ }
1383+ }
1384+}
1385+
1367 #[derive(knuffel::Decode, Debug, Clone, PartialEq, Eq)]1386 #[derive(knuffel::Decode, Debug, Clone, PartialEq, Eq)]
1368 pub struct Workspace {1387 pub struct Workspace {
1369 #[knuffel(argument)]1388 #[knuffel(argument)]
@@ -4796,6 +4815,10 @@ mod tests {
4796 },4815 },
4797 ],4816 ],
4798 ),4817 ),
4818+ xwayland_satellite: XwaylandSatellite {
4819+ off: false,
4820+ path: "xwayland-satellite",
4821+ },
4799 window_rules: [4822 window_rules: [
4800 WindowRule {4823 WindowRule {
4801 matches: [4824 matches: [
src/main.rsmodified+15 -2
@@ -17,11 +17,11 @@ use niri::dbus;
17 use niri::ipc::client::handle_msg;17 use niri::ipc::client::handle_msg;
18 use niri::niri::State;18 use niri::niri::State;
19 use niri::utils::spawning::{19 use niri::utils::spawning::{
20- spawn, store_and_increase_nofile_rlimit, CHILD_ENV, REMOVE_ENV_RUST_BACKTRACE,20+ spawn, store_and_increase_nofile_rlimit, CHILD_DISPLAY, CHILD_ENV, REMOVE_ENV_RUST_BACKTRACE,
21 REMOVE_ENV_RUST_LIB_BACKTRACE,21 REMOVE_ENV_RUST_LIB_BACKTRACE,
22 };22 };
23 use niri::utils::watcher::Watcher;23 use niri::utils::watcher::Watcher;
24-use niri::utils::{cause_panic, version, IS_SYSTEMD_SERVICE};24+use niri::utils::{cause_panic, version, xwayland, IS_SYSTEMD_SERVICE};
25 use niri_config::Config;25 use niri_config::Config;
26 use niri_ipc::socket::SOCKET_PATH_ENV;26 use niri_ipc::socket::SOCKET_PATH_ENV;
27 use portable_atomic::Ordering;27 use portable_atomic::Ordering;
@@ -200,6 +200,18 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
200 info!("IPC listening on: {}", socket_path.to_string_lossy());200 info!("IPC listening on: {}", socket_path.to_string_lossy());
201 }201 }
202 202
203+ // Setup xwayland-satellite integration.
204+ xwayland::satellite::setup(&mut state);
205+ if let Some(satellite) = &state.niri.satellite {
206+ let name = satellite.display_name();
207+ *CHILD_DISPLAY.write().unwrap() = Some(name.to_owned());
208+ env::set_var("DISPLAY", name);
209+ info!("listening on X11 socket: {name}");
210+ } else {
211+ // Avoid spawning children in the host X11.
212+ env::remove_var("DISPLAY");
213+ }
214+
203 if cli.session {215 if cli.session {
204 // We're starting as a session. Import our variables.216 // We're starting as a session. Import our variables.
205 import_environment();217 import_environment();
@@ -275,6 +287,7 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
275 fn import_environment() {287 fn import_environment() {
276 let variables = [288 let variables = [
277 "WAYLAND_DISPLAY",289 "WAYLAND_DISPLAY",
290+ "DISPLAY",
278 "XDG_CURRENT_DESKTOP",291 "XDG_CURRENT_DESKTOP",
279 "XDG_SESSION_TYPE",292 "XDG_SESSION_TYPE",
280 SOCKET_PATH_ENV,293 SOCKET_PATH_ENV,
src/niri.rsmodified+36 -2
@@ -160,11 +160,12 @@ use crate::ui::hotkey_overlay::HotkeyOverlay;
160 use crate::ui::screen_transition::{self, ScreenTransition};160 use crate::ui::screen_transition::{self, ScreenTransition};
161 use crate::ui::screenshot_ui::{OutputScreenshot, ScreenshotUi, ScreenshotUiRenderElement};161 use crate::ui::screenshot_ui::{OutputScreenshot, ScreenshotUi, ScreenshotUiRenderElement};
162 use crate::utils::scale::{closest_representable_scale, guess_monitor_scale};162 use crate::utils::scale::{closest_representable_scale, guess_monitor_scale};
163-use crate::utils::spawning::CHILD_ENV;163+use crate::utils::spawning::{CHILD_DISPLAY, CHILD_ENV};
164+use crate::utils::xwayland::satellite::Satellite;
164 use crate::utils::{165 use crate::utils::{
165 center, center_f64, expand_home, get_monotonic_time, ipc_transform_to_smithay, is_mapped,166 center, center_f64, expand_home, get_monotonic_time, ipc_transform_to_smithay, is_mapped,
166 logical_output, make_screenshot_path, output_matches_name, output_size, send_scale_transform,167 logical_output, make_screenshot_path, output_matches_name, output_size, send_scale_transform,
167- write_png_rgba8,168+ write_png_rgba8, xwayland,
168 };169 };
169 use crate::window::mapped::MappedId;170 use crate::window::mapped::MappedId;
170 use crate::window::{InitialConfigureState, Mapped, ResolvedWindowRules, Unmapped, WindowRef};171 use crate::window::{InitialConfigureState, Mapped, ResolvedWindowRules, Unmapped, WindowRef};
@@ -376,6 +377,8 @@ pub struct Niri {
376 pub ipc_server: Option<IpcServer>,377 pub ipc_server: Option<IpcServer>,
377 pub ipc_outputs_changed: bool,378 pub ipc_outputs_changed: bool,
378 379
380+ pub satellite: Option<Satellite>,
381+
379 // Casts are dropped before PipeWire to prevent a double-free (yay).382 // Casts are dropped before PipeWire to prevent a double-free (yay).
380 pub casts: Vec<Cast>,383 pub casts: Vec<Cast>,
381 pub pipewire: Option<PipeWire>,384 pub pipewire: Option<PipeWire>,
@@ -1332,6 +1335,7 @@ impl State {
1332 let mut layer_rules_changed = false;1335 let mut layer_rules_changed = false;
1333 let mut shaders_changed = false;1336 let mut shaders_changed = false;
1334 let mut cursor_inactivity_timeout_changed = false;1337 let mut cursor_inactivity_timeout_changed = false;
1338+ let mut xwls_changed = false;
1335 let mut old_config = self.niri.config.borrow_mut();1339 let mut old_config = self.niri.config.borrow_mut();
1336 1340
1337 // Reload the cursor.1341 // Reload the cursor.
@@ -1443,6 +1447,10 @@ impl State {
1443 output_config_changed = true;1447 output_config_changed = true;
1444 }1448 }
1445 1449
1450+ if config.xwayland_satellite != old_config.xwayland_satellite {
1451+ xwls_changed = true;
1452+ }
1453+
1446 *old_config = config;1454 *old_config = config;
1447 1455
1448 if let Some(outputs) = preserved_output_config {1456 if let Some(outputs) = preserved_output_config {
@@ -1506,6 +1514,30 @@ impl State {
1506 self.niri.reset_pointer_inactivity_timer();1514 self.niri.reset_pointer_inactivity_timer();
1507 }1515 }
1508 1516
1517+ if xwls_changed {
1518+ // If xwl-s was previously working and is now off, we don't try to kill it or stop
1519+ // watching the sockets, for simplicity's sake.
1520+ let was_working = self.niri.satellite.is_some();
1521+
1522+ // Try to start, or restart in case the user corrected the path or something.
1523+ xwayland::satellite::setup(self);
1524+
1525+ let config = self.niri.config.borrow();
1526+ let display_name = (!config.xwayland_satellite.off)
1527+ .then_some(self.niri.satellite.as_ref())
1528+ .flatten()
1529+ .map(|satellite| satellite.display_name().to_owned());
1530+
1531+ if let Some(name) = &display_name {
1532+ if !was_working {
1533+ info!("listening on X11 socket: {name}");
1534+ }
1535+ }
1536+
1537+ // This won't change the systemd environment, but oh well.
1538+ *CHILD_DISPLAY.write().unwrap() = display_name;
1539+ }
1540+
1509 // Can't really update xdg-decoration settings since we have to hide the globals for CSD1541 // Can't really update xdg-decoration settings since we have to hide the globals for CSD
1510 // due to the SDL2 bug... I don't imagine clients are prepared for the xdg-decoration1542 // due to the SDL2 bug... I don't imagine clients are prepared for the xdg-decoration
1511 // global suddenly appearing? Either way, right now it's live-reloaded in a sense that new1543 // global suddenly appearing? Either way, right now it's live-reloaded in a sense that new
@@ -2569,6 +2601,8 @@ impl Niri {
2569 ipc_server,2601 ipc_server,
2570 ipc_outputs_changed: false,2602 ipc_outputs_changed: false,
2571 2603
2604+ satellite: None,
2605+
2572 pipewire: None,2606 pipewire: None,
2573 casts: vec![],2607 casts: vec![],
2574 #[cfg(feature = "xdp-gnome-screencast")]2608 #[cfg(feature = "xdp-gnome-screencast")]
src/utils/mod.rsmodified+1 -0
@@ -37,6 +37,7 @@ pub mod scale;
37 pub mod spawning;37 pub mod spawning;
38 pub mod transaction;38 pub mod transaction;
39 pub mod watcher;39 pub mod watcher;
40+pub mod xwayland;
40 41
41 pub static IS_SYSTEMD_SERVICE: AtomicBool = AtomicBool::new(false);42 pub static IS_SYSTEMD_SERVICE: AtomicBool = AtomicBool::new(false);
42 43
src/utils/spawning.rsmodified+9 -0
@@ -16,6 +16,7 @@ use crate::utils::expand_home;
16 pub static REMOVE_ENV_RUST_BACKTRACE: AtomicBool = AtomicBool::new(false);16 pub static REMOVE_ENV_RUST_BACKTRACE: AtomicBool = AtomicBool::new(false);
17 pub static REMOVE_ENV_RUST_LIB_BACKTRACE: AtomicBool = AtomicBool::new(false);17 pub static REMOVE_ENV_RUST_LIB_BACKTRACE: AtomicBool = AtomicBool::new(false);
18 pub static CHILD_ENV: RwLock<Environment> = RwLock::new(Environment(Vec::new()));18 pub static CHILD_ENV: RwLock<Environment> = RwLock::new(Environment(Vec::new()));
19+pub static CHILD_DISPLAY: RwLock<Option<String>> = RwLock::new(None);
19 20
20 static ORIGINAL_NOFILE_RLIMIT_CUR: Atomic<rlim_t> = Atomic::new(0);21 static ORIGINAL_NOFILE_RLIMIT_CUR: Atomic<rlim_t> = Atomic::new(0);
21 static ORIGINAL_NOFILE_RLIMIT_MAX: Atomic<rlim_t> = Atomic::new(0);22 static ORIGINAL_NOFILE_RLIMIT_MAX: Atomic<rlim_t> = Atomic::new(0);
@@ -116,6 +117,14 @@ fn spawn_sync(
116 process.env_remove("RUST_LIB_BACKTRACE");117 process.env_remove("RUST_LIB_BACKTRACE");
117 }118 }
118 119
120+ // Set DISPLAY if needed.
121+ let display = CHILD_DISPLAY.read().unwrap();
122+ if let Some(display) = &*display {
123+ process.env("DISPLAY", display);
124+ } else {
125+ process.env_remove("DISPLAY");
126+ }
127+
119 // Set configured environment.128 // Set configured environment.
120 let env = CHILD_ENV.read().unwrap();129 let env = CHILD_ENV.read().unwrap();
121 for var in &env.0 {130 for var in &env.0 {
src/utils/xwayland/mod.rsadded+151 -0
@@ -0,0 +1,151 @@
1+use std::os::fd::OwnedFd;
2+use std::os::linux::net::SocketAddrExt;
3+use std::os::unix::net::{SocketAddr, UnixListener};
4+
5+use anyhow::{anyhow, ensure, Context as _};
6+use rustix::fs::{lstat, mkdir};
7+use rustix::io::Errno;
8+use rustix::process::getuid;
9+use smithay::reexports::rustix::fs::{unlink, OFlags};
10+use smithay::reexports::rustix::process::getpid;
11+use smithay::reexports::rustix::{self};
12+
13+pub mod satellite;
14+
15+const TMP_UNIX_DIR: &str = "/tmp";
16+const X11_TMP_UNIX_DIR: &str = "/tmp/.X11-unix";
17+
18+struct X11Connection {
19+ display_name: String,
20+ abstract_fd: OwnedFd,
21+ unix_fd: OwnedFd,
22+ _unix_guard: Unlink,
23+ _lock_guard: Unlink,
24+}
25+
26+struct Unlink(String);
27+impl Drop for Unlink {
28+ fn drop(&mut self) {
29+ let _ = unlink(&self.0);
30+ }
31+}
32+
33+// Adapted from Mutter code:
34+// https://gitlab.gnome.org/GNOME/mutter/-/blob/48.3.1/src/wayland/meta-xwayland.c?ref_type=tags#L513
35+fn ensure_x11_unix_dir() -> anyhow::Result<()> {
36+ match mkdir(X11_TMP_UNIX_DIR, 0o1777.into()) {
37+ Ok(()) => Ok(()),
38+ Err(Errno::EXIST) => {
39+ ensure_x11_unix_perms().context("wrong X11 directory permissions")?;
40+ Ok(())
41+ }
42+ Err(err) => Err(err).context("error creating X11 directory"),
43+ }
44+}
45+
46+fn ensure_x11_unix_perms() -> anyhow::Result<()> {
47+ let x11_tmp = lstat(X11_TMP_UNIX_DIR).context("error checking X11 directory permissions")?;
48+ let tmp = lstat(TMP_UNIX_DIR).context("error checking /tmp directory permissions")?;
49+
50+ ensure!(
51+ x11_tmp.st_uid == tmp.st_uid || x11_tmp.st_uid == getuid().as_raw(),
52+ "wrong ownership for X11 directory"
53+ );
54+ ensure!(
55+ (x11_tmp.st_mode & 0o022) == 0o022,
56+ "X11 directory is not writable"
57+ );
58+ ensure!(
59+ (x11_tmp.st_mode & 0o1000) == 0o1000,
60+ "X11 directory is missing the sticky bit"
61+ );
62+
63+ Ok(())
64+}
65+
66+fn pick_x11_display(start: u32) -> anyhow::Result<(u32, OwnedFd, Unlink)> {
67+ for n in start..start + 50 {
68+ let lock_path = format!("/tmp/.X{n}-lock");
69+ let flags = OFlags::WRONLY | OFlags::CLOEXEC | OFlags::CREATE | OFlags::EXCL;
70+ let Ok(lock_fd) = rustix::fs::open(&lock_path, flags, 0o444.into()) else {
71+ // FIXME: check if the target process is dead and reuse the lock.
72+ continue;
73+ };
74+ return Ok((n, lock_fd, Unlink(lock_path)));
75+ }
76+
77+ Err(anyhow!("no free X11 display found after 50 attempts"))
78+}
79+
80+fn bind_to_socket(addr: &SocketAddr) -> anyhow::Result<UnixListener> {
81+ let listener = UnixListener::bind_addr(addr).context("error binding socket")?;
82+ Ok(listener)
83+}
84+
85+fn bind_to_abstract_socket(display: u32) -> anyhow::Result<UnixListener> {
86+ let name = format!("/tmp/.X11-unix/X{display}");
87+ let addr = SocketAddr::from_abstract_name(name).unwrap();
88+ bind_to_socket(&addr)
89+}
90+
91+fn bind_to_unix_socket(display: u32) -> anyhow::Result<(UnixListener, Unlink)> {
92+ let name = format!("/tmp/.X11-unix/X{display}");
93+ let addr = SocketAddr::from_pathname(&name).unwrap();
94+ // Unlink old leftover socket if any.
95+ let _ = unlink(&name);
96+ let guard = Unlink(name);
97+ bind_to_socket(&addr).map(|listener| (listener, guard))
98+}
99+
100+fn open_display_sockets(display: u32) -> anyhow::Result<(UnixListener, UnixListener, Unlink)> {
101+ let a = bind_to_abstract_socket(display).context("error binding to abstract socket")?;
102+ let (u, g) = bind_to_unix_socket(display).context("error binding to unix socket")?;
103+ Ok((a, u, g))
104+}
105+
106+fn setup_connection() -> anyhow::Result<X11Connection> {
107+ let _span = tracy_client::span!("open_x11_sockets");
108+
109+ ensure_x11_unix_dir()?;
110+
111+ let mut n = 0;
112+ let mut attempt = 0;
113+ let (display, lock_guard, a, u, unix_guard) = loop {
114+ let (display, lock_fd, lock_guard) = pick_x11_display(n)?;
115+
116+ // Write our PID into the lock file.
117+ let pid_string = format!("{:>10}\n", getpid().as_raw_nonzero());
118+ if let Err(err) = rustix::io::write(&lock_fd, pid_string.as_bytes()) {
119+ return Err(err).context("error writing PID to X11 lock file");
120+ }
121+ drop(lock_fd);
122+
123+ match open_display_sockets(display) {
124+ Ok((a, u, g)) => {
125+ break (display, lock_guard, a, u, g);
126+ }
127+ Err(err) => {
128+ if attempt == 50 {
129+ return Err(err)
130+ .context("error opening X11 sockets after creating a lock file");
131+ }
132+
133+ n = display + 1;
134+ attempt += 1;
135+ continue;
136+ }
137+ }
138+ };
139+
140+ let display_name = format!(":{display}");
141+ let abstract_fd = OwnedFd::from(a);
142+ let unix_fd = OwnedFd::from(u);
143+
144+ Ok(X11Connection {
145+ display_name,
146+ abstract_fd,
147+ unix_fd,
148+ _unix_guard: unix_guard,
149+ _lock_guard: lock_guard,
150+ })
151+}
src/utils/xwayland/satellite.rsadded+309 -0
@@ -0,0 +1,309 @@
1+use std::os::fd::{AsRawFd as _, BorrowedFd, OwnedFd};
2+use std::os::unix::net::UnixListener;
3+use std::os::unix::process::CommandExt as _;
4+use std::path::{Path, PathBuf};
5+use std::process::{Command, Stdio};
6+use std::thread;
7+
8+use calloop::channel::Sender;
9+use calloop::generic::Generic;
10+use calloop::{Interest, Mode, PostAction, RegistrationToken};
11+use smithay::reexports::rustix::io::{fcntl_setfd, FdFlags};
12+
13+use crate::niri::State;
14+use crate::utils::expand_home;
15+use crate::utils::xwayland::X11Connection;
16+
17+pub struct Satellite {
18+ x11: X11Connection,
19+ abstract_token: Option<RegistrationToken>,
20+ unix_token: Option<RegistrationToken>,
21+ to_main: Sender<ToMain>,
22+}
23+
24+enum ToMain {
25+ SetupWatch,
26+}
27+
28+impl Satellite {
29+ pub fn display_name(&self) -> &str {
30+ &self.x11.display_name
31+ }
32+}
33+
34+pub fn setup(state: &mut State) {
35+ if state.niri.satellite.is_some() {
36+ return;
37+ }
38+
39+ let config = state.niri.config.borrow();
40+ let xwls_config = &config.xwayland_satellite;
41+ if xwls_config.off {
42+ return;
43+ }
44+
45+ if !test_ondemand(&xwls_config.path) {
46+ return;
47+ }
48+ drop(config);
49+
50+ let x11 = match super::setup_connection() {
51+ Ok(x11) => x11,
52+ Err(err) => {
53+ warn!("error opening X11 sockets, disabling xwayland-satellite integration: {err:?}");
54+ return;
55+ }
56+ };
57+
58+ let event_loop = &state.niri.event_loop;
59+ let (to_main, rx) = calloop::channel::channel();
60+ event_loop
61+ .insert_source(rx, move |event, _, state| match event {
62+ calloop::channel::Event::Msg(msg) => match msg {
63+ ToMain::SetupWatch => setup_watch(state),
64+ },
65+ calloop::channel::Event::Closed => (),
66+ })
67+ .unwrap();
68+
69+ state.niri.satellite = Some(Satellite {
70+ x11,
71+ abstract_token: None,
72+ unix_token: None,
73+ to_main,
74+ });
75+
76+ setup_watch(state);
77+}
78+
79+fn test_ondemand(path: &str) -> bool {
80+ let _span = tracy_client::span!("satellite::test_ondemand");
81+
82+ // Expand `~` at the start.
83+ let mut path = Path::new(path);
84+ let expanded = expand_home(path);
85+ match &expanded {
86+ Ok(Some(expanded)) => path = expanded.as_ref(),
87+ Ok(None) => (),
88+ Err(err) => {
89+ warn!("error expanding ~: {err:?}");
90+ }
91+ }
92+
93+ let mut process = Command::new(path);
94+ process
95+ .args([":0", "--test-listenfd-support"])
96+ .stdin(Stdio::null())
97+ .stdout(Stdio::null())
98+ .stderr(Stdio::null())
99+ .env_remove("DISPLAY")
100+ .env_remove("RUST_BACKTRACE")
101+ .env_remove("RUST_LIB_BACKTRACE");
102+
103+ let mut child = match process.spawn() {
104+ Ok(child) => child,
105+ Err(err) => {
106+ info!("error spawning xwayland-satellite at {path:?}, disabling integration: {err}");
107+ return false;
108+ }
109+ };
110+
111+ let status = match child.wait() {
112+ Ok(status) => status,
113+ Err(err) => {
114+ info!("error waiting for xwayland-satellite, disabling integration: {err}");
115+ return false;
116+ }
117+ };
118+
119+ if !status.success() {
120+ info!("xwayland-satellite doesn't support on-demand activation, disabling integration");
121+ return false;
122+ }
123+
124+ true
125+}
126+
127+// When xwayland-satellite fails to start and accept a connection on the socket, the socket will
128+// keep triggering our event source, even after the X11 client quits, resulting in a busyloop of
129+// trying to start xwayland-satellite. This function will clear out (accept and drop) all pending
130+// connections on the socket before registering a new event source, working around this problem.
131+// When the problem happens, it's very likely that xwayland-satellite won't be able to accept the
132+// pending client (since it had just failed to do so), so it's fine to drop the connections.
133+fn clear_out_pending_connections(fd: OwnedFd) -> OwnedFd {
134+ let listener = UnixListener::from(fd);
135+
136+ if let Err(err) = listener.set_nonblocking(true) {
137+ warn!("error setting X11 socket to nonblocking: {err:?}");
138+ return OwnedFd::from(listener);
139+ }
140+
141+ while listener.accept().is_ok() {}
142+
143+ if let Err(err) = listener.set_nonblocking(false) {
144+ warn!("error setting X11 socket to blocking: {err:?}");
145+ }
146+
147+ OwnedFd::from(listener)
148+}
149+
150+fn setup_watch(state: &mut State) {
151+ let Some(satellite) = state.niri.satellite.as_mut() else {
152+ return;
153+ };
154+
155+ let event_loop = &state.niri.event_loop;
156+
157+ if let Some(token) = satellite.abstract_token.take() {
158+ error!("abstract_token must be None in setup_watch()");
159+ event_loop.remove(token);
160+ }
161+ if let Some(token) = satellite.unix_token.take() {
162+ error!("unix_token must be None in setup_watch()");
163+ event_loop.remove(token);
164+ }
165+
166+ let fd = satellite.x11.abstract_fd.try_clone().unwrap();
167+ let fd = clear_out_pending_connections(fd);
168+ let source = Generic::new(fd, Interest::READ, Mode::Level);
169+ let token = event_loop
170+ .insert_source(source, move |_, _, state| {
171+ if let Some(satellite) = &mut state.niri.satellite {
172+ // Remove the other source.
173+ if let Some(token) = satellite.unix_token.take() {
174+ state.niri.event_loop.remove(token);
175+ }
176+ // Clear this source.
177+ satellite.abstract_token = None;
178+
179+ debug!("connection to X11 abstract socket; spawning xwayland-satellite");
180+ let path = state.niri.config.borrow().xwayland_satellite.path.clone();
181+ spawn(path, satellite);
182+ }
183+ Ok(PostAction::Remove)
184+ })
185+ .unwrap();
186+ satellite.abstract_token = Some(token);
187+
188+ let fd = satellite.x11.unix_fd.try_clone().unwrap();
189+ let fd = clear_out_pending_connections(fd);
190+ let source = Generic::new(fd, Interest::READ, Mode::Level);
191+ let token = event_loop
192+ .insert_source(source, move |_, _, state| {
193+ if let Some(satellite) = &mut state.niri.satellite {
194+ // Remove the other source.
195+ if let Some(token) = satellite.abstract_token.take() {
196+ state.niri.event_loop.remove(token);
197+ }
198+ // Clear this source.
199+ satellite.unix_token = None;
200+
201+ debug!("connection to X11 unix socket; spawning xwayland-satellite");
202+ let path = state.niri.config.borrow().xwayland_satellite.path.clone();
203+ spawn(path, satellite);
204+ }
205+ Ok(PostAction::Remove)
206+ })
207+ .unwrap();
208+ satellite.unix_token = Some(token);
209+}
210+
211+fn spawn(path: String, xwl: &Satellite) {
212+ let _span = tracy_client::span!("satellite::spawn");
213+
214+ let abstract_fd = xwl.x11.abstract_fd.try_clone().unwrap();
215+ let unix_fd = xwl.x11.unix_fd.try_clone().unwrap();
216+ let to_main = xwl.to_main.clone();
217+
218+ // Expand `~` at the start.
219+ let mut path = PathBuf::from(path);
220+ let expanded = expand_home(&path);
221+ match expanded {
222+ Ok(Some(expanded)) => path = expanded,
223+ Ok(None) => (),
224+ Err(err) => {
225+ warn!("error expanding ~: {err:?}");
226+ }
227+ }
228+
229+ let mut process = Command::new(&path);
230+ process.arg(&xwl.x11.display_name).env_remove("DISPLAY");
231+
232+ // We don't want it spamming the niri output.
233+ process
234+ .env_remove("RUST_BACKTRACE")
235+ .env_remove("RUST_LIB_BACKTRACE");
236+ process
237+ .stdin(Stdio::null())
238+ .stdout(Stdio::null())
239+ .stderr(Stdio::null());
240+
241+ // Spawning and waiting takes some milliseconds, so do it in a thread.
242+ let res = thread::Builder::new()
243+ .name("Xwl-s Spawner".to_owned())
244+ .spawn(move || {
245+ spawn_and_wait(&path, process, abstract_fd, unix_fd);
246+
247+ // Once xwayland-satellite crashes or fails to spawn, re-establish our X11 socket watch
248+ // to try again next time.
249+ let _ = to_main.send(ToMain::SetupWatch);
250+ });
251+
252+ if let Err(err) = res {
253+ warn!("error spawning a thread to spawn xwayland-satellite: {err:?}");
254+ let _ = xwl.to_main.send(ToMain::SetupWatch);
255+ }
256+}
257+
258+fn spawn_and_wait(path: &Path, mut process: Command, abstract_fd: OwnedFd, unix_fd: OwnedFd) {
259+ let abstract_raw = abstract_fd.as_raw_fd();
260+ let unix_raw = unix_fd.as_raw_fd();
261+
262+ process
263+ .arg("-listenfd")
264+ .arg(abstract_raw.to_string())
265+ .arg("-listenfd")
266+ .arg(unix_raw.to_string());
267+
268+ unsafe {
269+ process.pre_exec(move || {
270+ // We're about to exec xwl-s; perfect time to clear CLOEXEC on the file descriptors
271+ // that we want to pass it.
272+
273+ // We're not dropping these until after spawn().
274+ let abstract_fd = BorrowedFd::borrow_raw(abstract_raw);
275+ let unix_fd = BorrowedFd::borrow_raw(unix_raw);
276+
277+ fcntl_setfd(abstract_fd, FdFlags::empty())?;
278+ fcntl_setfd(unix_fd, FdFlags::empty())?;
279+
280+ Ok(())
281+ })
282+ };
283+
284+ let mut child = {
285+ let _span = tracy_client::span!();
286+ match process.spawn() {
287+ Ok(child) => child,
288+ Err(err) => {
289+ warn!("error spawning {path:?}: {err:?}");
290+ return;
291+ }
292+ }
293+ };
294+
295+ // The process spawned, we can drop our fds.
296+ drop(abstract_fd);
297+ drop(unix_fd);
298+
299+ let status = match child.wait() {
300+ Ok(status) => status,
301+ Err(err) => {
302+ warn!("error waiting for xwayland-satellite: {err:?}");
303+ return;
304+ }
305+ };
306+
307+ // This is most likely a crash, hence warn!().
308+ warn!("xwayland-satellite exited with: {status}");
309+}
wiki/Configuration:-Miscellaneous.mdmodified+27 -0
@@ -36,6 +36,11 @@ overview {
36 }36 }
37 }37 }
38 38
39+xwayland-satellite {
40+ // off
41+ path "xwayland-satellite"
42+}
43+
39 clipboard {44 clipboard {
40 disable-primary45 disable-primary
41 }46 }
@@ -207,6 +212,28 @@ overview {
207 }212 }
208 ```213 ```
209 214
215+### `xwayland-satellite`
216+
217+<sup>Since: next release</sup>
218+
219+Settings for integration with [xwayland-satellite](https://github.com/Supreeeme/xwayland-satellite).
220+
221+When a recent enough xwayland-satellite is detected, niri will create the X11 sockets and set `DISPLAY`, then automatically spawn `xwayland-satellite` when an X11 client tries to connect.
222+If Xwayland dies, niri will keep watching the X11 socket and restart `xwayland-satellite` as needed.
223+This is very similar to how built-in Xwayland works in other compositors.
224+
225+`off` disables the integration: niri won't create an X11 socket and won't set the `DISPLAY` environment variable.
226+
227+`path` sets the path to the `xwayland-satellite` binary.
228+By default, it's just `xwayland-satellite`, so it's looked up like any other non-absolute program name.
229+
230+```kdl
231+// Use a custom build of xwayland-satellite.
232+xwayland-satellite {
233+ path "~/source/rs/xwayland-satellite/target/release/xwayland-satellite"
234+}
235+```
236+
210 ### `clipboard`237 ### `clipboard`
211 238
212 <sup>Since: 25.02</sup>239 <sup>Since: 25.02</sup>
wiki/Xwayland.mdmodified+8 -0
@@ -8,6 +8,14 @@ It makes X11 windows appear as normal windows, just like a native Xwayland integ
8 xwayland-satellite works well with most applications: Steam, games, Discord, even more exotic things like Ardour with wine Windows VST plugins.8 xwayland-satellite works well with most applications: Steam, games, Discord, even more exotic things like Ardour with wine Windows VST plugins.
9 However, X11 apps that want to position windows or bars at specific screen coordinates won't behave correctly.9 However, X11 apps that want to position windows or bars at specific screen coordinates won't behave correctly.
10 10
11+> [!NOTE]
12+> In the next release, niri will have [built-in xwayland-satellite integration](./Configuration:-Miscellaneous.md#xwayland-satellite).
13+> You can try it by installing git versions of both niri and xwayland-satellite.
14+> With no further configuration, niri will create X11 sockets, then when an X11 client connects, automatically start xwayland-satellite.
15+>
16+> This matches how other compositors run Xwayland (but in niri's case, it's xwayland-satellite rather than Xwayland itself).
17+> It also makes X11 apps work fine in `spawn-at-startup` and in XDG autostart.
18+
11 Install it from your package manager, or build it according to instructions from its README, then run the `xwayland-satellite` binary.19 Install it from your package manager, or build it according to instructions from its README, then run the `xwayland-satellite` binary.
12 Look for a log message like: `Connected to Xwayland on :0`.20 Look for a log message like: `Connected to Xwayland on :0`.
13 Now you can start X11 applications on this X11 DISPLAY:21 Now you can start X11 applications on this X11 DISPLAY: