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 costs
9//!
10//! Geometry, not colour. Above sixteen colours colour separates every depth
11//! the vocabulary has. The two cases that still collapse at truecolor are
12//! themes whose raised surface is already white, so the well's lightening
13//! clamps onto its face; those render identically in a browser.
14//!
15//! **An edge occupies a whole cell on each side.** A cell is roughly 8x17
16//! pixels, so a one-pixel bevel becomes something an order of magnitude
17//! heavier, which is why [`frame`] hands back a shrunk [`Rect`] instead of
18//! pretending the region survived intact. There is nowhere to put a corner
19//! radius, so `radius_control` and `radius_container` mean the same thing here.
20//! A fill can only begin and end on a cell boundary. That is the constraint to
21//! design against: it does not improve and it is not detectable.
22//!
23//! What it does not mean is that the shape inside the cell stops mattering.
24//! Half of a cell is still addressable, and a bevel drawn in half-blocks reads
25//! as a lit edge where the same bevel in box-drawing reads as a line: `─` and
26//! `│` are one stroke through the middle, identical on all four sides, saying
27//! nothing about where the light is. Half-blocks also make the two corners
28//! where light meets shadow expressible, since a glyph that fills half a cell
29//! leaves the other half to the second tone.
30//!
31//! # Where fidelity does matter
32//!
33//! At [`Fidelity::Ansi16`], and at [`Fidelity::NoColor`], the depth vocabulary
34//! collapses outright: a well cannot be filled distinctly on most themes *and* a
35//! bevel loses an edge on every one of them, so a raised card and a well both
36//! read as a single-tone box. Colour cannot carry the distinction, so [`frame`] carries it with the
37//! glyphs instead.
38//!
39//! Above that, colour carries it and the glyph fallback never fires.
40//!
41//! [`Palette::shows`] is not a low-colour workaround. It is a correctness check
42//! that a fill will be visible against what is behind it, and at truecolor it
43//! fires on exactly the clamping themes, which is when it should.
44//!
45//! # Overlays, selection and the focus ring
46//!
47//! [`Palette::fill`] answers `Fill::Overlay`, so
48//! [`Depth::Overlay`] needs nothing beyond the
49//! route from a description. A test asserts that route, because a route nothing
50//! exercises is one a refactor can quietly lose.
51//!
52//! `Theme::selection_on` and `Theme::focus_ring` are DERIVED rather than
53//! authored, and the direction is one-way: an authored key can fall back to a
54//! derivation and break no theme on disk, while a key this crate started
55//! requiring would break every theme that lacks it. So the theme format does not
56//! change, and the promotion stays available for a theme that ever needs to tune
57//! either. Without them a port does selection with `REVERSED` for want of an
58//! on-accent foreground, and spends makeover's `border-strong` on a focus ring,
59//! which is a divider at 1.63:1 on Akari Dawn.
60//!
61//! # The table
62//!
63//! [`table`] is the one thing here that draws content rather than a surface. It
64//! is a mapping layer over [`ratatui::widgets::Table`] rather than a table
65//! implementation, because ratatui already lays tracks out, draws a header,
66//! highlights a row and scrolls. What it has no answer for is content
67//! measurement and narrowing, and those are what the module is.
68//!
69//! # `piece`, not `widget`
70//!
71//! `makeover-layout` owns `Region::Widget`, the tier between a primitive and
72//! `Region::Widget`: a named assembly of primitives that each renderer draws
73//! its own way. That is host-agnostic and sits *above* every renderer.
74//!
75//! This crate's [`piece`] module is the opposite end of the same stack:
76//! renderer-local, the answer to what a badge looks like in cells, taking a
77//! description plus what only a terminal knows. Two different things must not
78//! wear one word, least of all in a crate that has to implement the tier. Its
79//! types are [`piece::PieceStyle`], the marks, and [`piece::Ink`], the marks
80//! and the [`Palette`]'s tones resolved together.
81//!
82//! # Every colour is in the palette
83//!
84//! [`Palette`] holds the surfaces and bevel pair a frame needs and the
85//! [`Tones`] text and tables are drawn in. The styles hold metrics and marks
86//! only. A tone the palette leaves empty is said with a modifier instead, so a
87//! terminal with no colour to spend still separates every role.
88//!
89//! # The vocabulary's members are drawn by the host
90//!
91//! A meter, a control, a figure, facts, a form field and a chart are drawn by
92//! `quasi-tui`, which owns those types, on top of [`piece::Ink`] and [`text`].
93//! This crate draws what every terminal app needs whether or not it speaks
94//! that vocabulary: surfaces, tables, badges, waits and wrapped text.
95//!
96//! # Substitution is renderer policy
97//!
98//! Substituting one intent for another belongs to a renderer, never to the
99//! description. Falling back from `Fill::Well` to `Page` is an answer for a
100//! renderer that can always paint a colour; here it is wrong, because the page
101//! *is* the surface a well is usually cut into, so the substitution produces the
102//! exact invisibility it was meant to avoid. `makeover-immediate` wants that
103//! fallback and this renderer does not.
104
105#![forbid(unsafe_code)]
106
107use makeover_layout::{Bevel, Depth, Edge, Fill};
108use ratatui::buffer::Buffer;
109use ratatui::layout::Rect;
110use ratatui::style::Color;
111
112/// The description this crate renders, re-exported.
113///
114/// Every entry point here takes a type from it, so a consumer would otherwise
115/// have to depend on the description separately and keep two version
116/// requirements in step to name the argument it is already being handed.
117pub use makeover_layout;
118
119/// Whether the reader asked for less motion, as [`activity_lit`] takes it.
120pub use makeover_timing::MotionPreference;
121
122#[cfg(feature = "theme")]
123pub mod theme;
124
125#[cfg(feature = "theme")]
126pub use theme::{LoadError, Quantize, Theme, ThemeError};
127
128pub mod table;
129
130pub mod text;
131
132pub mod piece;
133
134/// How many colours the terminal can actually show.
135///
136/// Only [`Fidelity::Ansi16`] and [`Fidelity::NoColor`] change what this crate
137/// draws. Above them, colour
138/// separates a raised surface from a well on every shipped theme, and the
139/// glyph fallback below never fires. Recorded rather than inferred, because a
140/// caller that quantised its palette knows the answer and this crate cannot
141/// recover it from the colours afterwards.
142#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
143pub enum Fidelity {
144    /// No colour at all: the reader set `NO_COLOR`. Every role is drawn in the
145    /// terminal's own ink and carried by a modifier, and depth by glyphs, as at
146    /// [`Ansi16`](Self::Ansi16).
147    NoColor,
148    /// Sixteen colours. Depth cannot be carried by colour: a well collapses
149    /// onto its face on most themes and a bevel loses an edge on all of them.
150    Ansi16,
151    /// The 6x6x6 cube and the grey ramp. Enough to carry depth on nearly
152    /// every theme.
153    Ansi256,
154    /// 24-bit. The only failures left belong to the theme, not the terminal.
155    #[default]
156    TrueColor,
157}
158
159impl Fidelity {
160    /// Read the reader's request and then the terminal's claim: a non-empty
161    /// `NO_COLOR` is [`NoColor`](Self::NoColor) whatever the terminal says,
162    /// and otherwise `COLORTERM` then `TERM` decide, as [`from_env`](Self::from_env).
163    ///
164    /// Deliberately credulous, and the fall-through is where that is decided.
165    /// An unrecognised `TERM` is assumed capable, because the two wrong answers
166    /// do not cost the same: guessing [`TrueColor`](Self::TrueColor) on a
167    /// limited terminal costs some fidelity, and guessing
168    /// [`Ansi16`](Self::Ansi16) on a capable one throws away colour the user
169    /// paid for and, for a caller that quantises its palette off this answer,
170    /// throws away the whole theme. `COLORTERM` is routinely stripped by ssh
171    /// and by multiplexers, so an unrecognised name is the common case rather
172    /// than the exotic one: `foot`, `xterm` and `screen` all land here.
173    ///
174    /// So sixteen colours is reached by naming the terminals that really have
175    /// them. The list is short and it does not grow: these are the fixed
176    /// consoles, and `TERM=linux` is the case this exists for: the Linux
177    /// virtual console, which is what an installer and a machine with no
178    /// desktop draw on.
179    #[must_use]
180    pub fn detect() -> Self {
181        Self::from_request(
182            std::env::var_os("NO_COLOR").as_deref(),
183            &std::env::var("COLORTERM").unwrap_or_default(),
184            &std::env::var("TERM").unwrap_or_default(),
185        )
186    }
187
188    /// [`detect`](Self::detect) with `NO_COLOR` passed in. An empty value is
189    /// unset, as no-color.org defines it.
190    fn from_request(no_color: Option<&std::ffi::OsStr>, colorterm: &str, term: &str) -> Self {
191        if no_color.is_some_and(|value| !value.is_empty()) {
192            return Self::NoColor;
193        }
194        Self::from_env(colorterm, term)
195    }
196
197    /// [`detect`](Self::detect) with the environment passed in, so the decision
198    /// can be tested without mutating a process-wide variable from a parallel
199    /// test.
200    #[must_use]
201    pub fn from_env(colorterm: &str, term: &str) -> Self {
202        if colorterm.contains("truecolor") || colorterm.contains("24bit") {
203            return Self::TrueColor;
204        }
205        // `-direct` is terminfo's name for 24-bit colour set directly, as in
206        // `xterm-direct`, so it is the truecolor claim made in `TERM`.
207        match term {
208            "linux" | "vt100" | "vt220" | "ansi" | "dumb" => Self::Ansi16,
209            _ if term.ends_with("-direct") => Self::TrueColor,
210            _ if term.contains("256color") => Self::Ansi256,
211            _ if term.contains("16color") => Self::Ansi16,
212            _ => Self::TrueColor,
213        }
214    }
215
216    /// Whether colour alone can tell a raised surface from a well here.
217    #[must_use]
218    pub const fn separates_depth(self) -> bool {
219        !matches!(self, Self::Ansi16 | Self::NoColor)
220    }
221}
222
223/// The resolved colours this renderer needs.
224///
225/// Supply them already quantised to whatever the terminal can show. That is
226/// what makes [`Palette::shows`] a plain inequality rather than a colour-space
227/// calculation: by the time a colour reaches here, the question of what the
228/// terminal will actually paint has been answered.
229///
230/// Every colour this crate draws with is here: the surfaces and bevel pair
231/// [`frame`] needs, and the [`Tones`] text and tables are drawn in.
232/// [`PieceStyle`](piece::PieceStyle) and [`TableStyle`](table::TableStyle) hold
233/// metrics and marks only. A consumer with a loaded theme takes this from
234/// `Theme::palette`; one that paints bevels and nothing else builds it with
235/// [`Palette::new`] and leaves the tones empty.
236#[derive(Debug, Clone, Copy, PartialEq, Eq)]
237#[non_exhaustive]
238pub struct Palette {
239    /// `surface-page`.
240    pub page: Color,
241    /// `surface-raised`.
242    pub raised: Color,
243    /// `surface-overlay`.
244    pub overlay: Color,
245    /// `surface-well`, when the theme has one.
246    pub well: Option<Color>,
247    /// `bevel-light`.
248    pub bevel_light: Color,
249    /// `bevel-dark`.
250    pub bevel_dark: Color,
251    /// What the terminal can show.
252    pub fidelity: Fidelity,
253    /// The colours text and tables are drawn in.
254    pub tones: Tones,
255}
256
257/// The colours text, controls and tables are drawn in.
258///
259/// Each is optional, and an empty one is a real answer: the terminal's own
260/// ink. Where a role has no colour, the drawing says it with a modifier
261/// instead (muted text dims, a danger line is bold, a link is underlined, the
262/// cursor row is reversed), which is what a terminal with no colour to spend
263/// has left. [`Tones::NONE`] is that terminal.
264#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
265#[non_exhaustive]
266pub struct Tones {
267    /// Ordinary content, and what a neutral tone reads as. `content-primary`.
268    pub content: Option<Color>,
269    /// Content one step back: a field's label, a column heading. `content-secondary`.
270    pub secondary: Option<Color>,
271    /// Content two steps back: a caption, a hint, a reading. `content-muted`.
272    pub muted: Option<Color>,
273    /// The label of a control that will not answer, fainter than any hint.
274    /// `content-disabled`.
275    pub disabled: Option<Color>,
276    /// Text that goes somewhere, and a control's label. `action-primary`.
277    pub action: Option<Color>,
278    /// Text legible on [`action`](Self::action), for a control filled with it.
279    pub on_action: Option<Color>,
280    /// Something worth knowing and nothing to do about it. `status-info`.
281    pub info: Option<Color>,
282    /// Something finished and it worked. `status-success`.
283    pub success: Option<Color>,
284    /// Something the user should look at. `status-warning`.
285    pub warning: Option<Color>,
286    /// Something broken, or about to be destroyed. `status-danger`.
287    pub danger: Option<Color>,
288    /// The fill of an info badge. `info-surface`.
289    pub info_surface: Option<Color>,
290    /// The fill of a success badge. `success-surface`.
291    pub success_surface: Option<Color>,
292    /// The fill of a warning badge. `warning-surface`.
293    pub warning_surface: Option<Color>,
294    /// The fill of a danger badge. `danger-surface`.
295    pub danger_surface: Option<Color>,
296    /// The fill of a neutral badge. `row-hover`, the weight the tone fills sit at.
297    pub neutral_surface: Option<Color>,
298    /// A neutral badge's edge. `line-border`.
299    pub border: Option<Color>,
300    /// A surface set back from the one it sits on: a code run, a table's heading strip. `surface-sunken`.
301    pub sunken: Option<Color>,
302    /// What a table's rows sit on. `surface-raised`.
303    pub ground: Option<Color>,
304    /// What every second table row sits on. `surface-page`: a step of the
305    /// theme's neutral ramp, not a tone of its own.
306    pub stripe: Option<Color>,
307    /// The row under the cursor. `row-selected`.
308    pub selected: Option<Color>,
309    /// The measure ramp's fills, quietest first: `heat-0` to `heat-4`. A
310    /// background and never an ink, read through
311    /// [`Ink::heat`](crate::piece::Ink::heat).
312    pub heat_0: Option<Color>,
313    /// `heat-1`.
314    pub heat_1: Option<Color>,
315    /// `heat-2`.
316    pub heat_2: Option<Color>,
317    /// `heat-3`.
318    pub heat_3: Option<Color>,
319    /// `heat-4`.
320    pub heat_4: Option<Color>,
321}
322
323/// [`Tones::NONE`] and one setter per field, from one list of the fields.
324///
325/// `NONE` is a struct literal over the list, so a field added to [`Tones`] and
326/// left out of the list fails to compile rather than going unset.
327macro_rules! tone_setters {
328    ($($field:ident),+ $(,)?) => {
329        impl Tones {
330            /// No colours at all: every role drawn in the terminal's own ink,
331            /// and carried by modifiers.
332            pub const NONE: Self = Self {
333                $($field: None),+
334            };
335
336            $(
337                #[doc = concat!("Set [`", stringify!($field), "`](Self::", stringify!($field), ").")]
338                #[must_use]
339                pub const fn $field(mut self, color: Color) -> Self {
340                    self.$field = Some(color);
341                    self
342                }
343            )+
344        }
345    };
346}
347
348tone_setters!(
349    content,
350    secondary,
351    muted,
352    disabled,
353    action,
354    on_action,
355    info,
356    success,
357    warning,
358    danger,
359    info_surface,
360    success_surface,
361    warning_surface,
362    danger_surface,
363    neutral_surface,
364    border,
365    sunken,
366    ground,
367    stripe,
368    selected,
369    heat_0,
370    heat_1,
371    heat_2,
372    heat_3,
373    heat_4,
374);
375
376impl Palette {
377    /// Surfaces and a bevel pair at `fidelity`, with no well and no tones.
378    #[must_use]
379    pub const fn new(
380        page: Color,
381        raised: Color,
382        overlay: Color,
383        bevel_light: Color,
384        bevel_dark: Color,
385        fidelity: Fidelity,
386    ) -> Self {
387        Self {
388            page,
389            raised,
390            overlay,
391            well: None,
392            bevel_light,
393            bevel_dark,
394            fidelity,
395            tones: Tones::NONE,
396        }
397    }
398
399    /// Set [`well`](Self::well).
400    #[must_use]
401    pub const fn well(mut self, well: Color) -> Self {
402        self.well = Some(well);
403        self
404    }
405
406    /// Set [`tones`](Self::tones).
407    #[must_use]
408    pub const fn tones(mut self, tones: Tones) -> Self {
409        self.tones = tones;
410        self
411    }
412
413    /// Resolve a surface intent, or `None` where this renderer has no colour
414    /// for it.
415    ///
416    /// No substitution happens here. A missing intent stays missing, and
417    /// [`frame`] answers it with structure instead of with a different colour.
418    /// That rule is what lets the wildcard below be a real answer rather than
419    /// a hole: [`Fill`] is `#[non_exhaustive]`, so the description can name a
420    /// surface this renderer has not learned to paint, and saying so is better
421    /// than failing to build.
422    #[must_use]
423    pub const fn fill(&self, fill: Fill) -> Option<Color> {
424        match fill {
425            Fill::Page => Some(self.page),
426            Fill::Raised => Some(self.raised),
427            Fill::Overlay => Some(self.overlay),
428            Fill::Well => self.well,
429            // Includes Fill::Sunken, which this renderer has no tone for: a
430            // terminal cell has one background, so a surface set back by
431            // colour alone is not a thing it can say. The chosen tab is drawn
432            // forward instead.
433            _ => None,
434        }
435    }
436
437    /// Resolve a bevel edge intent.
438    #[must_use]
439    pub const fn edge(&self, edge: Edge) -> Color {
440        match edge {
441            Edge::Light => self.bevel_light,
442            Edge::Dark => self.bevel_dark,
443            // `Edge` is `#[non_exhaustive]`; an edge this renderer has not
444            // learned is drawn as the border, the one line every surface
445            // already has, and as the shadowed edge where no border is set.
446            _ => match self.tones.border {
447                Some(border) => border,
448                None => self.bevel_dark,
449            },
450        }
451    }
452
453    /// Whether painting `fill` over `behind` would show anything.
454    ///
455    /// The whole of the terminal's problem in one predicate. On a truecolor
456    /// terminal this is almost always true; in sixteen colours it is false
457    /// often enough that a design relying on fills is a design that vanishes.
458    #[must_use]
459    pub fn shows(fill: Color, behind: Color) -> bool {
460        fill != behind
461    }
462
463    /// Whether depth has to be carried by glyphs rather than by colour.
464    ///
465    /// True when the terminal cannot separate the two surfaces: at sixteen
466    /// colours, and with no colour at all.
467    #[must_use]
468    pub const fn needs_glyph_depth(&self) -> bool {
469        !self.fidelity.separates_depth()
470    }
471}
472
473/// The characters a frame's edges and corners are drawn with.
474///
475/// Per side rather than per axis, because the set that reads best as a bevel
476/// does not use the same glyph on opposite sides: a half-block edge is only
477/// half a cell, and which half it occupies is what says where the edge is.
478/// Box-drawing sets fill `top`/`bottom` and `left`/`right` with the same
479/// character and lose nothing by it.
480///
481/// Three sets. [`BEVEL`] is what a terminal that can show two tones gets. The
482/// other two exist because at sixteen colours the glyphs are the only thing
483/// left to carry depth: a well cannot be filled distinctly and a bevel loses
484/// an edge, so a raised card and a well would otherwise be the same
485/// single-tone box. A doubled line reads as standing off the page and a light
486/// one as cut into it, which is the same claim the fill and the bevel make in
487/// colour.
488#[derive(Debug, Clone, Copy, PartialEq, Eq)]
489pub(crate) struct GlyphSet {
490    pub(crate) top: &'static str,
491    pub(crate) bottom: &'static str,
492    pub(crate) left: &'static str,
493    pub(crate) right: &'static str,
494    pub(crate) top_left: &'static str,
495    pub(crate) top_right: &'static str,
496    pub(crate) bottom_left: &'static str,
497    pub(crate) bottom_right: &'static str,
498    /// Whether the two corners where light meets shadow carry both tones in
499    /// one cell, foreground over background.
500    ///
501    /// Only a half-cell glyph can: it already divides the cell, so the split
502    /// costs nothing and the corner reads as a transition rather than as one
503    /// edge overrunning the other. A box-drawing corner is a single stroke
504    /// with no such division, so those sets say `false` and both shared
505    /// corners go to dark. See [`paint_bevel_with`] for why that particular
506    /// fallback and not the other one.
507    pub(crate) split_corners: bool,
508}
509
510/// Half-blocks, which is what a bevel actually wants.
511///
512/// A cell is roughly 8x17 device pixels, so a half-block along the top and a
513/// half-cell column down the side are about the same number of pixels and the
514/// edge reads as even thickness. Box-drawing cannot do that: `─` and `│` are
515/// both a thin stroke through the middle of the cell, identical on all four
516/// sides, which draws a *line* rather than a lit edge and gives up the light
517/// model that makes a bevel legible.
518pub(crate) const BEVEL: GlyphSet = GlyphSet {
519    top: "▀",
520    bottom: "▄",
521    left: "▌",
522    right: "▐",
523    top_left: "▛",
524    // The two shared corners are the split ones: an upper half continues the
525    // lit top edge while the lower half starts the shaded right edge, and the
526    // mirror of that at bottom left.
527    top_right: "▀",
528    bottom_left: "▄",
529    bottom_right: "▟",
530    split_corners: true,
531};
532
533pub(crate) const LIGHT: GlyphSet = GlyphSet {
534    top: "─",
535    bottom: "─",
536    left: "│",
537    right: "│",
538    top_left: "┌",
539    top_right: "┐",
540    bottom_left: "└",
541    bottom_right: "┘",
542    split_corners: false,
543};
544
545pub(crate) const DOUBLE: GlyphSet = GlyphSet {
546    top: "═",
547    bottom: "═",
548    left: "║",
549    right: "║",
550    top_left: "╔",
551    top_right: "╗",
552    bottom_left: "╚",
553    bottom_right: "╝",
554    split_corners: false,
555};
556
557/// Paint a two-tone edge around the outside of `area`.
558///
559/// Light takes the top and left, dark the bottom and right. What happens at
560/// the two corners where they meet depends on what the terminal can show.
561/// Above sixteen colours the edge is drawn in half-blocks and those corners
562/// carry both tones, one per half-cell. At sixteen it is box-drawing, whose
563/// single stroke has no half to give, so both shared corners go to dark.
564///
565/// Costs a cell on each side, which a pixel renderer's bevel does not. Use the
566/// [`Rect`] returned by [`frame`] rather than assuming the area is intact.
567pub fn paint_bevel(buf: &mut Buffer, area: Rect, bevel: Bevel, palette: &Palette) {
568    paint_bevel_with(buf, area, bevel, palette, set_for(palette, None));
569}
570
571/// Whether the activity mark is lit, this far into a wait.
572///
573/// Which of the activity mark's two cells to draw, `elapsed` into a wait, so
574/// that `piece::activity` can stay a pure drawing and this crate can still hold
575/// no clock. The phase is `makeover_timing::blink`'s.
576///
577/// ```
578/// use makeover_tui::{MotionPreference, activity_lit};
579/// use std::time::Duration;
580///
581/// assert!(activity_lit(Duration::from_millis(0), MotionPreference::Full));
582/// assert!(!activity_lit(Duration::from_millis(600), MotionPreference::Full));
583/// assert!(activity_lit(Duration::from_millis(1100), MotionPreference::Full));
584/// // Motion off: lit, and it stays lit.
585/// assert!(activity_lit(Duration::from_millis(600), MotionPreference::Reduced));
586/// ```
587#[must_use]
588pub fn activity_lit(elapsed: std::time::Duration, motion: MotionPreference) -> bool {
589    makeover_timing::blink(elapsed, motion).0
590}
591
592/// Which glyphs to draw with, given what the terminal can show.
593///
594/// Above sixteen colours the two tones are available and [`BEVEL`] renders
595/// them as light. At sixteen the tones collapse, so the box-drawing sets carry
596/// the distinction in weight instead, and `depth` picks which: a doubled frame
597/// for a raised card and a light one for everything else. `None` means the
598/// caller is drawing a bevel with no depth behind it, which is never the
599/// doubled case.
600fn set_for(palette: &Palette, depth: Option<Depth>) -> GlyphSet {
601    if !palette.needs_glyph_depth() {
602        return BEVEL;
603    }
604    match depth {
605        Some(Depth::Raised) => DOUBLE,
606        _ => LIGHT,
607    }
608}
609
610fn paint_bevel_with(buf: &mut Buffer, area: Rect, bevel: Bevel, palette: &Palette, set: GlyphSet) {
611    // Clipped to the buffer first: indexing a cell outside it panics, and a
612    // layout that overshoots on a small terminal should lose the overshoot,
613    // not the process.
614    let area = area.intersection(*buf.area());
615    if area.width < 2 || area.height < 2 {
616        return;
617    }
618    let (top_left, bottom_right) = bevel.edges();
619    let light = palette.edge(top_left);
620    let dark = palette.edge(bottom_right);
621
622    let (x0, y0) = (area.x, area.y);
623    let (x1, y1) = (area.right() - 1, area.bottom() - 1);
624
625    // Light first: top edge and left edge, corners included.
626    for x in x0..=x1 {
627        buf[(x, y0)].set_symbol(set.top).set_fg(light);
628    }
629    for y in y0..=y1 {
630        buf[(x0, y)].set_symbol(set.left).set_fg(light);
631    }
632    // Dark second, so on a set without split corners the two shared ones land
633    // on it by draw order alone.
634    //
635    // An open edge leaves the bottom run undrawn: three sides of a box, which
636    // is what a folder tab is in a terminal. The right run still draws, and
637    // the two corners that sit on the missing run are left alone so whatever
638    // is under them keeps showing through.
639    let closed = bevel.draws_bottom();
640    if closed {
641        for x in x0..=x1 {
642            buf[(x, y1)].set_symbol(set.bottom).set_fg(dark);
643        }
644    }
645    for y in y0..=y1 {
646        buf[(x1, y)].set_symbol(set.right).set_fg(dark);
647    }
648
649    buf[(x0, y0)].set_symbol(set.top_left).set_fg(light);
650    if closed {
651        buf[(x1, y1)].set_symbol(set.bottom_right).set_fg(dark);
652    }
653
654    if !closed {
655        // Only the lit corner is a corner now. The top-right one still marks
656        // where the lit run hands over to the shaded one, and it takes the
657        // same tone it would in a closed box.
658        buf[(x1, y0)].set_symbol(set.top_right).set_fg(dark);
659    } else if set.split_corners {
660        // Where light meets shadow, both tones share the cell: the half the
661        // glyph fills is the foreground and the half it leaves is the
662        // background, so the corner is a transition rather than one edge
663        // overrunning the other.
664        buf[(x1, y0)]
665            .set_symbol(set.top_right)
666            .set_fg(light)
667            .set_bg(dark);
668        buf[(x0, y1)]
669            .set_symbol(set.bottom_left)
670            .set_fg(dark)
671            .set_bg(light);
672    } else {
673        // Both shared corners to dark. Not arbitrary: it is the same rule
674        // `makeover-immediate` produces by drawing its dark polyline second,
675        // so a control does not change which corner is lit when it moves
676        // between a terminal and a window. A single-stroke corner has no half
677        // to give the other tone, so this is the only rule available to these
678        // sets anyway.
679        buf[(x1, y0)].set_symbol(set.top_right).set_fg(dark);
680        buf[(x0, y1)].set_symbol(set.bottom_left).set_fg(dark);
681    }
682}
683
684/// Draw a region at a given [`Depth`] and return the area left for content.
685///
686/// The fill is painted only when it would be visible against what is already
687/// in the buffer. Everything else is the edge, which is why a well still reads
688/// as a well on a terminal that cannot colour one.
689pub fn frame(buf: &mut Buffer, area: Rect, depth: Depth, palette: &Palette) -> Rect {
690    // `paint_bevel_with`'s reason: what lies outside the buffer is not drawn.
691    let area = area.intersection(*buf.area());
692    if area.is_empty() {
693        return area;
694    }
695    let behind = buf[(area.x, area.y)].bg;
696
697    if let Some(color) = depth.fill().and_then(|f| palette.fill(f))
698        && Palette::shows(color, behind)
699    {
700        for y in area.top()..area.bottom() {
701            for x in area.left()..area.right() {
702                buf[(x, y)].set_bg(color);
703            }
704        }
705    }
706
707    match depth.bevel() {
708        Some(bevel) if area.width >= 2 && area.height >= 2 => {
709            // Colour separates raised from well wherever it can. Where it
710            // cannot, the glyphs do, and only then: a doubled frame on every
711            // terminal would be shouting.
712            let set = set_for(palette, Some(depth));
713            paint_bevel_with(buf, area, bevel, palette, set);
714            Rect::new(area.x + 1, area.y + 1, area.width - 2, area.height - 2)
715        }
716        _ => area,
717    }
718}
719
720#[cfg(test)]
721mod tests {
722    use super::*;
723
724    fn palette(well: Option<Color>) -> Palette {
725        let palette = Palette::new(
726            Color::Indexed(7),
727            Color::Indexed(15),
728            Color::Indexed(8),
729            Color::Indexed(15),
730            Color::Indexed(0),
731            Fidelity::TrueColor,
732        );
733        match well {
734            Some(well) => palette.well(well),
735            None => palette,
736        }
737    }
738
739    fn buffer() -> Buffer {
740        Buffer::empty(Rect::new(0, 0, 6, 4))
741    }
742
743    #[test]
744    fn a_well_that_cannot_be_coloured_is_still_drawn() {
745        // A theme with no surface-well token at all.
746        let p = palette(None);
747        let mut buf = buffer();
748        frame(&mut buf, Rect::new(0, 0, 6, 4), Depth::Well, &p);
749        // No fill was available, but the region still reads as recessed.
750        assert_eq!(buf[(0, 0)].symbol(), BEVEL.top_left);
751        assert_eq!(buf[(0, 0)].bg, Color::Reset);
752    }
753
754    #[test]
755    fn a_fill_that_matches_its_surroundings_is_not_painted() {
756        let p = palette(Some(Color::Indexed(7)));
757        let mut buf = buffer();
758        // Everything behind is already page-coloured, and the well quantised
759        // onto it. Painting it would be a no-op that hides the real problem.
760        for y in 0..4 {
761            for x in 0..6 {
762                buf[(x, y)].set_bg(Color::Indexed(7));
763            }
764        }
765        frame(&mut buf, Rect::new(0, 0, 6, 4), Depth::Well, &p);
766        assert!(!Palette::shows(Color::Indexed(7), Color::Indexed(7)));
767        // The edge is what carries the meaning here.
768        assert_eq!(buf[(5, 3)].symbol(), BEVEL.bottom_right);
769    }
770
771    #[test]
772    fn a_visible_fill_is_painted() {
773        let p = palette(Some(Color::Indexed(4)));
774        let mut buf = buffer();
775        frame(&mut buf, Rect::new(0, 0, 6, 4), Depth::Well, &p);
776        assert_eq!(buf[(2, 2)].bg, Color::Indexed(4));
777    }
778
779    #[test]
780    fn an_overlay_is_painted_and_left_unedged() {
781        // `Palette::fill` answers `Fill::Overlay`, so `Depth::Overlay` needs
782        // nothing beyond the route. This is the assertion that would catch the
783        // route being lost.
784        let p = palette(None);
785        let mut buf = buffer();
786        let inner = frame(&mut buf, Rect::new(0, 0, 6, 4), Depth::Overlay, &p);
787
788        assert_eq!(buf[(2, 2)].bg, p.overlay);
789        // A surface over the page is separated by the lift and by what sits
790        // behind it, so it takes no edge, and with no edge drawn, nothing is
791        // given up to one: the content area is the whole region.
792        assert_eq!(buf[(0, 0)].symbol(), " ");
793        assert_eq!(inner, Rect::new(0, 0, 6, 4));
794    }
795
796    #[test]
797    fn the_light_falls_from_the_top_left() {
798        let p = palette(None);
799        let mut buf = buffer();
800        paint_bevel(&mut buf, Rect::new(0, 0, 6, 4), Bevel::Raised, &p);
801        assert_eq!(buf[(0, 0)].fg, p.bevel_light); // top-left
802        assert_eq!(buf[(3, 0)].fg, p.bevel_light); // top edge
803        assert_eq!(buf[(0, 2)].fg, p.bevel_light); // left edge
804        assert_eq!(buf[(5, 3)].fg, p.bevel_dark); // bottom-right
805        assert_eq!(buf[(3, 3)].fg, p.bevel_dark); // bottom edge
806        assert_eq!(buf[(5, 2)].fg, p.bevel_dark); // right edge
807    }
808
809    // Half-cell glyphs divide the cell already, so the corner where light
810    // meets shadow can hold both rather than picking one.
811    #[test]
812    fn the_shared_corners_carry_both_tones_when_the_glyph_can_split() {
813        let p = palette(None);
814        let mut buf = buffer();
815        paint_bevel(&mut buf, Rect::new(0, 0, 6, 4), Bevel::Raised, &p);
816        let top_right = &buf[(5, 0)];
817        assert_eq!(top_right.fg, p.bevel_light);
818        assert_eq!(top_right.bg, p.bevel_dark);
819        let bottom_left = &buf[(0, 3)];
820        assert_eq!(bottom_left.fg, p.bevel_dark);
821        assert_eq!(bottom_left.bg, p.bevel_light);
822    }
823
824    // A single-stroke corner has no half to give the second tone, so the
825    // box-drawing sets keep the old rule: both shared corners to dark, which
826    // is what makeover-immediate produces by drawing its dark polyline second.
827    // Changing that would move the lit corner between a terminal and a window.
828    #[test]
829    fn box_drawing_corners_stay_dark_and_match_the_immediate_renderer() {
830        let p = Palette {
831            fidelity: Fidelity::Ansi16,
832            ..palette(None)
833        };
834        let mut buf = buffer();
835        paint_bevel(&mut buf, Rect::new(0, 0, 6, 4), Bevel::Raised, &p);
836        assert_eq!(buf[(5, 0)].symbol(), LIGHT.top_right);
837        assert_eq!(buf[(5, 0)].fg, p.bevel_dark);
838        assert_eq!(buf[(5, 0)].bg, Color::Reset, "a stroke has no second tone");
839        assert_eq!(buf[(0, 3)].fg, p.bevel_dark);
840    }
841
842    // The whole outline, as a reader sees it. Asserted as glyphs because the
843    // shape is the point: an even-weight edge on all four sides, which is what
844    // box-drawing could not give.
845    #[test]
846    fn a_bevel_draws_an_even_outline_and_leaves_the_middle_alone() {
847        let p = palette(None);
848        let mut buf = Buffer::empty(Rect::new(0, 0, 5, 4));
849        paint_bevel(&mut buf, Rect::new(0, 0, 5, 4), Bevel::Raised, &p);
850        let rows: Vec<String> = (0..4)
851            .map(|y| (0..5).map(|x| buf[(x, y)].symbol()).collect())
852            .collect();
853        assert_eq!(rows, vec!["▛▀▀▀▀", "▌   ▐", "▌   ▐", "▄▄▄▄▟"]);
854    }
855
856    #[test]
857    fn pressing_swaps_the_lit_side() {
858        let p = palette(None);
859        let mut buf = buffer();
860        paint_bevel(&mut buf, Rect::new(0, 0, 6, 4), Bevel::Raised.pressed(), &p);
861        assert_eq!(buf[(0, 0)].fg, p.bevel_dark);
862    }
863
864    #[test]
865    fn an_edge_costs_a_cell_on_every_side() {
866        let p = palette(None);
867        let mut buf = buffer();
868        let inner = frame(&mut buf, Rect::new(0, 0, 6, 4), Depth::Raised, &p);
869        assert_eq!(inner, Rect::new(1, 1, 4, 2));
870        // Flat takes no cells, because it draws no edge.
871        let same = frame(&mut buf, Rect::new(0, 0, 6, 4), Depth::Flat, &p);
872        assert_eq!(same, Rect::new(0, 0, 6, 4));
873    }
874
875    #[test]
876    fn sixteen_colours_carries_depth_in_the_glyphs_instead() {
877        // Colour cannot separate raised from well here: the fill collapses on
878        // most themes and an edge vanishes on all of them. The frame has to
879        // say it some other way or the two become the same box.
880        let p = Palette {
881            fidelity: Fidelity::Ansi16,
882            ..palette(None)
883        };
884        assert!(p.needs_glyph_depth());
885        let mut raised = buffer();
886        frame(&mut raised, Rect::new(0, 0, 6, 4), Depth::Raised, &p);
887        let mut well = buffer();
888        frame(&mut well, Rect::new(0, 0, 6, 4), Depth::Well, &p);
889        assert_eq!(raised[(0, 0)].symbol(), DOUBLE.top_left);
890        assert_eq!(well[(0, 0)].symbol(), LIGHT.top_left);
891        assert_ne!(raised[(0, 0)].symbol(), well[(0, 0)].symbol());
892    }
893
894    #[test]
895    fn above_sixteen_colours_the_glyphs_stay_out_of_it() {
896        // The doubled fallback must not fire where colour already works, or
897        // every modern terminal gets a heavier frame it did not need. What it
898        // gets instead is the half-block bevel.
899        for f in [Fidelity::Ansi256, Fidelity::TrueColor] {
900            let p = Palette {
901                fidelity: f,
902                ..palette(Some(Color::Indexed(4)))
903            };
904            assert!(!p.needs_glyph_depth());
905            let mut buf = buffer();
906            frame(&mut buf, Rect::new(0, 0, 6, 4), Depth::Raised, &p);
907            assert_eq!(
908                buf[(0, 0)].symbol(),
909                BEVEL.top_left,
910                "{f:?} got a heavier frame"
911            );
912            assert_ne!(buf[(0, 0)].symbol(), DOUBLE.top_left);
913        }
914    }
915
916    // Raised and well are both bevels and differ only in which way they are
917    // lit, so above sixteen colours they draw the same glyphs and the tones
918    // carry the difference. That is exactly what stops holding at Ansi16, and
919    // why the doubled set exists.
920    #[test]
921    fn colour_alone_separates_raised_from_well_where_it_can() {
922        let p = palette(Some(Color::Indexed(4)));
923        let mut raised = buffer();
924        frame(&mut raised, Rect::new(0, 0, 6, 4), Depth::Raised, &p);
925        let mut well = buffer();
926        frame(&mut well, Rect::new(0, 0, 6, 4), Depth::Well, &p);
927        assert_eq!(raised[(0, 0)].symbol(), well[(0, 0)].symbol());
928        assert_eq!(raised[(0, 0)].fg, p.bevel_light);
929        assert_eq!(well[(0, 0)].fg, p.bevel_dark);
930    }
931
932    #[test]
933    fn detection_defaults_generously_and_only_downgrades_on_evidence() {
934        assert!(Fidelity::default().separates_depth());
935        assert!(Fidelity::TrueColor.separates_depth());
936        assert!(Fidelity::Ansi256.separates_depth());
937        assert!(!Fidelity::Ansi16.separates_depth());
938    }
939
940    // Sixteen colours is reached by naming a console, never by failing to
941    // recognise a terminal. `COLORTERM` is stripped by ssh and by every
942    // multiplexer, so an unrecognised name carries no evidence at all, and a
943    // caller quantising its palette off this answer would flatten a whole theme
944    // on the strength of it.
945    #[test]
946    fn an_unrecognised_terminal_is_assumed_capable() {
947        let f = Fidelity::from_env;
948        assert_eq!(f("", "foot"), Fidelity::TrueColor);
949        assert_eq!(f("", "xterm"), Fidelity::TrueColor);
950        assert_eq!(f("", "screen"), Fidelity::TrueColor);
951        assert_eq!(f("", ""), Fidelity::TrueColor);
952    }
953
954    #[test]
955    fn no_color_wins_over_whatever_the_terminal_claims() {
956        let f = Fidelity::from_request;
957        let set = Some(std::ffi::OsStr::new("1"));
958        assert_eq!(f(set, "truecolor", "xterm-256color"), Fidelity::NoColor);
959        assert_eq!(f(set, "", "linux"), Fidelity::NoColor);
960        assert_eq!(
961            f(Some(std::ffi::OsStr::new("")), "truecolor", ""),
962            Fidelity::TrueColor
963        );
964        assert_eq!(f(None, "", "linux"), Fidelity::Ansi16);
965        assert!(!Fidelity::NoColor.separates_depth());
966    }
967
968    #[test]
969    fn a_console_that_really_has_sixteen_colours_is_named() {
970        let f = Fidelity::from_env;
971        assert_eq!(f("", "linux"), Fidelity::Ansi16);
972        assert_eq!(f("", "vt100"), Fidelity::Ansi16);
973        assert_eq!(f("", "dumb"), Fidelity::Ansi16);
974    }
975
976    #[test]
977    fn a_terminal_naming_its_depth_is_taken_at_its_word() {
978        let f = Fidelity::from_env;
979        assert_eq!(f("", "xterm-256color"), Fidelity::Ansi256);
980        assert_eq!(f("", "screen-256color"), Fidelity::Ansi256);
981        assert_eq!(f("", "xterm-direct"), Fidelity::TrueColor);
982        assert_eq!(f("", "xterm-16color"), Fidelity::Ansi16);
983        // And a claim of 24-bit beats the name, which is only ever a floor.
984        assert_eq!(f("truecolor", "xterm-256color"), Fidelity::TrueColor);
985        assert_eq!(f("24bit", "linux"), Fidelity::TrueColor);
986    }
987
988    #[test]
989    fn a_frame_outside_the_buffer_is_clipped_rather_than_panicking() {
990        let palette = palette(Some(Color::Rgb(40, 40, 40)));
991        let mut buf = Buffer::empty(Rect::new(0, 0, 4, 3));
992        for area in [Rect::new(2, 1, 6, 6), Rect::new(10, 10, 3, 3)] {
993            frame(&mut buf, area, Depth::Raised, &palette);
994            frame(&mut buf, area, Depth::Well, &palette);
995        }
996    }
997
998    #[test]
999    fn a_region_too_small_for_an_edge_is_left_alone() {
1000        let p = palette(None);
1001        let mut buf = buffer();
1002        let inner = frame(&mut buf, Rect::new(0, 0, 1, 1), Depth::Raised, &p);
1003        assert_eq!(inner, Rect::new(0, 0, 1, 1));
1004    }
1005}