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//! # Where fidelity does matter
37//!
38//! At [`Fidelity::Ansi16`] the depth vocabulary collapses outright: a well
39//! cannot be filled distinctly on most themes *and* a bevel loses an edge on
40//! every one of them, so a raised card and a well both read as a single-tone
41//! box. Colour cannot carry the distinction, so [`frame`] carries it with the
42//! glyphs instead.
43//!
44//! Above that, colour carries it and the glyph fallback never fires.
45//!
46//! [`Palette::shows`] is worth reading correctly in light of the numbers: it
47//! is **not** a low-colour workaround. It is a correctness check that a fill
48//! will be visible against what is behind it, and at truecolor it fires on
49//! exactly the two clamping themes, which is precisely when it should.
50//!
51//! # The correction this renderer forced
52//!
53//! [`makeover_layout::Fill`] briefly carried a `fallback` method, returning
54//! `Page` for `Well` so a consumer without `surface-well` had something to
55//! use. That is an answer for a renderer that can always paint a colour. Here
56//! it is actively wrong: page *is* the surface a well is usually cut into, so
57//! falling back to it produces the exact invisibility the fallback was meant
58//! to avoid.
59//!
60//! Substituting one intent for another is renderer policy, not description.
61//! The fallback moved out of the description and into
62//! `makeover-immediate`, where it belongs, which is the first thing a second
63//! renderer was built to find.
64
65#![forbid(unsafe_code)]
66
67use makeover_layout::{Bevel, Depth, Edge, Fill};
68use ratatui::buffer::Buffer;
69use ratatui::layout::Rect;
70use ratatui::style::Color;
71
72/// How many colours the terminal can actually show.
73///
74/// Only [`Fidelity::Ansi16`] changes what this crate draws. Above it, colour
75/// separates a raised surface from a well on every shipped theme, and the
76/// glyph fallback below never fires. Recorded rather than inferred, because a
77/// caller that quantised its palette knows the answer and this crate cannot
78/// recover it from the colours afterwards.
79#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
80pub enum Fidelity {
81    /// Sixteen colours. Depth cannot be carried by colour: a well collapses
82    /// onto its face on 18 of 31 themes and a bevel loses an edge on all 31.
83    Ansi16,
84    /// The 6x6x6 cube and the grey ramp. Enough on 27 of 31 themes.
85    Ansi256,
86    /// 24-bit. The only failures left belong to the theme, not the terminal.
87    #[default]
88    TrueColor,
89}
90
91impl Fidelity {
92    /// Read the terminal's own claim, from `COLORTERM` then `TERM`.
93    ///
94    /// Deliberately credulous. A terminal that understates itself costs a
95    /// slightly heavier frame; one that overstates itself was going to render
96    /// wrongly regardless of what this crate assumed.
97    #[must_use]
98    pub fn detect() -> Self {
99        let colorterm = std::env::var("COLORTERM").unwrap_or_default();
100        if colorterm.contains("truecolor") || colorterm.contains("24bit") {
101            return Self::TrueColor;
102        }
103        let term = std::env::var("TERM").unwrap_or_default();
104        if term.contains("256color") || term.contains("direct") {
105            return Self::Ansi256;
106        }
107        if term.is_empty() {
108            return Self::TrueColor;
109        }
110        Self::Ansi16
111    }
112
113    /// Whether colour alone can tell a raised surface from a well here.
114    #[must_use]
115    pub const fn separates_depth(self) -> bool {
116        !matches!(self, Self::Ansi16)
117    }
118}
119
120/// The resolved colours this renderer needs.
121///
122/// Supply them already quantised to whatever the terminal can show. That is
123/// what makes [`Palette::shows`] a plain inequality rather than a colour-space
124/// calculation: by the time a colour reaches here, the question of what the
125/// terminal will actually paint has been answered.
126#[derive(Debug, Clone, Copy, PartialEq, Eq)]
127pub struct Palette {
128    /// `surface-page`.
129    pub page: Color,
130    /// `surface-raised`.
131    pub raised: Color,
132    /// `surface-overlay`.
133    pub overlay: Color,
134    /// `surface-well`, absent on makeover before 2.3.0.
135    pub well: Option<Color>,
136    /// `bevel-light`.
137    pub bevel_light: Color,
138    /// `bevel-dark`.
139    pub bevel_dark: Color,
140    /// What the terminal can show. Defaults to [`Fidelity::TrueColor`].
141    pub fidelity: Fidelity,
142}
143
144impl Palette {
145    /// Resolve a surface intent, or `None` where the theme has no such colour.
146    ///
147    /// No substitution happens here. A missing intent stays missing, and
148    /// [`frame`] answers it with structure instead of with a different colour.
149    #[must_use]
150    pub const fn fill(&self, fill: Fill) -> Option<Color> {
151        match fill {
152            Fill::Page => Some(self.page),
153            Fill::Raised => Some(self.raised),
154            Fill::Overlay => Some(self.overlay),
155            Fill::Well => self.well,
156        }
157    }
158
159    /// Resolve a bevel edge intent.
160    #[must_use]
161    pub const fn edge(&self, edge: Edge) -> Color {
162        match edge {
163            Edge::Light => self.bevel_light,
164            Edge::Dark => self.bevel_dark,
165        }
166    }
167
168    /// Whether painting `fill` over `behind` would show anything.
169    ///
170    /// The whole of the terminal's problem in one predicate. On a truecolor
171    /// terminal this is almost always true; in sixteen colours it is false
172    /// often enough that a design relying on fills is a design that vanishes.
173    #[must_use]
174    pub fn shows(fill: Color, behind: Color) -> bool {
175        fill != behind
176    }
177
178    /// Whether this palette can express a bevel as two distinct edges.
179    ///
180    /// Measured, this is the wrong thing to worry about: the two edge colours
181    /// never quantise onto each other, at any depth, on any shipped theme.
182    /// What does happen is an edge vanishing into the *face* it is drawn on,
183    /// on every theme at sixteen colours. Kept because a hand-built palette
184    /// can still collide, and cheap to ask.
185    #[must_use]
186    pub fn two_tone(&self) -> bool {
187        self.bevel_light != self.bevel_dark
188    }
189
190    /// Whether depth has to be carried by glyphs rather than by colour.
191    ///
192    /// True when the terminal cannot separate the two surfaces, which is the
193    /// sixteen-colour case and nothing else.
194    #[must_use]
195    pub const fn needs_glyph_depth(&self) -> bool {
196        !self.fidelity.separates_depth()
197    }
198}
199
200/// Box-drawing characters for a frame's edges and corners.
201///
202/// Two sets, because at sixteen colours the glyphs are the only thing left to
203/// carry depth: a well cannot be filled distinctly and a bevel loses an edge,
204/// so a raised card and a well would otherwise be the same single-tone box.
205/// A doubled line reads as standing off the page and a light one as cut into
206/// it, which is the same claim the fill and the bevel make in colour.
207#[derive(Debug, Clone, Copy, PartialEq, Eq)]
208pub(crate) struct GlyphSet {
209    pub(crate) horizontal: &'static str,
210    pub(crate) vertical: &'static str,
211    pub(crate) top_left: &'static str,
212    pub(crate) top_right: &'static str,
213    pub(crate) bottom_left: &'static str,
214    pub(crate) bottom_right: &'static str,
215}
216
217pub(crate) const LIGHT: GlyphSet = GlyphSet {
218    horizontal: "─",
219    vertical: "│",
220    top_left: "┌",
221    top_right: "┐",
222    bottom_left: "└",
223    bottom_right: "┘",
224};
225
226pub(crate) const DOUBLE: GlyphSet = GlyphSet {
227    horizontal: "═",
228    vertical: "║",
229    top_left: "╔",
230    top_right: "╗",
231    bottom_left: "╚",
232    bottom_right: "╝",
233};
234
235/// Paint a two-tone edge around the outside of `area`.
236///
237/// Light takes the top and left, dark the bottom and right, and the two shared
238/// corners go to dark. That corner rule is not arbitrary: it is the same one
239/// `makeover-immediate` produces by drawing its dark polyline second, so a
240/// control does not change which corner is lit when it moves between a
241/// terminal and a window.
242///
243/// Costs a cell on each side, which a pixel renderer's bevel does not. Use the
244/// [`Rect`] returned by [`frame`] rather than assuming the area is intact.
245pub fn paint_bevel(buf: &mut Buffer, area: Rect, bevel: Bevel, palette: &Palette) {
246    paint_bevel_with(buf, area, bevel, palette, LIGHT);
247}
248
249fn paint_bevel_with(buf: &mut Buffer, area: Rect, bevel: Bevel, palette: &Palette, set: GlyphSet) {
250    if area.width < 2 || area.height < 2 {
251        return;
252    }
253    let (top_left, bottom_right) = bevel.edges();
254    let light = palette.edge(top_left);
255    let dark = palette.edge(bottom_right);
256
257    let (x0, y0) = (area.x, area.y);
258    let (x1, y1) = (area.right() - 1, area.bottom() - 1);
259
260    // Light first: top edge and left edge, corners included.
261    for x in x0..=x1 {
262        buf[(x, y0)].set_symbol(set.horizontal).set_fg(light);
263    }
264    for y in y0..=y1 {
265        buf[(x0, y)].set_symbol(set.vertical).set_fg(light);
266    }
267    // Dark second, so the two shared corners land on it.
268    for x in x0..=x1 {
269        buf[(x, y1)].set_symbol(set.horizontal).set_fg(dark);
270    }
271    for y in y0..=y1 {
272        buf[(x1, y)].set_symbol(set.vertical).set_fg(dark);
273    }
274
275    buf[(x0, y0)].set_symbol(set.top_left).set_fg(light);
276    buf[(x1, y0)].set_symbol(set.top_right).set_fg(dark);
277    buf[(x0, y1)].set_symbol(set.bottom_left).set_fg(dark);
278    buf[(x1, y1)].set_symbol(set.bottom_right).set_fg(dark);
279}
280
281/// Draw a region at a given [`Depth`] and return the area left for content.
282///
283/// The fill is painted only when it would be visible against what is already
284/// in the buffer. Everything else is the edge, which is why a well still reads
285/// as a well on a terminal that cannot colour one.
286pub fn frame(buf: &mut Buffer, area: Rect, depth: Depth, palette: &Palette) -> Rect {
287    if area.is_empty() {
288        return area;
289    }
290    let behind = buf[(area.x, area.y)].bg;
291
292    if let Some(color) = depth.fill().and_then(|f| palette.fill(f))
293        && Palette::shows(color, behind)
294    {
295        for y in area.top()..area.bottom() {
296            for x in area.left()..area.right() {
297                buf[(x, y)].set_bg(color);
298            }
299        }
300    }
301
302    match depth.bevel() {
303        Some(bevel) if area.width >= 2 && area.height >= 2 => {
304            // Colour separates raised from well wherever it can. Where it
305            // cannot, the glyphs do, and only then: a doubled frame on every
306            // terminal would be shouting.
307            let set = match (palette.needs_glyph_depth(), depth) {
308                (true, Depth::Raised) => DOUBLE,
309                _ => LIGHT,
310            };
311            paint_bevel_with(buf, area, bevel, palette, set);
312            Rect::new(area.x + 1, area.y + 1, area.width - 2, area.height - 2)
313        }
314        _ => area,
315    }
316}
317
318#[cfg(test)]
319mod tests {
320    use super::*;
321
322    fn palette(well: Option<Color>) -> Palette {
323        Palette {
324            page: Color::Indexed(7),
325            raised: Color::Indexed(15),
326            overlay: Color::Indexed(8),
327            well,
328            bevel_light: Color::Indexed(15),
329            bevel_dark: Color::Indexed(0),
330            fidelity: Fidelity::TrueColor,
331        }
332    }
333
334    fn buffer() -> Buffer {
335        Buffer::empty(Rect::new(0, 0, 6, 4))
336    }
337
338    #[test]
339    fn a_well_that_cannot_be_coloured_is_still_drawn() {
340        // The 18-of-31 case: no surface-well token at all.
341        let p = palette(None);
342        let mut buf = buffer();
343        frame(&mut buf, Rect::new(0, 0, 6, 4), Depth::Well, &p);
344        // No fill was available, but the region still reads as recessed.
345        assert_eq!(buf[(0, 0)].symbol(), LIGHT.top_left);
346        assert_eq!(buf[(0, 0)].bg, Color::Reset);
347    }
348
349    #[test]
350    fn a_fill_that_matches_its_surroundings_is_not_painted() {
351        let p = palette(Some(Color::Indexed(7)));
352        let mut buf = buffer();
353        // Everything behind is already page-coloured, and the well quantised
354        // onto it. Painting it would be a no-op that hides the real problem.
355        for y in 0..4 {
356            for x in 0..6 {
357                buf[(x, y)].set_bg(Color::Indexed(7));
358            }
359        }
360        frame(&mut buf, Rect::new(0, 0, 6, 4), Depth::Well, &p);
361        assert!(!Palette::shows(Color::Indexed(7), Color::Indexed(7)));
362        // The edge is what carries the meaning here.
363        assert_eq!(buf[(5, 3)].symbol(), LIGHT.bottom_right);
364    }
365
366    #[test]
367    fn a_visible_fill_is_painted() {
368        let p = palette(Some(Color::Indexed(4)));
369        let mut buf = buffer();
370        frame(&mut buf, Rect::new(0, 0, 6, 4), Depth::Well, &p);
371        assert_eq!(buf[(2, 2)].bg, Color::Indexed(4));
372    }
373
374    #[test]
375    fn the_light_falls_from_the_top_left_and_corners_go_dark() {
376        let p = palette(None);
377        let mut buf = buffer();
378        paint_bevel(&mut buf, Rect::new(0, 0, 6, 4), Bevel::Raised, &p);
379        assert_eq!(buf[(0, 0)].fg, p.bevel_light); // top-left
380        assert_eq!(buf[(3, 0)].fg, p.bevel_light); // top edge
381        assert_eq!(buf[(0, 2)].fg, p.bevel_light); // left edge
382        assert_eq!(buf[(5, 3)].fg, p.bevel_dark); // bottom-right
383        // The two shared corners go to dark, matching what the immediate
384        // renderer produces by drawing its dark polyline second.
385        assert_eq!(buf[(5, 0)].fg, p.bevel_dark);
386        assert_eq!(buf[(0, 3)].fg, p.bevel_dark);
387    }
388
389    #[test]
390    fn pressing_swaps_the_lit_side() {
391        let p = palette(None);
392        let mut buf = buffer();
393        paint_bevel(&mut buf, Rect::new(0, 0, 6, 4), Bevel::Raised.pressed(), &p);
394        assert_eq!(buf[(0, 0)].fg, p.bevel_dark);
395    }
396
397    #[test]
398    fn a_sixteen_colour_terminal_can_lose_the_second_tone() {
399        // Not a failure: one box is still a boundary. The palette says so
400        // rather than the renderer pretending otherwise.
401        let flat = Palette {
402            bevel_dark: Color::Indexed(15),
403            ..palette(None)
404        };
405        assert!(!flat.two_tone());
406        assert!(palette(None).two_tone());
407    }
408
409    #[test]
410    fn an_edge_costs_a_cell_on_every_side() {
411        let p = palette(None);
412        let mut buf = buffer();
413        let inner = frame(&mut buf, Rect::new(0, 0, 6, 4), Depth::Raised, &p);
414        assert_eq!(inner, Rect::new(1, 1, 4, 2));
415        // Flat takes no cells, because it draws no edge.
416        let same = frame(&mut buf, Rect::new(0, 0, 6, 4), Depth::Flat, &p);
417        assert_eq!(same, Rect::new(0, 0, 6, 4));
418    }
419
420    #[test]
421    fn sixteen_colours_carries_depth_in_the_glyphs_instead() {
422        // Colour cannot separate raised from well here: the fill collapses on
423        // most themes and an edge vanishes on all of them. The frame has to
424        // say it some other way or the two become the same box.
425        let p = Palette {
426            fidelity: Fidelity::Ansi16,
427            ..palette(None)
428        };
429        assert!(p.needs_glyph_depth());
430        let mut raised = buffer();
431        frame(&mut raised, Rect::new(0, 0, 6, 4), Depth::Raised, &p);
432        let mut well = buffer();
433        frame(&mut well, Rect::new(0, 0, 6, 4), Depth::Well, &p);
434        assert_eq!(raised[(0, 0)].symbol(), DOUBLE.top_left);
435        assert_eq!(well[(0, 0)].symbol(), LIGHT.top_left);
436        assert_ne!(raised[(0, 0)].symbol(), well[(0, 0)].symbol());
437    }
438
439    #[test]
440    fn above_sixteen_colours_the_glyphs_stay_out_of_it() {
441        // The fallback must not fire where colour already works, or every
442        // modern terminal gets a doubled frame it did not need.
443        for f in [Fidelity::Ansi256, Fidelity::TrueColor] {
444            let p = Palette {
445                fidelity: f,
446                ..palette(Some(Color::Indexed(4)))
447            };
448            assert!(!p.needs_glyph_depth());
449            let mut buf = buffer();
450            frame(&mut buf, Rect::new(0, 0, 6, 4), Depth::Raised, &p);
451            assert_eq!(
452                buf[(0, 0)].symbol(),
453                LIGHT.top_left,
454                "{f:?} got a heavier frame"
455            );
456        }
457    }
458
459    #[test]
460    fn detection_defaults_generously_and_only_downgrades_on_evidence() {
461        assert!(Fidelity::default().separates_depth());
462        assert!(Fidelity::TrueColor.separates_depth());
463        assert!(Fidelity::Ansi256.separates_depth());
464        assert!(!Fidelity::Ansi16.separates_depth());
465    }
466
467    #[test]
468    fn a_region_too_small_for_an_edge_is_left_alone() {
469        let p = palette(None);
470        let mut buf = buffer();
471        let inner = frame(&mut buf, Rect::new(0, 0, 1, 1), Depth::Raised, &p);
472        assert_eq!(inner, Rect::new(0, 0, 1, 1));
473    }
474}