makeover-tui 0.65.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
//! A loaded makeover theme, resolved into the colours ratatui draws with.
//!
//! Behind the `theme` feature, because it is the one thing here that needs
//! `makeover` itself. The rest of this crate takes [`Color`]s it is handed and
//! never asks where they came from, which keeps a consumer that only wants
//! [`frame`](crate::frame) off the theme loader and its embedded theme files.
//!
//! # Why this lives here rather than in each consumer
//!
//! Reading makeover's intents into ratatui `Color`s is the same work every
//! terminal consumer does, and doing it twice is how two of them end up
//! disagreeing about which intent a surface reads from. The mapping is
//! mechanical, the failure mode is silent, and there is exactly one right
//! answer, so it belongs with the renderer.
//!
//! # What is deliberately absent
//!
//! Tokens a consumer derives for itself. A consumer may mix a `border-subtle`
//! and its own `border-strong` out of the authored border, holding the latter
//! to WCAG AA-UI against the page because it spends it as its entire **focus
//! ring**. makeover emits a `border-strong` too, and it is a flat 5% darkening:
//! a firmer divider, and not a focus ring at all. Those are different tokens
//! wearing one name, and on Akari Dawn they land at 1.63:1 and 3.27:1. This
//! struct carries makeover's, and a consumer that needs its own keeps deriving
//! it. Adopting one for the other would take a focus ring to half its floor.
//!
//! **Reach** and **focus** are absent for a different reason: they are not
//! colours and not this crate's at all. A terminal consumer derives reach from
//! draw order and tracks focus itself; a description states neither. The three
//! terms are defined once in `makeover_layout`'s crate header, "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.
///
/// `#[non_exhaustive]`: this gains a field whenever makeover gains an intent,
/// and without the attribute every one of those would be a major here. Nothing
/// should be building one field-by-field anyway, since [`Theme::from_theme`] is
/// the only way to get one and a partial theme is an error rather than a
/// default.
#[derive(Debug, Clone, Copy)]
#[non_exhaustive]
pub struct Theme {
    pub surface_page: Color,
    pub surface_raised: Color,
    pub surface_sunken: Color,
    pub surface_overlay: Color,

    /// makeover's inset content surface: the surface inside a raised container,
    /// so a list reads as content in a container rather than as bands on a
    /// panel.
    ///
    /// Not [`surface_sunken`](Theme::surface_sunken). A theme is free to author
    /// sunken *darker* than raised while a well always inverts away from the
    /// text, so substituting one for the other lands a well on the wrong side of
    /// its face on exactly the themes where it matters.
    ///
    /// `None` where makeover derived nothing, which is a theme authoring no
    /// raised surface or no content colour. Left missing rather than guessed,
    /// the same way [`Palette::fill`](crate::Palette::fill) answers a missing
    /// well with structure instead of a substitute colour.
    pub surface_well: Option<Color>,

    pub content_primary: Color,
    pub content_secondary: Color,
    pub content_muted: Color,
    /// makeover's `content-disabled`: a control that will not answer.
    pub content_disabled: Color,

    pub action_primary: Color,

    pub status_danger: Color,
    pub status_success: Color,
    pub status_warning: Color,
    pub status_info: Color,

    /// A badge's fill for each status tone: `surface_raised` with 12 percent of
    /// the tone in it, derived by makeover (wiki `table-model`).
    ///
    /// A fill and not an ink: a tone as text can sit near its own surface, so a
    /// badge is inked in content and says its tone with this and with its
    /// edges.
    pub status_danger_surface: Color,
    pub status_success_surface: Color,
    pub status_warning_surface: Color,
    pub status_info_surface: Color,

    /// The table model's row tones, makeover's derivation: ink mixed into
    /// `surface_raised` at 9 and 26 percent.
    ///
    /// The terminal spends the hover's step on a badge with no tone. It draws
    /// no rule, since a rule between rows costs a whole row of cells; the field
    /// is here so a consumer drawing its own divider takes the same tone the
    /// other hosts draw with. Alternate rows take no tone of their own: they
    /// sit on [`surface_page`](Theme::surface_page), a step of the neutral ramp.
    pub row_hover: Color,
    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,
    /// so a failed row stays red under the cursor.
    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 border colour.
    pub line_border: Color,
    /// makeover's derived firmer divider: the authored border, 5% darker.
    ///
    /// A divider, not a focus ring. See the module header before spending it as
    /// one.
    pub border_strong: Color,

    /// The foreground for text sitting on [`action_primary`](Theme::action_primary).
    ///
    /// DERIVED, not authored. Every consumer measured did selection with
    /// `REVERSED`, because there was no on-accent foreground to pair with an
    /// accent background, and four ports were each about to invent one.
    ///
    /// makeover's `content-on-action`: the theme's page or content where one
    /// reads at 4.5:1 on the accent, black or white otherwise, so a selected
    /// row stays inside the palette the theme wrote wherever it can.
    pub selection_on: Color,
    /// The colour of a focus ring: makeover's `focus-ring`, the accent held
    /// to AA-UI against the page and the raised surface.
    ///
    /// Deliberately not [`border_strong`](Theme::border_strong). That is a
    /// divider at 5% darkening (see the module header), and spending it here
    /// takes a focus ring to half its floor.
    pub focus_ring: Color,

    /// The lit and shadowed edges of a raised surface.
    ///
    /// A control is lit from the top left, so its top and left edges take
    /// `bevel_light` and its bottom and right edges `bevel_dark`; swapping the
    /// two recesses it, which is what a pressed state and a text well are. The
    /// light source does not flip with polarity, or the rule stops transferring
    /// between widgets, which is the whole reason to have one.
    pub bevel_light: Color,
    pub bevel_dark: Color,

    pub category: [Color; 6],
}

/// Why a theme could not be resolved.
///
/// Both variants name the key, because "the theme is bad" is not something a
/// user can act on and "the theme is missing `content.muted`" is.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub enum ThemeError {
    MissingKey(&'static str),
    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
    /// rejected rather than papered over with defaults: rendering in colours
    /// that appear nowhere in the theme file is worse than refusing to render.
    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. Otherwise every colour becomes a palette index, which is the
    /// point: left as 24-bit, the terminal approximates them itself, and its
    /// approximation collapses tones the theme keeps apart. Alloy's console lost
    /// its frame that way, drawing a border in a colour the Linux console could
    /// not tell from the page behind it.
    ///
    /// Anything that has to be seen against the page is quantised against it
    /// rather than on its own, so a border stays a border and text stays
    /// readable. The surfaces themselves are quantised plainly: they are what
    /// the others are measured against.
    ///
    /// The bevel edges are quantised plainly too, for a different reason. They
    /// are measured against the raised surface they surround rather than against
    /// the page, and running them through [`Quantize::against`] would push both
    /// onto the same entry and invert the bevel on one side. At
    /// [`Ansi16`](crate::Fidelity::Ansi16) the palette cannot hold the pair at
    /// all and one edge lands back on its face, which is a property of sixteen
    /// colours rather than something this can fix. A caller drawing there does
    /// not have to handle it: [`Theme::palette`] carries the fidelity through,
    /// and [`frame`](crate::frame) answers it with glyphs instead of tones.
    ///
    /// At [`NoColor`](crate::Fidelity::NoColor) every colour becomes
    /// `Color::Reset`, the terminal's own ink and ground.
    ///
    /// A consumer holding tokens of its own quantises them alongside this, with
    /// the same [`Quantize`], rather than after the fact.
    ///
    /// Text is quantised against every surface it is drawn on, not only the
    /// page: body and secondary text at the AA text floor against the page, the
    /// raised ground, the sunken strip and the stripe, and muted text and the
    /// status inks at the AA-UI floor against the page, the raised ground and
    /// the cursor row. Measured against the page alone, body text landed at
    /// 3.2:1 on the raised surface of seven bundled themes at sixteen colours.
    ///
    /// 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 marked = [self.surface_page, self.surface_raised, self.row_selected];
        let ink = |c: Color| q.legible(c, &marked, UI_FLOOR);

        Self {
            surface_page: plain(self.surface_page),
            surface_raised: plain(self.surface_raised),
            surface_sunken: plain(self.surface_sunken),
            surface_overlay: plain(self.surface_overlay),
            // Plainly, like the other surfaces and for the same reason as the
            // bevel pair: a well is measured against the raised face it is cut
            // into, not against the page, so quantising it against the page
            // would push it toward contrast it is not supposed to have.
            surface_well: self.surface_well.map(plain),

            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),

            // Plainly, as surfaces. Each is measured against the raised ground
            // it is a step from, and a stripe that lands on its ground's entry
            // is a stripe this terminal cannot show: it disappears rather than
            // being pushed to a contrast it was never meant to have.
            status_danger_surface: plain(self.status_danger_surface),
            status_success_surface: plain(self.status_success_surface),
            status_warning_surface: plain(self.status_warning_surface),
            status_info_surface: plain(self.status_info_surface),

            row_hover: plain(self.row_hover),
            row_rule: plain(self.row_rule),
            row_selected: plain(self.row_selected),
            // Plainly, as the row tones are: a band that lands on its
            // neighbour's entry is a band this terminal cannot show.
            heat: self.heat.map(plain),

            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 bridge between the two halves of this crate: [`Theme`] is what a
    /// theme file says, [`Palette`](crate::Palette) is the subset
    /// [`frame`](crate::frame) and [`paint_bevel`](crate::paint_bevel) need. A
    /// consumer holding a `Theme` should not be assembling that by hand and
    /// picking the wrong surface for the well.
    #[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 a
    /// stripe, the heading a sunken strip, selection on the background alone,
    /// and a badge filled with its tone's surface and edged in the tone. A
    /// neutral badge fills with the hover's step, which shows on a striped row
    /// where the raised surface would vanish into the ground.
    #[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_0(self.heat[0])
            .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;

/// The AA-UI floor a non-text cue has to clear against what it sits on.
///
/// 3:1 rather than 4.5:1 because a status mark is a graphical object and not
/// text.
const UI_FLOOR: f32 = 3.0;

/// The palette a [`Fidelity`](crate::Fidelity) quantises into, and the rules for
/// landing a colour in it.
///
/// Public because a consumer carrying tokens of its own has to quantise them the
/// same way this crate quantises the ones it knows about. A divider or focus
/// ring a consumer derives from the authored border is its own token, but "a
/// colour that must stay legible against the page is quantised against the
/// page" is not its rule to reinvent.
#[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`.
    ///
    /// 256 resolves to makeover's fixed region rather than the whole table: the
    /// low sixteen are repaintable in every emulator, so a match landing there
    /// is a match against a colour the user may have moved out from under it.
    #[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 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 guaranteed to stay legible against `on`.
    ///
    /// [`legible`](Self::legible) with one ground at the 3:1 a border or ring
    /// needs.
    ///
    /// Only for a colour whose job is to be told apart from a known background.
    /// It answers "nearest entry that still contrasts with `on`" and has no
    /// notion of which side of `on` the answer should fall, so a pair of colours
    /// that must also stay apart from *each other* is the one thing it must not
    /// be used for: both get pushed onto the same contrasting entry. That is why
    /// the bevel edges go through [`plain`](Self::plain).
    #[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:?}"),
            }
        }
    }

    #[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));
    }
}