git-custom-cli 2.4.0

Fast, keyboard-driven terminal UI for dated Git commits
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
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
use crate::mascot::{self, Look, Mood};
use anyhow::{Context, Result};
use crossterm::{
    cursor,
    event::{DisableMouseCapture, EnableMouseCapture},
    execute, queue,
    style::{Color, Print, ResetColor, SetForegroundColor},
    terminal::{self, Clear, ClearType, EnterAlternateScreen, LeaveAlternateScreen},
};
use std::{
    io::{stdout, BufWriter, Write},
    sync::{
        atomic::{AtomicBool, AtomicU32, AtomicU8, Ordering},
        OnceLock,
    },
};

const PANEL_MAX_WIDTH: u16 = 96;
const PANEL_MIN_WIDTH: u16 = 48;
const PANEL_MIN_HEIGHT: u16 = 12;

/// Columns around the panel center where the mascot keeps the center frame.
const DEAD_ZONE: i32 = 6;

static MOOD: AtomicU8 = AtomicU8::new(0);
static LOOK: AtomicU8 = AtomicU8::new(1);
static SUBTITLE: AtomicBool = AtomicBool::new(true);

/// Last known terminal size packed as `columns << 16 | rows`; 0 means unknown.
static SIZE: AtomicU32 = AtomicU32::new(0);
/// Size of the last full-screen clear, same packing; 0 forces a clear on the next draw.
static CLEARED: AtomicU32 = AtomicU32::new(0);

const NO_ACCENT: u32 = u32::MAX;
static ACCENT: AtomicU32 = AtomicU32::new(NO_ACCENT);
static SHOW_HEADER: AtomicBool = AtomicBool::new(true);
static SHOW_MASCOT: AtomicBool = AtomicBool::new(true);
static SHOW_SUBTITLE: AtomicBool = AtomicBool::new(true);

/// Look settings for the renderer. The default matches the built-in look.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct ThemeSettings {
    pub accent: Option<(u8, u8, u8)>,
    pub show_header: bool,
    pub show_mascot: bool,
    pub show_subtitle: bool,
}

impl Default for ThemeSettings {
    fn default() -> Self {
        Self {
            accent: None,
            show_header: true,
            show_mascot: true,
            show_subtitle: true,
        }
    }
}

/// Applies a theme to the following frames.
pub fn set_theme(theme: ThemeSettings) {
    let packed = theme.accent.map_or(NO_ACCENT, |(r, g, b)| {
        (r as u32) << 16 | (g as u32) << 8 | b as u32
    });
    ACCENT.store(packed, Ordering::Relaxed);
    SHOW_HEADER.store(theme.show_header, Ordering::Relaxed);
    SHOW_MASCOT.store(theme.show_mascot, Ordering::Relaxed);
    SHOW_SUBTITLE.store(theme.show_subtitle, Ordering::Relaxed);
}

fn accent_rgb() -> Option<(u8, u8, u8)> {
    let packed = ACCENT.load(Ordering::Relaxed);
    (packed != NO_ACCENT).then_some(((packed >> 16) as u8, (packed >> 8) as u8, packed as u8))
}

fn border_color() -> Color {
    accent_rgb().map_or(Color::Cyan, |(r, g, b)| {
        if truecolor() {
            Color::Rgb { r, g, b }
        } else {
            Color::AnsiValue(rgb_to_256(r, g, b))
        }
    })
}

/// Whether the terminal is assumed to understand 24-bit color (detected once).
fn truecolor() -> bool {
    static TRUECOLOR: OnceLock<bool> = OnceLock::new();
    *TRUECOLOR.get_or_init(|| {
        cfg!(windows)
            || std::env::var_os("WT_SESSION").is_some()
            || std::env::var("COLORTERM").is_ok_and(|v| {
                v.eq_ignore_ascii_case("truecolor") || v.eq_ignore_ascii_case("24bit")
            })
    })
}

/// Nearest xterm-256 index for an RGB color (6x6x6 cube or the gray ramp).
fn rgb_to_256(r: u8, g: u8, b: u8) -> u8 {
    let level = |v: u8| -> u8 {
        if v < 48 {
            0
        } else if v < 115 {
            1
        } else {
            (v - 35) / 40
        }
    };
    let value = |l: u8| -> i32 {
        if l == 0 {
            0
        } else {
            55 + 40 * l as i32
        }
    };
    let (lr, lg, lb) = (level(r), level(g), level(b));
    let cube = 16 + 36 * lr + 6 * lg + lb;
    let dist = |(x, y, z): (i32, i32, i32)| {
        (x - r as i32).pow(2) + (y - g as i32).pow(2) + (z - b as i32).pow(2)
    };
    let cube_dist = dist((value(lr), value(lg), value(lb)));
    let avg = (r as i32 + g as i32 + b as i32) / 3;
    let step = ((avg - 8 + 5) / 10).clamp(0, 23);
    let gray = 8 + 10 * step;
    if dist((gray, gray, gray)) < cube_dist {
        232 + step as u8
    } else {
        cube
    }
}

/// SGR parameters for a foreground (`38`) or background (`48`) accent color.
fn color_params(base: u8, r: u8, g: u8, b: u8) -> String {
    if truecolor() {
        format!("{base};2;{r};{g};{b}")
    } else {
        format!("{base};5;{}", rgb_to_256(r, g, b))
    }
}

/// Readable text color on an accent background: black on light, bright white on dark.
fn contrast_fg(r: u8, g: u8, b: u8) -> u8 {
    if 0.299 * r as f32 + 0.587 * g as f32 + 0.114 * b as f32 > 140.0 {
        30
    } else {
        97
    }
}

fn subtitle_shown() -> bool {
    SUBTITLE.load(Ordering::Relaxed) && SHOW_SUBTITLE.load(Ordering::Relaxed)
}

fn mascot_shown(columns: u16, rows: u16) -> bool {
    SHOW_HEADER.load(Ordering::Relaxed)
        && SHOW_MASCOT.load(Ordering::Relaxed)
        && mascot::fits(columns, rows)
}

/// Shows or hides the header subtitle (the main menu hides it).
pub fn set_subtitle(show: bool) {
    SUBTITLE.store(show, Ordering::Relaxed);
}

/// Black text on the mascot's green (or the theme accent), for key facts on the main menu.
pub fn tag(message: impl AsRef<str>) -> String {
    match accent_rgb() {
        Some((r, g, b)) => format!(
            "\x1b[{};{}m {} \x1b[0m",
            contrast_fg(r, g, b),
            color_params(48, r, g, b),
            message.as_ref()
        ),
        None => format!(
            "\x1b[30;{}m {} \x1b[0m",
            color_params(48, 0x10, 0xb9, 0x81),
            message.as_ref()
        ),
    }
}

/// Sets the mascot face used by the following frames.
pub fn set_mood(mood: Mood) {
    MOOD.store(mood.index() as u8, Ordering::Relaxed);
}

fn mood() -> Mood {
    Mood::from_index(MOOD.load(Ordering::Relaxed) as usize)
}

fn look() -> Look {
    Look::from_index(LOOK.load(Ordering::Relaxed) as usize)
}

fn pack_size(columns: u16, rows: u16) -> u32 {
    (columns as u32) << 16 | rows as u32
}

/// Queries the terminal size and refreshes the cache.
fn current_size() -> (u16, u16) {
    let (columns, rows) = terminal::size().unwrap_or((100, 30));
    SIZE.store(pack_size(columns, rows), Ordering::Relaxed);
    (columns, rows)
}

fn cached_size() -> (u16, u16) {
    match SIZE.load(Ordering::Relaxed) {
        0 => current_size(),
        packed => ((packed >> 16) as u16, packed as u16),
    }
}

/// Turns the mascot toward the pointer. Returns true only when the frame changes,
/// so small moves inside the dead zone do not force a redraw.
pub fn track_pointer(column: u16) -> bool {
    let (columns, rows) = cached_size();
    if !mascot_shown(columns, rows) {
        return false;
    }
    let (left, _, width, _) = panel(columns, rows);
    let offset = column as i32 - (left + width / 2) as i32;
    let target = if offset < -DEAD_ZONE {
        Look::Left
    } else if offset > DEAD_ZONE {
        Look::Right
    } else {
        Look::Center
    };
    LOOK.swap(target.index() as u8, Ordering::Relaxed) != target.index() as u8
}

fn panel(columns: u16, rows: u16) -> (u16, u16, u16, u16) {
    let width = PANEL_MAX_WIDTH
        .min(columns.saturating_sub(4))
        .max(PANEL_MIN_WIDTH)
        .min(columns.max(4));
    let height = rows
        .saturating_sub(2)
        .max(PANEL_MIN_HEIGHT)
        .min(rows.saturating_sub(1).max(4));
    let left = columns.saturating_sub(width) / 2;
    (left, 1, width, height)
}

fn border(width: u16, left: &str, fill: &str, right: &str) -> String {
    format!(
        "{left}{fill}{right}",
        fill = fill.repeat(width.saturating_sub(2) as usize)
    )
}

fn visible_width(value: &str) -> usize {
    let mut visible = 0;
    let mut escape = false;
    for character in value.chars() {
        if escape {
            escape = character != 'm';
        } else if character == '\x1b' {
            escape = true;
        } else {
            visible += 1;
        }
    }
    visible
}

/// Cuts `value` to `columns` visible characters and keeps its color codes intact.
fn fit(value: &str, columns: usize) -> String {
    let mut out = String::new();
    let mut visible = 0;
    let mut escape = false;
    for character in value.chars() {
        if escape {
            out.push(character);
            escape = character != 'm';
        } else if character == '\x1b' {
            out.push(character);
            escape = true;
        } else {
            if visible == columns {
                out.push_str("\x1b[0m");
                break;
            }
            out.push(character);
            visible += 1;
        }
    }
    out
}

/// Fits one line inside the frame: two spaces of margin on each side, padded to `inner`.
fn pad(value: &str, inner: u16) -> String {
    let text_width = inner.saturating_sub(4) as usize;
    let shown = fit(value, text_width);
    let spare = text_width.saturating_sub(visible_width(&shown));
    format!("  {shown}{}  ", " ".repeat(spare))
}

/// Puts `text` at `offset` columns inside a `text_area`-wide row.
fn place(text: &str, offset: usize, text_area: usize) -> String {
    let spare = text_area.saturating_sub(offset + visible_width(text));
    format!("{}{text}{}", " ".repeat(offset), " ".repeat(spare))
}

/// Number of header rows, without building any strings. Must match `header` exactly:
/// title, optional subtitle, then mascot block and status line when the mascot fits.
fn header_rows(columns: u16, rows: u16) -> u16 {
    if !SHOW_HEADER.load(Ordering::Relaxed) {
        return 0;
    }
    let mut count = 1 + u16::from(subtitle_shown());
    if mascot_shown(columns, rows) {
        count += mascot::HEIGHT as u16 + 1;
    }
    count
}

/// Centered title, then the mascot centered below it when the terminal is big enough.
fn header(columns: u16, rows: u16, text_area: usize) -> Vec<String> {
    if !SHOW_HEADER.load(Ordering::Relaxed) {
        return Vec::new();
    }
    let mood = mood();

    let mut info = vec!["\x1b[1m◆  GCT  ·  GIT COMMIT CONTROL  ◆\x1b[0m".to_string()];
    if subtitle_shown() {
        info.push(muted("Fast, dated commits from your terminal"));
    }
    let mut lines: Vec<String> = info
        .iter()
        .map(|text| {
            let offset = text_area.saturating_sub(visible_width(text)) / 2;
            place(text, offset, text_area)
        })
        .collect();
    if mascot_shown(columns, rows) {
        let offset = text_area.saturating_sub(mascot::WIDTH) / 2;
        lines.extend(
            shaded_frame(look(), mood)
                .iter()
                .map(|row| place(row, offset, text_area)),
        );
        let status = format!("{}{}\x1b[0m", rgb(MID_HEX), status_text(mood));
        let offset = text_area.saturating_sub(visible_width(&status)) / 2;
        lines.push(place(&status, offset, text_area));
    }
    lines
}

/// Shaded mascot rows for one look and mood, built once for all 12 combinations.
fn shaded_frame(look: Look, mood: Mood) -> &'static [String] {
    static CACHE: OnceLock<Vec<Vec<String>>> = OnceLock::new();
    let cache = CACHE.get_or_init(|| {
        let mut all = Vec::with_capacity(Look::COUNT * Mood::COUNT);
        for l in 0..Look::COUNT {
            for m in 0..Mood::COUNT {
                let rows = mascot::frame(Look::from_index(l), Mood::from_index(m));
                all.push(rows.iter().map(|row| shade(row)).collect());
            }
        }
        all
    });
    &cache[look.index() * Mood::COUNT + mood.index()]
}

/// Hex colors for the mascot gradient, from the rim inward, plus the eyes and nose.
const RIM_HEX: u32 = 0x6ee7b7;
const MID_HEX: u32 = 0x10b981;
const INNER_HEX: u32 = 0x059669;
const FACE_HEX: u32 = 0xa7f3d0;

/// 24-bit foreground escape for a `0xRRGGBB` color.
fn rgb(hex: u32) -> String {
    format!(
        "\x1b[38;2;{};{};{}m",
        hex >> 16 & 0xff,
        hex >> 8 & 0xff,
        hex & 0xff
    )
}

/// Colors each mascot character: `@` rim, `$` middle, `.` inner, eyes and nose bright.
fn shade(row: &str) -> String {
    row.chars()
        .map(|ch| match ch {
            ' ' => " ".to_string(),
            '@' => format!("{}{ch}\x1b[0m", rgb(RIM_HEX)),
            '$' => format!("{}{ch}\x1b[0m", rgb(MID_HEX)),
            '.' => format!("{}{ch}\x1b[0m", rgb(INNER_HEX)),
            '^' | '?' | 'x' | 'o' | 'v' => format!("\x1b[1m{}{ch}\x1b[0m", rgb(FACE_HEX)),
            _ => format!("{}{ch}\x1b[0m", rgb(MID_HEX)),
        })
        .collect()
}

fn status_text(mood: Mood) -> &'static str {
    match mood {
        Mood::Idle => "ready when you are",
        Mood::Thinking => "working on it...",
        Mood::Happy => "all done!",
        Mood::Error => "something went wrong",
    }
}

fn frame_row(out: &mut impl Write, left: u16, row: u16, inner: u16, text: &str) -> Result<()> {
    queue!(
        out,
        cursor::MoveTo(left, row),
        SetForegroundColor(border_color()),
        Print("│"),
        ResetColor,
        Print(pad(text, inner)),
        SetForegroundColor(border_color()),
        Print("│"),
        Clear(ClearType::UntilNewLine),
    )?;
    Ok(())
}

fn divider(out: &mut impl Write, left: u16, row: u16, width: u16) -> Result<()> {
    queue!(
        out,
        cursor::MoveTo(left, row),
        SetForegroundColor(border_color()),
        Print(border(width, "├", "─", "┤")),
        Clear(ClearType::UntilNewLine),
    )?;
    Ok(())
}

/// Panel geometry for the current terminal size, shared by `draw`, `body_rows` and
/// `body_line`. Numbers only: it never builds the header strings.
struct Layout {
    columns: u16,
    rows: u16,
    left: u16,
    top: u16,
    width: u16,
    height: u16,
    inner: u16,
    header_rows: u16,
    body_top: u16,
    body_rows: u16,
}

fn layout() -> Layout {
    let (columns, rows) = current_size();
    let (left, top, width, height) = panel(columns, rows);
    let inner = width - 2;
    let header_rows = header_rows(columns, rows);
    // The header divider only exists when there is a header above it.
    let divider = u16::from(header_rows > 0);
    let body_top = top + 1 + header_rows + divider;
    let body_rows = height.saturating_sub(header_rows + divider + 4);
    Layout {
        columns,
        rows,
        left,
        top,
        width,
        height,
        inner,
        header_rows,
        body_top,
        body_rows,
    }
}

/// Number of body rows `draw` shows at the current terminal size.
pub fn body_rows() -> usize {
    layout().body_rows as usize
}

/// Body line index under terminal row `row`, or None outside the body.
pub fn body_line(row: u16) -> Option<usize> {
    let Layout {
        body_top,
        body_rows,
        ..
    } = layout();
    (body_top..body_top + body_rows)
        .contains(&row)
        .then(|| (row - body_top) as usize)
}

/// Draws the panel: mascot header, body lines, footer hints, and an optional cursor.
/// `cursor` is (row, column) inside the body.
pub fn draw(body: &[String], footer: &str, cursor: Option<(u16, u16)>) -> Result<()> {
    let Layout {
        columns,
        rows,
        left,
        top,
        width,
        height,
        inner,
        header_rows,
        body_top,
        body_rows,
    } = layout();
    let header = header(columns, rows, inner.saturating_sub(4) as usize);
    debug_assert_eq!(header.len() as u16, header_rows);
    let footer_divider = body_top + body_rows;

    let mut out = BufWriter::with_capacity(16 * 1024, stdout().lock());
    queue!(out, terminal::BeginSynchronizedUpdate, cursor::Hide)?;
    // The panel paints every cell it owns, so only clear when the screen is fresh or resized.
    let size = pack_size(columns, rows);
    if CLEARED.load(Ordering::Relaxed) != size {
        queue!(out, Clear(ClearType::All))?;
    }
    queue!(
        out,
        cursor::MoveTo(left, top),
        SetForegroundColor(border_color()),
        Print(border(width, "╭", "─", "╮")),
    )?;
    for (index, line) in header.iter().enumerate() {
        frame_row(&mut out, left, top + 1 + index as u16, inner, line)?;
    }
    if header_rows > 0 {
        divider(&mut out, left, top + header_rows + 1, width)?;
    }
    for row in 0..body_rows {
        let line = body.get(row as usize).map_or("", String::as_str);
        frame_row(&mut out, left, body_top + row, inner, line)?;
    }
    divider(&mut out, left, footer_divider, width)?;
    frame_row(&mut out, left, footer_divider + 1, inner, &muted(footer))?;
    queue!(
        out,
        cursor::MoveTo(left, top + height - 1),
        SetForegroundColor(border_color()),
        Print(border(width, "╰", "─", "╯")),
        ResetColor,
    )?;
    match cursor {
        Some((row, column)) => queue!(
            out,
            cursor::MoveTo(left + 3 + column, body_top + row),
            cursor::Show,
            terminal::EndSynchronizedUpdate,
        )?,
        None => queue!(out, cursor::Hide, terminal::EndSynchronizedUpdate)?,
    }
    out.flush()?;
    // Only remember the clear once it reached the terminal; an undersized terminal never caches.
    let fits = columns >= PANEL_MIN_WIDTH && rows >= PANEL_MIN_HEIGHT + 2;
    CLEARED.store(if fits { size } else { 0 }, Ordering::Relaxed);
    Ok(())
}

/// Forces the next `draw` to clear the whole screen (call on resize).
pub fn invalidate() {
    CLEARED.store(0, Ordering::Relaxed);
}

pub struct Guard;

impl Guard {
    pub fn enter() -> Result<Self> {
        resume()?;
        Ok(Self)
    }
}

impl Drop for Guard {
    fn drop(&mut self) {
        restore();
    }
}

/// Leaves raw mode and the alternate screen. Safe to call more than once.
pub fn restore() {
    let _ = terminal::disable_raw_mode();
    let _ = execute!(
        stdout(),
        DisableMouseCapture,
        cursor::Show,
        LeaveAlternateScreen,
        ResetColor
    );
}

/// Hands the terminal back to the shell, for example while an external editor runs.
pub fn suspend() {
    restore();
}

pub fn resume() -> Result<()> {
    terminal::enable_raw_mode().context("could not enable terminal raw mode")?;
    CLEARED.store(0, Ordering::Relaxed);
    execute!(
        stdout(),
        EnterAlternateScreen,
        EnableMouseCapture,
        Clear(ClearType::All),
        cursor::Hide
    )
    .context("could not enter terminal UI")
}

pub fn muted(message: impl AsRef<str>) -> String {
    format!("\x1b[90m{}\x1b[0m", message.as_ref())
}

pub fn accent(message: impl AsRef<str>) -> String {
    match accent_rgb() {
        Some((r, g, b)) => format!(
            "\x1b[{}m{}\x1b[0m",
            color_params(38, r, g, b),
            message.as_ref()
        ),
        None => format!("\x1b[36m{}\x1b[0m", message.as_ref()),
    }
}

pub fn success(message: impl AsRef<str>) -> String {
    format!("\x1b[32m{}\x1b[0m", message.as_ref())
}

pub fn warning(message: impl AsRef<str>) -> String {
    format!("\x1b[33m{}\x1b[0m", message.as_ref())
}

pub fn danger(message: impl AsRef<str>) -> String {
    format!("\x1b[31m{}\x1b[0m", message.as_ref())
}

pub fn selected(message: impl AsRef<str>) -> String {
    match accent_rgb() {
        Some((r, g, b)) => format!(
            "\x1b[1;{};{}m{}\x1b[0m",
            contrast_fg(r, g, b),
            color_params(48, r, g, b),
            message.as_ref()
        ),
        None => format!("\x1b[1;30;46m{}\x1b[0m", message.as_ref()),
    }
}

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

    /// The original, uncached shading, kept verbatim as the reference.
    fn old_shade(row: &str) -> String {
        row.chars()
            .map(|ch| match ch {
                ' ' => " ".to_string(),
                '@' => format!("{}{ch}\x1b[0m", rgb(RIM_HEX)),
                '$' => format!("{}{ch}\x1b[0m", rgb(MID_HEX)),
                '.' => format!("{}{ch}\x1b[0m", rgb(INNER_HEX)),
                '^' | '?' | 'x' | 'o' | 'v' => format!("\x1b[1m{}{ch}\x1b[0m", rgb(FACE_HEX)),
                _ => format!("{}{ch}\x1b[0m", rgb(MID_HEX)),
            })
            .collect()
    }

    #[test]
    fn cached_shading_matches_old_for_all_combos() {
        for l in 0..Look::COUNT {
            for m in 0..Mood::COUNT {
                let (look, mood) = (Look::from_index(l), Mood::from_index(m));
                let old: Vec<String> = mascot::frame(look, mood)
                    .iter()
                    .map(|row| old_shade(row))
                    .collect();
                assert_eq!(shaded_frame(look, mood), old.as_slice());
            }
        }
    }

    #[test]
    fn header_rows_match_header() {
        // Theme state is global, so every case lives in this one test.
        for &(columns, rows) in &[(100, 30), (100, 40), (49, 40), (60, 32)] {
            for bits in 0..16u8 {
                set_theme(ThemeSettings {
                    accent: None,
                    show_header: bits & 1 != 0,
                    show_mascot: bits & 2 != 0,
                    show_subtitle: bits & 4 != 0,
                });
                set_subtitle(bits & 8 != 0);
                let lines = header(columns, rows, 80);
                assert_eq!(header_rows(columns, rows) as usize, lines.len());
            }
        }
        set_theme(ThemeSettings::default());
        set_subtitle(true);
        assert_eq!(header_rows(100, 40), 1 + 1 + mascot::HEIGHT as u16 + 1);
        assert_eq!(header_rows(100, 30), 2);
        assert_eq!(accent("x"), "\x1b[36mx\x1b[0m");
        assert_eq!(selected("x"), "\x1b[1;30;46mx\x1b[0m");
        if truecolor() {
            assert_eq!(tag("x"), "\x1b[30;48;2;16;185;129m x \x1b[0m");
        }
    }

    #[test]
    fn rgb_to_256_maps_known_colors() {
        assert_eq!(rgb_to_256(0, 0, 0), 16);
        assert_eq!(rgb_to_256(255, 255, 255), 231);
        assert_eq!(rgb_to_256(255, 0, 0), 196);
        assert_eq!(rgb_to_256(128, 128, 128), 244);
    }

    #[test]
    fn panel_fits_tiny_terminals() {
        for columns in 4..120u16 {
            for rows in 5..60u16 {
                let (left, top, width, height) = panel(columns, rows);
                assert!(left + width <= columns);
                assert!(top + height <= rows);
            }
        }
        assert_eq!(panel(100, 40), (2, 1, 96, 38));
    }
}