Skip to main content

clairlune_platform/
wlr.rs

1//! Compositors with the wlr layer-shell protocol (Sway, Hyprland, river,
2//! Wayfire, labwc and others): Clairlune's own surfaces in the background
3//! layer of every output, drawn in shared memory. They show the still
4//! wallpaper where the compositor has no wallpaper tool of its own
5//! ([`show_still`], held by a thread for as long as the app runs), and the
6//! live wallpaper's frames ([`Surfaces`], driven by the live host).
7//!
8//! Every output shows the same image (Linux composes one scene, at the
9//! largest output's size): the largest centred part with the output's
10//! shape, scaled by the compositor to fill it (`wp_viewporter`).
11//!
12//! Untried: written and compile-checked without a Wayland session.
13
14use sctk::compositor::{CompositorHandler, CompositorState};
15use sctk::output::{OutputHandler, OutputState};
16use sctk::reexports::client::globals::{GlobalList, registry_queue_init};
17use sctk::reexports::client::protocol::{wl_output, wl_shm, wl_surface};
18use sctk::reexports::client::{Connection, Dispatch, EventQueue, QueueHandle};
19use sctk::reexports::protocols::wp::viewporter::client::{wp_viewport, wp_viewporter};
20use sctk::registry::{ProvidesRegistryState, RegistryState, SimpleGlobal};
21use sctk::shell::WaylandSurface;
22use sctk::shell::wlr_layer::{
23    Anchor, KeyboardInteractivity, Layer, LayerShell, LayerShellHandler, LayerSurface,
24    LayerSurfaceConfigure,
25};
26use sctk::shm::slot::{Buffer, SlotPool};
27use sctk::shm::{Shm, ShmHandler};
28use sctk::{
29    delegate_compositor, delegate_layer, delegate_output, delegate_registry, delegate_shm,
30    delegate_simple, registry_handlers,
31};
32use smithay_client_toolkit as sctk;
33use std::os::fd::AsRawFd;
34use std::path::Path;
35use std::sync::Mutex;
36use std::sync::mpsc;
37use std::time::Duration;
38
39/// The namespace compositors see for our surfaces.
40const NAMESPACE: &str = "clairlune";
41/// Past this many rectangles, one rectangle around them all is cheaper.
42const MAX_RECTS: usize = 64;
43
44/// A rectangle of the image, in pixels.
45#[derive(Clone, Copy, Debug, PartialEq, Eq)]
46pub struct Rect {
47    pub x: u32,
48    pub y: u32,
49    pub w: u32,
50    pub h: u32,
51}
52
53/// An output, as the compositor describes it.
54#[derive(Clone, Debug, PartialEq, Eq)]
55pub struct Output {
56    /// The connector name (`DP-1`), or the compositor's id for it.
57    pub name: String,
58    /// Physical pixels.
59    pub width: u32,
60    pub height: u32,
61}
62
63/// The part of an `image`-sized picture an `output`-shaped screen shows
64/// when filled: the largest centred crop with the output's shape, as
65/// `(x, y, w, h)` in image pixels.
66pub fn fill_crop(image: (u32, u32), output: (u32, u32)) -> (f64, f64, f64, f64) {
67    let (iw, ih) = (f64::from(image.0), f64::from(image.1));
68    let (ow, oh) = (f64::from(output.0.max(1)), f64::from(output.1.max(1)));
69    let scale = (iw / ow).min(ih / oh);
70    let (w, h) = (ow * scale, oh * scale);
71    ((iw - w) / 2.0, (ih - h) / 2.0, w, h)
72}
73
74/// `rects` as at most [`MAX_RECTS`] rectangles: themselves, or the one
75/// around them all.
76fn bounded(rects: Vec<Rect>) -> Vec<Rect> {
77    if rects.len() <= MAX_RECTS {
78        return rects;
79    }
80    let x0 = rects.iter().map(|r| r.x).min().unwrap_or(0);
81    let y0 = rects.iter().map(|r| r.y).min().unwrap_or(0);
82    let x1 = rects.iter().map(|r| r.x + r.w).max().unwrap_or(0);
83    let y1 = rects.iter().map(|r| r.y + r.h).max().unwrap_or(0);
84    vec![Rect {
85        x: x0,
86        y: y0,
87        w: x1 - x0,
88        h: y1 - y0,
89    }]
90}
91
92/// Whether this session can show our background surfaces: Wayland, with
93/// layer shell, shared memory and the viewporter.
94pub fn available() -> Result<(), String> {
95    if std::env::var_os("WAYLAND_DISPLAY").is_none() {
96        return Err("not a Wayland session".into());
97    }
98    let conn = Connection::connect_to_env().map_err(|e| format!("Wayland: {e}"))?;
99    let (globals, _queue) =
100        registry_queue_init::<Probe>(&conn).map_err(|e| format!("Wayland: {e}"))?;
101    let names: Vec<String> = globals
102        .contents()
103        .with_list(|l| l.iter().map(|g| g.interface.clone()).collect());
104    for needed in ["zwlr_layer_shell_v1", "wl_shm", "wp_viewporter"] {
105        if !names.iter().any(|n| n == needed) {
106            return Err(format!("the compositor has no `{needed}`"));
107        }
108    }
109    Ok(())
110}
111
112/// Registry events while probing: nothing to do.
113struct Probe;
114impl
115    Dispatch<
116        sctk::reexports::client::protocol::wl_registry::WlRegistry,
117        sctk::reexports::client::globals::GlobalListContents,
118    > for Probe
119{
120    fn event(
121        _: &mut Self,
122        _: &sctk::reexports::client::protocol::wl_registry::WlRegistry,
123        _: sctk::reexports::client::protocol::wl_registry::Event,
124        _: &sctk::reexports::client::globals::GlobalListContents,
125        _: &Connection,
126        _: &QueueHandle<Self>,
127    ) {
128    }
129}
130
131/// One buffer of an output's surface, and the parts of the image it lacks.
132struct Slotted {
133    buffer: Buffer,
134    stale: Vec<Rect>,
135}
136
137/// One output's background surface.
138struct Entry {
139    output: wl_output::WlOutput,
140    layer: LayerSurface,
141    viewport: wp_viewport::WpViewport,
142    /// Logical size from the last configure; `None` until the first.
143    size: Option<(u32, u32)>,
144    /// Physical size, for the crop's shape.
145    physical: (u32, u32),
146    /// A frame callback is out: the compositor hasn't asked for more yet.
147    waiting: bool,
148    /// Changed since the last commit (what to damage), and whether it has
149    /// never been drawn.
150    damage: Vec<Rect>,
151    fresh: bool,
152    buffers: Vec<Slotted>,
153}
154
155struct State {
156    registry: RegistryState,
157    outputs: OutputState,
158    compositor: CompositorState,
159    layer_shell: LayerShell,
160    shm: Shm,
161    viewporter: SimpleGlobal<wp_viewporter::WpViewporter, 1>,
162    entries: Vec<Entry>,
163    image: (u32, u32),
164}
165
166impl State {
167    fn physical(&self, output: &wl_output::WlOutput) -> (u32, u32) {
168        let Some(info) = self.outputs.info(output) else {
169            return self.image;
170        };
171        let mode = info
172            .modes
173            .iter()
174            .find(|m| m.current)
175            .map(|m| m.dimensions)
176            .or_else(|| {
177                info.logical_size
178                    .map(|(w, h)| (w * info.scale_factor, h * info.scale_factor))
179            })
180            .unwrap_or((self.image.0 as i32, self.image.1 as i32));
181        let (w, h) = (mode.0.max(1) as u32, mode.1.max(1) as u32);
182        // Modes are given unrotated.
183        match info.transform {
184            wl_output::Transform::_90
185            | wl_output::Transform::_270
186            | wl_output::Transform::Flipped90
187            | wl_output::Transform::Flipped270 => (h, w),
188            _ => (w, h),
189        }
190    }
191
192    fn add(&mut self, qh: &QueueHandle<State>, output: wl_output::WlOutput) {
193        if self.entries.iter().any(|e| e.output == output) {
194            return;
195        }
196        let Ok(viewporter) = self.viewporter.get() else {
197            return;
198        };
199        let surface = self.compositor.create_surface(qh);
200        let viewport = viewporter.get_viewport(&surface, qh, ());
201        let layer = self.layer_shell.create_layer_surface(
202            qh,
203            surface,
204            Layer::Background,
205            Some(NAMESPACE),
206            Some(&output),
207        );
208        layer.set_anchor(Anchor::TOP | Anchor::BOTTOM | Anchor::LEFT | Anchor::RIGHT);
209        // Under panels too, like any wallpaper.
210        layer.set_exclusive_zone(-1);
211        layer.set_keyboard_interactivity(KeyboardInteractivity::None);
212        layer.set_size(0, 0);
213        // An empty input region: clicks go to the desktop below.
214        if let Ok(region) = sctk::compositor::Region::new(&self.compositor) {
215            layer
216                .wl_surface()
217                .set_input_region(Some(region.wl_region()));
218        }
219        layer.commit();
220        let physical = self.physical(&output);
221        self.entries.push(Entry {
222            output,
223            layer,
224            viewport,
225            size: None,
226            physical,
227            waiting: false,
228            damage: Vec::new(),
229            fresh: true,
230            buffers: Vec::new(),
231        });
232    }
233}
234
235/// Background surfaces on every output, showing one image.
236pub struct Surfaces {
237    queue: EventQueue<State>,
238    state: State,
239    pool: SlotPool,
240}
241
242impl Surfaces {
243    /// Opens a background surface on every output, for an image of `size`
244    /// pixels. Nothing shows until [`Surfaces::present`].
245    pub fn new(size: (u32, u32)) -> Result<Surfaces, String> {
246        let conn = Connection::connect_to_env().map_err(|e| format!("Wayland: {e}"))?;
247        let (globals, queue) =
248            registry_queue_init::<State>(&conn).map_err(|e| format!("Wayland: {e}"))?;
249        let qh = queue.handle();
250        let state = bind(&globals, &qh, size)?;
251        let pool = SlotPool::new((size.0 * size.1 * 4) as usize, &state.shm)
252            .map_err(|e| format!("shared memory: {e}"))?;
253        let mut s = Surfaces { queue, state, pool };
254        // Output descriptions arrive with the first round trips; then a
255        // surface per output, then their first configures.
256        for _ in 0..2 {
257            s.queue
258                .roundtrip(&mut s.state)
259                .map_err(|e| format!("Wayland: {e}"))?;
260        }
261        let outputs: Vec<_> = s.state.outputs.outputs().collect();
262        for o in outputs {
263            s.state.add(&qh, o);
264        }
265        s.queue
266            .roundtrip(&mut s.state)
267            .map_err(|e| format!("Wayland: {e}"))?;
268        if s.state.entries.is_empty() {
269            return Err("no outputs".into());
270        }
271        Ok(s)
272    }
273
274    /// The image size these surfaces show.
275    pub fn image_size(&self) -> (u32, u32) {
276        self.state.image
277    }
278
279    /// The outputs shown on.
280    pub fn outputs(&self) -> Vec<Output> {
281        self.state
282            .entries
283            .iter()
284            .map(|e| {
285                let info = self.state.outputs.info(&e.output);
286                Output {
287                    name: info
288                        .as_ref()
289                        .and_then(|i| i.name.clone())
290                        .unwrap_or_else(|| format!("wl-output-{}", info.map_or(0, |i| i.id))),
291                    width: e.physical.0,
292                    height: e.physical.1,
293                }
294            })
295            .collect()
296    }
297
298    /// Sends what is queued, then reads and handles what the compositor
299    /// sent, waiting at most `wait` for it.
300    pub fn dispatch(&mut self, wait: Duration) -> Result<(), String> {
301        self.queue.flush().map_err(|e| format!("Wayland: {e}"))?;
302        if let Some(guard) = self.queue.prepare_read() {
303            let mut fd = libc::pollfd {
304                fd: guard.connection_fd().as_raw_fd(),
305                events: libc::POLLIN,
306                revents: 0,
307            };
308            let ms = wait.as_millis().min(i32::MAX as u128) as i32;
309            // SAFETY: one valid pollfd for the duration of the call.
310            let ready = unsafe { libc::poll(&mut fd, 1, ms) };
311            if ready > 0 {
312                guard.read().map_err(|e| format!("Wayland: {e}"))?;
313            }
314        }
315        self.queue
316            .dispatch_pending(&mut self.state)
317            .map_err(|e| format!("Wayland: {e}"))?;
318        Ok(())
319    }
320
321    /// Outputs still waiting for their first frame.
322    pub fn pending(&self) -> usize {
323        self.state.entries.iter().filter(|e| e.fresh).count()
324    }
325
326    /// The image changed in `changed`: shows it on every output that is
327    /// ready (configured, and asked for a frame). `fill` writes one
328    /// rectangle of the current image into a canvas of the image's size,
329    /// XRGB8888 little-endian with the given stride in bytes. Returns the
330    /// outputs drawn.
331    pub fn present(
332        &mut self,
333        changed: &[Rect],
334        fill: &mut dyn FnMut(Rect, &mut [u8], usize),
335    ) -> Result<usize, String> {
336        let qh = self.queue.handle();
337        let (iw, ih) = self.state.image;
338        let whole = Rect {
339            x: 0,
340            y: 0,
341            w: iw,
342            h: ih,
343        };
344        let stride = iw as usize * 4;
345        let mut drawn = 0;
346        for e in &mut self.state.entries {
347            e.damage.extend_from_slice(changed);
348            for b in &mut e.buffers {
349                b.stale.extend_from_slice(changed);
350            }
351            let Some((lw, lh)) = e.size else { continue };
352            if e.waiting || (e.damage.is_empty() && !e.fresh) {
353                continue;
354            }
355            // A buffer the compositor has let go of, or a new one.
356            let free = e
357                .buffers
358                .iter()
359                .position(|b| b.buffer.canvas(&mut self.pool).is_some());
360            let i = match free {
361                Some(i) => i,
362                None if e.buffers.len() < 2 => {
363                    let (buffer, _) = self
364                        .pool
365                        .create_buffer(
366                            iw as i32,
367                            ih as i32,
368                            stride as i32,
369                            wl_shm::Format::Xrgb8888,
370                        )
371                        .map_err(|err| format!("shared memory: {err}"))?;
372                    e.buffers.push(Slotted {
373                        buffer,
374                        stale: vec![whole],
375                    });
376                    e.buffers.len() - 1
377                }
378                None => continue, // both still on screen: next time
379            };
380            let slot = &mut e.buffers[i];
381            let canvas = slot
382                .buffer
383                .canvas(&mut self.pool)
384                .ok_or("a free buffer has no canvas")?;
385            for r in bounded(std::mem::take(&mut slot.stale)) {
386                fill(r, canvas, stride);
387            }
388            let surface = e.layer.wl_surface();
389            let damage = if e.fresh {
390                vec![whole]
391            } else {
392                bounded(std::mem::take(&mut e.damage))
393            };
394            for r in damage {
395                surface.damage_buffer(r.x as i32, r.y as i32, r.w as i32, r.h as i32);
396            }
397            e.damage.clear();
398            let (sx, sy, sw, sh) = fill_crop((iw, ih), e.physical);
399            e.viewport.set_source(sx, sy, sw, sh);
400            e.viewport.set_destination(lw as i32, lh as i32);
401            surface.frame(&qh, surface.clone());
402            slot.buffer
403                .attach_to(surface)
404                .map_err(|err| format!("attach: {err:?}"))?;
405            e.layer.commit();
406            e.waiting = true;
407            e.fresh = false;
408            drawn += 1;
409        }
410        self.queue.flush().map_err(|e| format!("Wayland: {e}"))?;
411        Ok(drawn)
412    }
413}
414
415fn bind(globals: &GlobalList, qh: &QueueHandle<State>, image: (u32, u32)) -> Result<State, String> {
416    Ok(State {
417        registry: RegistryState::new(globals),
418        outputs: OutputState::new(globals, qh),
419        compositor: CompositorState::bind(globals, qh)
420            .map_err(|e| format!("wl_compositor: {e}"))?,
421        layer_shell: LayerShell::bind(globals, qh)
422            .map_err(|e| format!("the compositor has no layer shell: {e}"))?,
423        shm: Shm::bind(globals, qh).map_err(|e| format!("wl_shm: {e}"))?,
424        viewporter: SimpleGlobal::bind(globals, qh).map_err(|e| format!("wp_viewporter: {e}"))?,
425        entries: Vec::new(),
426        image,
427    })
428}
429
430impl CompositorHandler for State {
431    fn scale_factor_changed(
432        &mut self,
433        _: &Connection,
434        _: &QueueHandle<Self>,
435        _: &wl_surface::WlSurface,
436        _: i32,
437    ) {
438    }
439
440    fn transform_changed(
441        &mut self,
442        _: &Connection,
443        _: &QueueHandle<Self>,
444        _: &wl_surface::WlSurface,
445        _: wl_output::Transform,
446    ) {
447    }
448
449    fn frame(
450        &mut self,
451        _: &Connection,
452        _: &QueueHandle<Self>,
453        surface: &wl_surface::WlSurface,
454        _: u32,
455    ) {
456        if let Some(e) = self
457            .entries
458            .iter_mut()
459            .find(|e| e.layer.wl_surface() == surface)
460        {
461            e.waiting = false;
462        }
463    }
464
465    fn surface_enter(
466        &mut self,
467        _: &Connection,
468        _: &QueueHandle<Self>,
469        _: &wl_surface::WlSurface,
470        _: &wl_output::WlOutput,
471    ) {
472    }
473
474    fn surface_leave(
475        &mut self,
476        _: &Connection,
477        _: &QueueHandle<Self>,
478        _: &wl_surface::WlSurface,
479        _: &wl_output::WlOutput,
480    ) {
481    }
482}
483
484impl OutputHandler for State {
485    fn output_state(&mut self) -> &mut OutputState {
486        &mut self.outputs
487    }
488
489    /// A screen plugged in after the start gets its surface too.
490    fn new_output(&mut self, _: &Connection, qh: &QueueHandle<Self>, output: wl_output::WlOutput) {
491        if !self.entries.is_empty() {
492            self.add(qh, output);
493        }
494    }
495
496    fn update_output(
497        &mut self,
498        _: &Connection,
499        _: &QueueHandle<Self>,
500        output: wl_output::WlOutput,
501    ) {
502        let physical = self.physical(&output);
503        if let Some(e) = self.entries.iter_mut().find(|e| e.output == output) {
504            e.physical = physical;
505            e.fresh = true;
506        }
507    }
508
509    fn output_destroyed(
510        &mut self,
511        _: &Connection,
512        _: &QueueHandle<Self>,
513        output: wl_output::WlOutput,
514    ) {
515        self.entries.retain(|e| e.output != output);
516    }
517}
518
519impl LayerShellHandler for State {
520    fn closed(&mut self, _: &Connection, _: &QueueHandle<Self>, layer: &LayerSurface) {
521        self.entries.retain(|e| &e.layer != layer);
522    }
523
524    fn configure(
525        &mut self,
526        _: &Connection,
527        _: &QueueHandle<Self>,
528        layer: &LayerSurface,
529        configure: LayerSurfaceConfigure,
530        _: u32,
531    ) {
532        if let Some(e) = self.entries.iter_mut().find(|e| &e.layer == layer) {
533            let (w, h) = configure.new_size;
534            let size = (w.max(1), h.max(1));
535            if e.size != Some(size) {
536                e.size = Some(size);
537                e.fresh = true;
538            }
539        }
540    }
541}
542
543impl ShmHandler for State {
544    fn shm_state(&mut self) -> &mut Shm {
545        &mut self.shm
546    }
547}
548
549impl ProvidesRegistryState for State {
550    fn registry(&mut self) -> &mut RegistryState {
551        &mut self.registry
552    }
553    registry_handlers![OutputState];
554}
555
556impl AsMut<SimpleGlobal<wp_viewporter::WpViewporter, 1>> for State {
557    fn as_mut(&mut self) -> &mut SimpleGlobal<wp_viewporter::WpViewporter, 1> {
558        &mut self.viewporter
559    }
560}
561
562impl Dispatch<wp_viewport::WpViewport, ()> for State {
563    fn event(
564        _: &mut Self,
565        _: &wp_viewport::WpViewport,
566        _: wp_viewport::Event,
567        _: &(),
568        _: &Connection,
569        _: &QueueHandle<Self>,
570    ) {
571        // wp_viewport has no events.
572    }
573}
574
575delegate_compositor!(State);
576delegate_output!(State);
577delegate_shm!(State);
578delegate_layer!(State);
579delegate_registry!(State);
580delegate_simple!(State, wp_viewporter::WpViewporter, 1);
581
582// ---- The still wallpaper, held by a thread.
583
584/// An image as XRGB8888 pixels.
585struct Image {
586    width: u32,
587    height: u32,
588    pixels: Vec<u32>,
589}
590
591enum Command {
592    Show(Image),
593    Stop,
594}
595
596struct StillThread {
597    tx: mpsc::Sender<Command>,
598}
599
600static STILL: Mutex<Option<StillThread>> = Mutex::new(None);
601
602/// Decodes a PNG (any colour type) to XRGB8888.
603fn decode(path: &Path) -> Result<Image, String> {
604    let file = std::fs::File::open(path).map_err(|e| format!("{}: {e}", path.display()))?;
605    let mut dec = png::Decoder::new(std::io::BufReader::new(file));
606    dec.set_transformations(png::Transformations::EXPAND | png::Transformations::STRIP_16);
607    let mut reader = dec
608        .read_info()
609        .map_err(|e| format!("{}: {e}", path.display()))?;
610    let mut buf = vec![0u8; reader.output_buffer_size().unwrap_or(0)];
611    let info = reader
612        .next_frame(&mut buf)
613        .map_err(|e| format!("{}: {e}", path.display()))?;
614    let channels = info.color_type.samples();
615    let pixels = buf[..info.buffer_size()]
616        .chunks_exact(channels)
617        .map(|p| match channels {
618            1 | 2 => u32::from(p[0]) * 0x01_0101,
619            _ => (u32::from(p[0]) << 16) | (u32::from(p[1]) << 8) | u32::from(p[2]),
620        })
621        .collect();
622    Ok(Image {
623        width: info.width,
624        height: info.height,
625        pixels,
626    })
627}
628
629/// Shows a still image on every output, in the background layer, until
630/// [`hide_still`] or the process ends. Returns once the surfaces exist.
631pub fn show_still(path: &Path) -> Result<(), String> {
632    let image = decode(path)?;
633    let mut held = STILL.lock().map_err(|_| "the still thread panicked")?;
634    if let Some(t) = held.as_ref() {
635        match t.tx.send(Command::Show(image)) {
636            Ok(()) => return Ok(()),
637            // The thread ended (the compositor went away): start again.
638            Err(mpsc::SendError(Command::Show(img))) => return start(&mut held, img),
639            Err(_) => unreachable!("only Show is sent here"),
640        }
641    }
642    start(&mut held, image)
643}
644
645/// Takes the still surfaces away (what the compositor draws itself shows).
646pub fn hide_still() {
647    if let Ok(mut held) = STILL.lock()
648        && let Some(t) = held.take()
649    {
650        let _ = t.tx.send(Command::Stop);
651    }
652}
653
654fn start(held: &mut Option<StillThread>, image: Image) -> Result<(), String> {
655    let (tx, rx) = mpsc::channel();
656    let (ready_tx, ready_rx) = mpsc::channel();
657    std::thread::Builder::new()
658        .name("clairlune-wlr-still".into())
659        .spawn(move || still_loop(image, &rx, &ready_tx))
660        .map_err(|e| format!("still thread: {e}"))?;
661    ready_rx
662        .recv()
663        .map_err(|_| "the still thread ended".to_string())??;
664    *held = Some(StillThread { tx });
665    Ok(())
666}
667
668fn still_loop(
669    first: Image,
670    rx: &mpsc::Receiver<Command>,
671    ready: &mpsc::Sender<Result<(), String>>,
672) {
673    let open = |img: &Image| Surfaces::new((img.width, img.height));
674    let mut surfaces = match open(&first) {
675        Ok(s) => {
676            let _ = ready.send(Ok(()));
677            s
678        }
679        Err(e) => {
680            let _ = ready.send(Err(e));
681            return;
682        }
683    };
684    let mut image = first;
685    let mut changed = true;
686    loop {
687        match rx.try_recv() {
688            Ok(Command::Show(img)) => {
689                if (img.width, img.height) != surfaces.image_size() {
690                    match open(&img) {
691                        Ok(s) => surfaces = s,
692                        Err(e) => {
693                            tracing::warn!(target: "clairlune_platform", error = %e, "still surfaces");
694                            return;
695                        }
696                    }
697                }
698                image = img;
699                changed = true;
700            }
701            Ok(Command::Stop) | Err(mpsc::TryRecvError::Disconnected) => return,
702            Err(mpsc::TryRecvError::Empty) => {}
703        }
704        if let Err(e) = surfaces.dispatch(Duration::from_millis(250)) {
705            tracing::warn!(target: "clairlune_platform", error = %e, "still surfaces lost");
706            return;
707        }
708        let whole = Rect {
709            x: 0,
710            y: 0,
711            w: image.width,
712            h: image.height,
713        };
714        let rects = if changed { vec![whole] } else { Vec::new() };
715        let img = &image;
716        let result = surfaces.present(&rects, &mut |r, canvas, stride| {
717            copy_rect(&img.pixels, img.width, r, canvas, stride);
718        });
719        if let Err(e) = result {
720            tracing::warn!(target: "clairlune_platform", error = %e, "still surfaces");
721            return;
722        }
723        changed = false;
724    }
725}
726
727/// Copies rectangle `r` of an XRGB image `width` pixels wide into a canvas
728/// of the same size.
729pub fn copy_rect(pixels: &[u32], width: u32, r: Rect, canvas: &mut [u8], stride: usize) {
730    for y in r.y..r.y + r.h {
731        let src = &pixels[(y * width + r.x) as usize..][..r.w as usize];
732        let dst = &mut canvas[y as usize * stride + r.x as usize * 4..][..r.w as usize * 4];
733        for (d, s) in dst.as_chunks_mut::<4>().0.iter_mut().zip(src) {
734            d.copy_from_slice(&s.to_le_bytes());
735        }
736    }
737}
738
739#[cfg(test)]
740mod tests {
741    use super::*;
742
743    #[test]
744    fn a_wider_screen_shows_a_band_across_the_middle() {
745        // A 16:9 image on a 21:9 screen: full width, a centred band.
746        let (x, y, w, h) = fill_crop((1920, 1080), (2560, 1080));
747        assert_eq!((x, w), (0.0, 1920.0));
748        assert!((h - 810.0).abs() < 1e-9 && (y - 135.0).abs() < 1e-9);
749        // The same shape: everything.
750        assert_eq!(
751            fill_crop((1920, 1080), (3840, 2160)),
752            (0.0, 0.0, 1920.0, 1080.0)
753        );
754        // Portrait: a centred column.
755        let (x, _, w, h) = fill_crop((1920, 1080), (1080, 1920));
756        assert_eq!(h, 1080.0);
757        assert!((w - 607.5).abs() < 1e-9 && (x - 656.25).abs() < 1e-9);
758    }
759
760    #[test]
761    fn many_rects_become_one_around_them() {
762        let few = vec![
763            Rect {
764                x: 1,
765                y: 2,
766                w: 3,
767                h: 4
768            };
769            3
770        ];
771        assert_eq!(bounded(few.clone()), few);
772        let many: Vec<Rect> = (0..100)
773            .map(|i| Rect {
774                x: i,
775                y: 10 + i,
776                w: 2,
777                h: 1,
778            })
779            .collect();
780        assert_eq!(
781            bounded(many),
782            vec![Rect {
783                x: 0,
784                y: 10,
785                w: 101,
786                h: 100
787            }]
788        );
789    }
790
791    #[test]
792    fn rects_copy_as_little_endian_xrgb() {
793        let pixels = vec![
794            0x00_11_22_33u32,
795            0x00_44_55_66,
796            0x00_77_88_99,
797            0x00_AA_BB_CC,
798        ];
799        let mut canvas = vec![0u8; 16];
800        copy_rect(
801            &pixels,
802            2,
803            Rect {
804                x: 1,
805                y: 1,
806                w: 1,
807                h: 1,
808            },
809            &mut canvas,
810            8,
811        );
812        assert_eq!(&canvas[12..16], &[0xCC, 0xBB, 0xAA, 0x00]);
813        assert!(canvas[..12].iter().all(|&b| b == 0));
814    }
815}