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
//! The terminal renderer for [`makeover_layout`].
//!
//! <!-- wiki: makeover-tui -->
//!
//! # Surfaces
//!
//! [`frame`] draws a region at a [`Depth`]. It paints the depth's fill where
//! [`Palette::shows`] says the fill differs from what is behind it, draws the
//! bevel around the outside, and returns the [`Rect`] left for content: one
//! cell in from each side an edge took. A fill begins and ends on a cell
//! boundary, and a frame has no corner radius.
//!
//! Above sixteen colours the bevel is drawn in half-blocks, and the two
//! corners where its tones meet carry both, one per half-cell. At
//! [`Fidelity::Ansi16`] and [`Fidelity::NoColor`] it is drawn in box-drawing
//! characters: doubled for [`Depth::Raised`], light for every other depth.
//!
//! # Overlays, selection and the focus ring
//!
//! [`Palette::fill`] answers `Fill::Overlay`, so [`Depth::Overlay`] is painted
//! from a description with no edge. `Theme::selection_on` and
//! `Theme::focus_ring` are derived from the theme's other tokens, so the
//! theme format has no key for either; `border-strong` is a divider.
//!
//! # Modules
//!
//! - [`table`] draws a described table through
//!   [`ratatui::widgets::Table`], measuring content and narrowing columns.
//! - [`text`] wraps styled runs in terminal cells.
//! - [`piece`] draws the renderer-local pieces; its docs say which of the
//!   vocabulary's members the host draws instead.
//! - `theme` (feature `theme`) loads a makeover theme into a [`Palette`]
//!   quantised for a [`Fidelity`].
//!
//! # Every colour is in the palette
//!
//! [`Palette`] holds the surfaces and bevel pair a frame needs and the
//! [`Tones`] text and tables are drawn in. The styles hold metrics and marks
//! only. A tone the palette leaves empty is said with a modifier instead.
//!
//! # No substitution
//!
//! [`Palette::fill`] returns `None` for an intent it has no colour for, and
//! [`frame`] then draws the edge alone. `Fill::Well` does not fall back to
//! `Fill::Page`.

#![forbid(unsafe_code)]

use makeover_layout::{Bevel, Depth, Edge, Fill};
use ratatui::buffer::Buffer;
use ratatui::layout::Rect;
use ratatui::style::Color;

/// The description this crate renders, re-exported, so a consumer names the
/// types every entry point takes without a dependency of its own.
pub use makeover_layout;

/// Whether the reader asked for less motion, as [`activity_lit`] takes it.
pub use makeover_timing::MotionPreference;

#[cfg(feature = "theme")]
pub mod theme;

#[cfg(feature = "theme")]
pub use theme::{LoadError, Quantize, Theme, ThemeError};

pub mod table;

pub mod text;

pub mod piece;

/// How many colours the terminal can show, as the caller recorded it.
///
/// [`frame`] and [`paint_bevel`] draw differently only at
/// [`Ansi16`](Self::Ansi16) and [`NoColor`](Self::NoColor), where depth is
/// carried by box-drawing glyphs; see [`separates_depth`](Self::separates_depth).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum Fidelity {
    /// No colour at all: the reader set `NO_COLOR`. Every role is drawn in the
    /// terminal's own ink and carried by a modifier, and depth by glyphs, as at
    /// [`Ansi16`](Self::Ansi16).
    NoColor,
    /// Sixteen colours. Depth is carried by glyphs.
    Ansi16,
    /// The 6x6x6 cube and the grey ramp.
    Ansi256,
    /// 24-bit.
    #[default]
    TrueColor,
}

impl Fidelity {
    /// Read the process environment: a non-empty `NO_COLOR` is
    /// [`NoColor`](Self::NoColor) whatever the terminal says, and otherwise
    /// `COLORTERM` and `TERM` decide as in [`from_env`](Self::from_env).
    #[must_use]
    pub fn detect() -> Self {
        Self::from_request(
            std::env::var_os("NO_COLOR").as_deref(),
            &std::env::var("COLORTERM").unwrap_or_default(),
            &std::env::var("TERM").unwrap_or_default(),
        )
    }

    /// [`detect`](Self::detect) with `NO_COLOR` passed in. An empty value is
    /// unset, as no-color.org defines it.
    fn from_request(no_color: Option<&std::ffi::OsStr>, colorterm: &str, term: &str) -> Self {
        if no_color.is_some_and(|value| !value.is_empty()) {
            return Self::NoColor;
        }
        Self::from_env(colorterm, term)
    }

    /// Decide from `COLORTERM` and `TERM` alone. There is no `NO_COLOR`
    /// input, so this never returns [`NoColor`](Self::NoColor).
    ///
    /// A `COLORTERM` containing `truecolor` or `24bit` is
    /// [`TrueColor`](Self::TrueColor). Otherwise `TERM` decides: `linux`,
    /// `vt100`, `vt220`, `ansi` and `dumb` are [`Ansi16`](Self::Ansi16); a name
    /// ending in `-direct` is `TrueColor`, one containing `256color` is
    /// [`Ansi256`](Self::Ansi256) and one containing `16color` is `Ansi16`.
    /// Any other name, and an empty one, is `TrueColor`.
    #[must_use]
    pub fn from_env(colorterm: &str, term: &str) -> Self {
        if colorterm.contains("truecolor") || colorterm.contains("24bit") {
            return Self::TrueColor;
        }
        // `-direct` is terminfo's name for 24-bit colour set directly, as in
        // `xterm-direct`, so it is the truecolor claim made in `TERM`.
        match term {
            "linux" | "vt100" | "vt220" | "ansi" | "dumb" => Self::Ansi16,
            _ if term.ends_with("-direct") => Self::TrueColor,
            _ if term.contains("256color") => Self::Ansi256,
            _ if term.contains("16color") => Self::Ansi16,
            _ => Self::TrueColor,
        }
    }

    /// Whether colour alone can tell a raised surface from a well here.
    #[must_use]
    pub const fn separates_depth(self) -> bool {
        !matches!(self, Self::Ansi16 | Self::NoColor)
    }
}

/// The resolved colours this renderer needs.
///
/// Supply them already quantised to whatever the terminal can show:
/// [`Palette::shows`] compares two colours for equality.
///
/// Every colour this crate draws with is here: the surfaces and bevel pair
/// [`frame`] needs, and the [`Tones`] text and tables are drawn in.
/// [`PieceStyle`](piece::PieceStyle) and [`TableStyle`](table::TableStyle) hold
/// metrics and marks only. A consumer with a loaded theme takes this from
/// `Theme::palette`; one that paints bevels and nothing else builds it with
/// [`Palette::new`] and leaves the tones empty.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct Palette {
    /// `surface-page`.
    pub page: Color,
    /// `surface-raised`.
    pub raised: Color,
    /// `surface-overlay`.
    pub overlay: Color,
    /// `surface-well`, when the theme has one.
    pub well: Option<Color>,
    /// `bevel-light`.
    pub bevel_light: Color,
    /// `bevel-dark`.
    pub bevel_dark: Color,
    /// What the terminal can show.
    pub fidelity: Fidelity,
    /// The colours text and tables are drawn in.
    pub tones: Tones,
}

/// The colours text, controls and tables are drawn in.
///
/// Each is optional. An empty one draws in the terminal's own ink, and
/// [`Ink`](crate::piece::Ink) says some roles with a modifier instead: muted
/// and disabled text dim, danger bold, an action underlined, a filled control
/// reversed, a sunken run dim. [`Tones::NONE`] leaves every role empty.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
#[non_exhaustive]
pub struct Tones {
    /// Ordinary content, and what a neutral tone reads as. `content-primary`.
    pub content: Option<Color>,
    /// Content one step back: a field's label, a column heading. `content-secondary`.
    pub secondary: Option<Color>,
    /// Content two steps back: a caption, a hint, a reading. `content-muted`.
    pub muted: Option<Color>,
    /// The label of a control that will not answer, fainter than any hint.
    /// `content-disabled`.
    pub disabled: Option<Color>,
    /// Text that goes somewhere, and a control's label. `action-primary`.
    pub action: Option<Color>,
    /// Text legible on [`action`](Self::action), for a control filled with it.
    pub on_action: Option<Color>,
    /// Something worth knowing and nothing to do about it. `status-info`.
    pub info: Option<Color>,
    /// Something finished and it worked. `status-success`.
    pub success: Option<Color>,
    /// Something the user should look at. `status-warning`.
    pub warning: Option<Color>,
    /// Something broken, or about to be destroyed. `status-danger`.
    pub danger: Option<Color>,
    /// The fill of an info badge. `info-surface`.
    pub info_surface: Option<Color>,
    /// The fill of a success badge. `success-surface`.
    pub success_surface: Option<Color>,
    /// The fill of a warning badge. `warning-surface`.
    pub warning_surface: Option<Color>,
    /// The fill of a danger badge. `danger-surface`.
    pub danger_surface: Option<Color>,
    /// The fill of a neutral badge. `row-hover`, the weight the tone fills sit at.
    pub neutral_surface: Option<Color>,
    /// A neutral badge's edge. `line-border`.
    pub border: Option<Color>,
    /// A surface set back from the one it sits on: a code run, a table's heading strip. `surface-sunken`.
    pub sunken: Option<Color>,
    /// What a table's rows sit on. `surface-raised`.
    pub ground: Option<Color>,
    /// What every second table row sits on. `surface-page`: a step of the
    /// theme's neutral ramp, not a tone of its own.
    pub stripe: Option<Color>,
    /// The row under the cursor. `row-selected`.
    pub selected: Option<Color>,
    /// `heat-0`, the quietest of the measure ramp's fills. Not read:
    /// [`Ink::heat`](crate::piece::Ink::heat) draws band 0 with no fill, as
    /// every renderer does.
    #[deprecated(
        since = "0.67.1",
        note = "band 0 draws no fill on every renderer, so nothing reads this"
    )]
    pub heat_0: Option<Color>,
    /// `heat-1`, the first measure band that draws a fill (`heat-1` to
    /// `heat-4`), each a background and never an ink.
    pub heat_1: Option<Color>,
    /// `heat-2`.
    pub heat_2: Option<Color>,
    /// `heat-3`.
    pub heat_3: Option<Color>,
    /// `heat-4`.
    pub heat_4: Option<Color>,
}

/// [`Tones::NONE`] and one setter per field, from one list of the fields.
///
/// `NONE` is a struct literal over the list, so a field added to [`Tones`] and
/// left out of the list fails to compile rather than going unset.
macro_rules! tone_setters {
    ($($(#[$attr:meta])* $field:ident),+ $(,)?) => {
        // A deprecated field is still a field: `NONE` sets it and its setter
        // writes it.
        #[allow(deprecated)]
        impl Tones {
            /// No colours at all: every role drawn in the terminal's own ink,
            /// and carried by modifiers.
            pub const NONE: Self = Self {
                $($field: None),+
            };

            $(
                #[doc = concat!("Set [`", stringify!($field), "`](Self::", stringify!($field), ").")]
                $(#[$attr])*
                #[must_use]
                pub const fn $field(mut self, color: Color) -> Self {
                    self.$field = Some(color);
                    self
                }
            )+
        }
    };
}

tone_setters!(
    content,
    secondary,
    muted,
    disabled,
    action,
    on_action,
    info,
    success,
    warning,
    danger,
    info_surface,
    success_surface,
    warning_surface,
    danger_surface,
    neutral_surface,
    border,
    sunken,
    ground,
    stripe,
    selected,
    #[deprecated(
        since = "0.67.1",
        note = "band 0 draws no fill on every renderer, so nothing reads this"
    )]
    heat_0,
    heat_1,
    heat_2,
    heat_3,
    heat_4,
);

impl Palette {
    /// Surfaces and a bevel pair at `fidelity`, with no well and no tones.
    #[must_use]
    pub const fn new(
        page: Color,
        raised: Color,
        overlay: Color,
        bevel_light: Color,
        bevel_dark: Color,
        fidelity: Fidelity,
    ) -> Self {
        Self {
            page,
            raised,
            overlay,
            well: None,
            bevel_light,
            bevel_dark,
            fidelity,
            tones: Tones::NONE,
        }
    }

    /// Set [`well`](Self::well).
    #[must_use]
    pub const fn well(mut self, well: Color) -> Self {
        self.well = Some(well);
        self
    }

    /// Set [`tones`](Self::tones).
    #[must_use]
    pub const fn tones(mut self, tones: Tones) -> Self {
        self.tones = tones;
        self
    }

    /// Resolve a surface intent, or `None` where this renderer has no colour
    /// for it: `Fill::Well` on a palette with no well, `Fill::Sunken`, and any
    /// intent this renderer does not know. No other intent is substituted.
    #[must_use]
    pub const fn fill(&self, fill: Fill) -> Option<Color> {
        match fill {
            Fill::Page => Some(self.page),
            Fill::Raised => Some(self.raised),
            Fill::Overlay => Some(self.overlay),
            Fill::Well => self.well,
            // Includes Fill::Sunken, which this renderer has no tone for: a
            // terminal cell has one background, so a surface set back by
            // colour alone is not a thing it can say. The chosen tab is drawn
            // forward instead.
            _ => None,
        }
    }

    /// Resolve a bevel edge intent.
    #[must_use]
    pub const fn edge(&self, edge: Edge) -> Color {
        match edge {
            Edge::Light => self.bevel_light,
            Edge::Dark => self.bevel_dark,
            // `Edge` is `#[non_exhaustive]`; an edge this renderer has not
            // learned is drawn as the border, the one line every surface
            // already has, and as the shadowed edge where no border is set.
            _ => match self.tones.border {
                Some(border) => border,
                None => self.bevel_dark,
            },
        }
    }

    /// Whether painting `fill` over `behind` would show anything: the two
    /// colours differ.
    #[must_use]
    pub fn shows(fill: Color, behind: Color) -> bool {
        fill != behind
    }

    /// Whether depth has to be carried by glyphs rather than by colour.
    ///
    /// True when the terminal cannot separate the two surfaces: at sixteen
    /// colours, and with no colour at all.
    #[must_use]
    pub const fn needs_glyph_depth(&self) -> bool {
        !self.fidelity.separates_depth()
    }
}

/// The characters a frame's edges and corners are drawn with, one per side.
///
/// [`BEVEL`] is drawn where colour separates depth. [`DOUBLE`] and [`LIGHT`]
/// are drawn where it does not: doubled for a raised surface, light for any
/// other.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct GlyphSet {
    pub(crate) top: &'static str,
    pub(crate) bottom: &'static str,
    pub(crate) left: &'static str,
    pub(crate) right: &'static str,
    pub(crate) top_left: &'static str,
    pub(crate) top_right: &'static str,
    pub(crate) bottom_left: &'static str,
    pub(crate) bottom_right: &'static str,
    /// Whether the two corners where light meets shadow carry both tones in
    /// one cell, foreground over background. Only the half-block set does;
    /// on the others both shared corners take the bottom-right tone.
    pub(crate) split_corners: bool,
}

/// Half-blocks, with split corners.
pub(crate) const BEVEL: GlyphSet = GlyphSet {
    top: "▀",
    bottom: "▄",
    left: "▌",
    right: "▐",
    top_left: "▛",
    // The two shared corners are the split ones: an upper half continues the
    // lit top edge while the lower half starts the shaded right edge, and the
    // mirror of that at bottom left.
    top_right: "▀",
    bottom_left: "▄",
    bottom_right: "▟",
    split_corners: true,
};

pub(crate) const LIGHT: GlyphSet = GlyphSet {
    top: "─",
    bottom: "─",
    left: "│",
    right: "│",
    top_left: "┌",
    top_right: "┐",
    bottom_left: "└",
    bottom_right: "┘",
    split_corners: false,
};

pub(crate) const DOUBLE: GlyphSet = GlyphSet {
    top: "═",
    bottom: "═",
    left: "║",
    right: "║",
    top_left: "╔",
    top_right: "╗",
    bottom_left: "╚",
    bottom_right: "╝",
    split_corners: false,
};

/// Paint a two-tone edge around the outside of `area`.
///
/// [`Bevel::edges`] picks the tones: the first takes the top and left, the
/// second the bottom and right, so a raised bevel is light at the top left and
/// an inset or pressed one is dark there. Above sixteen colours the edge is
/// drawn in half-blocks and the two corners where the tones meet carry both,
/// one per half-cell. At [`Fidelity::Ansi16`] and [`Fidelity::NoColor`] it is
/// the light box-drawing set, and both shared corners take the bottom-right
/// tone. [`Bevel::RaisedOpen`] leaves the bottom run undrawn, and the two
/// side runs continue down to the last row.
///
/// The area is clipped to the buffer, and one smaller than two cells either
/// way draws nothing. The edge takes a cell on each side; draw content in the
/// [`Rect`] [`frame`] returns.
pub fn paint_bevel(buf: &mut Buffer, area: Rect, bevel: Bevel, palette: &Palette) {
    paint_bevel_with(buf, area, bevel, palette, set_for(palette, None));
}

/// Whether the activity mark is lit, `elapsed` into a wait: the phase of
/// `makeover_timing::blink`. With motion reduced it is always lit.
///
/// ```
/// use makeover_tui::{MotionPreference, activity_lit};
/// use std::time::Duration;
///
/// assert!(activity_lit(Duration::from_millis(0), MotionPreference::Full));
/// assert!(!activity_lit(Duration::from_millis(600), MotionPreference::Full));
/// assert!(activity_lit(Duration::from_millis(1100), MotionPreference::Full));
/// // Motion off: lit, and it stays lit.
/// assert!(activity_lit(Duration::from_millis(600), MotionPreference::Reduced));
/// ```
#[must_use]
pub fn activity_lit(elapsed: std::time::Duration, motion: MotionPreference) -> bool {
    makeover_timing::blink(elapsed, motion).0
}

/// Which glyphs to draw with: [`BEVEL`] where colour separates depth,
/// otherwise [`DOUBLE`] for [`Depth::Raised`] and [`LIGHT`] for any other
/// depth or for `None`, a bevel drawn with no depth behind it.
fn set_for(palette: &Palette, depth: Option<Depth>) -> GlyphSet {
    if !palette.needs_glyph_depth() {
        return BEVEL;
    }
    match depth {
        Some(Depth::Raised) => DOUBLE,
        _ => LIGHT,
    }
}

fn paint_bevel_with(buf: &mut Buffer, area: Rect, bevel: Bevel, palette: &Palette, set: GlyphSet) {
    // Clipped to the buffer first: indexing a cell outside it panics, and a
    // layout that overshoots on a small terminal should lose the overshoot,
    // not the process.
    let area = area.intersection(*buf.area());
    if area.width < 2 || area.height < 2 {
        return;
    }
    let (top_left, bottom_right) = bevel.edges();
    let light = palette.edge(top_left);
    let dark = palette.edge(bottom_right);

    let (x0, y0) = (area.x, area.y);
    let (x1, y1) = (area.right() - 1, area.bottom() - 1);

    // Light first: top edge and left edge, corners included.
    for x in x0..=x1 {
        buf[(x, y0)].set_symbol(set.top).set_fg(light);
    }
    for y in y0..=y1 {
        buf[(x0, y)].set_symbol(set.left).set_fg(light);
    }
    // Dark second, so on a set without split corners the two shared ones land
    // on it by draw order alone.
    //
    // An open edge leaves the bottom run undrawn: three sides of a box, which
    // is what a folder tab is in a terminal. The right run still draws, and
    // the two corners that sit on the missing run are left alone so whatever
    // is under them keeps showing through.
    let closed = bevel.draws_bottom();
    if closed {
        for x in x0..=x1 {
            buf[(x, y1)].set_symbol(set.bottom).set_fg(dark);
        }
    }
    for y in y0..=y1 {
        buf[(x1, y)].set_symbol(set.right).set_fg(dark);
    }

    buf[(x0, y0)].set_symbol(set.top_left).set_fg(light);
    if closed {
        buf[(x1, y1)].set_symbol(set.bottom_right).set_fg(dark);
    }

    if !closed {
        // Only the lit corner is a corner now. The top-right one still marks
        // where the lit run hands over to the shaded one, and it takes the
        // same tone it would in a closed box.
        buf[(x1, y0)].set_symbol(set.top_right).set_fg(dark);
    } else if set.split_corners {
        // Where light meets shadow, both tones share the cell: the half the
        // glyph fills is the foreground and the half it leaves is the
        // background, so the corner is a transition rather than one edge
        // overrunning the other.
        buf[(x1, y0)]
            .set_symbol(set.top_right)
            .set_fg(light)
            .set_bg(dark);
        buf[(x0, y1)]
            .set_symbol(set.bottom_left)
            .set_fg(dark)
            .set_bg(light);
    } else {
        // Both shared corners to dark. Not arbitrary: it is the same rule
        // `makeover-immediate` produces by drawing its dark polyline second,
        // so a control does not change which corner is lit when it moves
        // between a terminal and a window. A single-stroke corner has no half
        // to give the other tone, so this is the only rule available to these
        // sets anyway.
        buf[(x1, y0)].set_symbol(set.top_right).set_fg(dark);
        buf[(x0, y1)].set_symbol(set.bottom_left).set_fg(dark);
    }
}

/// Draw a region at a given [`Depth`] and return the area left for content.
///
/// The area is clipped to the buffer. The depth's fill is painted only where
/// [`Palette::shows`] says it differs from the background of the area's
/// top-left cell.
/// A depth with a bevel draws it when the area is at least two cells either
/// way and returns the area one cell in on each side; otherwise the clipped
/// area comes back whole.
pub fn frame(buf: &mut Buffer, area: Rect, depth: Depth, palette: &Palette) -> Rect {
    // `paint_bevel_with`'s reason: what lies outside the buffer is not drawn.
    let area = area.intersection(*buf.area());
    if area.is_empty() {
        return area;
    }
    let behind = buf[(area.x, area.y)].bg;

    if let Some(color) = depth.fill().and_then(|f| palette.fill(f))
        && Palette::shows(color, behind)
    {
        for y in area.top()..area.bottom() {
            for x in area.left()..area.right() {
                buf[(x, y)].set_bg(color);
            }
        }
    }

    match depth.bevel() {
        Some(bevel) if area.width >= 2 && area.height >= 2 => {
            // Colour separates raised from well wherever it can. Where it
            // cannot, the glyphs do, and only then: a doubled frame on every
            // terminal would be shouting.
            let set = set_for(palette, Some(depth));
            paint_bevel_with(buf, area, bevel, palette, set);
            Rect::new(area.x + 1, area.y + 1, area.width - 2, area.height - 2)
        }
        _ => area,
    }
}

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

    fn palette(well: Option<Color>) -> Palette {
        let palette = Palette::new(
            Color::Indexed(7),
            Color::Indexed(15),
            Color::Indexed(8),
            Color::Indexed(15),
            Color::Indexed(0),
            Fidelity::TrueColor,
        );
        match well {
            Some(well) => palette.well(well),
            None => palette,
        }
    }

    fn buffer() -> Buffer {
        Buffer::empty(Rect::new(0, 0, 6, 4))
    }

    #[test]
    fn a_well_that_cannot_be_coloured_is_still_drawn() {
        // A theme with no surface-well token at all.
        let p = palette(None);
        let mut buf = buffer();
        frame(&mut buf, Rect::new(0, 0, 6, 4), Depth::Well, &p);
        // No fill was available, but the region still reads as recessed.
        assert_eq!(buf[(0, 0)].symbol(), BEVEL.top_left);
        assert_eq!(buf[(0, 0)].bg, Color::Reset);
    }

    #[test]
    fn a_fill_that_matches_its_surroundings_is_not_painted() {
        let p = palette(Some(Color::Indexed(7)));
        let mut buf = buffer();
        // Everything behind is already page-coloured, and the well quantised
        // onto it. Painting it would be a no-op that hides the real problem.
        for y in 0..4 {
            for x in 0..6 {
                buf[(x, y)].set_bg(Color::Indexed(7));
            }
        }
        frame(&mut buf, Rect::new(0, 0, 6, 4), Depth::Well, &p);
        assert!(!Palette::shows(Color::Indexed(7), Color::Indexed(7)));
        // The edge is what carries the meaning here.
        assert_eq!(buf[(5, 3)].symbol(), BEVEL.bottom_right);
    }

    #[test]
    fn a_visible_fill_is_painted() {
        let p = palette(Some(Color::Indexed(4)));
        let mut buf = buffer();
        frame(&mut buf, Rect::new(0, 0, 6, 4), Depth::Well, &p);
        assert_eq!(buf[(2, 2)].bg, Color::Indexed(4));
    }

    #[test]
    fn an_overlay_is_painted_and_left_unedged() {
        // `Palette::fill` answers `Fill::Overlay`, so `Depth::Overlay` needs
        // nothing beyond the route. This is the assertion that would catch the
        // route being lost.
        let p = palette(None);
        let mut buf = buffer();
        let inner = frame(&mut buf, Rect::new(0, 0, 6, 4), Depth::Overlay, &p);

        assert_eq!(buf[(2, 2)].bg, p.overlay);
        // A surface over the page is separated by the lift and by what sits
        // behind it, so it takes no edge, and with no edge drawn, nothing is
        // given up to one: the content area is the whole region.
        assert_eq!(buf[(0, 0)].symbol(), " ");
        assert_eq!(inner, Rect::new(0, 0, 6, 4));
    }

    #[test]
    fn the_light_falls_from_the_top_left() {
        let p = palette(None);
        let mut buf = buffer();
        paint_bevel(&mut buf, Rect::new(0, 0, 6, 4), Bevel::Raised, &p);
        assert_eq!(buf[(0, 0)].fg, p.bevel_light); // top-left
        assert_eq!(buf[(3, 0)].fg, p.bevel_light); // top edge
        assert_eq!(buf[(0, 2)].fg, p.bevel_light); // left edge
        assert_eq!(buf[(5, 3)].fg, p.bevel_dark); // bottom-right
        assert_eq!(buf[(3, 3)].fg, p.bevel_dark); // bottom edge
        assert_eq!(buf[(5, 2)].fg, p.bevel_dark); // right edge
    }

    // Half-cell glyphs divide the cell already, so the corner where light
    // meets shadow can hold both rather than picking one.
    #[test]
    fn the_shared_corners_carry_both_tones_when_the_glyph_can_split() {
        let p = palette(None);
        let mut buf = buffer();
        paint_bevel(&mut buf, Rect::new(0, 0, 6, 4), Bevel::Raised, &p);
        let top_right = &buf[(5, 0)];
        assert_eq!(top_right.fg, p.bevel_light);
        assert_eq!(top_right.bg, p.bevel_dark);
        let bottom_left = &buf[(0, 3)];
        assert_eq!(bottom_left.fg, p.bevel_dark);
        assert_eq!(bottom_left.bg, p.bevel_light);
    }

    // A single-stroke corner has no half to give the second tone, so the
    // box-drawing sets keep the old rule: both shared corners to dark, which
    // is what makeover-immediate produces by drawing its dark polyline second.
    // Changing that would move the lit corner between a terminal and a window.
    #[test]
    fn box_drawing_corners_stay_dark_and_match_the_immediate_renderer() {
        let p = Palette {
            fidelity: Fidelity::Ansi16,
            ..palette(None)
        };
        let mut buf = buffer();
        paint_bevel(&mut buf, Rect::new(0, 0, 6, 4), Bevel::Raised, &p);
        assert_eq!(buf[(5, 0)].symbol(), LIGHT.top_right);
        assert_eq!(buf[(5, 0)].fg, p.bevel_dark);
        assert_eq!(buf[(5, 0)].bg, Color::Reset, "a stroke has no second tone");
        assert_eq!(buf[(0, 3)].fg, p.bevel_dark);
    }

    // The whole outline, as a reader sees it. Asserted as glyphs because the
    // shape is the point: an even-weight edge on all four sides, which is what
    // box-drawing could not give.
    #[test]
    fn a_bevel_draws_an_even_outline_and_leaves_the_middle_alone() {
        let p = palette(None);
        let mut buf = Buffer::empty(Rect::new(0, 0, 5, 4));
        paint_bevel(&mut buf, Rect::new(0, 0, 5, 4), Bevel::Raised, &p);
        let rows: Vec<String> = (0..4)
            .map(|y| (0..5).map(|x| buf[(x, y)].symbol()).collect())
            .collect();
        assert_eq!(rows, vec!["▛▀▀▀▀", "▌   ▐", "▌   ▐", "▄▄▄▄▟"]);
    }

    #[test]
    fn pressing_swaps_the_lit_side() {
        let p = palette(None);
        let mut buf = buffer();
        paint_bevel(&mut buf, Rect::new(0, 0, 6, 4), Bevel::Raised.pressed(), &p);
        assert_eq!(buf[(0, 0)].fg, p.bevel_dark);
    }

    #[test]
    fn an_edge_costs_a_cell_on_every_side() {
        let p = palette(None);
        let mut buf = buffer();
        let inner = frame(&mut buf, Rect::new(0, 0, 6, 4), Depth::Raised, &p);
        assert_eq!(inner, Rect::new(1, 1, 4, 2));
        // Flat takes no cells, because it draws no edge.
        let same = frame(&mut buf, Rect::new(0, 0, 6, 4), Depth::Flat, &p);
        assert_eq!(same, Rect::new(0, 0, 6, 4));
    }

    #[test]
    fn sixteen_colours_carries_depth_in_the_glyphs_instead() {
        // Colour cannot separate raised from well here: the fill collapses on
        // most themes and an edge vanishes on all of them. The frame has to
        // say it some other way or the two become the same box.
        let p = Palette {
            fidelity: Fidelity::Ansi16,
            ..palette(None)
        };
        assert!(p.needs_glyph_depth());
        let mut raised = buffer();
        frame(&mut raised, Rect::new(0, 0, 6, 4), Depth::Raised, &p);
        let mut well = buffer();
        frame(&mut well, Rect::new(0, 0, 6, 4), Depth::Well, &p);
        assert_eq!(raised[(0, 0)].symbol(), DOUBLE.top_left);
        assert_eq!(well[(0, 0)].symbol(), LIGHT.top_left);
        assert_ne!(raised[(0, 0)].symbol(), well[(0, 0)].symbol());
    }

    #[test]
    fn above_sixteen_colours_the_glyphs_stay_out_of_it() {
        // The doubled fallback must not fire where colour already works, or
        // every modern terminal gets a heavier frame it did not need. What it
        // gets instead is the half-block bevel.
        for f in [Fidelity::Ansi256, Fidelity::TrueColor] {
            let p = Palette {
                fidelity: f,
                ..palette(Some(Color::Indexed(4)))
            };
            assert!(!p.needs_glyph_depth());
            let mut buf = buffer();
            frame(&mut buf, Rect::new(0, 0, 6, 4), Depth::Raised, &p);
            assert_eq!(
                buf[(0, 0)].symbol(),
                BEVEL.top_left,
                "{f:?} got a heavier frame"
            );
            assert_ne!(buf[(0, 0)].symbol(), DOUBLE.top_left);
        }
    }

    // Raised and well are both bevels and differ only in which way they are
    // lit, so above sixteen colours they draw the same glyphs and the tones
    // carry the difference. That is exactly what stops holding at Ansi16, and
    // why the doubled set exists.
    #[test]
    fn colour_alone_separates_raised_from_well_where_it_can() {
        let p = palette(Some(Color::Indexed(4)));
        let mut raised = buffer();
        frame(&mut raised, Rect::new(0, 0, 6, 4), Depth::Raised, &p);
        let mut well = buffer();
        frame(&mut well, Rect::new(0, 0, 6, 4), Depth::Well, &p);
        assert_eq!(raised[(0, 0)].symbol(), well[(0, 0)].symbol());
        assert_eq!(raised[(0, 0)].fg, p.bevel_light);
        assert_eq!(well[(0, 0)].fg, p.bevel_dark);
    }

    /// Set in the environment of the child [`detect_reads_the_process_environment`]
    /// starts, so the child test asserts and the ordinary run of it does not.
    const DETECT_CHILD: &str = "MAKEOVER_TUI_DETECT_CHILD";

    #[test]
    fn detect_reads_the_process_environment() {
        // The variables are set on a child running one test, so no other test
        // in this process sees them.
        let status = std::process::Command::new(std::env::current_exe().expect("the test binary"))
            .args(["--exact", "tests::detect_child", "--quiet"])
            .env(DETECT_CHILD, "1")
            .env("NO_COLOR", "1")
            .env("COLORTERM", "truecolor")
            .status()
            .expect("the test binary runs");
        assert!(status.success(), "the child saw {status}");
    }

    #[test]
    fn detect_child() {
        if std::env::var_os(DETECT_CHILD).is_none() {
            return;
        }
        assert_eq!(Fidelity::detect(), Fidelity::NoColor);
    }

    #[test]
    fn detection_defaults_generously_and_only_downgrades_on_evidence() {
        assert!(Fidelity::default().separates_depth());
        assert!(Fidelity::TrueColor.separates_depth());
        assert!(Fidelity::Ansi256.separates_depth());
        assert!(!Fidelity::Ansi16.separates_depth());
    }

    // Sixteen colours is reached by naming a console, never by failing to
    // recognise a terminal. `COLORTERM` is stripped by ssh and by every
    // multiplexer, so an unrecognised name carries no evidence at all, and a
    // caller quantising its palette off this answer would flatten a whole theme
    // on the strength of it.
    #[test]
    fn an_unrecognised_terminal_is_assumed_capable() {
        let f = Fidelity::from_env;
        assert_eq!(f("", "foot"), Fidelity::TrueColor);
        assert_eq!(f("", "xterm"), Fidelity::TrueColor);
        assert_eq!(f("", "screen"), Fidelity::TrueColor);
        assert_eq!(f("", ""), Fidelity::TrueColor);
    }

    #[test]
    fn no_color_wins_over_whatever_the_terminal_claims() {
        let f = Fidelity::from_request;
        let set = Some(std::ffi::OsStr::new("1"));
        assert_eq!(f(set, "truecolor", "xterm-256color"), Fidelity::NoColor);
        assert_eq!(f(set, "", "linux"), Fidelity::NoColor);
        assert_eq!(
            f(Some(std::ffi::OsStr::new("")), "truecolor", ""),
            Fidelity::TrueColor
        );
        assert_eq!(f(None, "", "linux"), Fidelity::Ansi16);
        assert!(!Fidelity::NoColor.separates_depth());
    }

    #[test]
    fn a_console_that_really_has_sixteen_colours_is_named() {
        let f = Fidelity::from_env;
        assert_eq!(f("", "linux"), Fidelity::Ansi16);
        assert_eq!(f("", "vt100"), Fidelity::Ansi16);
        assert_eq!(f("", "dumb"), Fidelity::Ansi16);
    }

    #[test]
    fn a_terminal_naming_its_depth_is_taken_at_its_word() {
        let f = Fidelity::from_env;
        assert_eq!(f("", "xterm-256color"), Fidelity::Ansi256);
        assert_eq!(f("", "screen-256color"), Fidelity::Ansi256);
        assert_eq!(f("", "xterm-direct"), Fidelity::TrueColor);
        assert_eq!(f("", "xterm-16color"), Fidelity::Ansi16);
        // And a claim of 24-bit beats the name, which is only ever a floor.
        assert_eq!(f("truecolor", "xterm-256color"), Fidelity::TrueColor);
        assert_eq!(f("24bit", "linux"), Fidelity::TrueColor);
    }

    #[test]
    fn a_frame_outside_the_buffer_is_clipped_rather_than_panicking() {
        let palette = palette(Some(Color::Rgb(40, 40, 40)));
        let mut buf = Buffer::empty(Rect::new(0, 0, 4, 3));
        for area in [Rect::new(2, 1, 6, 6), Rect::new(10, 10, 3, 3)] {
            frame(&mut buf, area, Depth::Raised, &palette);
            frame(&mut buf, area, Depth::Well, &palette);
        }
    }

    #[test]
    fn a_region_too_small_for_an_edge_is_left_alone() {
        let p = palette(None);
        let mut buf = buffer();
        let inner = frame(&mut buf, Rect::new(0, 0, 1, 1), Depth::Raised, &p);
        assert_eq!(inner, Rect::new(0, 0, 1, 1));
    }
}