metop 0.4.0

Linux memory analysis TUI: RSS/PSS/USS per process, VMA drill-down
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
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
//! Built-in colour themes.
//!
//! A theme is a compile-time [`Palette`]: metop intentionally has no config
//! file (see `docs/REQUIREMENTS.md`), so selecting one is a CLI flag
//! (`--theme`), the `METOP_THEME` environment variable, or the `t` key while
//! the TUI is running.
//!
//! Every palette slot is semantic rather than per-widget: a light terminal can
//! turn "too much memory" into a dark amber without any draw-code change. The
//! default theme keeps the shipped chrome colours (highlight, dim, accent,
//! severity, treemap); every theme's PSS composition colours are its own, with
//! a per-theme test that they stay distinct.

use ratatui::style::{Color, Style};

/// How many colours the terminal can actually display.
///
/// Themes are authored in 24-bit RGB; [`Theme::rendered`] converts each slot to
/// the terminal's depth, so a 256-colour terminal gets `38;5;n` instead of RGB
/// SGR it may not parse, and a 16-colour terminal gets named ANSI colours.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ColorSupport {
    TrueColor,
    Ansi256,
    Ansi16,
}

impl ColorSupport {
    /// Best-effort detection from `COLORTERM`/`TERM`, falling back to
    /// crossterm's count. Checking both matters: crossterm prefers an empty
    /// `COLORTERM` over a perfectly good `TERM=...-256color`.
    pub fn detect() -> Self {
        if let Some(value) = std::env::var_os("COLORTERM") {
            let value = value.to_string_lossy();
            if value.contains("truecolor") || value.contains("24bit") {
                return Self::TrueColor;
            }
        }
        if let Some(value) = std::env::var_os("TERM") {
            let value = value.to_string_lossy();
            if value.contains("256color") {
                return Self::Ansi256;
            }
            if value.contains("direct") {
                return Self::TrueColor;
            }
        }
        match ratatui::crossterm::style::available_color_count() {
            u16::MAX => Self::TrueColor,
            256 => Self::Ansi256,
            _ => Self::Ansi16,
        }
    }

    pub const NAMES: &'static str = "auto, truecolor, 256, 16";

    /// Parse a `--color` value; `auto` performs detection.
    pub fn parse(value: &str) -> Option<Self> {
        match value.to_ascii_lowercase().as_str() {
            "auto" => Some(Self::detect()),
            "truecolor" | "24bit" => Some(Self::TrueColor),
            "256" | "ansi256" => Some(Self::Ansi256),
            "16" | "ansi16" => Some(Self::Ansi16),
            _ => None,
        }
    }
}

/// Semantic colours used by the whole UI.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Palette {
    /// Secondary text, graph chrome, unfilled bar cells.
    pub dim: Color,
    /// `dim`, lifted so it stays readable on the tinted selected row.
    pub dim_selected: Color,
    /// Selected row / badge background.
    ///
    /// Only the background is set: per-cell foregrounds (bars, deltas) must
    /// survive selection instead of being flattened to one colour.
    pub highlight_bg: Color,
    /// Titles, table headers, sparklines.
    pub accent: Color,
    /// Share bar in its normal (not warning/critical) range.
    pub bar: Color,
    /// Healthy state: low memory pressure, negative deltas.
    pub ok: Color,
    /// Warning state: 5–20% PSI, 75–90% memory use.
    pub warn: Color,
    /// Critical state: OOM kills, >20% PSI, >90% memory use.
    pub crit: Color,
    /// Input prompt and cursor.
    pub focus: Color,
    /// PSS mix: anonymous pages.
    pub anon: Color,
    /// PSS mix: file-backed pages.
    pub file: Color,
    /// PSS mix: shared-memory pages.
    pub shmem: Color,
    /// PSS mix: PSS-weighted swapped-out pages.
    pub swap: Color,
    /// Swap-PSS shown numerically in the detail summary.
    pub swap_pss: Color,
    /// Secondary text drawn on treemap tiles.
    pub tile_fg: Color,
    /// Treemap tile fills, cycled by group index.
    pub treemap: [Color; 6],
}

impl Palette {
    /// metop's original colours.
    pub const DEFAULT: Self = Self {
        dim: Color::DarkGray,
        dim_selected: Color::Gray,
        highlight_bg: Color::Rgb(38, 79, 120),
        accent: Color::Cyan,
        bar: Color::Cyan,
        ok: Color::Green,
        warn: Color::Yellow,
        crit: Color::Red,
        focus: Color::Yellow,
        anon: Color::Magenta,
        file: Color::Cyan,
        shmem: Color::Yellow,
        swap: Color::LightBlue,
        swap_pss: Color::LightBlue,
        tile_fg: Color::Gray,
        treemap: [
            Color::Rgb(46, 64, 94),
            Color::Rgb(60, 47, 82),
            Color::Rgb(36, 72, 72),
            Color::Rgb(82, 62, 42),
            Color::Rgb(52, 72, 46),
            Color::Rgb(78, 47, 58),
        ],
    };

    pub fn highlight(&self) -> Style {
        Style::new().bg(self.highlight_bg)
    }

    /// Secondary text; on the tinted selected row `dim` would vanish.
    pub fn dim(&self, selected: bool) -> Color {
        if selected {
            self.dim_selected
        } else {
            self.dim
        }
    }

    /// Convert every RGB slot to the terminal's colour depth.
    pub fn rendered(self, support: ColorSupport) -> Self {
        Self {
            dim: render_color(self.dim, support),
            dim_selected: render_color(self.dim_selected, support),
            highlight_bg: render_color(self.highlight_bg, support),
            accent: render_color(self.accent, support),
            bar: render_color(self.bar, support),
            ok: render_color(self.ok, support),
            warn: render_color(self.warn, support),
            crit: render_color(self.crit, support),
            focus: render_color(self.focus, support),
            anon: render_color(self.anon, support),
            file: render_color(self.file, support),
            shmem: render_color(self.shmem, support),
            swap: render_color(self.swap, support),
            swap_pss: render_color(self.swap_pss, support),
            tile_fg: render_color(self.tile_fg, support),
            treemap: self.treemap.map(|color| render_color(color, support)),
        }
    }
}

/// `Color::Rgb` with byte components, so theme tables read like the hex they
/// came from.
const fn rgb(r: u8, g: u8, b: u8) -> Color {
    Color::Rgb(r, g, b)
}

/// Convert one RGB colour to what `support` can display.
fn render_color(color: Color, support: ColorSupport) -> Color {
    match (support, color) {
        (ColorSupport::TrueColor, color) => color,
        (ColorSupport::Ansi256, Color::Rgb(r, g, b)) => Color::Indexed(rgb_to_256(r, g, b)),
        (ColorSupport::Ansi16, Color::Rgb(r, g, b)) => nearest_ansi16(r, g, b),
        (_, color) => color,
    }
}

/// btop's truecolor->256 rule: the 232-255 grey ramp when the channels are
/// close, otherwise the 6x6x6 colour cube.
fn rgb_to_256(r: u8, g: u8, b: u8) -> u8 {
    let (rf, gf, bf) = (r as f64, g as f64, b as f64);
    if (rf / 11.0).round() == (gf / 11.0).round() && (gf / 11.0).round() == (bf / 11.0).round() {
        (232.0 + (rf / 11.0).round()).min(255.0) as u8
    } else {
        (16.0 + (rf / 51.0).round() * 36.0 + (gf / 51.0).round() * 6.0 + (bf / 51.0).round()) as u8
    }
}

#[rustfmt::skip]
const ANSI16_RGB: [(u8, u8, u8); 16] = [
    (0, 0, 0), (128, 0, 0), (0, 128, 0), (128, 128, 0),
    (0, 0, 128), (128, 0, 128), (0, 128, 128), (192, 192, 192),
    (85, 85, 85), (255, 0, 0), (0, 255, 0), (255, 255, 0),
    (0, 0, 255), (255, 0, 255), (0, 255, 255), (255, 255, 255),
];

#[rustfmt::skip]
const ANSI16_COLORS: [Color; 16] = [
    Color::Black, Color::Red, Color::Green, Color::Yellow,
    Color::Blue, Color::Magenta, Color::Cyan, Color::Gray,
    Color::DarkGray, Color::LightRed, Color::LightGreen, Color::LightYellow,
    Color::LightBlue, Color::LightMagenta, Color::LightCyan, Color::White,
];

fn nearest_ansi16(r: u8, g: u8, b: u8) -> Color {
    let mut best = 0;
    let mut best_distance = u32::MAX;
    for (index, (r2, g2, b2)) in ANSI16_RGB.into_iter().enumerate() {
        let distance = (i32::from(r) - i32::from(r2)).pow(2) as u32
            + (i32::from(g) - i32::from(g2)).pow(2) as u32
            + (i32::from(b) - i32::from(b2)).pow(2) as u32;
        if distance < best_distance {
            best_distance = distance;
            best = index;
        }
    }
    ANSI16_COLORS[best]
}

/// A named built-in palette.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Theme {
    pub name: &'static str,
    pub palette: Palette,
}

impl Theme {
    pub const DEFAULT: Self = Self {
        name: "default",
        palette: Palette::DEFAULT,
    };

    /// btop's built-in Default theme (`src/btop_theme.cpp`, `Default_theme`).
    /// btop's two-digit hex values are greyscale (`#ee` -> 238,238,238).
    pub const BTOP: Self = Self {
        name: "btop",
        palette: Palette {
            dim: rgb(0x40, 0x40, 0x40),
            dim_selected: rgb(0xee, 0xee, 0xee),
            highlight_bg: rgb(0x6a, 0x2f, 0x2f),
            accent: rgb(0xee, 0xee, 0xee),
            bar: rgb(0x80, 0xd0, 0xa3),
            ok: rgb(0x77, 0xca, 0x9b),
            warn: rgb(0xcb, 0xc0, 0x6c),
            crit: rgb(0xdc, 0x4c, 0x4c),
            focus: rgb(0xb5, 0x40, 0x40),
            anon: rgb(0xff, 0x47, 0x69),
            file: rgb(0x26, 0xc5, 0xff),
            shmem: rgb(0xff, 0xb8, 0x14),
            swap: rgb(0xb0, 0xa9, 0xde),
            swap_pss: rgb(0xb0, 0xa9, 0xde),
            tile_fg: rgb(0x22, 0x22, 0x22),
            treemap: [
                rgb(0xff, 0x47, 0x69),
                rgb(0x26, 0xc5, 0xff),
                rgb(0xff, 0xb8, 0x14),
                rgb(0xdc, 0xff, 0x85),
                rgb(0xb0, 0xa9, 0xde),
                rgb(0xdc, 0xaf, 0xde),
            ],
        },
    };

    /// btop's `dracula.theme`: selected_bg/title/hi_fg/gradients are taken from
    /// the file; its CPU gradient is purple->cyan->green, so severity uses
    /// Dracula's canonical red/yellow/green instead.
    pub const DRACULA: Self = Self {
        name: "dracula",
        palette: Palette {
            dim: rgb(0x44, 0x47, 0x5a),
            dim_selected: rgb(0xf8, 0xf8, 0xf2),
            highlight_bg: rgb(0xff, 0x79, 0xc6),
            accent: rgb(0xf8, 0xf8, 0xf2),
            bar: rgb(0x50, 0xfa, 0x7b),
            ok: rgb(0x50, 0xfa, 0x7b),
            warn: rgb(0xf1, 0xfa, 0x8c),
            crit: rgb(0xff, 0x55, 0x55),
            focus: rgb(0x62, 0x72, 0xa4),
            anon: rgb(0x0d, 0xfa, 0x49),
            file: rgb(0x26, 0xd7, 0xfd),
            shmem: rgb(0xff, 0x9c, 0x33),
            swap: rgb(0xbd, 0x93, 0xf9),
            swap_pss: rgb(0xbd, 0x93, 0xf9),
            tile_fg: rgb(0x28, 0x2a, 0x36),
            treemap: [
                rgb(0x50, 0xfa, 0x7b),
                rgb(0xbd, 0x93, 0xf9),
                rgb(0xff, 0x79, 0xc6),
                rgb(0x8b, 0xe9, 0xfd),
                rgb(0xff, 0x9c, 0x33),
                rgb(0xff, 0x33, 0xa8),
            ],
        },
    };

    /// btop's `gruvbox_dark.theme`. btop's inactive_fg/selected_bg are nearly
    /// the same as main_bg, so the slots metop uses for readable secondary text
    /// and selection are lifted to gruvbox bg1/fg4.
    pub const GRUVBOX: Self = Self {
        name: "gruvbox-dark",
        palette: Palette {
            dim: rgb(0x7c, 0x6f, 0x64),
            dim_selected: rgb(0xfa, 0xbd, 0x2f),
            highlight_bg: rgb(0x3c, 0x38, 0x36),
            accent: rgb(0xeb, 0xdb, 0xb2),
            bar: rgb(0xb8, 0xbb, 0x26),
            ok: rgb(0xb8, 0xbb, 0x26),
            warn: rgb(0xfa, 0xbd, 0x2f),
            crit: rgb(0xfb, 0x49, 0x34),
            focus: rgb(0xd7, 0x99, 0x21),
            anon: rgb(0xfb, 0x49, 0x34),
            file: rgb(0x83, 0xa5, 0x98),
            shmem: rgb(0xfa, 0xbd, 0x2f),
            swap: rgb(0xa3, 0xa8, 0xf7),
            swap_pss: rgb(0xa3, 0xa8, 0xf7),
            tile_fg: rgb(0x1d, 0x20, 0x21),
            treemap: [
                rgb(0xb8, 0xbb, 0x26),
                rgb(0x83, 0xa5, 0x98),
                rgb(0xfa, 0xbd, 0x2f),
                rgb(0x98, 0x97, 0x1a),
                rgb(0xa3, 0xa8, 0xf7),
                rgb(0xd3, 0x86, 0x9b),
            ],
        },
    };

    /// btop's `kanagawa-wave.theme`; treemap hues are that theme's gradient
    /// starts, bright with dark tile labels so the app view matches the theme.
    pub const KANAGAWA: Self = Self {
        name: "kanagawa-wave",
        palette: Palette {
            dim: rgb(0x72, 0x71, 0x69),
            dim_selected: rgb(0xdc, 0xa5, 0x61),
            highlight_bg: rgb(0x22, 0x32, 0x49),
            accent: rgb(0xdc, 0xd7, 0xba),
            bar: rgb(0x98, 0xbb, 0x6c),
            ok: rgb(0x98, 0xbb, 0x6c),
            warn: rgb(0xdc, 0xa5, 0x61),
            crit: rgb(0xe8, 0x24, 0x24),
            focus: rgb(0xc3, 0x40, 0x43),
            anon: rgb(0x7f, 0xb4, 0xca),
            file: rgb(0xff, 0x9e, 0x3b),
            shmem: rgb(0x98, 0xbb, 0x6c),
            swap: rgb(0x95, 0x7f, 0xbb),
            swap_pss: rgb(0x95, 0x7f, 0xbb),
            tile_fg: rgb(0x16, 0x16, 0x1d),
            treemap: [
                rgb(0x98, 0xbb, 0x6c),
                rgb(0xc0, 0xa3, 0x6e),
                rgb(0x93, 0x8a, 0xa9),
                rgb(0xe8, 0x24, 0x24),
                rgb(0x7e, 0x9c, 0xdb),
                rgb(0xdc, 0xa5, 0x61),
            ],
        },
    };

    /// For light terminals (dark text on a light background).
    pub const LIGHT: Self = Self {
        name: "light",
        palette: Palette {
            dim: Color::DarkGray,
            dim_selected: Color::Black,
            highlight_bg: Color::Rgb(191, 219, 254),
            accent: Color::Blue,
            bar: Color::Blue,
            ok: Color::Green,
            // Yellow is unreadable on white; dark amber keeps the meaning.
            warn: Color::Rgb(146, 64, 14),
            crit: Color::Red,
            focus: Color::Blue,
            anon: Color::Magenta,
            file: Color::Blue,
            shmem: Color::Rgb(146, 64, 14),
            swap: Color::Rgb(0x8e, 0x45, 0x85),
            swap_pss: Color::Rgb(0x8e, 0x45, 0x85),
            tile_fg: Color::Black,
            treemap: [
                Color::Rgb(219, 234, 254),
                Color::Rgb(237, 233, 254),
                Color::Rgb(204, 251, 241),
                Color::Rgb(254, 243, 199),
                Color::Rgb(220, 252, 231),
                Color::Rgb(254, 226, 226),
            ],
        },
    };

    /// Only the 16 ANSI colours: usable on limited terminals and in tmux,
    /// where RGB is quantised unpredictably.
    pub const ANSI16: Self = Self {
        name: "ansi16",
        palette: Palette {
            dim: Color::DarkGray,
            dim_selected: Color::Gray,
            highlight_bg: Color::Blue,
            accent: Color::Cyan,
            bar: Color::Cyan,
            ok: Color::Green,
            warn: Color::Yellow,
            crit: Color::Red,
            focus: Color::Yellow,
            anon: Color::Blue,
            file: Color::Cyan,
            shmem: Color::Yellow,
            swap: Color::Magenta,
            swap_pss: Color::Magenta,
            tile_fg: Color::Gray,
            treemap: [
                Color::Blue,
                Color::Magenta,
                Color::Cyan,
                Color::Yellow,
                Color::Green,
                Color::Red,
            ],
        },
    };

    /// Apply terminal colour-depth conversion while keeping the theme name.
    pub fn rendered(self, support: ColorSupport) -> Self {
        Self {
            name: self.name,
            palette: self.palette.rendered(support),
        }
    }

    pub const ALL: [Self; 7] = [
        Self::DEFAULT,
        Self::BTOP,
        Self::DRACULA,
        Self::GRUVBOX,
        Self::KANAGAWA,
        Self::LIGHT,
        Self::ANSI16,
    ];
    pub const NAMES: &'static str =
        "default, btop, dracula, gruvbox-dark, kanagawa-wave, light, ansi16";

    pub fn by_name(name: &str) -> Option<Self> {
        Self::ALL
            .iter()
            .copied()
            .find(|theme| theme.name.eq_ignore_ascii_case(name))
    }

    pub fn next(self) -> Self {
        let index = Self::ALL
            .iter()
            .position(|theme| theme.name == self.name)
            .unwrap_or(0);
        Self::ALL[(index + 1) % Self::ALL.len()]
    }
}

#[cfg(test)]
mod tests {
    use super::{Palette, Theme};
    use ratatui::style::Color;

    #[test]
    fn default_theme_keeps_the_shipped_chrome_colours() {
        let p = Theme::DEFAULT.palette;
        assert_eq!(p, Palette::DEFAULT);
        assert_eq!(p.highlight_bg, Color::Rgb(38, 79, 120));
        assert_eq!(p.dim, Color::DarkGray);
        assert_eq!(p.dim_selected, Color::Gray);
        assert_eq!(p.accent, Color::Cyan);
        assert_eq!(p.bar, Color::Cyan);
        assert_eq!(p.focus, Color::Yellow);
        assert_eq!(p.treemap[0], Color::Rgb(46, 64, 94));
        assert_eq!(p.treemap[5], Color::Rgb(78, 47, 58));
    }

    #[test]
    fn theme_lookup_is_case_insensitive_and_rejects_unknown_names() {
        assert_eq!(Theme::by_name("default"), Some(Theme::DEFAULT));
        assert_eq!(Theme::by_name("BTOP"), Some(Theme::BTOP));
        assert_eq!(Theme::by_name("Dracula"), Some(Theme::DRACULA));
        assert_eq!(Theme::by_name("gruvbox-dark"), Some(Theme::GRUVBOX));
        assert_eq!(Theme::by_name("Kanagawa-Wave"), Some(Theme::KANAGAWA));
        assert_eq!(Theme::by_name("Light"), Some(Theme::LIGHT));
        assert_eq!(Theme::by_name("ANSI16"), Some(Theme::ANSI16));
        assert_eq!(Theme::by_name("solarized"), None);
    }

    #[test]
    fn t_cycles_through_every_builtin_and_wraps() {
        for pair in Theme::ALL.windows(2) {
            assert_eq!(pair[0].next(), pair[1], "{} ->", pair[0].name);
        }
        assert_eq!(Theme::ALL[Theme::ALL.len() - 1].next(), Theme::ALL[0]);
    }

    #[test]
    fn names_lists_every_theme_in_order() {
        let joined = Theme::ALL
            .iter()
            .map(|theme| theme.name)
            .collect::<Vec<_>>()
            .join(", ");
        assert_eq!(joined, Theme::NAMES);
    }

    #[test]
    fn btop_theme_matches_the_btop_default_palette() {
        let p = Theme::BTOP.palette;
        assert_eq!(p.highlight_bg, Color::Rgb(0x6a, 0x2f, 0x2f));
        assert_eq!(p.ok, Color::Rgb(0x77, 0xca, 0x9b));
        assert_eq!(p.warn, Color::Rgb(0xcb, 0xc0, 0x6c));
        assert_eq!(p.crit, Color::Rgb(0xdc, 0x4c, 0x4c));
        assert_eq!(p.treemap[1], Color::Rgb(0x26, 0xc5, 0xff));
    }

    #[test]
    fn ansi256_conversion_uses_the_cube_and_grey_ramp() {
        assert_eq!(super::rgb_to_256(255, 0, 0), 196);
        assert_eq!(super::rgb_to_256(0, 255, 0), 46);
        assert_eq!(super::rgb_to_256(0, 0, 255), 21);
        assert_eq!(super::rgb_to_256(0, 0, 0), 232);
        assert_eq!(super::rgb_to_256(255, 255, 255), 255);
        assert_eq!(super::rgb_to_256(128, 128, 128), 244);
    }

    #[test]
    fn rendered_256_maps_rgb_to_indexed_and_keeps_the_name() {
        let theme = Theme::BTOP.rendered(super::ColorSupport::Ansi256);
        assert_eq!(theme.name, "btop");
        assert_eq!(
            theme.palette.highlight_bg,
            Color::Indexed(super::rgb_to_256(0x6a, 0x2f, 0x2f))
        );
        assert!(matches!(theme.palette.treemap[0], Color::Indexed(_)));
    }

    #[test]
    fn rendered_16_uses_named_ansi_colours() {
        use super::ColorSupport;
        assert_eq!(
            super::render_color(Color::Rgb(255, 0, 0), ColorSupport::Ansi16),
            Color::LightRed
        );
        assert_eq!(
            super::render_color(Color::Rgb(0, 0, 0), ColorSupport::Ansi16),
            Color::Black
        );
        assert_eq!(
            super::render_color(Color::Rgb(255, 255, 255), ColorSupport::Ansi16),
            Color::White
        );
        // Dark grey must not collapse to black on a dark terminal.
        assert_eq!(
            super::render_color(Color::Rgb(0x44, 0x47, 0x5a), ColorSupport::Ansi16),
            Color::DarkGray
        );
        // Named colours from the ansi16 theme are already terminal indices.
        assert_eq!(
            super::render_color(Color::Cyan, ColorSupport::Ansi16),
            Color::Cyan
        );
    }

    #[test]
    fn truecolor_rendering_is_a_no_op() {
        assert_eq!(
            Theme::DRACULA.rendered(super::ColorSupport::TrueColor),
            Theme::DRACULA
        );
    }

    #[test]
    fn pss_mix_colours_are_theme_derived_and_distinct() {
        for theme in Theme::ALL {
            let palette = theme.palette;
            let distinct: std::collections::HashSet<Color> =
                [palette.anon, palette.file, palette.shmem, palette.swap]
                    .into_iter()
                    .collect();
            assert_eq!(distinct.len(), 4, "{} reuses a PSS mix colour", theme.name);
            assert_eq!(palette.swap_pss, palette.swap, "{}", theme.name);
        }

        // The default theme keeps its original PSS composition colours.
        let p = Theme::DEFAULT.palette;
        assert_eq!(p.anon, Color::Magenta);
        assert_eq!(p.file, Color::Cyan);
        assert_eq!(p.shmem, Color::Yellow);
        assert_eq!(p.swap, Color::LightBlue);
    }

    #[test]
    fn every_theme_has_distinct_fills_and_no_tile_fg_collision() {
        for theme in Theme::ALL {
            let palette = theme.palette;
            let distinct: std::collections::HashSet<Color> =
                palette.treemap.iter().copied().collect();
            assert_eq!(distinct.len(), 6, "{} reuses a tile fill", theme.name);
            assert!(
                !distinct.contains(&palette.tile_fg),
                "{} tile_fg is also a tile fill",
                theme.name
            );
        }
    }

    #[test]
    fn ansi16_uses_no_rgb_or_indexed_colours() {
        let p = Theme::ANSI16.palette;
        let slots = [
            p.dim,
            p.dim_selected,
            p.highlight_bg,
            p.accent,
            p.bar,
            p.ok,
            p.warn,
            p.crit,
            p.focus,
            p.anon,
            p.file,
            p.shmem,
            p.swap,
            p.swap_pss,
            p.tile_fg,
        ];
        for color in slots.into_iter().chain(p.treemap) {
            assert!(
                !matches!(color, Color::Rgb(..) | Color::Indexed(_)),
                "ansi16 theme leaked {color:?}"
            );
        }
    }
}