Skip to main content

clairlune_live/
lib.rs

1//! Clairlune's live wallpaper (PLAN.md sections 2 and 5.3): a saved scene
2//! plays behind the desktop icons.
3//!
4//! [`Player`] keeps the frame between ticks with the incremental compositor
5//! and writes only the rectangles that changed into a 0RGB buffer, which the
6//! presenter copies to the screen as damage. The pixels come from the same
7//! compositor as the still PNG, so the first live frame (at the hero time)
8//! is the static wallpaper exactly, and so is every frame's palette.
9
10use clairlune_render::clock::Clock;
11use clairlune_render::{IncrementalFrame, IndexedImage, PixelRect, ScenePackage};
12use clairlune_scene::Theme;
13use std::sync::Arc;
14use std::time::Instant;
15
16#[cfg(windows)]
17pub mod desktop;
18pub mod gpu;
19
20/// Plays one saved scene, one frame at a time.
21pub struct Player {
22    pkg: Arc<ScenePackage>,
23    theme: Theme,
24    buddy: bool,
25    frame: IncrementalFrame,
26    /// Palette index to 0RGB.
27    colors: [u32; 256],
28    /// Scene time when playback started (the hero time, so the first frame
29    /// is the still), and when that was.
30    t0: u64,
31    started: Instant,
32}
33
34impl Player {
35    /// `None` if the scene has no such theme.
36    pub fn new(pkg: Arc<ScenePackage>, theme: Theme, buddy: bool) -> Option<Player> {
37        let frame = pkg.incremental(theme)?;
38        let mut colors = [0u32; 256];
39        for (i, c) in pkg.palette(theme)?.colors().iter().enumerate() {
40            colors[i] = (u32::from(c.r) << 16) | (u32::from(c.g) << 8) | u32::from(c.b);
41        }
42        let t0 = pkg.hero_ms(theme)?;
43        Some(Player {
44            pkg,
45            theme,
46            buddy,
47            frame,
48            colors,
49            t0,
50            started: Instant::now(),
51        })
52    }
53
54    pub fn size(&self) -> (u32, u32) {
55        (self.pkg.width, self.pkg.height)
56    }
57
58    /// The current frame as palette indices.
59    pub fn image(&self) -> &IndexedImage {
60        self.frame.image()
61    }
62
63    /// The palette as 0RGB, by index.
64    pub fn colors(&self) -> &[u32; 256] {
65        &self.colors
66    }
67
68    /// Scene time now: the hero time plus the time since playback started.
69    /// A pause only stops drawing; the next frame shows the time it is.
70    pub fn now_ms(&self) -> u64 {
71        self.t0 + self.started.elapsed().as_millis() as u64
72    }
73
74    /// Moves to `t_ms`; returns the rectangles that changed.
75    pub fn advance(&mut self, t_ms: u64) -> Vec<PixelRect> {
76        self.pkg
77            .advance(&mut self.frame, self.theme, self.buddy, t_ms, Clock::Live)
78            .unwrap_or_default()
79    }
80
81    /// Writes those rectangles of the current frame into a 0RGB buffer of the
82    /// frame's size.
83    pub fn write(&self, buf: &mut [u32], rects: &[PixelRect]) {
84        let img = self.frame.image();
85        let w = img.width as usize;
86        debug_assert_eq!(buf.len(), img.pixels.len());
87        for r in rects {
88            for y in r.y..r.y + r.h {
89                let a = y as usize * w + r.x as usize;
90                let b = a + r.w as usize;
91                for (out, &i) in buf[a..b].iter_mut().zip(&img.pixels[a..b]) {
92                    *out = self.colors[usize::from(i)];
93                }
94            }
95        }
96    }
97
98    /// Writes the whole current frame.
99    pub fn write_all(&self, buf: &mut [u32]) {
100        for (out, &i) in buf.iter_mut().zip(&self.frame.image().pixels) {
101            *out = self.colors[usize::from(i)];
102        }
103    }
104}
105
106/// Live frame rates, by their names in Settings (PLAN.md section 5.3).
107pub const SMOOTHNESS_FPS: [(u32, &str); 5] = [
108    (6, "Battery saver"),
109    (12, "Balanced"),
110    (24, "Smooth"),
111    (30, "Very smooth"),
112    (60, "Ultra smooth"),
113];
114
115#[cfg(test)]
116mod tests {
117    use super::*;
118    use clairlune_render::to_rgba;
119    use clairlune_scene::{Aspect, ContentContext, compose};
120
121    fn player() -> Player {
122        let r = compose(42, Aspect::from_size(320, 180), &ContentContext::default());
123        let pkg = Arc::new(ScenePackage::capture(&r, 320, 180).unwrap());
124        let theme = pkg.themes()[0];
125        Player::new(pkg, theme, true).unwrap()
126    }
127
128    fn rgb(buf: &[u32]) -> Vec<u8> {
129        buf.iter()
130            .flat_map(|p| [(p >> 16) as u8, (p >> 8) as u8, *p as u8, 255])
131            .collect()
132    }
133
134    #[test]
135    fn the_first_frame_is_the_still_and_updates_keep_the_buffer_exact() {
136        let mut p = player();
137        let (w, h) = p.size();
138        let mut buf = vec![0u32; (w * h) as usize];
139        let t0 = p.t0;
140        let rects = p.advance(t0);
141        p.write_all(&mut buf);
142        let _ = rects;
143        let (still, palette) = p.pkg.still(p.theme, true).unwrap();
144        assert_eq!(rgb(&buf), to_rgba(&still, palette));
145        // Then only the changed rects, as a presenter does.
146        for k in 1..40u64 {
147            let t = t0 + k * 83;
148            let rects = p.advance(t);
149            p.write(&mut buf, &rects);
150            let (full, palette) = p.pkg.frame(p.theme, true, t, Clock::Live).unwrap();
151            assert_eq!(rgb(&buf), to_rgba(&full, palette), "t {t}");
152        }
153    }
154}