splashboard 2.10.2

A customizable terminal splash screen with plugin-based data sources
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
//! Shared shape body builders for the `steam_recently_played` / `steam_owned_games` /
//! `steam_charts` siblings.
//!
//! All three surface a ranked list of games where each row carries an appid, a display name,
//! a numeric value (minutes played / concurrent players), and a store URL derived from the
//! appid. Normalising into [`GameRow`] lets every sibling stay around the catalog's
//! ~100-lines-per-fetcher guideline.

use crate::fetcher::steam::common::{format_count, header_image_url, players_word, store_url};
use crate::fetcher::thumbnails;
use crate::payload::{
    BadgeData, Bar, BarsData, Body, EntriesData, Entry, ImageData, ImageLinkedItem,
    ImageLinkedListData, LinkedLine, LinkedTextBlockData, MarkdownTextBlockData, NumberSeriesData,
    RatioData, Status, TextBlockData, TextData,
};

/// Normalised view of one game in a ranked list. `value` carries minutes for playtime-flavoured
/// fetchers (recently-played, owned-games) and concurrent-player count for the chart fetcher.
/// `value_label` lets each fetcher format the right side of the row appropriately ("80h",
/// "1.2k players") without leaking format strings into the helpers.
#[derive(Debug, Clone)]
pub struct GameRow {
    pub rank: usize,
    pub appid: u32,
    pub name: String,
    pub value: u64,
    pub value_label: String,
}

impl GameRow {
    pub fn store_url(&self) -> String {
        store_url(self.appid)
    }

    pub fn header_image(&self) -> String {
        header_image_url(self.appid)
    }
}

pub fn headline(rows: &[GameRow], empty_label: &str) -> String {
    match rows.first() {
        Some(top) => format!("#{} {}  ({})", top.rank, top.name, top.value_label),
        None => empty_label.into(),
    }
}

pub fn text_body(rows: &[GameRow], empty_label: &str) -> Body {
    Body::Text(TextData {
        value: headline(rows, empty_label),
    })
}

pub fn text_block_body(rows: &[GameRow], empty_label: &str) -> Body {
    Body::TextBlock(TextBlockData {
        lines: lines(rows, empty_label),
    })
}

fn lines(rows: &[GameRow], empty_label: &str) -> Vec<String> {
    if rows.is_empty() {
        return vec![empty_label.into()];
    }
    rows.iter()
        .map(|r| format!("#{} {}  {}", r.rank, r.name, r.value_label))
        .collect()
}

pub fn markdown_body(rows: &[GameRow], empty_label: &str) -> Body {
    let value = if rows.is_empty() {
        format!("_{empty_label}_")
    } else {
        rows.iter()
            .map(|r| format!("- **#{} {}** — {}", r.rank, r.name, r.value_label))
            .collect::<Vec<_>>()
            .join("\n")
    };
    Body::MarkdownTextBlock(MarkdownTextBlockData { value })
}

pub fn linked_text_body(rows: &[GameRow], empty_label: &str) -> Body {
    let items: Vec<LinkedLine> = if rows.is_empty() {
        vec![LinkedLine {
            text: empty_label.into(),
            url: None,
        }]
    } else {
        rows.iter()
            .map(|r| LinkedLine {
                text: format!("#{} {}  {}", r.rank, r.name, r.value_label),
                url: Some(r.store_url()),
            })
            .collect()
    };
    Body::LinkedTextBlock(LinkedTextBlockData { items })
}

pub async fn image_linked_body(rows: &[GameRow]) -> Body {
    let urls: Vec<Option<String>> = rows.iter().map(|r| Some(r.header_image())).collect();
    let paths = thumbnails::download_many(&urls).await;
    let items = rows
        .iter()
        .zip(paths)
        .map(|(r, path)| ImageLinkedItem {
            title: format!("#{} {}", r.rank, r.name),
            url: Some(r.store_url()),
            thumbnail_path: path.map(|p| p.to_string_lossy().into_owned()),
            subtitle: Some(r.value_label.clone()),
        })
        .collect();
    Body::ImageLinkedList(ImageLinkedListData { items })
}

pub fn entries_body(rows: &[GameRow], empty_label: &str) -> Body {
    let items: Vec<Entry> = if rows.is_empty() {
        vec![Entry {
            key: "—".into(),
            value: Some(empty_label.into()),
            status: None,
        }]
    } else {
        rows.iter()
            .map(|r| Entry {
                key: format!("#{} {}", r.rank, r.name),
                value: Some(r.value_label.clone()),
                status: None,
            })
            .collect()
    };
    Body::Entries(EntriesData { items })
}

/// Top game's share of the total value across the surfaced window. `denominator` carries the
/// summed value so a gauge can spell "80h of 142h" if it wants.
pub fn ratio_body(rows: &[GameRow]) -> Body {
    let total: u64 = rows.iter().map(|r| r.value).sum();
    let (value, label, denominator) = match rows.first() {
        Some(top) if total > 0 => (
            top.value as f64 / total as f64,
            Some(top.name.clone()),
            Some(total),
        ),
        _ => (0.0, None, None),
    };
    Body::Ratio(RatioData {
        value,
        label,
        denominator,
    })
}

pub fn number_series_body(rows: &[GameRow]) -> Body {
    Body::NumberSeries(NumberSeriesData {
        values: rows.iter().map(|r| r.value).collect(),
    })
}

pub fn bars_body(rows: &[GameRow]) -> Body {
    Body::Bars(BarsData {
        bars: rows
            .iter()
            .map(|r| Bar {
                label: r.name.clone(),
                value: r.value,
                // Carry the fetcher's formatted unit so `list_ranking` shows `"80h"` or
                // `"2024-07-03"` in the value column instead of the raw `u64`.
                value_label: Some(r.value_label.clone()),
            })
            .collect(),
    })
}

/// Top game's header image as a standalone Image body — the value-add is the cover art, not
/// a list. Falls back to an empty path when the list is empty so the empty-state placeholder
/// kicks in at `render_payload`.
pub async fn image_body(rows: &[GameRow]) -> Body {
    let path = match rows.first() {
        Some(top) => thumbnails::download_to_cache(&top.header_image())
            .await
            .ok()
            .flatten()
            .map(|p| p.to_string_lossy().into_owned())
            .unwrap_or_default(),
        None => String::new(),
    };
    Body::Image(ImageData { path })
}

/// Promotes the top game to the badge label; falls back to a quiet-window pill so the widget
/// stays visible when the user has no recent playtime / the chart is empty. `unit_label`
/// distinguishes "Xh this week" (playtime fetchers) from "1.2k players" (chart fetcher) — the
/// caller picks the unit the top row's value is denominated in.
pub fn badge_body(rows: &[GameRow], unit_label: &str, empty_label: &str) -> Body {
    let (status, label) = match rows.first() {
        Some(top) => (Status::Ok, format!("#1 {} · {}", top.name, top.value_label)),
        None => (Status::Warn, format!("{empty_label} ({unit_label})")),
    };
    Body::Badge(BadgeData { status, label })
}

/// `"42 players"` (singular when applicable) — exposed so the chart fetcher can build a
/// `value_label` without re-deriving the pluralisation rule.
pub fn players_label(n: u64) -> String {
    format!("{} {}", format_count(n), players_word(n))
}

#[cfg(test)]
mod tests {
    use super::*;

    fn row(rank: usize, appid: u32, name: &str, value: u64, label: &str) -> GameRow {
        GameRow {
            rank,
            appid,
            name: name.into(),
            value,
            value_label: label.into(),
        }
    }

    #[test]
    fn store_url_and_header_image_are_appid_derived() {
        let r = row(1, 730, "CS2", 0, "");
        assert!(r.store_url().contains("/app/730/"));
        assert!(r.header_image().contains("/730/header.jpg"));
    }

    #[test]
    fn headline_reports_top_row_with_rank_prefix() {
        let rows = vec![
            row(1, 730, "CS2", 60, "60h"),
            row(2, 570, "Dota 2", 30, "30h"),
        ];
        assert_eq!(headline(&rows, "empty"), "#1 CS2  (60h)");
    }

    #[test]
    fn headline_falls_back_to_empty_label() {
        assert_eq!(headline(&[], "quiet"), "quiet");
    }

    #[test]
    fn linked_text_body_carries_store_url_per_row() {
        let rows = vec![row(1, 730, "CS2", 60, "60h")];
        let Body::LinkedTextBlock(b) = linked_text_body(&rows, "empty") else {
            panic!("expected linked_text_block");
        };
        assert_eq!(b.items.len(), 1);
        assert!(b.items[0].url.as_deref().unwrap().contains("/app/730/"));
        assert!(b.items[0].text.contains("CS2"));
    }

    #[test]
    fn linked_text_body_emits_unlinked_empty_row_on_empty_input() {
        let Body::LinkedTextBlock(b) = linked_text_body(&[], "empty") else {
            panic!("expected linked_text_block");
        };
        assert_eq!(b.items.len(), 1);
        assert!(b.items[0].url.is_none());
    }

    #[test]
    fn ratio_body_is_zero_when_rows_are_empty() {
        let Body::Ratio(r) = ratio_body(&[]) else {
            panic!("expected ratio");
        };
        assert_eq!(r.value, 0.0);
        assert!(r.label.is_none());
        assert!(r.denominator.is_none());
    }

    #[test]
    fn ratio_body_carries_top_share_and_total_as_denominator() {
        let rows = vec![
            row(1, 1, "A", 60, "60"),
            row(2, 2, "B", 30, "30"),
            row(3, 3, "C", 10, "10"),
        ];
        let Body::Ratio(r) = ratio_body(&rows) else {
            panic!("expected ratio");
        };
        assert!((r.value - 0.6).abs() < 1e-9);
        assert_eq!(r.label.as_deref(), Some("A"));
        assert_eq!(r.denominator, Some(100));
    }

    #[test]
    fn ratio_body_returns_zero_when_total_is_zero() {
        let rows = vec![row(1, 1, "A", 0, "0"), row(2, 2, "B", 0, "0")];
        let Body::Ratio(r) = ratio_body(&rows) else {
            panic!("expected ratio");
        };
        assert_eq!(r.value, 0.0);
        assert!(r.label.is_none());
    }

    #[test]
    fn number_series_lifts_values_in_order() {
        let rows = vec![row(1, 1, "A", 30, "30"), row(2, 2, "B", 20, "20")];
        let Body::NumberSeries(s) = number_series_body(&rows) else {
            panic!("expected number_series");
        };
        assert_eq!(s.values, vec![30, 20]);
    }

    #[test]
    fn bars_body_uses_name_as_label_and_value_as_height() {
        let rows = vec![row(1, 1, "CS2", 60, "60h")];
        let Body::Bars(b) = bars_body(&rows) else {
            panic!("expected bars");
        };
        assert_eq!(b.bars[0].label, "CS2");
        assert_eq!(b.bars[0].value, 60);
    }

    #[test]
    fn entries_body_uses_value_label_column() {
        let rows = vec![row(1, 1, "CS2", 60, "60h")];
        let Body::Entries(e) = entries_body(&rows, "empty") else {
            panic!("expected entries");
        };
        assert_eq!(e.items[0].key, "#1 CS2");
        assert_eq!(e.items[0].value.as_deref(), Some("60h"));
    }

    #[test]
    fn badge_body_promotes_top_row_and_warns_on_empty() {
        let rows = vec![row(1, 1, "CS2", 60, "60h")];
        let Body::Badge(b) = badge_body(&rows, "this week", "no playtime") else {
            panic!("expected badge");
        };
        assert_eq!(b.status, Status::Ok);
        assert!(b.label.contains("CS2"));
        assert!(b.label.contains("60h"));

        let Body::Badge(empty) = badge_body(&[], "this week", "no playtime") else {
            panic!("expected badge");
        };
        assert_eq!(empty.status, Status::Warn);
        assert!(empty.label.contains("this week"));
    }

    #[test]
    fn players_label_pluralises_only_for_non_singular() {
        assert_eq!(players_label(0), "0 players");
        assert_eq!(players_label(1), "1 player");
        assert_eq!(players_label(1500), "1.5k players");
    }

    #[test]
    fn markdown_body_italicises_empty_label() {
        let Body::MarkdownTextBlock(m) = markdown_body(&[], "quiet") else {
            panic!("expected markdown");
        };
        assert_eq!(m.value, "_quiet_");
    }

    #[test]
    fn text_block_body_emits_single_empty_label_line_on_empty_input() {
        let Body::TextBlock(b) = text_block_body(&[], "no games yet") else {
            panic!("expected text_block");
        };
        assert_eq!(b.lines, vec!["no games yet".to_string()]);
    }

    #[test]
    fn text_block_body_lists_one_line_per_row() {
        let rows = vec![
            row(1, 730, "CS2", 60, "60h"),
            row(2, 570, "Dota 2", 30, "30h"),
        ];
        let Body::TextBlock(b) = text_block_body(&rows, "empty") else {
            panic!("expected text_block");
        };
        assert_eq!(b.lines.len(), 2);
        assert_eq!(b.lines[0], "#1 CS2  60h");
    }

    #[test]
    fn entries_body_emits_dash_placeholder_row_on_empty_input() {
        let Body::Entries(e) = entries_body(&[], "no games yet") else {
            panic!("expected entries");
        };
        assert_eq!(e.items.len(), 1);
        assert_eq!(e.items[0].key, "—");
        assert_eq!(e.items[0].value.as_deref(), Some("no games yet"));
    }

    /// Hash a URL the same way `thumbnails` content-addresses its cache, so a pre-seeded file
    /// at `<hash>.png` makes `download_to_cache` resolve via `existing_cached` — exercising the
    /// non-empty `image_*_body` arms without any network I/O.
    fn thumbnail_hash(url: &str) -> String {
        use sha2::{Digest, Sha256};
        Sha256::digest(url.as_bytes())
            .iter()
            .map(|b| format!("{b:02x}"))
            .collect()
    }

    /// RAII guard: points `SPLASHBOARD_HOME` at a temp dir and restores it on drop, so a
    /// panic mid-test can't leak the override into later tests sharing the process env.
    struct SplashHomeGuard(Option<String>);

    impl SplashHomeGuard {
        fn set(path: &std::path::Path) -> Self {
            let previous = std::env::var("SPLASHBOARD_HOME").ok();
            unsafe { std::env::set_var("SPLASHBOARD_HOME", path) };
            Self(previous)
        }
    }

    impl Drop for SplashHomeGuard {
        fn drop(&mut self) {
            unsafe {
                match self.0.take() {
                    Some(value) => std::env::set_var("SPLASHBOARD_HOME", value),
                    None => std::env::remove_var("SPLASHBOARD_HOME"),
                }
            }
        }
    }

    /// Drive an async body builder to completion on a fresh current-thread runtime. Sync so the
    /// `TEST_ENV_LOCK` guard is never held across an `.await` (clippy `await_holding_lock`).
    fn block_on<T>(future: impl std::future::Future<Output = T>) -> T {
        tokio::runtime::Builder::new_current_thread()
            .enable_all()
            .build()
            .unwrap()
            .block_on(future)
    }

    #[test]
    fn image_linked_body_resolves_cached_thumbnails_without_network() {
        let _lock = crate::paths::TEST_ENV_LOCK
            .lock()
            .unwrap_or_else(|e| e.into_inner());
        let dir = tempfile::tempdir().unwrap();
        let _home = SplashHomeGuard::set(dir.path());

        let rows = vec![
            row(1, 730, "CS2", 60, "60h"),
            row(2, 570, "Dota 2", 30, "30h"),
        ];
        let thumbs = dir.path().join("cache").join("thumbnails");
        std::fs::create_dir_all(&thumbs).unwrap();
        for r in &rows {
            let file = thumbs.join(format!("{}.png", thumbnail_hash(&r.header_image())));
            std::fs::write(&file, b"\x89PNG\r\n\x1a\n").unwrap();
        }

        let body = block_on(image_linked_body(&rows));

        let Body::ImageLinkedList(d) = body else {
            panic!("expected image_linked_list");
        };
        assert_eq!(d.items.len(), 2);
        assert_eq!(d.items[0].title, "#1 CS2");
        assert_eq!(
            d.items[0].url.as_deref(),
            Some(rows[0].store_url().as_str())
        );
        assert_eq!(d.items[0].subtitle.as_deref(), Some("60h"));
        assert!(
            d.items[0]
                .thumbnail_path
                .as_deref()
                .is_some_and(|p| p.ends_with(".png"))
        );
    }

    #[test]
    fn image_body_resolves_top_cached_thumbnail_without_network() {
        let _lock = crate::paths::TEST_ENV_LOCK
            .lock()
            .unwrap_or_else(|e| e.into_inner());
        let dir = tempfile::tempdir().unwrap();
        let _home = SplashHomeGuard::set(dir.path());

        let rows = vec![
            row(1, 730, "CS2", 60, "60h"),
            row(2, 570, "Dota 2", 30, "30h"),
        ];
        let thumbs = dir.path().join("cache").join("thumbnails");
        std::fs::create_dir_all(&thumbs).unwrap();
        let file = thumbs.join(format!("{}.png", thumbnail_hash(&rows[0].header_image())));
        std::fs::write(&file, b"\x89PNG\r\n\x1a\n").unwrap();

        let body = block_on(image_body(&rows));

        let Body::Image(img) = body else {
            panic!("expected image");
        };
        assert!(img.path.ends_with(".png"));
    }
}