Skip to main content

hyprstream_compositor/
background.rs

1//! Animated background styles for the empty-window state.
2//!
3//! `BackgroundState` holds the animation state for the three offered styles:
4//! - `Blank`  — solid black, no characters
5//! - `Stars`  — sparse braille-dot starfield that slowly twinkles
6//! - `Matrix` — katakana/digit columns falling top-to-bottom, green gradient
7
8use ratatui::layout::Rect;
9use ratatui::style::{Color, Style};
10use ratatui::text::{Line, Span};
11use ratatui::widgets::Paragraph;
12use ratatui::Frame;
13
14// ============================================================================
15// BackgroundStyle
16// ============================================================================
17
18/// Which animated background to show when no windows are open.
19#[derive(Clone, Copy, PartialEq, Eq, Default)]
20pub enum BackgroundStyle {
21    #[default]
22    Blank,
23    Stars,
24    Matrix,
25}
26
27impl std::fmt::Display for BackgroundStyle {
28    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
29        match self {
30            Self::Blank => write!(f, "blank"),
31            Self::Stars => write!(f, "stars"),
32            Self::Matrix => write!(f, "matrix"),
33        }
34    }
35}
36
37/// All styles in display order (used to build the settings SelectList).
38pub const ALL_STYLES: &[BackgroundStyle] = &[
39    BackgroundStyle::Blank,
40    BackgroundStyle::Stars,
41    BackgroundStyle::Matrix,
42];
43
44/// Suggested width/height for the preview box inside the settings modal.
45pub const PREVIEW_W: u16 = 32;
46pub const PREVIEW_H: u16 = 8;
47
48// ============================================================================
49// Stars
50// ============================================================================
51
52const STAR_CHARS: &[char] = &[
53    ' ', ' ', ' ', ' ', ' ', // mostly empty space — sparse field
54    '⠁', '⠂', '⠄', '⠈', '⠐', '⠠', '⡀', '⢀', // single braille dots
55    '·', '✦',
56];
57
58struct StarParticle {
59    x: u16,
60    y: u16,
61    phase: u8,  // index into STAR_CHARS
62    period: u8, // ticks between phase increments
63}
64
65// ============================================================================
66// Matrix
67// ============================================================================
68
69const MATRIX_CHARS: &[char] = &[
70    'ヲ', 'ァ', 'ィ', 'ゥ', 'ェ', 'ォ', 'ャ', 'ュ', 'ョ', 'ッ', 'ー', 'ア', 'イ', 'ウ', 'エ', 'オ', 'カ', 'キ', 'ク',
71    'ケ', 'コ', 'サ', 'シ', 'ス', 'セ', 'ソ', 'タ', 'チ', 'ツ', 'テ', 'ト', 'ナ', 'ニ', 'ヌ', 'ネ', 'ノ', 'ハ', 'ヒ',
72    'フ', 'ヘ', 'ホ', 'マ', 'ミ', 'ム', 'メ', 'モ', 'ヤ', 'ユ', 'ヨ', 'ラ', 'リ', 'ル', 'レ', 'ロ', 'ワ', 'ン', '0',
73    '1', '2', '3', '4', '5', '6', '7', '8', '9',
74];
75
76/// Foreground colour for each trail position (0 = head = brightest).
77const MATRIX_COLORS: &[Color] = &[
78    Color::White,           // head — bright white
79    Color::Rgb(0, 220, 40), // trail 1 — bright green
80    Color::Rgb(0, 140, 20), // trail 2
81    Color::Rgb(0, 70, 10),  // trail 3
82    Color::Rgb(0, 30, 5),   // trail 4 — dim
83];
84
85struct MatrixColumn {
86    head: i32, // y-row of the falling head (may be negative before it enters)
87    speed: u8, // ticks per row advance
88    counter: u8,
89    trail: u8, // length of the trailing glyph streak
90    chars: Vec<char>,
91}
92
93// ============================================================================
94// LCG pseudo-random helper (no external dep)
95// ============================================================================
96
97#[inline]
98fn lcg(seed: u64) -> u64 {
99    seed.wrapping_mul(6_364_136_223_846_793_005)
100        .wrapping_add(1_442_695_040_888_963_407)
101}
102
103// ============================================================================
104// BackgroundState
105// ============================================================================
106
107pub struct BackgroundState {
108    pub style: BackgroundStyle,
109    tick: u64,
110    // Dimensions for which stars/matrix were initialised.
111    init_w: u16,
112    init_h: u16,
113    init_style: Option<BackgroundStyle>,
114    // Per-style state (only one is populated at a time).
115    stars: Vec<StarParticle>,
116    matrix_cols: Vec<MatrixColumn>,
117}
118
119impl BackgroundState {
120    pub fn new(style: BackgroundStyle) -> Self {
121        Self {
122            style,
123            tick: 0,
124            init_w: 0,
125            init_h: 0,
126            init_style: None,
127            stars: vec![],
128            matrix_cols: vec![],
129        }
130    }
131
132    // ── Initialisation ──────────────────────────────────────────────────────
133
134    fn init_stars(&mut self, w: u16, h: u16) {
135        let count = ((w as u32 * h as u32) / 10).clamp(8, 600) as usize;
136        self.stars = (0..count)
137            .map(|i| {
138                let r1 = lcg(i as u64 * 17 + 3);
139                let r2 = lcg(r1);
140                let r3 = lcg(r2);
141                StarParticle {
142                    x: (r1 % w as u64) as u16,
143                    y: (r2 % h as u64) as u16,
144                    phase: (r3 % STAR_CHARS.len() as u64) as u8,
145                    period: 4 + (lcg(r3) % 9) as u8,
146                }
147            })
148            .collect();
149    }
150
151    fn init_matrix(&mut self, w: u16, h: u16) {
152        self.matrix_cols = (0..w as usize)
153            .map(|i| {
154                let r = lcg(i as u64 * 31 + 7);
155                let r2 = lcg(r);
156                let trail = 4 + (r % 7) as u8;
157                let speed = 1 + (r2 % 2) as u8;
158                let start = -((lcg(r2) % h as u64) as i32);
159                let chars: Vec<char> = (0..trail as usize)
160                    .map(|j| MATRIX_CHARS[(i * 5 + j * 11) % MATRIX_CHARS.len()])
161                    .collect();
162                MatrixColumn {
163                    head: start,
164                    speed,
165                    counter: 0,
166                    trail,
167                    chars,
168                }
169            })
170            .collect();
171    }
172
173    fn needs_reset(&self, w: u16, h: u16) -> bool {
174        w != self.init_w || h != self.init_h || self.init_style != Some(self.style)
175    }
176
177    // ── Tick ────────────────────────────────────────────────────────────────
178
179    /// Advance the animation by one step.  Call before each render frame.
180    pub fn tick(&mut self, w: u16, h: u16) {
181        if w == 0 || h == 0 {
182            return;
183        }
184
185        if self.needs_reset(w, h) {
186            self.init_w = w;
187            self.init_h = h;
188            self.init_style = Some(self.style);
189            self.stars.clear();
190            self.matrix_cols.clear();
191            match self.style {
192                BackgroundStyle::Blank => {}
193                BackgroundStyle::Stars => self.init_stars(w, h),
194                BackgroundStyle::Matrix => self.init_matrix(w, h),
195            }
196        }
197
198        self.tick = self.tick.wrapping_add(1);
199
200        match self.style {
201            BackgroundStyle::Blank => {}
202
203            BackgroundStyle::Stars => {
204                for star in &mut self.stars {
205                    if self.tick.is_multiple_of(star.period as u64) {
206                        star.phase = (star.phase + 1) % STAR_CHARS.len() as u8;
207                    }
208                }
209            }
210
211            BackgroundStyle::Matrix => {
212                for (col_idx, col) in self.matrix_cols.iter_mut().enumerate() {
213                    col.counter += 1;
214                    if col.counter >= col.speed {
215                        col.counter = 0;
216                        col.head += 1;
217                        // Randomise the head char.
218                        let rng = lcg(self.tick ^ col_idx as u64 ^ 0xDEAD_BEEF);
219                        col.chars[0] = MATRIX_CHARS[rng as usize % MATRIX_CHARS.len()];
220                        col.chars.rotate_right(1);
221                        // Wrap when fully below the screen.
222                        if col.head - col.trail as i32 >= h as i32 {
223                            col.head = -(col.trail as i32);
224                        }
225                    }
226                }
227            }
228        }
229    }
230
231    // ── Render ──────────────────────────────────────────────────────────────
232
233    /// Render the current animation frame into `area`.
234    pub fn render(&self, frame: &mut Frame, area: Rect) {
235        match self.style {
236            BackgroundStyle::Blank => {
237                frame.render_widget(
238                    Paragraph::new("").style(Style::default().bg(Color::Black)),
239                    area,
240                );
241            }
242
243            BackgroundStyle::Stars => {
244                let w = area.width as usize;
245                let h = area.height as usize;
246                let mut grid: Vec<Vec<char>> = (0..h).map(|_| vec![' '; w]).collect();
247                for star in &self.stars {
248                    let sx = star.x as usize;
249                    let sy = star.y as usize;
250                    if sy < h && sx < w {
251                        grid[sy][sx] = STAR_CHARS[star.phase as usize];
252                    }
253                }
254                let dim = Style::default().fg(Color::DarkGray).bg(Color::Black);
255                let lines: Vec<Line> = grid
256                    .into_iter()
257                    .map(|row| Line::from(Span::styled(row.into_iter().collect::<String>(), dim)))
258                    .collect();
259                frame.render_widget(Paragraph::new(lines), area);
260            }
261
262            BackgroundStyle::Matrix => {
263                let w = area.width as usize;
264                let h = area.height as usize;
265                let mut grid: Vec<Vec<(char, u8)>> =
266                    (0..h).map(|_| vec![(' ', 255u8); w]).collect();
267
268                for (col_idx, col) in self.matrix_cols.iter().enumerate() {
269                    if col_idx >= w {
270                        break;
271                    }
272                    for trail_pos in 0..col.trail as i32 {
273                        let row = col.head - trail_pos;
274                        if row < 0 || row >= h as i32 {
275                            continue;
276                        }
277                        let ch = col.chars.get(trail_pos as usize).copied().unwrap_or(' ');
278                        let lvl = (trail_pos as usize).min(MATRIX_COLORS.len() - 1) as u8;
279                        grid[row as usize][col_idx] = (ch, lvl);
280                    }
281                }
282
283                let lines: Vec<Line> = grid
284                    .into_iter()
285                    .map(|row| {
286                        let mut spans: Vec<Span> = Vec::new();
287                        let mut cur_lvl: u8 = 255;
288                        let mut text: String = String::new();
289
290                        for (ch, lvl) in row {
291                            if lvl != cur_lvl {
292                                if !text.is_empty() {
293                                    let fg = color_for_lvl(cur_lvl);
294                                    spans.push(Span::styled(
295                                        std::mem::take(&mut text),
296                                        Style::default().fg(fg).bg(Color::Black),
297                                    ));
298                                }
299                                cur_lvl = lvl;
300                            }
301                            text.push(ch);
302                        }
303                        if !text.is_empty() {
304                            spans.push(Span::styled(
305                                text,
306                                Style::default().fg(color_for_lvl(cur_lvl)).bg(Color::Black),
307                            ));
308                        }
309                        Line::from(spans)
310                    })
311                    .collect();
312
313                frame.render_widget(Paragraph::new(lines), area);
314            }
315        }
316    }
317
318    /// True when the background is animated (needs periodic redraws).
319    pub fn is_animated(&self) -> bool {
320        !matches!(self.style, BackgroundStyle::Blank)
321    }
322}
323
324#[inline]
325fn color_for_lvl(lvl: u8) -> Color {
326    if lvl as usize >= MATRIX_COLORS.len() {
327        Color::Black
328    } else {
329        MATRIX_COLORS[lvl as usize]
330    }
331}