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