Skip to main content

makeover_tui/
lib.rs

1//! The terminal renderer for [`makeover_layout`].
2//!
3//! <!-- wiki: makeover-tui -->
4//!
5//! Named for the target and not for ratatui, the same way
6//! `makeover-immediate` is named for the mode and not for egui.
7//!
8//! # What a terminal actually costs you
9//!
10//! Not colour. That was the original assumption here and it is wrong on any
11//! terminal built this decade. Measured across the 31 shipped themes
12//! (`makeover`'s `well_fidelity` example):
13//!
14//! | | ANSI-16 | ANSI-256 | truecolor |
15//! |---|---|---|---|
16//! | a well collapses onto its face | 18/31 | 4/31 | 2/31 |
17//! | at least one bevel edge vanishes into its face | 31/31 | 4/31 | 0 |
18//!
19//! The threshold is 256, not 24-bit, and the two failures that survive at
20//! truecolor are not terminal failures at all: they are the themes whose
21//! raised surface is already white, so the lightening clamps and the well
22//! lands exactly on its face. Those render identically in a browser.
23//! `makeover`'s own `well_is_distinct_from_its_face` test already names them.
24//!
25//! **What a terminal costs is geometry, and no amount of colour fixes it.**
26//! An edge occupies a whole cell on each side. A cell is roughly 8x17 pixels,
27//! so a one-pixel bevel becomes something an order of magnitude heavier, which
28//! is why [`frame`] hands back a shrunk [`Rect`] instead of pretending the
29//! region survived intact. There is nowhere to put a corner radius, so
30//! `radius_control` and `radius_container` mean the same thing here. A fill
31//! can only begin and end on a cell boundary.
32//!
33//! That is the constraint worth designing against. It does not improve, it is
34//! not detectable, and it applies equally to the best terminal ever written.
35//!
36//! What it does not mean is that the shape inside the cell stops mattering.
37//! Half of a cell is still addressable, and a bevel drawn in half-blocks reads
38//! as a lit edge where the same bevel in box-drawing reads as a line: `─` and
39//! `│` are one stroke through the middle, identical on all four sides, saying
40//! nothing about where the light is. Half-blocks also make the two corners
41//! where light meets shadow expressible, since a glyph that fills half a cell
42//! leaves the other half to the second tone.
43//!
44//! # Where fidelity does matter
45//!
46//! At [`Fidelity::Ansi16`] the depth vocabulary collapses outright: a well
47//! cannot be filled distinctly on most themes *and* a bevel loses an edge on
48//! every one of them, so a raised card and a well both read as a single-tone
49//! box. Colour cannot carry the distinction, so [`frame`] carries it with the
50//! glyphs instead.
51//!
52//! Above that, colour carries it and the glyph fallback never fires.
53//!
54//! [`Palette::shows`] is worth reading correctly in light of the numbers: it
55//! is **not** a low-colour workaround. It is a correctness check that a fill
56//! will be visible against what is behind it, and at truecolor it fires on
57//! exactly the two clamping themes, which is precisely when it should.
58//!
59//! # The correction this renderer forced
60//!
61//! [`makeover_layout::Fill`] briefly carried a `fallback` method, returning
62//! `Page` for `Well` so a consumer without `surface-well` had something to
63//! use. That is an answer for a renderer that can always paint a colour. Here
64//! it is actively wrong: page *is* the surface a well is usually cut into, so
65//! falling back to it produces the exact invisibility the fallback was meant
66//! to avoid.
67//!
68//! Substituting one intent for another is renderer policy, not description.
69//! The fallback moved out of the description and into
70//! `makeover-immediate`, where it belongs, which is the first thing a second
71//! renderer was built to find.
72
73#![forbid(unsafe_code)]
74
75use makeover_layout::{Bevel, Depth, Edge, Fill};
76use ratatui::buffer::Buffer;
77use ratatui::layout::Rect;
78use ratatui::style::Color;
79
80/// The description this crate renders, re-exported.
81///
82/// Every entry point here takes a type from it, so a consumer would otherwise
83/// have to depend on the description separately and keep two version
84/// requirements in step to name the argument it is already being handed.
85pub use makeover_layout;
86
87/// How many colours the terminal can actually show.
88///
89/// Only [`Fidelity::Ansi16`] changes what this crate draws. Above it, colour
90/// separates a raised surface from a well on every shipped theme, and the
91/// glyph fallback below never fires. Recorded rather than inferred, because a
92/// caller that quantised its palette knows the answer and this crate cannot
93/// recover it from the colours afterwards.
94#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
95pub enum Fidelity {
96    /// Sixteen colours. Depth cannot be carried by colour: a well collapses
97    /// onto its face on 18 of 31 themes and a bevel loses an edge on all 31.
98    Ansi16,
99    /// The 6x6x6 cube and the grey ramp. Enough on 27 of 31 themes.
100    Ansi256,
101    /// 24-bit. The only failures left belong to the theme, not the terminal.
102    #[default]
103    TrueColor,
104}
105
106impl Fidelity {
107    /// Read the terminal's own claim, from `COLORTERM` then `TERM`.
108    ///
109    /// Deliberately credulous, and the fall-through is where that is decided.
110    /// An unrecognised `TERM` is assumed capable, because the two wrong answers
111    /// do not cost the same: guessing [`TrueColor`](Self::TrueColor) on a
112    /// limited terminal costs some fidelity, and guessing
113    /// [`Ansi16`](Self::Ansi16) on a capable one throws away colour the user
114    /// paid for — and, for a caller that quantises its palette off this answer,
115    /// throws away the whole theme. `COLORTERM` is routinely stripped by ssh
116    /// and by multiplexers, so an unrecognised name is the common case rather
117    /// than the exotic one: `foot`, `xterm` and `screen` all land here.
118    ///
119    /// So sixteen colours is reached by naming the terminals that really have
120    /// them. The list is short and it does not grow: these are the fixed
121    /// consoles, and `TERM=linux` is the case this exists for — the Linux
122    /// virtual console, which is what an installer and a machine with no
123    /// desktop draw on.
124    #[must_use]
125    pub fn detect() -> Self {
126        Self::from_env(
127            &std::env::var("COLORTERM").unwrap_or_default(),
128            &std::env::var("TERM").unwrap_or_default(),
129        )
130    }
131
132    /// [`detect`](Self::detect) with the environment passed in, so the decision
133    /// can be tested without mutating a process-wide variable from a parallel
134    /// test.
135    #[must_use]
136    pub fn from_env(colorterm: &str, term: &str) -> Self {
137        if colorterm.contains("truecolor") || colorterm.contains("24bit") {
138            return Self::TrueColor;
139        }
140        match term {
141            "linux" | "vt100" | "vt220" | "ansi" | "dumb" => Self::Ansi16,
142            _ if term.contains("256color") || term.contains("direct") => Self::Ansi256,
143            _ => Self::TrueColor,
144        }
145    }
146
147    /// Whether colour alone can tell a raised surface from a well here.
148    #[must_use]
149    pub const fn separates_depth(self) -> bool {
150        !matches!(self, Self::Ansi16)
151    }
152}
153
154/// The resolved colours this renderer needs.
155///
156/// Supply them already quantised to whatever the terminal can show. That is
157/// what makes [`Palette::shows`] a plain inequality rather than a colour-space
158/// calculation: by the time a colour reaches here, the question of what the
159/// terminal will actually paint has been answered.
160#[derive(Debug, Clone, Copy, PartialEq, Eq)]
161pub struct Palette {
162    /// `surface-page`.
163    pub page: Color,
164    /// `surface-raised`.
165    pub raised: Color,
166    /// `surface-overlay`.
167    pub overlay: Color,
168    /// `surface-well`, absent on makeover before 2.3.0.
169    pub well: Option<Color>,
170    /// `bevel-light`.
171    pub bevel_light: Color,
172    /// `bevel-dark`.
173    pub bevel_dark: Color,
174    /// What the terminal can show. Defaults to [`Fidelity::TrueColor`].
175    pub fidelity: Fidelity,
176}
177
178impl Palette {
179    /// Resolve a surface intent, or `None` where this renderer has no colour
180    /// for it.
181    ///
182    /// No substitution happens here. A missing intent stays missing, and
183    /// [`frame`] answers it with structure instead of with a different colour.
184    /// That rule is what lets the wildcard below be a real answer rather than
185    /// a hole: [`Fill`] is `#[non_exhaustive]` from `makeover-layout` 0.4.0
186    /// onward, so the description can name a surface this renderer has not
187    /// learned to paint, and saying so is better than failing to build.
188    #[must_use]
189    pub const fn fill(&self, fill: Fill) -> Option<Color> {
190        match fill {
191            Fill::Page => Some(self.page),
192            Fill::Raised => Some(self.raised),
193            Fill::Overlay => Some(self.overlay),
194            Fill::Well => self.well,
195            // Includes Fill::Sunken, which this renderer has no tone for: a
196            // terminal cell has one background, so a surface set back by
197            // colour alone is not a thing it can say. The chosen tab is drawn
198            // forward instead.
199            _ => None,
200        }
201    }
202
203    /// Resolve a bevel edge intent.
204    #[must_use]
205    pub const fn edge(&self, edge: Edge) -> Color {
206        match edge {
207            Edge::Light => self.bevel_light,
208            Edge::Dark => self.bevel_dark,
209        }
210    }
211
212    /// Whether painting `fill` over `behind` would show anything.
213    ///
214    /// The whole of the terminal's problem in one predicate. On a truecolor
215    /// terminal this is almost always true; in sixteen colours it is false
216    /// often enough that a design relying on fills is a design that vanishes.
217    #[must_use]
218    pub fn shows(fill: Color, behind: Color) -> bool {
219        fill != behind
220    }
221
222    /// Whether this palette can express a bevel as two distinct edges.
223    ///
224    /// Measured, this is the wrong thing to worry about: the two edge colours
225    /// never quantise onto each other, at any depth, on any shipped theme.
226    /// What does happen is an edge vanishing into the *face* it is drawn on,
227    /// on every theme at sixteen colours. Kept because a hand-built palette
228    /// can still collide, and cheap to ask.
229    #[must_use]
230    pub fn two_tone(&self) -> bool {
231        self.bevel_light != self.bevel_dark
232    }
233
234    /// Whether depth has to be carried by glyphs rather than by colour.
235    ///
236    /// True when the terminal cannot separate the two surfaces, which is the
237    /// sixteen-colour case and nothing else.
238    #[must_use]
239    pub const fn needs_glyph_depth(&self) -> bool {
240        !self.fidelity.separates_depth()
241    }
242}
243
244/// The characters a frame's edges and corners are drawn with.
245///
246/// Per side rather than per axis, because the set that reads best as a bevel
247/// does not use the same glyph on opposite sides: a half-block edge is only
248/// half a cell, and which half it occupies is what says where the edge is.
249/// Box-drawing sets fill `top`/`bottom` and `left`/`right` with the same
250/// character and lose nothing by it.
251///
252/// Three sets. [`BEVEL`] is what a terminal that can show two tones gets. The
253/// other two exist because at sixteen colours the glyphs are the only thing
254/// left to carry depth: a well cannot be filled distinctly and a bevel loses
255/// an edge, so a raised card and a well would otherwise be the same
256/// single-tone box. A doubled line reads as standing off the page and a light
257/// one as cut into it, which is the same claim the fill and the bevel make in
258/// colour.
259#[derive(Debug, Clone, Copy, PartialEq, Eq)]
260pub(crate) struct GlyphSet {
261    pub(crate) top: &'static str,
262    pub(crate) bottom: &'static str,
263    pub(crate) left: &'static str,
264    pub(crate) right: &'static str,
265    pub(crate) top_left: &'static str,
266    pub(crate) top_right: &'static str,
267    pub(crate) bottom_left: &'static str,
268    pub(crate) bottom_right: &'static str,
269    /// Whether the two corners where light meets shadow carry both tones in
270    /// one cell, foreground over background.
271    ///
272    /// Only a half-cell glyph can: it already divides the cell, so the split
273    /// costs nothing and the corner reads as a transition rather than as one
274    /// edge overrunning the other. A box-drawing corner is a single stroke
275    /// with no such division, so those sets say `false` and both shared
276    /// corners go to dark — see [`paint_bevel_with`] for why that particular
277    /// fallback and not the other one.
278    pub(crate) split_corners: bool,
279}
280
281/// Half-blocks, which is what a bevel actually wants.
282///
283/// A cell is roughly 8x17 device pixels, so a half-block along the top and a
284/// half-cell column down the side are about the same number of pixels and the
285/// edge reads as even thickness. Box-drawing cannot do that: `─` and `│` are
286/// both a thin stroke through the middle of the cell, identical on all four
287/// sides, which draws a *line* rather than a lit edge and gives up the light
288/// model that makes a bevel legible.
289///
290/// Adopted from `alloy_tui`, which reached this independently and got there
291/// first (2026-07-26, two days before this crate existed).
292pub(crate) const BEVEL: GlyphSet = GlyphSet {
293    top: "▀",
294    bottom: "▄",
295    left: "▌",
296    right: "▐",
297    top_left: "▛",
298    // The two shared corners are the split ones: an upper half continues the
299    // lit top edge while the lower half starts the shaded right edge, and the
300    // mirror of that at bottom left.
301    top_right: "▀",
302    bottom_left: "▄",
303    bottom_right: "▟",
304    split_corners: true,
305};
306
307pub(crate) const LIGHT: GlyphSet = GlyphSet {
308    top: "─",
309    bottom: "─",
310    left: "│",
311    right: "│",
312    top_left: "┌",
313    top_right: "┐",
314    bottom_left: "└",
315    bottom_right: "┘",
316    split_corners: false,
317};
318
319pub(crate) const DOUBLE: GlyphSet = GlyphSet {
320    top: "═",
321    bottom: "═",
322    left: "║",
323    right: "║",
324    top_left: "╔",
325    top_right: "╗",
326    bottom_left: "╚",
327    bottom_right: "╝",
328    split_corners: false,
329};
330
331/// Paint a two-tone edge around the outside of `area`.
332///
333/// Light takes the top and left, dark the bottom and right. What happens at
334/// the two corners where they meet depends on what the terminal can show.
335/// Above sixteen colours the edge is drawn in half-blocks and those corners
336/// carry both tones, one per half-cell. At sixteen it is box-drawing, whose
337/// single stroke has no half to give, so both shared corners go to dark.
338///
339/// Costs a cell on each side, which a pixel renderer's bevel does not. Use the
340/// [`Rect`] returned by [`frame`] rather than assuming the area is intact.
341pub fn paint_bevel(buf: &mut Buffer, area: Rect, bevel: Bevel, palette: &Palette) {
342    paint_bevel_with(buf, area, bevel, palette, set_for(palette, None));
343}
344
345/// Which glyphs to draw with, given what the terminal can show.
346///
347/// Above sixteen colours the two tones are available and [`BEVEL`] renders
348/// them as light. At sixteen the tones collapse, so the box-drawing sets carry
349/// the distinction in weight instead, and `depth` picks which: a doubled frame
350/// for a raised card and a light one for everything else. `None` means the
351/// caller is drawing a bevel with no depth behind it, which is never the
352/// doubled case.
353fn set_for(palette: &Palette, depth: Option<Depth>) -> GlyphSet {
354    if !palette.needs_glyph_depth() {
355        return BEVEL;
356    }
357    match depth {
358        Some(Depth::Raised) => DOUBLE,
359        _ => LIGHT,
360    }
361}
362
363fn paint_bevel_with(buf: &mut Buffer, area: Rect, bevel: Bevel, palette: &Palette, set: GlyphSet) {
364    if area.width < 2 || area.height < 2 {
365        return;
366    }
367    let (top_left, bottom_right) = bevel.edges();
368    let light = palette.edge(top_left);
369    let dark = palette.edge(bottom_right);
370
371    let (x0, y0) = (area.x, area.y);
372    let (x1, y1) = (area.right() - 1, area.bottom() - 1);
373
374    // Light first: top edge and left edge, corners included.
375    for x in x0..=x1 {
376        buf[(x, y0)].set_symbol(set.top).set_fg(light);
377    }
378    for y in y0..=y1 {
379        buf[(x0, y)].set_symbol(set.left).set_fg(light);
380    }
381    // Dark second, so on a set without split corners the two shared ones land
382    // on it by draw order alone.
383    for x in x0..=x1 {
384        buf[(x, y1)].set_symbol(set.bottom).set_fg(dark);
385    }
386    for y in y0..=y1 {
387        buf[(x1, y)].set_symbol(set.right).set_fg(dark);
388    }
389
390    buf[(x0, y0)].set_symbol(set.top_left).set_fg(light);
391    buf[(x1, y1)].set_symbol(set.bottom_right).set_fg(dark);
392
393    if set.split_corners {
394        // Where light meets shadow, both tones share the cell: the half the
395        // glyph fills is the foreground and the half it leaves is the
396        // background, so the corner is a transition rather than one edge
397        // overrunning the other.
398        buf[(x1, y0)]
399            .set_symbol(set.top_right)
400            .set_fg(light)
401            .set_bg(dark);
402        buf[(x0, y1)]
403            .set_symbol(set.bottom_left)
404            .set_fg(dark)
405            .set_bg(light);
406    } else {
407        // Both shared corners to dark. Not arbitrary: it is the same rule
408        // `makeover-immediate` produces by drawing its dark polyline second,
409        // so a control does not change which corner is lit when it moves
410        // between a terminal and a window. A single-stroke corner has no half
411        // to give the other tone, so this is the only rule available to these
412        // sets anyway.
413        buf[(x1, y0)].set_symbol(set.top_right).set_fg(dark);
414        buf[(x0, y1)].set_symbol(set.bottom_left).set_fg(dark);
415    }
416}
417
418/// Draw a region at a given [`Depth`] and return the area left for content.
419///
420/// The fill is painted only when it would be visible against what is already
421/// in the buffer. Everything else is the edge, which is why a well still reads
422/// as a well on a terminal that cannot colour one.
423pub fn frame(buf: &mut Buffer, area: Rect, depth: Depth, palette: &Palette) -> Rect {
424    if area.is_empty() {
425        return area;
426    }
427    let behind = buf[(area.x, area.y)].bg;
428
429    if let Some(color) = depth.fill().and_then(|f| palette.fill(f))
430        && Palette::shows(color, behind)
431    {
432        for y in area.top()..area.bottom() {
433            for x in area.left()..area.right() {
434                buf[(x, y)].set_bg(color);
435            }
436        }
437    }
438
439    match depth.bevel() {
440        Some(bevel) if area.width >= 2 && area.height >= 2 => {
441            // Colour separates raised from well wherever it can. Where it
442            // cannot, the glyphs do, and only then: a doubled frame on every
443            // terminal would be shouting.
444            let set = set_for(palette, Some(depth));
445            paint_bevel_with(buf, area, bevel, palette, set);
446            Rect::new(area.x + 1, area.y + 1, area.width - 2, area.height - 2)
447        }
448        _ => area,
449    }
450}
451
452#[cfg(test)]
453mod tests {
454    use super::*;
455
456    fn palette(well: Option<Color>) -> Palette {
457        Palette {
458            page: Color::Indexed(7),
459            raised: Color::Indexed(15),
460            overlay: Color::Indexed(8),
461            well,
462            bevel_light: Color::Indexed(15),
463            bevel_dark: Color::Indexed(0),
464            fidelity: Fidelity::TrueColor,
465        }
466    }
467
468    fn buffer() -> Buffer {
469        Buffer::empty(Rect::new(0, 0, 6, 4))
470    }
471
472    #[test]
473    fn a_well_that_cannot_be_coloured_is_still_drawn() {
474        // The 18-of-31 case: no surface-well token at all.
475        let p = palette(None);
476        let mut buf = buffer();
477        frame(&mut buf, Rect::new(0, 0, 6, 4), Depth::Well, &p);
478        // No fill was available, but the region still reads as recessed.
479        assert_eq!(buf[(0, 0)].symbol(), BEVEL.top_left);
480        assert_eq!(buf[(0, 0)].bg, Color::Reset);
481    }
482
483    #[test]
484    fn a_fill_that_matches_its_surroundings_is_not_painted() {
485        let p = palette(Some(Color::Indexed(7)));
486        let mut buf = buffer();
487        // Everything behind is already page-coloured, and the well quantised
488        // onto it. Painting it would be a no-op that hides the real problem.
489        for y in 0..4 {
490            for x in 0..6 {
491                buf[(x, y)].set_bg(Color::Indexed(7));
492            }
493        }
494        frame(&mut buf, Rect::new(0, 0, 6, 4), Depth::Well, &p);
495        assert!(!Palette::shows(Color::Indexed(7), Color::Indexed(7)));
496        // The edge is what carries the meaning here.
497        assert_eq!(buf[(5, 3)].symbol(), BEVEL.bottom_right);
498    }
499
500    #[test]
501    fn a_visible_fill_is_painted() {
502        let p = palette(Some(Color::Indexed(4)));
503        let mut buf = buffer();
504        frame(&mut buf, Rect::new(0, 0, 6, 4), Depth::Well, &p);
505        assert_eq!(buf[(2, 2)].bg, Color::Indexed(4));
506    }
507
508    #[test]
509    fn the_light_falls_from_the_top_left() {
510        let p = palette(None);
511        let mut buf = buffer();
512        paint_bevel(&mut buf, Rect::new(0, 0, 6, 4), Bevel::Raised, &p);
513        assert_eq!(buf[(0, 0)].fg, p.bevel_light); // top-left
514        assert_eq!(buf[(3, 0)].fg, p.bevel_light); // top edge
515        assert_eq!(buf[(0, 2)].fg, p.bevel_light); // left edge
516        assert_eq!(buf[(5, 3)].fg, p.bevel_dark); // bottom-right
517        assert_eq!(buf[(3, 3)].fg, p.bevel_dark); // bottom edge
518        assert_eq!(buf[(5, 2)].fg, p.bevel_dark); // right edge
519    }
520
521    // Half-cell glyphs divide the cell already, so the corner where light
522    // meets shadow can hold both rather than picking one.
523    #[test]
524    fn the_shared_corners_carry_both_tones_when_the_glyph_can_split() {
525        let p = palette(None);
526        let mut buf = buffer();
527        paint_bevel(&mut buf, Rect::new(0, 0, 6, 4), Bevel::Raised, &p);
528        let top_right = &buf[(5, 0)];
529        assert_eq!(top_right.fg, p.bevel_light);
530        assert_eq!(top_right.bg, p.bevel_dark);
531        let bottom_left = &buf[(0, 3)];
532        assert_eq!(bottom_left.fg, p.bevel_dark);
533        assert_eq!(bottom_left.bg, p.bevel_light);
534    }
535
536    // A single-stroke corner has no half to give the second tone, so the
537    // box-drawing sets keep the old rule: both shared corners to dark, which
538    // is what makeover-immediate produces by drawing its dark polyline second.
539    // Changing that would move the lit corner between a terminal and a window.
540    #[test]
541    fn box_drawing_corners_stay_dark_and_match_the_immediate_renderer() {
542        let p = Palette {
543            fidelity: Fidelity::Ansi16,
544            ..palette(None)
545        };
546        let mut buf = buffer();
547        paint_bevel(&mut buf, Rect::new(0, 0, 6, 4), Bevel::Raised, &p);
548        assert_eq!(buf[(5, 0)].symbol(), LIGHT.top_right);
549        assert_eq!(buf[(5, 0)].fg, p.bevel_dark);
550        assert_eq!(buf[(5, 0)].bg, Color::Reset, "a stroke has no second tone");
551        assert_eq!(buf[(0, 3)].fg, p.bevel_dark);
552    }
553
554    // The whole outline, as a reader sees it. Asserted as glyphs because the
555    // shape is the point: an even-weight edge on all four sides, which is what
556    // box-drawing could not give.
557    #[test]
558    fn a_bevel_draws_an_even_outline_and_leaves_the_middle_alone() {
559        let p = palette(None);
560        let mut buf = Buffer::empty(Rect::new(0, 0, 5, 4));
561        paint_bevel(&mut buf, Rect::new(0, 0, 5, 4), Bevel::Raised, &p);
562        let rows: Vec<String> = (0..4)
563            .map(|y| (0..5).map(|x| buf[(x, y)].symbol()).collect())
564            .collect();
565        assert_eq!(rows, vec!["▛▀▀▀▀", "▌   ▐", "▌   ▐", "▄▄▄▄▟"]);
566    }
567
568    #[test]
569    fn pressing_swaps_the_lit_side() {
570        let p = palette(None);
571        let mut buf = buffer();
572        paint_bevel(&mut buf, Rect::new(0, 0, 6, 4), Bevel::Raised.pressed(), &p);
573        assert_eq!(buf[(0, 0)].fg, p.bevel_dark);
574    }
575
576    #[test]
577    fn a_sixteen_colour_terminal_can_lose_the_second_tone() {
578        // Not a failure: one box is still a boundary. The palette says so
579        // rather than the renderer pretending otherwise.
580        let flat = Palette {
581            bevel_dark: Color::Indexed(15),
582            ..palette(None)
583        };
584        assert!(!flat.two_tone());
585        assert!(palette(None).two_tone());
586    }
587
588    #[test]
589    fn an_edge_costs_a_cell_on_every_side() {
590        let p = palette(None);
591        let mut buf = buffer();
592        let inner = frame(&mut buf, Rect::new(0, 0, 6, 4), Depth::Raised, &p);
593        assert_eq!(inner, Rect::new(1, 1, 4, 2));
594        // Flat takes no cells, because it draws no edge.
595        let same = frame(&mut buf, Rect::new(0, 0, 6, 4), Depth::Flat, &p);
596        assert_eq!(same, Rect::new(0, 0, 6, 4));
597    }
598
599    #[test]
600    fn sixteen_colours_carries_depth_in_the_glyphs_instead() {
601        // Colour cannot separate raised from well here: the fill collapses on
602        // most themes and an edge vanishes on all of them. The frame has to
603        // say it some other way or the two become the same box.
604        let p = Palette {
605            fidelity: Fidelity::Ansi16,
606            ..palette(None)
607        };
608        assert!(p.needs_glyph_depth());
609        let mut raised = buffer();
610        frame(&mut raised, Rect::new(0, 0, 6, 4), Depth::Raised, &p);
611        let mut well = buffer();
612        frame(&mut well, Rect::new(0, 0, 6, 4), Depth::Well, &p);
613        assert_eq!(raised[(0, 0)].symbol(), DOUBLE.top_left);
614        assert_eq!(well[(0, 0)].symbol(), LIGHT.top_left);
615        assert_ne!(raised[(0, 0)].symbol(), well[(0, 0)].symbol());
616    }
617
618    #[test]
619    fn above_sixteen_colours_the_glyphs_stay_out_of_it() {
620        // The doubled fallback must not fire where colour already works, or
621        // every modern terminal gets a heavier frame it did not need. What it
622        // gets instead is the half-block bevel.
623        for f in [Fidelity::Ansi256, Fidelity::TrueColor] {
624            let p = Palette {
625                fidelity: f,
626                ..palette(Some(Color::Indexed(4)))
627            };
628            assert!(!p.needs_glyph_depth());
629            let mut buf = buffer();
630            frame(&mut buf, Rect::new(0, 0, 6, 4), Depth::Raised, &p);
631            assert_eq!(
632                buf[(0, 0)].symbol(),
633                BEVEL.top_left,
634                "{f:?} got a heavier frame"
635            );
636            assert_ne!(buf[(0, 0)].symbol(), DOUBLE.top_left);
637        }
638    }
639
640    // Raised and well are both bevels and differ only in which way they are
641    // lit, so above sixteen colours they draw the same glyphs and the tones
642    // carry the difference. That is exactly what stops holding at Ansi16, and
643    // why the doubled set exists.
644    #[test]
645    fn colour_alone_separates_raised_from_well_where_it_can() {
646        let p = palette(Some(Color::Indexed(4)));
647        let mut raised = buffer();
648        frame(&mut raised, Rect::new(0, 0, 6, 4), Depth::Raised, &p);
649        let mut well = buffer();
650        frame(&mut well, Rect::new(0, 0, 6, 4), Depth::Well, &p);
651        assert_eq!(raised[(0, 0)].symbol(), well[(0, 0)].symbol());
652        assert_eq!(raised[(0, 0)].fg, p.bevel_light);
653        assert_eq!(well[(0, 0)].fg, p.bevel_dark);
654    }
655
656    #[test]
657    fn detection_defaults_generously_and_only_downgrades_on_evidence() {
658        assert!(Fidelity::default().separates_depth());
659        assert!(Fidelity::TrueColor.separates_depth());
660        assert!(Fidelity::Ansi256.separates_depth());
661        assert!(!Fidelity::Ansi16.separates_depth());
662    }
663
664    // Sixteen colours is reached by naming a console, never by failing to
665    // recognise a terminal. `COLORTERM` is stripped by ssh and by every
666    // multiplexer, so an unrecognised name carries no evidence at all, and a
667    // caller quantising its palette off this answer would flatten a whole theme
668    // on the strength of it.
669    #[test]
670    fn an_unrecognised_terminal_is_assumed_capable() {
671        let f = Fidelity::from_env;
672        assert_eq!(f("", "foot"), Fidelity::TrueColor);
673        assert_eq!(f("", "xterm"), Fidelity::TrueColor);
674        assert_eq!(f("", "screen"), Fidelity::TrueColor);
675        assert_eq!(f("", ""), Fidelity::TrueColor);
676    }
677
678    #[test]
679    fn a_console_that_really_has_sixteen_colours_is_named() {
680        let f = Fidelity::from_env;
681        assert_eq!(f("", "linux"), Fidelity::Ansi16);
682        assert_eq!(f("", "vt100"), Fidelity::Ansi16);
683        assert_eq!(f("", "dumb"), Fidelity::Ansi16);
684    }
685
686    #[test]
687    fn a_terminal_naming_its_depth_is_taken_at_its_word() {
688        let f = Fidelity::from_env;
689        assert_eq!(f("", "xterm-256color"), Fidelity::Ansi256);
690        assert_eq!(f("", "screen-256color"), Fidelity::Ansi256);
691        assert_eq!(f("", "xterm-direct"), Fidelity::Ansi256);
692        // And a claim of 24-bit beats the name, which is only ever a floor.
693        assert_eq!(f("truecolor", "xterm-256color"), Fidelity::TrueColor);
694        assert_eq!(f("24bit", "linux"), Fidelity::TrueColor);
695    }
696
697    #[test]
698    fn a_region_too_small_for_an_edge_is_left_alone() {
699        let p = palette(None);
700        let mut buf = buffer();
701        let inner = frame(&mut buf, Rect::new(0, 0, 1, 1), Depth::Raised, &p);
702        assert_eq!(inner, Rect::new(0, 0, 1, 1));
703    }
704}