makeover-tui 0.68.0

The terminal renderer for makeover-layout, on ratatui. Colour stops being the constraint above 256 entries; geometry never does, because an edge occupies a whole cell on every side.
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
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
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
//! A loaded makeover theme, resolved into the colours ratatui draws with.
//!
//! Behind the `theme` feature, the one part of this crate that depends on
//! `makeover`. The rest takes the [`Color`]s it is handed.
//!
//! [`Theme`] carries makeover's own `border-strong`, a firmer divider. A
//! consumer that spends a border as its focus ring derives that colour itself
//! or takes [`Theme::focus_ring`]. Reach and focus are not colours and are not
//! carried here; `makeover_layout`'s crate header defines both, under "Reach,
//! focus and the focus ring".

use std::path::PathBuf;

use makeover::{Rgb, ThemeColors, ThemeDirs, ThemeId, Token};
use ratatui::style::Color;

/// A makeover theme's intents, resolved to ratatui colours.
///
/// Built by [`Theme::from_theme`] or [`Theme::load`]; `#[non_exhaustive]`, so a
/// field added for a new makeover intent is not a breaking change.
#[derive(Debug, Clone, Copy)]
#[non_exhaustive]
pub struct Theme {
    /// The authored `surface.page`.
    pub surface_page: Color,
    /// The authored `surface.raised`: what a table's rows sit on.
    pub surface_raised: Color,
    /// The authored `surface.sunken`: a code run, a table's heading strip.
    pub surface_sunken: Color,
    /// The authored `surface.overlay`.
    pub surface_overlay: Color,

    /// makeover's `surface-well`: the inset content surface inside a raised
    /// container. A separate token from
    /// [`surface_sunken`](Theme::surface_sunken), and never filled in from it.
    ///
    /// `None` where makeover derived nothing: a theme authoring no raised
    /// surface or no content colour.
    pub surface_well: Option<Color>,

    /// makeover's `content-primary`, lifted to its floor on the page.
    pub content_primary: Color,
    /// makeover's `content-secondary`, lifted to its floor on the page.
    pub content_secondary: Color,
    /// makeover's `content-muted`, lifted to its floor on the page.
    pub content_muted: Color,
    /// makeover's `content-disabled`: a control that will not answer.
    pub content_disabled: Color,

    /// The authored `action.primary`, the accent.
    pub action_primary: Color,

    /// makeover's `status-danger`, lifted to 3:1 on the page, the raised
    /// ground and the cursor row.
    pub status_danger: Color,
    /// makeover's `status-success`, lifted as
    /// [`status_danger`](Theme::status_danger) is.
    pub status_success: Color,
    /// makeover's `status-warning`, lifted as
    /// [`status_danger`](Theme::status_danger) is.
    pub status_warning: Color,
    /// makeover's `status-info`, lifted as
    /// [`status_danger`](Theme::status_danger) is.
    pub status_info: Color,

    /// A danger badge's fill: makeover's `danger-surface`, `surface_raised`
    /// with 12 percent of the tone in it (wiki `table-model`). A fill and never
    /// an ink; the badge's text takes content ink.
    pub status_danger_surface: Color,
    /// A success badge's fill: makeover's `success-surface`, derived as
    /// [`status_danger_surface`](Theme::status_danger_surface) is.
    pub status_success_surface: Color,
    /// A warning badge's fill: makeover's `warning-surface`, derived as
    /// [`status_danger_surface`](Theme::status_danger_surface) is.
    pub status_warning_surface: Color,
    /// An info badge's fill: makeover's `info-surface`, derived as
    /// [`status_danger_surface`](Theme::status_danger_surface) is.
    pub status_info_surface: Color,

    /// makeover's `row-hover`: ink mixed into `surface_raised` at 9 percent.
    /// This crate fills a neutral badge with it. Alternate rows take no tone
    /// of their own: they sit on [`surface_page`](Theme::surface_page).
    pub row_hover: Color,
    /// makeover's `row-rule`: ink mixed into `surface_raised` at 26 percent.
    /// This crate draws no rule between rows; a consumer drawing its own
    /// divider takes this colour.
    pub row_rule: Color,
    /// The row the cursor is on: makeover's `row-selected`, raised with 18
    /// percent of the ink (a neutral-ramp step). A fill and never a foreground.
    pub row_selected: Color,

    /// The measure ramp, quietest first: makeover's `heat-0` to `heat-4`,
    /// even steps of the ink mixed into `surface_raised` from none of it up
    /// to the cursor row's mix. Fills, never inks.
    pub heat: [Color; 5],

    /// The authored `line.border`.
    pub line_border: Color,
    /// makeover's `border-strong`, a firmer divider: the authored border
    /// stepped 5 percent further from the page, darker on a light theme and
    /// lighter on a dark one.
    pub border_strong: Color,

    /// The foreground for text sitting on [`action_primary`](Theme::action_primary):
    /// makeover's derived `content-on-action`, the theme's page or content
    /// where one reads at 4.5:1 on the accent, black or white otherwise.
    pub selection_on: Color,
    /// The colour of a focus ring: makeover's derived `focus-ring`, the accent
    /// held to AA-UI against the page and the raised surface.
    pub focus_ring: Color,

    /// makeover's derived `bevel-light`: the lit edge, top and left of a
    /// raised surface and bottom and right of an inset one, on every theme.
    pub bevel_light: Color,
    /// makeover's derived `bevel-dark`: the shadowed edge, opposite
    /// [`bevel_light`](Theme::bevel_light).
    pub bevel_dark: Color,

    /// The authored `category.one` to `category.six`, in that order.
    pub category: [Color; 6],
}

/// Why a theme could not be resolved. Both variants name the key.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub enum ThemeError {
    /// A key the theme lacks: the dotted file key (`content.muted`) for an
    /// authored colour, the token name (`bevel-light`) for a derived one.
    MissingKey(&'static str),
    /// An authored key whose value is not a hex colour.
    InvalidHex { key: &'static str, value: String },
}

impl std::fmt::Display for ThemeError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::MissingKey(k) => write!(f, "theme missing required key `{k}`"),
            Self::InvalidHex { key, value } => {
                write!(f, "theme key `{key}` has invalid hex value `{value}`")
            }
        }
    }
}

impl std::error::Error for ThemeError {}

/// Why [`Theme::load`] could not hand back a theme.
///
/// Every variant names the theme, and the two that go to disk name every
/// directory searched, so the message says where to put the file.
#[derive(Debug)]
#[non_exhaustive]
pub enum LoadError {
    /// No directory on the search path holds the theme.
    NotFound { id: ThemeId, searched: Vec<PathBuf> },
    /// The theme was found and could not be read or parsed.
    Read {
        id: ThemeId,
        searched: Vec<PathBuf>,
        source: Box<makeover::LoadError>,
    },
    /// The theme loaded and lacks an intent [`Theme`] requires.
    Incomplete { id: ThemeId, source: ThemeError },
}

impl std::fmt::Display for LoadError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let joined = |searched: &[PathBuf]| {
            searched
                .iter()
                .map(|path| path.display().to_string())
                .collect::<Vec<_>>()
                .join(", ")
        };
        match self {
            Self::NotFound { id, searched } => {
                write!(f, "no theme `{id}` (searched: {})", joined(searched))
            }
            Self::Read { id, searched, .. } => {
                write!(f, "loading theme `{id}` (searched: {})", joined(searched))
            }
            Self::Incomplete { id, .. } => write!(f, "theme `{id}` is incomplete"),
        }
    }
}

impl std::error::Error for LoadError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            Self::NotFound { .. } => None,
            Self::Read { source, .. } => Some(source.as_ref()),
            Self::Incomplete { source, .. } => Some(source),
        }
    }
}

impl Theme {
    /// Load theme `id` off `dirs` and resolve it as a terminal at `fidelity`
    /// can draw it: [`makeover::load_theme`], then [`from_theme`](Self::from_theme),
    /// then [`for_terminal`](Self::for_terminal).
    pub fn load(
        dirs: &ThemeDirs,
        id: &ThemeId,
        fidelity: crate::Fidelity,
    ) -> Result<Self, LoadError> {
        let searched = || -> Vec<PathBuf> {
            dirs.search_path()
                .map(|(path, _)| path.to_path_buf())
                .collect()
        };
        let colors = makeover::load_theme(dirs, id).map_err(|source| match source {
            makeover::LoadError::NotFound(_) => LoadError::NotFound {
                id: id.clone(),
                searched: searched(),
            },
            source => LoadError::Read {
                id: id.clone(),
                searched: searched(),
                source: Box::new(source),
            },
        })?;
        Self::from_theme(&colors)
            .map(|theme| theme.for_terminal(fidelity))
            .map_err(|source| LoadError::Incomplete {
                id: id.clone(),
                source,
            })
    }

    /// Resolve a loaded [`ThemeColors`] into the colours ratatui draws with.
    ///
    /// Every intent this struct names is required, apart from
    /// [`surface_well`](Theme::surface_well), which makeover derives only when
    /// the theme gave it enough to derive from. A malformed or partial theme is
    /// an error; no colour is defaulted.
    pub fn from_theme(theme: &ThemeColors) -> Result<Self, ThemeError> {
        let authored = |key: &'static str| -> Result<Rgb, ThemeError> {
            let hex = theme.colors.get(key).ok_or(ThemeError::MissingKey(key))?;
            Rgb::from_hex(hex).ok_or_else(|| ThemeError::InvalidHex {
                key,
                value: hex.clone(),
            })
        };

        // The bevel pair, the well and the firm border are makeover's derived
        // intents, so a console, a webview and an egui app light a raised
        // surface the same way. Read through `resolve` rather than recomputed
        // here, which is the point of them living in that crate.
        let resolved = makeover::resolve(theme);
        let derived = |token: Token| -> Result<Rgb, ThemeError> {
            resolved
                .color(token)
                .ok_or(ThemeError::MissingKey(token.as_str()))
        };

        // An ink as `resolve` lifted it to its floor on the page, which is the
        // one the webview and egui draw. The authored key is still read first,
        // so a theme missing it or spelling it badly is refused by that key.
        let lifted = |key: &'static str, token: Token| -> Result<Rgb, ThemeError> {
            authored(key)?;
            derived(token)
        };

        let accent = authored("action.primary")?;
        authored("content.primary")?;
        // A status ink is lifted by `resolve` to 3:1 on the page, the raised
        // ground a table sits on and the cursor row, the colour every host
        // draws.
        let status = |key: &'static str, token: Token| -> Result<Color, ThemeError> {
            Ok(rgb(lifted(key, token)?))
        };

        Ok(Self {
            surface_page: rgb(authored("surface.page")?),
            surface_raised: rgb(authored("surface.raised")?),
            surface_sunken: rgb(authored("surface.sunken")?),
            surface_overlay: rgb(authored("surface.overlay")?),
            surface_well: resolved.color(Token::SurfaceWell).map(rgb),

            content_primary: rgb(lifted("content.primary", Token::Content)?),
            content_secondary: rgb(lifted("content.secondary", Token::ContentSecondary)?),
            content_muted: rgb(lifted("content.muted", Token::ContentMuted)?),
            content_disabled: rgb(derived(Token::ContentDisabled)?),

            action_primary: rgb(accent),
            selection_on: rgb(derived(Token::ContentOnAction)?),
            focus_ring: rgb(derived(Token::FocusRing)?),

            status_danger: status("status.danger", Token::Danger)?,
            status_success: status("status.success", Token::Success)?,
            status_warning: status("status.warning", Token::Warning)?,
            status_info: status("status.info", Token::Info)?,

            status_danger_surface: rgb(derived(Token::DangerSurface)?),
            status_success_surface: rgb(derived(Token::SuccessSurface)?),
            status_warning_surface: rgb(derived(Token::WarningSurface)?),
            status_info_surface: rgb(derived(Token::InfoSurface)?),

            row_hover: rgb(derived(Token::RowHover)?),
            row_rule: rgb(derived(Token::RowRule)?),
            row_selected: rgb(derived(Token::RowSelected)?),
            heat: [
                rgb(derived(Token::Heat0)?),
                rgb(derived(Token::Heat1)?),
                rgb(derived(Token::Heat2)?),
                rgb(derived(Token::Heat3)?),
                rgb(derived(Token::Heat4)?),
            ],

            line_border: rgb(authored("line.border")?),
            border_strong: rgb(derived(Token::BorderStrong)?),

            bevel_light: rgb(derived(Token::BevelLight)?),
            bevel_dark: rgb(derived(Token::BevelDark)?),

            category: [
                rgb(authored("category.one")?),
                rgb(authored("category.two")?),
                rgb(authored("category.three")?),
                rgb(authored("category.four")?),
                rgb(authored("category.five")?),
                rgb(authored("category.six")?),
            ],
        })
    }

    /// This theme as the terminal can actually draw it.
    ///
    /// At [`TrueColor`](crate::Fidelity::TrueColor) the theme is returned
    /// untouched. At [`NoColor`](crate::Fidelity::NoColor) every colour
    /// becomes `Color::Reset`, the terminal's own ink and ground. Otherwise
    /// every colour becomes a palette index, by these rules:
    ///
    /// - The page, raised, sunken and overlay surfaces, the bevel pair,
    ///   `row_rule` and the heat bands are quantised plainly
    ///   ([`Quantize::plain`]); heat band 4 then takes the cursor row's entry.
    /// - Row hover, the cursor row and the four toned surfaces, in that order,
    ///   go through [`Quantize::distinct`], each on an entry that neither the
    ///   page, raised and sunken surfaces nor an earlier tone holds, stepping
    ///   further from the raised ground while body text holds 4.5:1 on it;
    ///   where no such entry is free the plain entry stands. The well goes
    ///   through it against the raised surface alone.
    /// - Body, secondary and muted text clear the AA text floor (4.5:1)
    ///   against the page, the raised ground and the sunken strip.
    /// - Disabled text and the status inks clear the AA-UI floor (3:1)
    ///   against the page, the raised ground and the cursor row.
    /// - [`selection_on`](Theme::selection_on) clears 4.5:1 against the accent.
    /// - The accent, the focus ring, both borders and the category colours go
    ///   through [`Quantize::against`] the page.
    ///
    /// A consumer holding tokens of its own quantises them with the same
    /// [`Quantize`].
    ///
    /// Call it once, on the theme [`from_theme`](Self::from_theme) built. A
    /// quantised theme holds palette indices and no longer knows the colours
    /// they came from, so quantising it again cannot reach a lower fidelity;
    /// debug builds assert on it.
    #[must_use]
    pub fn for_terminal(self, fidelity: crate::Fidelity) -> Self {
        let Some(q) = Quantize::for_fidelity(fidelity) else {
            return self;
        };
        debug_assert!(
            matches!(self.surface_page, Color::Rgb(..)),
            "for_terminal takes the authored theme; this one is already quantised"
        );

        let plain = |c: Color| q.plain(c);
        let on_page = |c: Color| q.against(c, self.surface_page);
        let read = [self.surface_page, self.surface_raised, self.surface_sunken];
        let text = |c: Color| q.legible(c, &read, TEXT_FLOOR);

        let surface_page = plain(self.surface_page);
        let surface_raised = plain(self.surface_raised);
        let surface_sunken = plain(self.surface_sunken);
        // Each tone is a step from the raised ground and is drawn beside the
        // grounds and the tones before it, so each takes an entry none of them
        // holds. Body text is drawn on every one of them.
        let mut taken = vec![surface_page, surface_raised, surface_sunken];
        let mut step = |c: Color| {
            let entry = q.distinct(c, self.surface_raised, &taken, self.content_primary);
            taken.push(entry);
            entry
        };
        let row_hover = step(self.row_hover);
        let row_selected = step(self.row_selected);
        let status_danger_surface = step(self.status_danger_surface);
        let status_success_surface = step(self.status_success_surface);
        let status_warning_surface = step(self.status_warning_surface);
        let status_info_surface = step(self.status_info_surface);
        // Apart from the raised face it is cut into, and nothing else: a well
        // is not drawn beside a row or a banner.
        let surface_well = self.surface_well.map(|well| {
            q.distinct(
                well,
                self.surface_raised,
                &[surface_raised],
                self.content_primary,
            )
        });

        // The cursor row as the terminal paints it, since that is what a
        // status ink on it has to clear.
        let marked = [
            self.surface_page,
            self.surface_raised,
            q.shown(row_selected),
        ];
        let ink = |c: Color| q.legible(c, &marked, UI_FLOOR);

        let mut heat = self.heat.map(plain);
        // Band 4 is the cursor row's tone, and stays it.
        heat[4] = row_selected;

        Self {
            surface_page,
            surface_raised,
            surface_sunken,
            surface_overlay: plain(self.surface_overlay),
            surface_well,

            content_primary: text(self.content_primary),
            content_secondary: text(self.content_secondary),
            content_muted: text(self.content_muted),
            content_disabled: ink(self.content_disabled),

            action_primary: on_page(self.action_primary),
            // Against the accent, not against the page: this is the one colour
            // here whose whole job is to be legible on the accent behind it.
            // Quantising it against the page would answer the wrong question
            // and hand a selected row unreadable text at Ansi16.
            selection_on: q.legible(self.selection_on, &[self.action_primary], TEXT_FLOOR),
            focus_ring: on_page(self.focus_ring),

            // At the UI floor and not the text floor: a status ink draws an
            // edge, a bracket or a glyph, never the words beside it, which take
            // content ink (wiki `quasi-vocabulary-findings`, toned text).
            status_danger: ink(self.status_danger),
            status_success: ink(self.status_success),
            status_warning: ink(self.status_warning),
            status_info: ink(self.status_info),

            status_danger_surface,
            status_success_surface,
            status_warning_surface,
            status_info_surface,

            row_hover,
            // Plainly: a hairline under the 3:1 that separates two areas on
            // purpose, so landing on its ground's entry is the rule's own look.
            row_rule: plain(self.row_rule),
            row_selected,
            // Plainly: a band that lands on its neighbour's entry is a band
            // this terminal cannot show.
            heat,

            line_border: on_page(self.line_border),
            border_strong: on_page(self.border_strong),

            bevel_light: plain(self.bevel_light),
            bevel_dark: plain(self.bevel_dark),

            category: self.category.map(on_page),
        }
    }

    /// The depth-painting palette this theme implies, at `fidelity`.
    ///
    /// The page, raised, overlay and well surfaces, the bevel pair and
    /// [`tones`](Self::tones), or [`Tones::NONE`](crate::Tones::NONE) at
    /// [`NoColor`](crate::Fidelity::NoColor).
    #[must_use]
    pub const fn palette(&self, fidelity: crate::Fidelity) -> crate::Palette {
        crate::Palette {
            page: self.surface_page,
            raised: self.surface_raised,
            overlay: self.surface_overlay,
            well: self.surface_well,
            bevel_light: self.bevel_light,
            bevel_dark: self.bevel_dark,
            fidelity,
            // Every tone empty, so each role falls back to its modifier.
            tones: if matches!(fidelity, crate::Fidelity::NoColor) {
                crate::Tones::NONE
            } else {
                self.tones()
            },
        }
    }

    /// The colours text, controls and tables are drawn in, from this theme.
    ///
    /// The table model (wiki `table-model`): rows on the raised ground with
    /// the page as the stripe, the heading on the sunken surface, the cursor
    /// row on `row_selected`, and a badge filled with its tone's surface. A
    /// neutral badge fills with `row_hover`.
    #[must_use]
    pub const fn tones(&self) -> crate::Tones {
        crate::Tones::NONE
            .content(self.content_primary)
            .secondary(self.content_secondary)
            .muted(self.content_muted)
            .disabled(self.content_disabled)
            .action(self.action_primary)
            .on_action(self.selection_on)
            .info(self.status_info)
            .success(self.status_success)
            .warning(self.status_warning)
            .danger(self.status_danger)
            .info_surface(self.status_info_surface)
            .success_surface(self.status_success_surface)
            .warning_surface(self.status_warning_surface)
            .danger_surface(self.status_danger_surface)
            .neutral_surface(self.row_hover)
            .border(self.line_border)
            .sunken(self.surface_sunken)
            .ground(self.surface_raised)
            .stripe(self.surface_page)
            .selected(self.row_selected)
            .heat_1(self.heat[1])
            .heat_2(self.heat[2])
            .heat_3(self.heat[3])
            .heat_4(self.heat[4])
    }
}

fn rgb(c: Rgb) -> Color {
    Color::Rgb(c.r, c.g, c.b)
}

/// The AA floor for text against what it sits on.
const TEXT_FLOOR: f32 = 4.5;

/// How far [`Quantize::distinct`] widens a step each try, as a multiple of the
/// step the theme authored.
const DISTINCT_STRIDE: f32 = 0.25;

/// How many tries [`Quantize::distinct`] makes: up to eight times the authored
/// step, which takes a 12 percent toned surface nearly to its tone.
const DISTINCT_STEPS: u32 = 28;

/// The AA-UI floor a non-text cue has to clear against what it sits on.
const UI_FLOOR: f32 = 3.0;

/// The palette a [`Fidelity`](crate::Fidelity) quantises into, and the rules for
/// landing a colour in it, for a consumer quantising tokens of its own the way
/// [`Theme::for_terminal`] quantises makeover's.
#[derive(Debug, Clone, Copy)]
pub struct Quantize {
    palette: &'static [Rgb],
    offset: usize,
}

impl Quantize {
    /// The quantiser for `fidelity`, or `None` at
    /// [`TrueColor`](crate::Fidelity::TrueColor), where nothing is quantised.
    ///
    /// At [`NoColor`](crate::Fidelity::NoColor) the palette is empty and every
    /// colour lands on `Color::Reset`. At [`Ansi256`](crate::Fidelity::Ansi256)
    /// it is makeover's `ANSI_240`, the table without its low sixteen entries.
    #[must_use]
    pub const fn for_fidelity(fidelity: crate::Fidelity) -> Option<Self> {
        match fidelity {
            crate::Fidelity::TrueColor => None,
            crate::Fidelity::Ansi256 => Some(Self {
                palette: makeover::ANSI_240,
                offset: makeover::ANSI_240_OFFSET,
            }),
            crate::Fidelity::Ansi16 => Some(Self {
                palette: &makeover::ANSI_16,
                offset: 0,
            }),
            crate::Fidelity::NoColor => Some(Self {
                palette: &[],
                offset: 0,
            }),
        }
    }

    /// The palette entry for `c`, as an index the terminal will not reinterpret.
    ///
    /// For a colour measured against the surface it sits on rather than against
    /// the page: the surfaces themselves, and the bevel pair.
    #[must_use]
    pub fn plain(&self, c: Color) -> Color {
        if self.palette.is_empty() {
            return Color::Reset;
        }
        match c {
            Color::Rgb(r, g, b) => Color::Indexed(
                (makeover::quantize(Rgb { r, g, b }, self.palette) + self.offset) as u8,
            ),
            other => other,
        }
    }

    /// As [`plain`](Self::plain), but on an entry none of `taken` holds.
    ///
    /// For a tone that is a small step from the ground `from`: a hover, a
    /// cursor row, a toned surface. When its plain entry is taken, `c` is
    /// stepped further along the line from `from` through it, so it keeps the
    /// hue and the direction the theme gave it and only the step widens, until
    /// it lands on a free entry. Each candidate must keep `ink` at the text
    /// floor; the first one that does not ends the search, and the plain entry
    /// stands.
    #[must_use]
    pub fn distinct(&self, c: Color, from: Color, taken: &[Color], ink: Color) -> Color {
        let first = self.plain(c);
        if self.palette.is_empty() || !taken.contains(&first) {
            return first;
        }
        let (Color::Rgb(r, g, b), Color::Rgb(fr, fg, fb), Color::Rgb(ir, ig, ib)) = (c, from, ink)
        else {
            return first;
        };
        let (c, from, ink) = (
            Rgb { r, g, b },
            Rgb {
                r: fr,
                g: fg,
                b: fb,
            },
            Rgb {
                r: ir,
                g: ig,
                b: ib,
            },
        );
        for step in 1..=DISTINCT_STEPS {
            let candidate = makeover::mix(from, c, (step as f32).mul_add(DISTINCT_STRIDE, 1.0));
            let index = makeover::quantize(candidate, self.palette);
            if makeover::wcag_contrast(self.palette[index], ink) < TEXT_FLOOR {
                break;
            }
            let entry = Color::Indexed((index + self.offset) as u8);
            if !taken.contains(&entry) {
                return entry;
            }
        }
        first
    }

    /// The colour an entry this quantiser chose stands for, so it can be
    /// measured as a ground. Anything else comes back as it is.
    fn shown(&self, c: Color) -> Color {
        match c {
            Color::Indexed(i) => (i as usize)
                .checked_sub(self.offset)
                .and_then(|i| self.palette.get(i))
                .map_or(c, |e| Color::Rgb(e.r, e.g, e.b)),
            other => other,
        }
    }

    /// As [`plain`](Self::plain), but clearing `floor` against every colour in
    /// `on`, or getting as close as this palette can.
    ///
    /// For a colour drawn on more than one surface: text sits on the page, the
    /// raised ground and the stripe, and one entry has to read on all of them.
    /// Pass 4.5 for text and 3.0 for a graphical cue. Same caution as
    /// [`against`](Self::against) about pairs that must stay apart from each
    /// other.
    #[must_use]
    pub fn legible(&self, c: Color, on: &[Color], floor: f32) -> Color {
        let Color::Rgb(r, g, b) = c else {
            return self.plain(c);
        };
        if self.palette.is_empty() {
            return Color::Reset;
        }
        let grounds: Vec<Rgb> = on
            .iter()
            .filter_map(|ground| match ground {
                Color::Rgb(r, g, b) => Some(Rgb {
                    r: *r,
                    g: *g,
                    b: *b,
                }),
                _ => None,
            })
            .collect();
        Color::Indexed(
            (makeover::quantize_legible(Rgb { r, g, b }, &grounds, floor, self.palette)
                + self.offset) as u8,
        )
    }

    /// As [`plain`](Self::plain), but clearing the 3:1 a border or ring needs
    /// against `on`, or getting as close as this palette can.
    ///
    /// At [`NoColor`](crate::Fidelity::NoColor) it is `Color::Reset`.
    ///
    /// It answers "nearest entry that still contrasts with `on`" and does not
    /// choose which side of `on` the answer falls, so two colours that must
    /// stay apart from each other can both land on the same entry.
    #[must_use]
    pub fn against(&self, c: Color, on: Color) -> Color {
        if self.palette.is_empty() {
            return Color::Reset;
        }
        match (c, on) {
            (Color::Rgb(r, g, b), Color::Rgb(br, bg, bb)) => Color::Indexed(
                (makeover::quantize_against(
                    Rgb { r, g, b },
                    Rgb {
                        r: br,
                        g: bg,
                        b: bb,
                    },
                    self.palette,
                ) + self.offset) as u8,
            ),
            _ => self.plain(c),
        }
    }
}

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

    fn shipped() -> makeover::ThemeDirs {
        makeover::ThemeDirs::new().bundled(Some(
            makeover::bundled_themes_dir().expect("makeover ships themes"),
        ))
    }

    fn bundled(id: &makeover::ThemeId) -> ThemeColors {
        makeover::load_theme(&shipped(), id).expect("bundled theme loads")
    }

    fn metas() -> Vec<makeover::ThemeMeta> {
        makeover::list_themes_from_dirs(&shipped()).themes
    }

    #[test]
    fn every_bundled_theme_resolves() {
        // The point of rejecting a partial theme is that it never happens to a
        // theme we ship. If one of these stops resolving, that is a real gap in
        // the theme file, not a reason to soften the error.
        let metas = metas();
        assert!(
            !metas.is_empty(),
            "makeover shipped no themes to test against"
        );
        for meta in &metas {
            let colors = bundled(&meta.id);
            assert!(
                Theme::from_theme(&colors).is_ok(),
                "bundled theme `{}` failed to resolve",
                meta.id
            );
        }
    }

    fn to_rgb(c: Color) -> Rgb {
        match c {
            Color::Rgb(r, g, b) => Rgb { r, g, b },
            other => panic!("expected a resolved colour, got {other:?}"),
        }
    }

    #[test]
    fn body_text_clears_the_text_floor_on_the_page_in_every_bundled_theme() {
        // Solarized Light authors its primary ink at 4.13:1 on its page, which
        // `resolve` lifts; reading the authored ink drew every TUI's body
        // text under the floor.
        for meta in metas() {
            let theme = Theme::from_theme(&bundled(&meta.id)).expect("resolves");
            let got =
                makeover::wcag_contrast(to_rgb(theme.content_primary), to_rgb(theme.surface_page));
            assert!(
                got >= TEXT_FLOOR,
                "{}: content_primary is {got:.2} on the page",
                meta.id
            );
        }
    }

    #[test]
    fn the_two_derived_cues_are_legible_in_every_bundled_theme() {
        // The test that would have caught `border_strong` being spent as a
        // focus ring: it lands at 1.63:1 on Akari Dawn, and nothing asked.
        // Every theme rather than one, because a derivation that works on the
        // theme it was written against says nothing about the other thirty.
        for meta in metas() {
            let theme = Theme::from_theme(&bundled(&meta.id)).expect("resolves");

            // Text on the accent, so the text floor.
            let selection =
                makeover::wcag_contrast(to_rgb(theme.selection_on), to_rgb(theme.action_primary));
            assert!(
                selection >= TEXT_FLOOR,
                "{}: selection_on is {selection:.2} on the accent",
                meta.id
            );

            // A ring is a graphical object, so the AA-UI floor.
            let ring =
                makeover::wcag_contrast(to_rgb(theme.focus_ring), to_rgb(theme.surface_page));
            assert!(
                ring >= UI_FLOOR,
                "{}: focus_ring is {ring:.2} on the page",
                meta.id
            );

            // And the ring is not the divider wearing the ring's name, which
            // is the whole reason it is derived rather than adopted.
            assert_ne!(theme.focus_ring, theme.border_strong, "{}", meta.id);
        }
    }

    #[test]
    fn the_cursor_row_is_its_own_colour_on_every_bundled_theme() {
        // makeover holds content to the text floor on `row-selected`. What is
        // this renderer's to check is that the cursor is a colour of its own,
        // since it moves over the stripe (the page) and the ground both.
        for meta in metas() {
            let theme = Theme::from_theme(&bundled(&meta.id)).expect("resolves");
            assert_ne!(theme.row_selected, theme.surface_page, "{}", meta.id);
            assert_ne!(theme.row_selected, theme.surface_raised, "{}", meta.id);
        }
    }

    #[test]
    fn the_derived_cues_are_quantised_for_the_surface_each_sits_on() {
        // A colour that has to be told apart from a known background is
        // quantised against that background, and the two cues do not share one.
        // Left plain, both collapse toward whatever the palette has nearest.
        let theme = Theme::from_theme(&bundled(&makeover::ThemeId::from_static("goingson")))
            .expect("resolves");
        let ansi16 = theme.for_terminal(crate::Fidelity::Ansi16);
        let q = Quantize::for_fidelity(crate::Fidelity::Ansi16).expect("Ansi16 quantises");

        assert_eq!(
            ansi16.selection_on,
            q.against(theme.selection_on, theme.action_primary)
        );
        assert_eq!(
            ansi16.focus_ring,
            q.against(theme.focus_ring, theme.surface_page)
        );
    }

    /// The worst contrast `ink` has against any of `grounds`, as painted.
    fn worst(ink: Color, grounds: &[Color], fidelity: crate::Fidelity) -> f32 {
        let paint = |c: Color| match c {
            Color::Rgb(r, g, b) => Rgb { r, g, b },
            Color::Indexed(i) => match fidelity {
                crate::Fidelity::Ansi16 => makeover::ANSI_16[i as usize],
                _ => makeover::ANSI_256[i as usize],
            },
            other => panic!("unexpected {other:?}"),
        };
        grounds
            .iter()
            .map(|g| makeover::wcag_contrast(paint(ink), paint(*g)))
            .fold(f32::INFINITY, f32::min)
    }

    #[test]
    fn text_reads_on_every_surface_it_is_drawn_on_at_every_fidelity() {
        // Body text was quantised against the page alone and landed at 3.2:1
        // on the raised surface of seven themes at sixteen colours. Each pair
        // now clears its floor, or is the best the palette can do: nothing in
        // sixteen colours clears 4.5 against four greys at once on every theme,
        // and then the walk's answer has to be the palette's best.
        for meta in metas() {
            let theme = Theme::from_theme(&bundled(&meta.id)).expect("resolves");
            for fidelity in [crate::Fidelity::Ansi16, crate::Fidelity::Ansi256] {
                let shown = theme.for_terminal(fidelity);
                let read = [
                    shown.surface_page,
                    shown.surface_raised,
                    shown.surface_sunken,
                ];
                let grey = |c: Rgb| {
                    let lab = c.to_oklab();
                    lab.a.hypot(lab.b) < 0.04
                };
                let entries: Vec<u8> = (0..=255u8)
                    .filter(|i| (fidelity == crate::Fidelity::Ansi16) == (*i < 16))
                    .collect();
                for (name, ink) in [
                    ("content_primary", shown.content_primary),
                    ("content_secondary", shown.content_secondary),
                ] {
                    let got = worst(ink, &read, fidelity);
                    // Clears the floor whenever a grey can: a grey is always a
                    // candidate, and the quantiser trades a hue for a grey but
                    // never a grey for a blue.
                    let possible = entries.iter().any(|i| {
                        let entry = match fidelity {
                            crate::Fidelity::Ansi16 => makeover::ANSI_16[*i as usize],
                            _ => makeover::ANSI_256[*i as usize],
                        };
                        // A grey is a candidate for every ink, grey or hued.
                        grey(entry) && worst(Color::Indexed(*i), &read, fidelity) >= TEXT_FLOOR
                    });
                    assert!(
                        got >= TEXT_FLOOR || !possible,
                        "{} {fidelity:?}: {name} worst {got:.2} though its kind can clear",
                        meta.id
                    );
                }
            }
        }
    }

    #[test]
    fn status_inks_clear_the_ui_floor_on_the_cursor_row_as_authored() {
        // Truecolor is the theme as authored, so no quantiser reaches it: the
        // inks are walked in from_theme.
        for meta in metas() {
            let theme = Theme::from_theme(&bundled(&meta.id)).expect("resolves");
            let grounds = [theme.surface_page, theme.surface_raised, theme.row_selected];
            for (name, ink) in [
                ("danger", theme.status_danger),
                ("success", theme.status_success),
                ("warning", theme.status_warning),
                ("info", theme.status_info),
            ] {
                let got = worst(ink, &grounds, crate::Fidelity::TrueColor);
                assert!(got >= UI_FLOOR, "{}: {name} worst {got:.2}", meta.id);
            }
        }
    }

    #[test]
    fn a_missing_intent_names_the_key_it_wanted() {
        let mut colors = bundled(&makeover::ThemeId::from_static("goingson"));
        colors.colors.remove("content.muted");
        match Theme::from_theme(&colors) {
            Err(ThemeError::MissingKey(k)) => assert_eq!(k, "content.muted"),
            other => panic!("expected MissingKey(content.muted), got {other:?}"),
        }
    }

    #[test]
    fn an_unparseable_hex_names_the_key_and_the_value() {
        let mut colors = bundled(&makeover::ThemeId::from_static("goingson"));
        colors
            .colors
            .insert("content.muted".into(), "not-a-colour".into());
        match Theme::from_theme(&colors) {
            Err(ThemeError::InvalidHex { key, value }) => {
                assert_eq!(key, "content.muted");
                assert_eq!(value, "not-a-colour");
            }
            other => panic!("expected InvalidHex, got {other:?}"),
        }
    }

    #[test]
    fn load_resolves_and_quantises_a_theme_on_the_search_path() {
        let id = makeover::ThemeId::from_static("goingson");
        let loaded = Theme::load(&shipped(), &id, crate::Fidelity::Ansi16).expect("loads");
        let by_hand = Theme::from_theme(&bundled(&id))
            .expect("resolves")
            .for_terminal(crate::Fidelity::Ansi16);
        assert_eq!(loaded.surface_page, by_hand.surface_page);
        assert_eq!(loaded.content_primary, by_hand.content_primary);
    }

    #[test]
    fn a_theme_missing_from_the_search_path_names_every_directory_searched() {
        let dirs = shipped();
        let id = makeover::ThemeId::from_static("no-such-theme");
        let err = Theme::load(&dirs, &id, crate::Fidelity::TrueColor).expect_err("missing");
        assert!(matches!(err, LoadError::NotFound { .. }), "{err:?}");
        let message = err.to_string();
        assert!(message.contains("`no-such-theme`"), "{message}");
        for (dir, _) in dirs.search_path() {
            assert!(message.contains(&dir.display().to_string()), "{message}");
        }
    }

    #[test]
    fn a_theme_missing_an_intent_is_reported_incomplete_with_the_key() {
        let dir = std::env::temp_dir().join(format!("makeover-tui-load-{}", std::process::id()));
        std::fs::create_dir_all(&dir).expect("temp dir");
        std::fs::write(dir.join("partial.toml"), "[surface]\npage = \"#ffffff\"\n")
            .expect("theme file");
        let dirs = makeover::ThemeDirs::new().custom(Some(dir.clone()));
        let id = makeover::ThemeId::from_static("partial");
        let err = Theme::load(&dirs, &id, crate::Fidelity::TrueColor).expect_err("incomplete");
        std::fs::remove_dir_all(&dir).ok();
        assert_eq!(err.to_string(), "theme `partial` is incomplete");
        let source = std::error::Error::source(&err).expect("names the key");
        assert!(
            source.to_string().contains("theme missing required key"),
            "{source}"
        );
    }

    // NO_COLOR: the terminal's own ink everywhere, and no tone set, so every
    // role falls back to its modifier rather than to Reset drawn as a colour.
    #[test]
    fn no_color_draws_in_the_terminals_own_ink() {
        let theme = Theme::from_theme(&bundled(&makeover::ThemeId::from_static("goingson")))
            .expect("resolves")
            .for_terminal(crate::Fidelity::NoColor);
        assert_eq!(theme.surface_page, Color::Reset);
        assert_eq!(theme.content_primary, Color::Reset);
        assert_eq!(theme.status_danger, Color::Reset);
        assert_eq!(theme.selection_on, Color::Reset);
        let palette = theme.palette(crate::Fidelity::NoColor);
        assert_eq!(palette.tones, crate::Tones::NONE);
        assert!(palette.needs_glyph_depth());
    }

    #[test]
    fn a_capable_terminal_gets_the_theme_as_authored() {
        let theme = Theme::from_theme(&bundled(&makeover::ThemeId::from_static("goingson")))
            .expect("resolves");
        let same = theme.for_terminal(crate::Fidelity::TrueColor);
        assert_eq!(same.surface_page, theme.surface_page);
        assert_eq!(same.content_primary, theme.content_primary);
        assert!(matches!(same.surface_page, Color::Rgb(..)));
    }

    #[test]
    fn a_limited_terminal_gets_indices_rather_than_rgb() {
        let theme = Theme::from_theme(&bundled(&makeover::ThemeId::from_static("goingson")))
            .expect("resolves");
        for fidelity in [crate::Fidelity::Ansi16, crate::Fidelity::Ansi256] {
            let q = theme.for_terminal(fidelity);
            assert!(
                matches!(q.surface_page, Color::Indexed(_)),
                "{fidelity:?} left a surface as rgb"
            );
            assert!(
                matches!(q.content_primary, Color::Indexed(_)),
                "{fidelity:?} left content as rgb"
            );
        }
    }

    #[test]
    fn the_256_indices_land_outside_the_repaintable_low_sixteen() {
        // The reason Quantize::for_fidelity resolves 256 to makeover's fixed
        // region: an index below 16 is one the user's emulator may have moved.
        let theme = Theme::from_theme(&bundled(&makeover::ThemeId::from_static("goingson")))
            .expect("resolves");
        let q = theme.for_terminal(crate::Fidelity::Ansi256);
        for (name, c) in [
            ("surface_page", q.surface_page),
            ("content_primary", q.content_primary),
            ("bevel_light", q.bevel_light),
            ("bevel_dark", q.bevel_dark),
        ] {
            match c {
                Color::Indexed(i) => assert!(i >= 16, "{name} landed on repaintable index {i}"),
                other => panic!("{name} was not quantised: {other:?}"),
            }
        }
    }

    /// Pairs of the small-step tones and the grounds beside them that share
    /// one entry, named.
    fn shared_entries(tones: &[(&'static str, Color)]) -> Vec<(&'static str, &'static str)> {
        let mut shared = Vec::new();
        for (i, (a, x)) in tones.iter().enumerate() {
            for (b, y) in &tones[i + 1..] {
                if x == y {
                    shared.push((*a, *b));
                }
            }
        }
        shared
    }

    fn small_steps(t: &Theme) -> [(&'static str, Color); 9] {
        [
            ("page", t.surface_page),
            ("raised", t.surface_raised),
            ("sunken", t.surface_sunken),
            ("row-hover", t.row_hover),
            ("row-selected", t.row_selected),
            ("danger-surface", t.status_danger_surface),
            ("success-surface", t.status_success_surface),
            ("warning-surface", t.status_warning_surface),
            ("info-surface", t.status_info_surface),
        ]
    }

    #[test]
    fn the_small_steps_hold_entries_of_their_own_at_256() {
        // A toned surface, the hover and the cursor row are a 9 to 18 percent
        // step from raised, closer than the palette's spacing. Quantised
        // plainly they shared their ground's entry and one another's; each has
        // to keep one of its own, with body text still legible on it.
        let mut failures = Vec::new();
        for meta in metas() {
            let theme = Theme::from_theme(&bundled(&meta.id)).expect("resolves");
            let q = theme.for_terminal(crate::Fidelity::Ansi256);
            let shared = shared_entries(&small_steps(&q));
            // page, raised and sunken are the theme's own steps; two of them
            // sharing an entry is the theme's, not this.
            let shared: Vec<_> = shared
                .into_iter()
                .filter(|(a, b)| !matches!((*a, *b), ("page" | "raised", "raised" | "sunken")))
                .collect();
            // nightfox's raised ground is already blue, and the cube holds
            // nothing between the hover's entry and one too light for its body
            // text, so its info banner keeps the hover's background.
            let known: &[(&str, &str)] = match meta.id.as_str() {
                "nightfox" => &[("row-hover", "info-surface")],
                _ => &[],
            };
            if shared != known {
                failures.push(format!("{}: {shared:?}", meta.id));
            }
        }
        assert!(
            failures.is_empty(),
            "shared entries at 256:\n{}",
            failures.join("\n")
        );
    }

    #[test]
    fn a_widened_step_keeps_body_text_legible() {
        // The search stops before the text floor, so every tone it moved
        // still reads body text at 4.5:1.
        for fidelity in [crate::Fidelity::Ansi256, crate::Fidelity::Ansi16] {
            let q = Quantize::for_fidelity(fidelity).expect("quantises");
            for meta in metas() {
                let theme = Theme::from_theme(&bundled(&meta.id)).expect("resolves");
                let term = theme.for_terminal(fidelity);
                for ((name, authored), (_, shown)) in
                    small_steps(&theme).iter().zip(small_steps(&term))
                {
                    if q.plain(*authored) == shown {
                        continue;
                    }
                    let to_rgb = |c: Color| match q.shown(c) {
                        Color::Rgb(r, g, b) => Rgb { r, g, b },
                        other => panic!("not an entry: {other:?}"),
                    };
                    let Color::Rgb(r, g, b) = theme.content_primary else {
                        panic!("authored ink");
                    };
                    let ratio = makeover::wcag_contrast(to_rgb(shown), Rgb { r, g, b });
                    assert!(
                        ratio >= TEXT_FLOOR,
                        "{fidelity:?} {}: {name} widened to {shown:?}, text at {ratio:.2}",
                        meta.id
                    );
                }
            }
        }
    }

    #[test]
    #[ignore = "a census, run by hand: cargo test -p makeover-tui --features theme census -- --ignored --nocapture"]
    fn census_of_shared_entries() {
        for fidelity in [crate::Fidelity::Ansi256, crate::Fidelity::Ansi16] {
            let q = Quantize::for_fidelity(fidelity).expect("quantises");
            for meta in metas() {
                let theme = Theme::from_theme(&bundled(&meta.id)).expect("resolves");
                let before = small_steps(&theme).map(|(n, c)| (n, q.plain(c)));
                let after = theme.for_terminal(fidelity);
                println!(
                    "{fidelity:?} {}\n  before {:?}\n  after  {:?}",
                    meta.id,
                    shared_entries(&before),
                    shared_entries(&small_steps(&after))
                );
            }
        }
    }

    #[test]
    fn the_bevel_pair_stays_two_tones_at_256() {
        // Quantised plainly rather than against the page, precisely so they do
        // not collapse onto one entry and invert the bevel on one side.
        let theme = Theme::from_theme(&bundled(&makeover::ThemeId::from_static("goingson")))
            .expect("resolves");
        let q = theme.for_terminal(crate::Fidelity::Ansi256);
        assert_ne!(q.bevel_light, q.bevel_dark);
    }

    #[test]
    fn the_palette_takes_the_well_and_not_the_sunken_surface() {
        // The substitution this crate deleted from the description, asserted
        // absent here too: a theme authoring sunken darker than raised would
        // land the well on the wrong side of its face.
        let colors = bundled(&makeover::ThemeId::from_static("goingson"));
        let theme = Theme::from_theme(&colors).expect("resolves");
        let palette = theme.palette(crate::Fidelity::TrueColor);
        assert_eq!(palette.well, theme.surface_well);
        assert_ne!(palette.well, Some(theme.surface_sunken));
    }

    #[test]
    fn a_heat_band_is_a_background_up_to_the_cursor_row_and_band_0_is_none() {
        use makeover_layout::Heat;
        use ratatui::style::Style;
        for meta in metas() {
            let theme = Theme::from_theme(&bundled(&meta.id)).expect("resolves");
            assert_eq!(theme.heat[0], theme.surface_raised, "{}", meta.id);
            assert_eq!(theme.heat[4], theme.row_selected, "{}", meta.id);
            let palette = theme.palette(crate::Fidelity::TrueColor);
            let ink = crate::piece::Ink::new(&palette, &crate::piece::PieceStyle::default());
            assert_eq!(ink.heat(Heat(0)), Style::new(), "{}", meta.id);
            for (band, fill) in (1u8..).zip(&theme.heat[1..]) {
                assert_eq!(ink.heat(Heat(band)), Style::new().bg(*fill), "{}", meta.id);
            }
            assert_eq!(ink.heat(Heat(9)), ink.heat(Heat(4)), "{}", meta.id);
        }
    }

    #[test]
    fn a_themes_palette_resolves_into_the_house_ink() {
        // The house ink: the colours are the theme's, read off its palette,
        // and the marks are the styles'.
        use ratatui::style::{Modifier, Style};
        let theme = Theme::from_theme(&bundled(&makeover::ThemeId::from_static("goingson")))
            .expect("resolves");
        let palette = theme.palette(crate::Fidelity::TrueColor);
        let ink = crate::piece::Ink::new(&palette, &crate::piece::PieceStyle::default());
        assert_eq!(ink.muted, Style::new().fg(theme.content_muted));
        assert_eq!(ink.disabled, Style::new().fg(theme.content_disabled));
        assert_eq!(
            ink.filled,
            Style::new().fg(theme.selection_on).bg(theme.action_primary)
        );
        assert_eq!(
            ink.page,
            Style::new()
                .fg(theme.action_primary)
                .add_modifier(Modifier::BOLD)
        );
        let danger = ink.badge(makeover_layout::Tone::Danger).expect("filled");
        assert_eq!(danger.fill.bg, Some(theme.status_danger_surface));
        assert_eq!(danger.edge.fg, Some(theme.status_danger));

        let table = crate::table::TableInk::new(&palette, &crate::table::TableStyle::default());
        assert_eq!(table.ground, Style::new().bg(theme.surface_raised));
        assert_eq!(table.stripe, Style::new().bg(theme.surface_page));
        assert_eq!(table.selected.bg, Some(theme.row_selected));
        assert!(table.selected.fg.is_none());
        assert_eq!(table.header.bg, Some(theme.surface_sunken));
    }

    #[test]
    #[allow(deprecated)]
    fn repro_tones_heat0_ignored() {
        // Ink::heat draws band 0 with no fill, so a theme's tones leave the
        // band 0 slot empty rather than setting a colour nothing reads.
        for meta in metas() {
            let theme = Theme::from_theme(&bundled(&meta.id)).expect("resolves");
            let tones = theme.palette(crate::Fidelity::TrueColor).tones;
            assert_eq!(tones.heat_0, None, "{}", meta.id);
        }
    }
}