1use ratatui::layout::Rect;
9use ratatui::style::{Color, Style};
10use ratatui::text::{Line, Span};
11use ratatui::widgets::Paragraph;
12use ratatui::Frame;
13
14#[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
37pub const ALL_STYLES: &[BackgroundStyle] = &[
39 BackgroundStyle::Blank,
40 BackgroundStyle::Stars,
41 BackgroundStyle::Matrix,
42];
43
44pub const PREVIEW_W: u16 = 32;
46pub const PREVIEW_H: u16 = 8;
47
48const STAR_CHARS: &[char] = &[
53 ' ', ' ', ' ', ' ', ' ', '⠁', '⠂', '⠄', '⠈', '⠐', '⠠', '⡀', '⢀', '·', '✦',
56];
57
58struct StarParticle {
59 x: u16,
60 y: u16,
61 phase: u8, period: u8, }
64
65const MATRIX_CHARS: &[char] = &[
70 'ヲ', 'ァ', 'ィ', 'ゥ', 'ェ', 'ォ', 'ャ', 'ュ', 'ョ', 'ッ', 'ー', 'ア', 'イ', 'ウ', 'エ', 'オ', 'カ', 'キ', 'ク',
71 'ケ', 'コ', 'サ', 'シ', 'ス', 'セ', 'ソ', 'タ', 'チ', 'ツ', 'テ', 'ト', 'ナ', 'ニ', 'ヌ', 'ネ', 'ノ', 'ハ', 'ヒ',
72 'フ', 'ヘ', 'ホ', 'マ', 'ミ', 'ム', 'メ', 'モ', 'ヤ', 'ユ', 'ヨ', 'ラ', 'リ', 'ル', 'レ', 'ロ', 'ワ', 'ン', '0',
73 '1', '2', '3', '4', '5', '6', '7', '8', '9',
74];
75
76const MATRIX_COLORS: &[Color] = &[
78 Color::White, Color::Rgb(0, 220, 40), Color::Rgb(0, 140, 20), Color::Rgb(0, 70, 10), Color::Rgb(0, 30, 5), ];
84
85struct MatrixColumn {
86 head: i32, speed: u8, counter: u8,
89 trail: u8, chars: Vec<char>,
91}
92
93#[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
103pub struct BackgroundState {
108 pub style: BackgroundStyle,
109 tick: u64,
110 init_w: u16,
112 init_h: u16,
113 init_style: Option<BackgroundStyle>,
114 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 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 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 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 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 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 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}