Guide API
Skip to main content

tvision_rs/
color.rs

1//! Typed colour and style.
2//!
3//! [`Color`] is a desired foreground or background colour — terminal default,
4//! a 4-bit BIOS index, an xterm-256 index, or 24-bit RGB. [`Style`] pairs a
5//! foreground and background `Color` with a [`Modifiers`] struct-of-bools
6//! (bold, italic, underline, …). These types describe colour in the abstract;
7//! converting an arbitrary colour to whatever a given terminal can actually
8//! display (the RGB→256→16→BIOS quantization ladder) happens in the
9//! [`Backend`](crate::Backend), since it only matters when colours are flushed
10//! to a real terminal.
11//!
12//! **Guide:** [Theming & colors](../../../apps/theming.html).
13//!
14//! # Turbo Vision heritage
15//!
16//! magiblot packs fg/bg/style into a 64-bit `TColorAttr` whose fg/bg are each a
17//! tagged-union `TColorDesired` (`colors.h`). tvision-rs keeps that four-variant
18//! design but drops the bit-packing: a plain enum plus a struct-of-bools
19//! (deviation D5). The quantization ladder (`mapcolor.cpp`) moves to the
20//! `Backend` (deviation D6).
21
22/// A desired foreground *or* background colour.
23///
24/// In a terminal, [`Color::Default`] is the colour of text with no display
25/// attributes set — so a default/default cell still produces visible text.
26///
27/// # Turbo Vision heritage
28///
29/// Faithful to `TColorDesired`'s four-variant design (`colors.h`), minus the
30/// bit-packing.
31#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
32pub enum Color {
33    /// Terminal default (`ctDefault`).
34    #[default]
35    Default,
36    /// 4-bit BIOS colour (`ctBIOS` / `TColorBIOS`). Invariant: 0..=15. C++
37    /// masks `bios & 0xF` on construction; we store the raw `u8`, so callers and
38    /// the quantization ladder must mask to keep a 16-entry palette lookup in
39    /// range.
40    Bios(u8),
41    /// Index into the xterm-256 palette, 0..=255 (`ctXTerm` / `TColorXTerm`).
42    Indexed(u8),
43    /// 24-bit true colour (`ctRGB` / `TColorRGB`).
44    Rgb(u8, u8, u8),
45}
46
47impl Color {
48    /// Canonical IBM VGA text-mode RGB for each of the 16 BIOS palette indices.
49    /// Single source of truth for resolving `Color::Bios(n)` to a definite
50    /// true-color value (used by the default theme and the colour picker).
51    pub const BIOS_RGB: [(u8, u8, u8); 16] = [
52        (0, 0, 0),       // 0 Black
53        (0, 0, 170),     // 1 Blue
54        (0, 170, 0),     // 2 Green
55        (0, 170, 170),   // 3 Cyan
56        (170, 0, 0),     // 4 Red
57        (170, 0, 170),   // 5 Magenta
58        (170, 85, 0),    // 6 Brown
59        (170, 170, 170), // 7 Light Gray
60        (85, 85, 85),    // 8 Dark Gray
61        (85, 85, 255),   // 9 Light Blue
62        (85, 255, 85),   // 10 Light Green
63        (85, 255, 255),  // 11 Light Cyan
64        (255, 85, 85),   // 12 Light Red
65        (255, 85, 255),  // 13 Light Magenta
66        (255, 255, 85),  // 14 Yellow
67        (255, 255, 255), // 15 White
68    ];
69
70    /// Resolve a 4-bit BIOS index to its canonical true-color RGB.
71    /// The index is masked to 0..=15.
72    pub fn bios_rgb(index: u8) -> Color {
73        let (r, g, b) = Color::BIOS_RGB[(index & 0x0F) as usize];
74        Color::Rgb(r, g, b)
75    }
76
77    pub fn is_default(self) -> bool {
78        matches!(self, Color::Default)
79    }
80    pub fn is_bios(self) -> bool {
81        matches!(self, Color::Bios(_))
82    }
83    pub fn is_indexed(self) -> bool {
84        matches!(self, Color::Indexed(_))
85    }
86    pub fn is_rgb(self) -> bool {
87        matches!(self, Color::Rgb(..))
88    }
89}
90
91/// Text-style modifiers — bold, italic, underline, and so on — as a
92/// struct-of-bools.
93///
94/// Set these on a [`Style`] to control per-cell terminal attributes. Most
95/// terminals support at least `bold`, `underline`, and `reverse`; `italic`,
96/// `blink`, and `strike` are honored on terminals that declare support for
97/// them. All default to `false` (normal text).
98///
99/// ```rust
100/// use tvision_rs::color::{Color, Modifiers, Style};
101///
102/// // Underlined text on the default background.
103/// let s = Style::with_modifiers(
104///     Color::Default,
105///     Color::Default,
106///     Modifiers { underline: true, ..Default::default() },
107/// );
108/// ```
109///
110/// `no_shadow` is a per-cell marker that window shadows must not be cast over
111/// this cell (used internally by the window shadow pass; leave it `false` in
112/// normal use).
113///
114/// # Turbo Vision heritage
115///
116/// Faithful to the `sl*` masks of `TColorAttr`'s 10-bit style word
117/// (`colors.h`), unpacked into a struct-of-bools. The four
118/// `TMonoSelector` attributes (Normal, Highlight=bold, Underline, Inverse=reverse)
119/// all have counterparts in this struct. `no_shadow` is the private `slNoShadow`.
120#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
121pub struct Modifiers {
122    pub bold: bool,      // slBold
123    pub italic: bool,    // slItalic
124    pub underline: bool, // slUnderline
125    pub blink: bool,     // slBlink
126    pub reverse: bool,   // slReverse  (prefer Style::reversed())
127    pub strike: bool,    // slStrike
128    pub no_shadow: bool, // slNoShadow (private)
129}
130
131/// The colour attributes of a screen cell: a foreground colour, a background
132/// colour, and a set of style modifiers.
133///
134/// A zero-initialized `Style` (via [`Default`]) has both colours `Default` and
135/// no modifiers — so a zero-initialized cell still produces visible text.
136///
137/// # Turbo Vision heritage
138///
139/// Faithful to `TColorAttr` (`colors.h`), minus the bit-packing.
140#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
141pub struct Style {
142    pub fg: Color,
143    pub bg: Color,
144    pub modifiers: Modifiers,
145}
146
147impl Style {
148    /// A style with the given colours and no modifiers.
149    pub fn new(fg: Color, bg: Color) -> Self {
150        Style {
151            fg,
152            bg,
153            modifiers: Modifiers::default(),
154        }
155    }
156
157    /// A style with explicit colours and modifiers.
158    pub fn with_modifiers(fg: Color, bg: Color, modifiers: Modifiers) -> Self {
159        Style { fg, bg, modifiers }
160    }
161
162    /// Port of the free function `reverseAttribute` (`colors.h`).
163    ///
164    /// The `slReverse` attribute is rendered inconsistently across terminals, so
165    /// TV swaps the colours manually — *unless* either colour is `Default`, in
166    /// which case there is nothing meaningful to swap and it falls back to
167    /// toggling the reverse flag.
168    pub fn reversed(self) -> Style {
169        let mut out = self;
170        if self.fg.is_default() || self.bg.is_default() {
171            out.modifiers.reverse = !out.modifiers.reverse;
172        } else {
173            out.fg = self.bg;
174            out.bg = self.fg;
175        }
176        out
177    }
178}
179
180#[cfg(test)]
181mod tests {
182    use super::*;
183
184    #[test]
185    fn color_predicates() {
186        assert!(Color::Default.is_default());
187        assert!(Color::Bios(7).is_bios());
188        assert!(Color::Indexed(200).is_indexed());
189        assert!(Color::Rgb(1, 2, 3).is_rgb());
190        assert!(!Color::Rgb(0, 0, 0).is_default());
191    }
192
193    #[test]
194    fn default_style_is_visible_text() {
195        let s = Style::default();
196        assert_eq!(s.fg, Color::Default);
197        assert_eq!(s.bg, Color::Default);
198        assert_eq!(s.modifiers, Modifiers::default());
199    }
200
201    #[test]
202    fn reversed_swaps_concrete_colors() {
203        let s = Style::new(Color::Bios(0x7), Color::Bios(0x1));
204        let r = s.reversed();
205        assert_eq!(r.fg, Color::Bios(0x1));
206        assert_eq!(r.bg, Color::Bios(0x7));
207        assert!(!r.modifiers.reverse); // flag untouched when colours swapped
208    }
209
210    #[test]
211    fn reversed_toggles_flag_when_a_color_is_default() {
212        // Default foreground -> swap is meaningless, toggle the flag instead.
213        let s = Style::new(Color::Default, Color::Bios(0x1));
214        let r = s.reversed();
215        assert_eq!(r.fg, Color::Default);
216        assert_eq!(r.bg, Color::Bios(0x1));
217        assert!(r.modifiers.reverse);
218
219        // toggling twice returns to the original
220        assert!(!r.reversed().modifiers.reverse);
221    }
222
223    #[test]
224    fn bios_rgb_canonical_values() {
225        assert_eq!(Color::bios_rgb(6), Color::Rgb(170, 85, 0)); // Brown special-case
226        assert_eq!(Color::bios_rgb(1), Color::Rgb(0, 0, 170)); // Blue
227        // Masking: 0x16 & 0x0F == 6, same as index 6
228        assert_eq!(Color::bios_rgb(0x16), Color::bios_rgb(6));
229    }
230}