Skip to main content

clairlune_live/
linux.rs

1//! The live wallpaper on Linux, where a surface of our own can sit under
2//! everything without hiding the desktop's icons:
3//!
4//! - Wayland compositors with the wlr layer shell (Sway, Hyprland, river,
5//!   Wayfire, labwc...): a background-layer surface per output, drawn in
6//!   shared memory ([`clairlune_platform::wlr::Surfaces`]).
7//! - X11 window managers without a desktop of their own (i3, Openbox,
8//!   bspwm...): a window per monitor at the bottom of the stack, ignoring
9//!   the mouse, drawn with `PutImage`.
10//!
11//! Desktops that draw their own desktop and icons (GNOME, KDE Plasma, XFCE,
12//! Cinnamon, MATE, LXQt) would be covered by such a surface, so there the
13//! still frame stays the wallpaper.
14//!
15//! Linux composes one scene for the whole desktop, at the largest output's
16//! size; each output shows the largest centred part of it with its shape.
17//! Only the rectangles that changed are copied. Untried: written and
18//! compile-checked without a Linux desktop.
19
20use crate::{CoverPolicy, FrameStats, Player};
21use clairlune_platform::Monitor;
22use clairlune_platform::wlr::{Rect, Surfaces};
23use clairlune_render::PixelRect;
24use std::time::{Duration, Instant};
25use x11rb::connection::{Connection as _, RequestConnection as _};
26use x11rb::protocol::Event;
27use x11rb::protocol::randr::ConnectionExt as _;
28use x11rb::protocol::shape::{self, ConnectionExt as _};
29use x11rb::protocol::xproto::{
30    self, ConfigureWindowAux, ConnectionExt as _, CreateGCAux, CreateWindowAux, EventMask,
31    ImageFormat, StackMode, WindowClass,
32};
33use x11rb::rust_connection::RustConnection;
34use x11rb::wrapper::ConnectionExt as _;
35
36/// Frame rate cap: every changed pixel goes through the CPU.
37const MAX_FPS: u32 = 30;
38
39/// Desktops that draw their own desktop and icons.
40const OWN_DESKTOPS: [&str; 10] = [
41    "gnome",
42    "kde",
43    "xfce",
44    "x-cinnamon",
45    "cinnamon",
46    "mate",
47    "lxqt",
48    "lxde",
49    "unity",
50    "budgie",
51];
52
53/// A desktop from `XDG_CURRENT_DESKTOP` that draws its own desktop, if any.
54pub fn own_desktop(current: &str) -> Option<String> {
55    current
56        .split(':')
57        .map(str::to_ascii_lowercase)
58        .find(|p| OWN_DESKTOPS.contains(&p.as_str()))
59}
60
61/// Whether live wallpapers can play in this session, with the reason if
62/// not.
63pub fn available() -> Result<(), String> {
64    let current = std::env::var("XDG_CURRENT_DESKTOP").unwrap_or_default();
65    if let Some(d) = own_desktop(&current) {
66        return Err(format!(
67            "{d} draws its own desktop and icons, which a live wallpaper would cover"
68        ));
69    }
70    if std::env::var_os("WAYLAND_DISPLAY").is_some() {
71        clairlune_platform::wlr::available()
72    } else if std::env::var_os("DISPLAY").is_some() {
73        let (conn, screen) = x11rb::connect(None).map_err(|e| format!("X11: {e}"))?;
74        let root = conn.setup().roots[screen].root;
75        match desktop_window(&conn, root)? {
76            Some(name) => Err(format!(
77                "the desktop ({name}) draws its own icons, which a live wallpaper would cover"
78            )),
79            None => Ok(()),
80        }
81    } else {
82        Err("no display".into())
83    }
84}
85
86/// The largest centred part of a `scene`-sized frame with an `output`'s
87/// shape, cut at whole pixels: what a screen of that size shows without
88/// scaling (X11), and where in the screen it goes when the scene is
89/// smaller.
90pub fn centred_view(scene: (u32, u32), output: (u32, u32)) -> (PixelRect, (i16, i16)) {
91    let w = scene.0.min(output.0);
92    let h = scene.1.min(output.1);
93    let view = PixelRect {
94        x: (scene.0 - w) / 2,
95        y: (scene.1 - h) / 2,
96        w,
97        h,
98    };
99    let at = (((output.0 - w) / 2) as i16, ((output.1 - h) / 2) as i16);
100    (view, at)
101}
102
103/// Live wallpapers on every screen, on Wayland or X11.
104pub struct LinuxDesktop {
105    host: Host,
106    pub cover_policy: CoverPolicy,
107}
108
109enum Host {
110    Wayland(Box<Wayland>),
111    X11(Box<X11>),
112}
113
114impl LinuxDesktop {
115    /// Plays the scene (Linux composes one, for the whole desktop) on every
116    /// screen.
117    pub fn start(scenes: Vec<(Monitor, Player)>) -> Result<LinuxDesktop, String> {
118        available()?;
119        let (monitor, player) = scenes.into_iter().next().ok_or("no scene to play")?;
120        let host = if std::env::var_os("WAYLAND_DISPLAY").is_some() {
121            Host::Wayland(Box::new(Wayland::start(monitor, player)?))
122        } else {
123            Host::X11(Box::new(X11::start(monitor, player)?))
124        };
125        Ok(LinuxDesktop {
126            host,
127            cover_policy: CoverPolicy::default(),
128        })
129    }
130
131    /// "wayland (shm)" or "x11 (putimage)".
132    pub fn presenter(&self) -> String {
133        match &self.host {
134            Host::Wayland(_) => "wayland (shm, layer shell)".into(),
135            Host::X11(_) => "x11 (putimage)".into(),
136        }
137    }
138
139    /// The highest frame rate worth asking for: the CPU copies every
140    /// changed pixel.
141    pub fn max_fps(&self) -> u32 {
142        MAX_FPS
143    }
144
145    /// The scene's "monitor" (the whole desktop).
146    pub fn monitors(&self) -> impl Iterator<Item = &Monitor> {
147        std::iter::once(match &self.host {
148            Host::Wayland(w) => &w.monitor,
149            Host::X11(x) => &x.monitor,
150        })
151    }
152
153    /// Draws the current time wherever it shows.
154    pub fn tick(&mut self) -> Result<FrameStats, String> {
155        match &mut self.host {
156            Host::Wayland(w) => w.tick(),
157            Host::X11(x) => x.tick(),
158        }
159    }
160}
161
162// ---- Wayland
163
164struct Wayland {
165    monitor: Monitor,
166    player: Player,
167    surfaces: Surfaces,
168}
169
170/// Writes rectangle `r` of the player's frame into an XRGB8888 canvas of
171/// the frame's size.
172fn fill(player: &Player, r: Rect, canvas: &mut [u8], stride: usize) {
173    let colors = player.colors();
174    for y in r.y..r.y + r.h {
175        let row = player.index_row(r.x, y, r.w);
176        let dst = &mut canvas[y as usize * stride + r.x as usize * 4..][..r.w as usize * 4];
177        for (d, &i) in dst.as_chunks_mut::<4>().0.iter_mut().zip(row) {
178            *d = colors[usize::from(i)].to_le_bytes();
179        }
180    }
181}
182
183impl Wayland {
184    fn start(monitor: Monitor, mut player: Player) -> Result<Wayland, String> {
185        let mut surfaces = Surfaces::new(player.size())?;
186        let t = player.now_ms();
187        player.advance(t);
188        surfaces.present(&[], &mut |r, c, s| fill(&player, r, c, s))?;
189        tracing::info!(
190            target: "clairlune",
191            outputs = ?surfaces.outputs(),
192            "live: background surfaces on Wayland"
193        );
194        Ok(Wayland {
195            monitor,
196            player,
197            surfaces,
198        })
199    }
200
201    fn tick(&mut self) -> Result<FrameStats, String> {
202        let started = Instant::now();
203        self.surfaces.dispatch(Duration::ZERO)?;
204        let t = self.player.now_ms();
205        let rects = self.player.advance(t);
206        let changed: Vec<Rect> = rects
207            .iter()
208            .map(|r| Rect {
209                x: r.x,
210                y: r.y,
211                w: r.w,
212                h: r.h,
213            })
214            .collect();
215        let t0 = Instant::now();
216        let player = &self.player;
217        let drawn = self
218            .surfaces
219            .present(&changed, &mut |r, c, s| fill(player, r, c, s))?;
220        Ok(FrameStats {
221            pixels: rects.iter().map(|r| u64::from(r.w * r.h)).sum::<u64>() * drawn as u64,
222            rects: rects.len() * drawn,
223            covered: 0,
224            away: false,
225            stalls: 0,
226            busy: started.elapsed(),
227            upload: t0.elapsed(),
228            present: Duration::ZERO,
229        })
230    }
231}
232
233// ---- X11
234
235struct XOutput {
236    player: Player,
237    window: xproto::Window,
238    gc: xproto::Gcontext,
239    /// Where the player's view goes in the window.
240    at: (i16, i16),
241    /// Exposed: draw everything again.
242    exposed: bool,
243}
244
245struct X11 {
246    monitor: Monitor,
247    conn: RustConnection,
248    depth: u8,
249    outputs: Vec<XOutput>,
250}
251
252/// A window of type desktop (a desktop drawing its icons), by its class.
253fn desktop_window(conn: &RustConnection, root: xproto::Window) -> Result<Option<String>, String> {
254    let atom = |name: &[u8]| -> Result<xproto::Atom, String> {
255        Ok(conn
256            .intern_atom(false, name)
257            .map_err(|e| e.to_string())?
258            .reply()
259            .map_err(|e| e.to_string())?
260            .atom)
261    };
262    let list = atom(b"_NET_CLIENT_LIST")?;
263    let kind = atom(b"_NET_WM_WINDOW_TYPE")?;
264    let desktop = atom(b"_NET_WM_WINDOW_TYPE_DESKTOP")?;
265    let windows: Vec<u32> = conn
266        .get_property(false, root, list, xproto::AtomEnum::WINDOW, 0, 4096)
267        .map_err(|e| e.to_string())?
268        .reply()
269        .map_err(|e| e.to_string())?
270        .value32()
271        .map(Iterator::collect)
272        .unwrap_or_default();
273    for w in windows {
274        let Ok(reply) = conn
275            .get_property(false, w, kind, xproto::AtomEnum::ATOM, 0, 32)
276            .map_err(|e| e.to_string())?
277            .reply()
278        else {
279            continue;
280        };
281        if reply.value32().is_some_and(|mut v| v.any(|a| a == desktop)) {
282            let class = conn
283                .get_property(
284                    false,
285                    w,
286                    xproto::AtomEnum::WM_CLASS,
287                    xproto::AtomEnum::STRING,
288                    0,
289                    64,
290                )
291                .ok()
292                .and_then(|c| c.reply().ok())
293                .map(|r| {
294                    String::from_utf8_lossy(&r.value)
295                        .split('\0')
296                        .find(|s| !s.is_empty())
297                        .unwrap_or("unknown")
298                        .to_string()
299                })
300                .unwrap_or_else(|| "unknown".into());
301            return Ok(Some(class));
302        }
303    }
304    Ok(None)
305}
306
307impl X11 {
308    fn start(monitor: Monitor, player: Player) -> Result<X11, String> {
309        let err = |e: &dyn std::fmt::Display| format!("X11: {e}");
310        let (conn, screen_num) = x11rb::connect(None).map_err(|e| err(&e))?;
311        let screen = conn.setup().roots[screen_num].clone();
312        // 32-bit little-endian pixels for the root depth: what 0RGB is.
313        let depth = screen.root_depth;
314        let bpp = conn
315            .setup()
316            .pixmap_formats
317            .iter()
318            .find(|f| f.depth == depth)
319            .map(|f| f.bits_per_pixel);
320        if depth != 24
321            || bpp != Some(32)
322            || conn.setup().image_byte_order != xproto::ImageOrder::LSB_FIRST
323        {
324            return Err(format!(
325                "X11: a {depth}-bit screen with {bpp:?} bits per pixel isn't supported"
326            ));
327        }
328        let monitors = conn
329            .randr_get_monitors(screen.root, true)
330            .map_err(|e| err(&e))?
331            .reply()
332            .map_err(|e| err(&e))?
333            .monitors;
334        if monitors.is_empty() {
335            return Err("X11: no monitors".into());
336        }
337        let scene = player.size();
338        let mut outputs = Vec::new();
339        for m in &monitors {
340            let (w, h) = (u32::from(m.width), u32::from(m.height));
341            let (view, at) = centred_view(scene, (w, h));
342            let p = player
343                .with_view(view)
344                .ok_or("X11: the view isn't inside the scene")?;
345            let window = conn.generate_id().map_err(|e| err(&e))?;
346            // Not managed by the window manager (it would tile or decorate
347            // it), black under the scene, redrawn when exposed.
348            conn.create_window(
349                depth,
350                window,
351                screen.root,
352                m.x,
353                m.y,
354                m.width,
355                m.height,
356                0,
357                WindowClass::INPUT_OUTPUT,
358                screen.root_visual,
359                &CreateWindowAux::new()
360                    .override_redirect(1)
361                    .background_pixel(screen.black_pixel)
362                    .event_mask(EventMask::EXPOSURE),
363            )
364            .map_err(|e| err(&e))?;
365            conn.change_property8(
366                xproto::PropMode::REPLACE,
367                window,
368                xproto::AtomEnum::WM_CLASS,
369                xproto::AtomEnum::STRING,
370                b"clairlune\0Clairlune\0",
371            )
372            .map_err(|e| err(&e))?;
373            // An empty input shape: clicks go through to the root window
374            // (window manager menus keep working).
375            conn.shape_rectangles(
376                shape::SO::SET,
377                shape::SK::INPUT,
378                xproto::ClipOrdering::UNSORTED,
379                window,
380                0,
381                0,
382                &[],
383            )
384            .map_err(|e| err(&e))?;
385            conn.map_window(window).map_err(|e| err(&e))?;
386            conn.configure_window(
387                window,
388                &ConfigureWindowAux::new().stack_mode(StackMode::BELOW),
389            )
390            .map_err(|e| err(&e))?;
391            let gc = conn.generate_id().map_err(|e| err(&e))?;
392            conn.create_gc(gc, window, &CreateGCAux::new())
393                .map_err(|e| err(&e))?;
394            outputs.push(XOutput {
395                player: p,
396                window,
397                gc,
398                at,
399                exposed: true,
400            });
401        }
402        conn.flush().map_err(|e| err(&e))?;
403        let mut x = X11 {
404            monitor,
405            conn,
406            depth,
407            outputs,
408        };
409        x.tick()?;
410        Ok(x)
411    }
412
413    fn tick(&mut self) -> Result<FrameStats, String> {
414        let err = |e: &dyn std::fmt::Display| format!("X11: {e}");
415        let started = Instant::now();
416        while let Some(event) = self.conn.poll_for_event().map_err(|e| err(&e))? {
417            if let Event::Expose(e) = event
418                && let Some(o) = self.outputs.iter_mut().find(|o| o.window == e.window)
419            {
420                o.exposed = true;
421            }
422        }
423        let limit = self
424            .conn
425            .maximum_request_bytes()
426            .saturating_sub(64)
427            .max(4096);
428        let (mut pixels, mut count) = (0u64, 0usize);
429        let mut row = Vec::new();
430        for o in &mut self.outputs {
431            let t = o.player.now_ms();
432            let mut rects = o.player.advance(t);
433            if std::mem::take(&mut o.exposed) {
434                let (w, h) = o.player.size();
435                rects = vec![PixelRect { x: 0, y: 0, w, h }];
436            }
437            for r in &rects {
438                // Whole rows per request, within the request size limit.
439                let rows = (limit / (r.w as usize * 4)).max(1) as u32;
440                let mut y = r.y;
441                while y < r.y + r.h {
442                    let n = rows.min(r.y + r.h - y);
443                    let part = PixelRect {
444                        x: r.x,
445                        y,
446                        w: r.w,
447                        h: n,
448                    };
449                    o.player.rect_pixels(&part, &mut row);
450                    let bytes: Vec<u8> = row.iter().flat_map(|p| p.to_le_bytes()).collect();
451                    self.conn
452                        .put_image(
453                            ImageFormat::Z_PIXMAP,
454                            o.window,
455                            o.gc,
456                            r.w as u16,
457                            n as u16,
458                            o.at.0 + r.x as i16,
459                            o.at.1 + y as i16,
460                            0,
461                            self.depth,
462                            &bytes,
463                        )
464                        .map_err(|e| err(&e))?;
465                    y += n;
466                }
467                pixels += u64::from(r.w * r.h);
468            }
469            count += rects.len();
470        }
471        self.conn.flush().map_err(|e| err(&e))?;
472        Ok(FrameStats {
473            pixels,
474            rects: count,
475            covered: 0,
476            away: false,
477            stalls: 0,
478            busy: started.elapsed(),
479            upload: started.elapsed(),
480            present: Duration::ZERO,
481        })
482    }
483}
484
485impl Drop for X11 {
486    fn drop(&mut self) {
487        for o in &self.outputs {
488            let _ = self.conn.free_gc(o.gc);
489            let _ = self.conn.destroy_window(o.window);
490        }
491        let _ = self.conn.flush();
492    }
493}
494
495#[cfg(test)]
496mod tests {
497    use super::*;
498
499    #[test]
500    fn desktops_with_icons_keep_the_still() {
501        assert_eq!(own_desktop("ubuntu:GNOME").as_deref(), Some("gnome"));
502        assert_eq!(own_desktop("KDE").as_deref(), Some("kde"));
503        assert_eq!(own_desktop("X-Cinnamon").as_deref(), Some("x-cinnamon"));
504        assert_eq!(own_desktop("sway"), None);
505        assert_eq!(own_desktop("Hyprland"), None);
506        assert_eq!(own_desktop("i3"), None);
507        assert_eq!(own_desktop(""), None);
508    }
509
510    #[test]
511    fn a_screen_shows_the_middle_of_a_larger_scene() {
512        // The scene is the largest screen's size: a smaller one shows its
513        // middle, at the screen's origin.
514        let (v, at) = centred_view((2560, 1440), (1920, 1080));
515        assert_eq!((v.x, v.y, v.w, v.h), (320, 180, 1920, 1080));
516        assert_eq!(at, (0, 0));
517        // A taller screen: the whole scene width, centred vertically.
518        let (v, at) = centred_view((1920, 1080), (1080, 1920));
519        assert_eq!((v.x, v.y, v.w, v.h), (420, 0, 1080, 1080));
520        assert_eq!(at, (0, 420));
521        // The same size: all of it.
522        let (v, at) = centred_view((1920, 1080), (1920, 1080));
523        assert_eq!((v.x, v.y, v.w, v.h, at), (0, 0, 1920, 1080, (0, 0)));
524    }
525}