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