heatsync-tui 0.1.1

heat-sorted live multichat in the terminal — twitch + kick, real emotes, vim keys
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
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
//! headless subcommands — the archive corpus as pipeable unix commands.
//! `heatsync log <channel> <date>` · `search <query>` · `hot`. plain stdout,
//! grep/fzf-friendly. this is the moat chatterino structurally can't match.

use std::time::{Duration, Instant};

use heatsync_core::Platform;

use crate::config;
use crate::http;
use crate::net::{self, ChatEvent};

/// split a `kick:name` / `twitch:name` / `name` token into (platform, name).
fn split_channel(tok: &str) -> (Platform, &str) {
    if let Some(rest) = tok.strip_prefix("kick:") {
        (Platform::Kick, rest)
    } else if let Some(rest) = tok.strip_prefix("twitch:") {
        (Platform::Twitch, rest)
    } else {
        (Platform::Twitch, tok)
    }
}

/// `heatsync log <channel> <YYYY-MM-DD>`
pub fn log(args: &[String]) -> std::io::Result<()> {
    let (channel, date) = match args {
        [c, d, ..] => (c.as_str(), d.as_str()),
        _ => {
            eprintln!("usage: heatsync log <channel> <YYYY-MM-DD>");
            std::process::exit(2);
        }
    };
    let (_plat, name) = split_channel(channel);
    let from = format!("{date}T00:00:00Z");
    let to = format!("{date}T23:59:59Z");
    match http::channel_log(name, &from, &to, 100) {
        Some(page) if !page.results.is_empty() => {
            for m in &page.results {
                let who = m.display_name.as_deref().unwrap_or(&m.username);
                println!("{}  {}: {}", short_ts(&m.timestamp), who, m.message);
            }
        }
        Some(_) => eprintln!("no logs for {name} on {date}"),
        None => {
            eprintln!("request failed");
            std::process::exit(1);
        }
    }
    Ok(())
}

/// `heatsync search <query> [channel]`
pub fn search(args: &[String]) -> std::io::Result<()> {
    let q = match args.first() {
        Some(q) => q.as_str(),
        None => {
            eprintln!("usage: heatsync search <query> [channel]");
            std::process::exit(2);
        }
    };
    let channel = args.get(1).map(|s| split_channel(s).1);
    match http::search(q, channel, 50) {
        Some(page) if !page.results.is_empty() => {
            for m in &page.results {
                let who = m.display_name.as_deref().unwrap_or(&m.username);
                println!(
                    "{}  [{}/{}] {}: {}",
                    short_ts(&m.timestamp),
                    m.platform,
                    m.channel,
                    who,
                    m.message
                );
            }
        }
        Some(_) => eprintln!("no matches for {q:?}"),
        None => {
            eprintln!("request failed");
            std::process::exit(1);
        }
    }
    Ok(())
}

/// `heatsync hot [hours]` — hottest posts, with real heat scores.
pub fn hot(args: &[String]) -> std::io::Result<()> {
    // Default 720h bounds the server-side scan only — the heat floor (12h
    // decay) decides what's hot, so a narrow default would just hide live heat.
    let hours: u32 = args.first().and_then(|s| s.parse().ok()).unwrap_or(720);
    match http::hot(25, hours) {
        Some(page) if !page.messages.is_empty() => {
            for m in &page.messages {
                let who = m.display_name.as_deref().unwrap_or(&m.username);
                let subj = m.subject.as_deref().unwrap_or("");
                println!(
                    "{:>6.0}  (peak {:>6.0})  {}: {} {}",
                    m.heat, m.max_heat, who, m.content, subj
                );
            }
        }
        Some(_) => eprintln!("nothing hot in the last {hours}h"),
        None => {
            eprintln!("request failed");
            std::process::exit(1);
        }
    }
    Ok(())
}

/// `heatsync login` — set up direct twitch sending (chatterino-style).
pub fn login() -> std::io::Result<()> {
    match config::ensure_token_file() {
        Some(p) => {
            println!(
                "twitch sending — sends go DIRECT to twitch (like chatterino), not via heatsync:"
            );
            println!("  1. get a twitch oauth token with the 'chat:edit' scope");
            println!("     e.g. https://twitchtokengenerator.com  (pick a bot/chat token)");
            println!("  2. edit {}", p.display());
            println!("       twitch_user=your_twitch_username");
            println!("       twitch_oauth=oauth:xxxxxxxxxxxxxxxx");
            println!("  3. restart heatsync. reading still comes through heatsync; only sending is direct.");
            println!("  (or set TWITCH_USER / TWITCH_OAUTH env instead of the file.)");
        }
        None => eprintln!("could not resolve ~/.config/heatsync/"),
    }
    Ok(())
}

/// `heatsync status` — mellen-only admin glance: mod queue, reports, NCMEC
/// backlog, capacity headroom. Reads the SAME endpoints the web admin
/// dashboard does; no vanity concurrent-user count on purpose.
pub fn status() -> std::io::Result<()> {
    let auth = config::load_auth();
    let Some(token) = auth.admin_token else {
        eprintln!("no admin token — add `admin_token=<jwt>` to ~/.config/heatsync/token");
        std::process::exit(1);
    };

    let mut ok = true;
    let health = http::admin_health(&token);
    let mod_queue = http::admin_mod_queue_total(&token);
    let reports = http::admin_pending_reports(&token);
    let ncmec = http::admin_ncmec_backlog(&token);

    println!("heatsync — prod status");
    match &health {
        Some(h) => {
            println!(
                "  postgres: {}   redis: {}",
                h.postgres_status, h.redis_status
            );
            println!(
                "  cpu {:>5.1}%   ram {:>5.1}%   disk {:>5.1}%   errors/min {:.1}",
                h.cpu_usage, h.ram_usage, h.disk_usage, h.error_rate
            );
            println!(
                "  ws conns: {}   msgs/min: {:.0}",
                h.ws_connections, h.messages_per_minute
            );
        }
        None => {
            println!("  health: unreachable (auth expired? check ~/.config/heatsync/token)");
            ok = false;
        }
    }
    match mod_queue {
        Some(n) => println!("  mod queue:    {n:>4}  pending"),
        None => {
            println!("  mod queue:    ?     (request failed)");
            ok = false;
        }
    }
    match reports {
        Some(n) => println!("  reports:      {n:>4}  pending"),
        None => {
            println!("  reports:      ?     (request failed)");
            ok = false;
        }
    }
    match ncmec {
        Some(n) if n > 0 => println!("  ncmec:        {n:>4}  STUCK — needs a look"),
        Some(_) => println!("  ncmec:           0  clear"),
        None => {
            println!("  ncmec:        ?     (request failed)");
            ok = false;
        }
    }
    if !ok {
        std::process::exit(1);
    }
    Ok(())
}

/// `heatsync probe [channels…]` — connect to the live relay, print raw lines
/// for 8s, report the count. an end-to-end WS smoke test (and a debug tap).
pub fn probe(args: &[String]) -> std::io::Result<()> {
    let subs = if args.is_empty() {
        vec![(Platform::Twitch, "xqc".to_string())]
    } else {
        args.iter()
            .map(|a| {
                let (p, n) = split_channel(a);
                (p, n.to_string())
            })
            .collect()
    };
    eprintln!("probing {} channel(s) for 8s…", subs.len());
    let (rx, _out) = net::spawn(subs, None);
    let deadline = Instant::now() + Duration::from_secs(8);
    let mut n = 0u32;
    while let Some(rem) = deadline.checked_duration_since(Instant::now()) {
        match rx.recv_timeout(rem) {
            Ok(ChatEvent::Line(l)) => {
                println!(
                    "[{}/{}] {}: {}",
                    plat_tag(l.platform),
                    l.channel,
                    l.user,
                    l.content
                );
                n += 1;
            }
            Ok(ChatEvent::Connected) => eprintln!("· connected"),
            Ok(ChatEvent::Disconnected) => eprintln!("· disconnected"),
            Ok(_) => {}
            Err(_) => break,
        }
    }
    eprintln!("{n} lines in 8s");
    Ok(())
}

fn plat_tag(p: Platform) -> &'static str {
    p.tag()
}

/// trim an ISO timestamp to `HH:MM:SS` for terminal density.
fn short_ts(ts: &str) -> &str {
    ts.split('T')
        .nth(1)
        .map(|t| &t[..t.len().min(8)])
        .unwrap_or(ts)
}

/// `heatsync render-test <base-url> [overlay-url…]` — VERIFICATION harness (not a
/// user command). composites a stack via the real pipeline and dumps the result:
/// the composited RGBA frame(s) as PNG, and the actual sixel bytes the terminal
/// would receive. decode those (sixel2png) to prove rendering end-to-end without
/// needing to eyeball a live terminal. run with `env -u TMUX` for raw (unwrapped)
/// sixel.
pub fn render_test(args: &[String]) -> std::io::Result<()> {
    use ratatui_image::picker::ProtocolType;

    if args.is_empty() {
        eprintln!("usage: heatsync render-test <base-url> [overlay-url …]");
        return Ok(());
    }
    let key = args.join("\n");
    let Some(frames) = crate::emote::render::composite_frames(&key, 32) else {
        eprintln!("render-test: composite failed (fetch/decode)");
        return Ok(());
    };
    let (w, h) = (frames[0].0.width(), frames[0].0.height());
    eprintln!(
        "render-test: {} layer(s) → {} composited frame(s), {w}x{h}px",
        args.len(),
        frames.len()
    );
    if frames.len() > 1 {
        let total: u32 = frames.iter().map(|f| f.1.max(20)).sum();
        let fps = frames.len() as f64 * 1000.0 / total.max(1) as f64;
        eprintln!(
            "  authored: {:.0}ms loop at {fps:.1}fps (a 100ms redraw cadence would \
             show {:.0} of these {} frames)",
            total,
            (total as f64 / 100.0).floor(),
            frames.len()
        );
    }
    let idxs = if frames.len() > 1 {
        vec![0usize, frames.len() / 2]
    } else {
        vec![0usize]
    };
    for i in &idxs {
        let p = format!("/tmp/emote_composite_{i}.png");
        if frames[*i].0.save(&p).is_ok() {
            eprintln!("  composite frame {i} → {p}");
        }
    }
    // run the REAL sizing + palette + encode path for an 8x16 cell terminal and
    // report the two things that were broken: the cell footprint, and how much
    // the sixel payload churns between consecutive frames. that churn IS the
    // flashing — a shared palette should leave only real motion changing.
    let (cw, ch) = (8u16, 16u16);
    let mut picker = ratatui_image::picker::Picker::from_fontsize((cw, ch));
    picker.set_protocol_type(ProtocolType::Sixel);
    let block_h = crate::emote::render::EMOTE_H as u32 * ch as u32;
    let w_cells = crate::emote::render::width_cells(w as f32 / h as f32, cw, ch);
    eprintln!(
        "  footprint on an {cw}x{ch} cell: {w_cells}x{} cells = {}x{block_h}px (source {w}x{h})",
        crate::emote::render::EMOTE_H,
        w_cells as u32 * cw as u32,
    );

    let take = frames.len().min(24);
    let mut canvases: Vec<image::RgbaImage> = frames[..take]
        .iter()
        .map(|(f, _)| crate::emote::render::fit_center(f, w_cells as u32 * cw as u32, block_h))
        .collect();
    for c in &mut canvases {
        crate::emote::render::flatten_onto_black(c);
    }
    let raw = encode_all(&picker, &canvases, w_cells);
    crate::emote::render::stabilize_palette(&mut canvases);
    let stable = encode_all(&picker, &canvases, w_cells);

    if let Some(first) = stable.first() {
        std::fs::write("/tmp/emote.six", first)?;
        let wrapped = first.contains("tmux;");
        eprintln!(
            "  sixel bytes → /tmp/emote.six ({} bytes){}",
            first.len(),
            if wrapped {
                " [tmux-wrapped — rerun with `env -u TMUX`]"
            } else {
                ""
            }
        );
    }
    if take > 1 {
        let px = (w_cells as u32 * cw as u32, block_h);
        eprintln!("  pixels changing between consecutive frames (lower = less shimmer):");
        eprintln!(
            "    per-frame palette (before): {:.1}%",
            pixel_churn(&raw, px) * 100.0
        );
        eprintln!(
            "    shared palette   (after):  {:.1}%",
            pixel_churn(&stable, px) * 100.0
        );
        eprintln!(
            "    source frames actually differ by: {:.1}% (the real motion)",
            source_churn(&canvases_src(
                &frames[..take],
                w_cells as u32 * cw as u32,
                block_h
            )) * 100.0
        );
    }
    Ok(())
}

fn canvases_src(frames: &[(image::RgbaImage, u32)], tw: u32, th: u32) -> Vec<image::RgbaImage> {
    frames
        .iter()
        .map(|(f, _)| {
            let mut c = crate::emote::render::fit_center(f, tw, th);
            crate::emote::render::flatten_onto_black(&mut c);
            c
        })
        .collect()
}

/// mean fraction of pixels differing between consecutive source frames — the
/// floor. anything a decoded sixel churns ABOVE this is encoder shimmer.
fn source_churn(frames: &[image::RgbaImage]) -> f64 {
    if frames.len() < 2 {
        return 0.0;
    }
    let mut total = 0.0;
    for w in frames.windows(2) {
        let n = w[0].pixels().len().max(1);
        let diff = w[0]
            .pixels()
            .zip(w[1].pixels())
            .filter(|(a, b)| a != b)
            .count();
        total += diff as f64 / n as f64;
    }
    total / (frames.len() - 1) as f64
}

/// decode each sixel back to pixels and report the mean fraction that changes
/// between consecutive frames. this is what the eye sees flicker.
fn pixel_churn(frames: &[String], (w, h): (u32, u32)) -> f64 {
    let decoded: Vec<Vec<u32>> = frames.iter().map(|s| sixel_decode(s, w, h)).collect();
    if decoded.len() < 2 {
        return 0.0;
    }
    let mut total = 0.0;
    for pair in decoded.windows(2) {
        let n = (w * h) as usize;
        let diff = pair[0].iter().zip(&pair[1]).filter(|(a, b)| a != b).count();
        total += diff as f64 / n.max(1) as f64;
    }
    total / (decoded.len() - 1) as f64
}

/// minimal sixel reader — enough of the grammar to rebuild the pixel grid an
/// emote encodes to (palette defs, color select, 6-pixel data bytes, RLE, `$`
/// carriage return, `-` newline). verification-only.
fn sixel_decode(data: &str, w: u32, h: u32) -> Vec<u32> {
    let mut out = vec![0u32; (w * h) as usize];
    let mut palette = std::collections::HashMap::new();
    let b: Vec<char> = data.chars().collect();
    let mut i = 0usize;
    // skip to the start of sixel data (after the `q` of the DCS header)
    while i < b.len() && b[i] != 'q' {
        i += 1;
    }
    i += 1;
    let (mut x, mut band, mut color) = (0u32, 0u32, 0u32);
    let num = |b: &[char], i: &mut usize| -> u32 {
        let mut n = 0u32;
        while *i < b.len() && b[*i].is_ascii_digit() {
            n = n
                .saturating_mul(10)
                .saturating_add(b[*i] as u32 - '0' as u32);
            *i += 1;
        }
        n
    };
    while i < b.len() {
        match b[i] {
            '#' => {
                i += 1;
                let idx = num(&b, &mut i);
                if i < b.len() && b[i] == ';' {
                    i += 1;
                    let _mode = num(&b, &mut i);
                    let mut c = [0u32; 3];
                    for slot in c.iter_mut() {
                        if i < b.len() && b[i] == ';' {
                            i += 1;
                        }
                        *slot = num(&b, &mut i);
                    }
                    palette.insert(idx, (c[0] << 16) | (c[1] << 8) | c[2] | 1 << 24);
                }
                color = idx;
            }
            '!' => {
                i += 1;
                let n = num(&b, &mut i);
                if i < b.len() {
                    let ch = b[i];
                    i += 1;
                    for _ in 0..n {
                        put(
                            &mut out,
                            w,
                            h,
                            x,
                            band,
                            ch,
                            *palette.get(&color).unwrap_or(&0),
                        );
                        x += 1;
                    }
                }
            }
            '$' => {
                x = 0;
                i += 1;
            }
            '-' => {
                x = 0;
                band += 1;
                i += 1;
            }
            '"' => {
                i += 1;
                while i < b.len() && (b[i].is_ascii_digit() || b[i] == ';') {
                    i += 1;
                }
            }
            c if ('?'..='~').contains(&c) => {
                put(
                    &mut out,
                    w,
                    h,
                    x,
                    band,
                    c,
                    *palette.get(&color).unwrap_or(&0),
                );
                x += 1;
                i += 1;
            }
            _ => i += 1,
        }
    }
    out
}

fn put(out: &mut [u32], w: u32, h: u32, x: u32, band: u32, ch: char, rgb: u32) {
    if x >= w {
        return;
    }
    let bits = (ch as u32).wrapping_sub('?' as u32);
    for bit in 0..6u32 {
        if bits & (1 << bit) != 0 {
            let y = band * 6 + bit;
            if y < h {
                out[(y * w + x) as usize] = rgb;
            }
        }
    }
}

fn encode_all(
    picker: &ratatui_image::picker::Picker,
    canvases: &[image::RgbaImage],
    w_cells: u16,
) -> Vec<String> {
    let size = ratatui::layout::Rect::new(0, 0, w_cells, crate::emote::render::EMOTE_H);
    canvases
        .iter()
        .filter_map(|c| {
            match picker.new_protocol(
                image::DynamicImage::ImageRgba8(c.clone()),
                size,
                ratatui_image::Resize::Fit(None),
            ) {
                Ok(ratatui_image::protocol::Protocol::Sixel(s)) => Some(s.data),
                _ => None,
            }
        })
        .collect()
}

/// `heatsync diag` — console/graphics diagnostic. no network, no TUI. prints
/// every input the emote-tier decision depends on, says which tier it would
/// pick and WHY the others were rejected, then (on a usable console) paints a
/// test rectangle straight to /dev/fb0 so scanout can be confirmed by eye.
pub fn diag(_args: &[String]) -> std::io::Result<()> {
    let env = |k: &str| std::env::var(k).unwrap_or_else(|_| "<unset>".into());
    println!(
        "TERM={}  TMUX={}  WAYLAND_DISPLAY={}  DISPLAY={}",
        env("TERM"),
        if std::env::var_os("TMUX").is_some() {
            "set"
        } else {
            "<unset>"
        },
        env("WAYLAND_DISPLAY"),
        env("DISPLAY")
    );

    let (cols, rows) = match crossterm::terminal::size() {
        Ok((c, r)) => {
            println!("crossterm size = {c}x{r} cells");
            (c, r)
        }
        Err(e) => {
            println!("crossterm size = ERR {e}");
            (0, 0)
        }
    };

    // glyph coverage: the kernel console font is 256/512 glyphs, so any of these
    // that show as blank/garbage explain missing UI chrome.
    println!("glyphs (blank = font can't map it): '\u{276f}' '\u{2588}' '\u{25cf}' '\u{25cb}' '\u{2500}' '\u{2502}' '\u{250c}'");

    println!("--- tier decision ---");
    let mut reasons: Vec<String> = Vec::new();
    if std::env::var_os("TMUX").is_some() {
        let client = std::process::Command::new("tmux")
            .args(["display", "-p", "#{client_termname}"])
            .output()
            .ok()
            .filter(|o| o.status.success())
            .map(|o| String::from_utf8_lossy(&o.stdout).trim().to_string())
            .unwrap_or_default();
        println!("tmux client_termname = {client:?}");
        if client != "linux" {
            reasons.push(format!("tmux client is {client:?}, not a kernel console"));
        }
    } else {
        if std::env::var("TERM").ok().as_deref() != Some("linux") {
            reasons.push("TERM != linux and not in tmux".into());
        }
        if std::env::var_os("WAYLAND_DISPLAY").is_some() {
            reasons.push("WAYLAND_DISPLAY set (fb0 is not the scanned-out surface)".into());
        }
        if std::env::var_os("DISPLAY").is_some() {
            reasons.push("DISPLAY set (fb0 is not the scanned-out surface)".into());
        }
    }
    if cols == 0 || rows == 0 {
        reasons.push("terminal size reported 0 — fb tier needs a real cell grid".into());
    }

    #[cfg(target_os = "linux")]
    {
        match framebuffer::Framebuffer::new("/dev/fb0") {
            Err(e) => reasons.push(format!("/dev/fb0 open failed: {e:?}")),
            Ok(fb) => {
                let v = fb.var_screen_info.clone();
                let f = fb.fix_screen_info.clone();
                println!(
                    "fb0: {}x{} bpp={} line_length={} smem_len={} xoff={} yoff={}",
                    v.xres,
                    v.yres,
                    v.bits_per_pixel,
                    f.line_length,
                    f.smem_len,
                    v.xoffset,
                    v.yoffset
                );
                println!(
                    "fb0 bitfields: r=({},{}) g=({},{}) b=({},{})",
                    v.red.offset,
                    v.red.length,
                    v.green.offset,
                    v.green.length,
                    v.blue.offset,
                    v.blue.length
                );
                println!("fb0 mmap len = {} bytes", fb.frame.len());
                if cols > 0 && rows > 0 {
                    println!(
                        "cell = {}x{} px",
                        (v.xres / cols as u32).max(1),
                        (v.yres / rows as u32).max(1)
                    );
                }
                if reasons.is_empty() {
                    paint_test(
                        fb,
                        v.xres,
                        v.yres,
                        f.line_length,
                        (v.bits_per_pixel / 8).max(1),
                    );
                }
            }
        }
    }

    if reasons.is_empty() {
        println!("=> framebuffer tier ACTIVE");
    } else {
        println!("=> framebuffer tier REJECTED:");
        for r in &reasons {
            println!("   - {r}");
        }
        println!("   (falls back to the terminal-graphics tier, else text)");
    }
    Ok(())
}

/// paint an orange 200x100 block at (100,100) straight to the framebuffer and
/// hold it, so "did anything reach the screen" is answered by looking.
#[cfg(target_os = "linux")]
fn paint_test(mut fb: framebuffer::Framebuffer, xres: u32, yres: u32, line_len: u32, bpp: u32) {
    let (w, h) = (200u32.min(xres), 100u32.min(yres));
    let buf = &mut fb.frame;
    for y in 100..(100 + h) {
        for x in 100..(100 + w) {
            let off = (y as usize) * line_len as usize + (x as usize) * bpp as usize;
            if off + bpp as usize > buf.len() {
                continue;
            }
            // heatsync orange #ff8700, written little-endian for xrgb8888.
            for (i, b) in [0x00u8, 0x87, 0xff, 0x00]
                .iter()
                .take(bpp as usize)
                .enumerate()
            {
                buf[off + i] = *b;
            }
        }
    }
    println!("painted an ORANGE block at px(100,100) size 200x100 — holding 5s");
    std::thread::sleep(std::time::Duration::from_secs(5));
}