Skip to main content

comb/core/
style.rs

1//! Colours and text attributes. Truecolor only (RGB) plus the terminal default.
2
3#[derive(Clone, Copy, PartialEq, Eq, Debug)]
4pub enum Color {
5    /// The terminal's default foreground/background.
6    Reset,
7    Rgb(u8, u8, u8),
8}
9
10impl Color {
11    pub const fn rgb(r: u8, g: u8, b: u8) -> Self {
12        Color::Rgb(r, g, b)
13    }
14}
15
16/// Text attributes, packed as a bitset so styles stay `Copy`.
17#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
18pub struct Modifier(pub u16);
19
20impl Modifier {
21    pub const NONE: Modifier = Modifier(0);
22    pub const BOLD: Modifier = Modifier(1 << 0);
23    pub const DIM: Modifier = Modifier(1 << 1);
24    pub const ITALIC: Modifier = Modifier(1 << 2);
25    pub const UNDERLINE: Modifier = Modifier(1 << 3);
26    pub const REVERSE: Modifier = Modifier(1 << 4);
27
28    pub const fn contains(self, other: Modifier) -> bool {
29        (self.0 & other.0) == other.0
30    }
31
32    pub const fn is_empty(self) -> bool {
33        self.0 == 0
34    }
35}
36
37impl std::ops::BitOr for Modifier {
38    type Output = Modifier;
39    fn bitor(self, rhs: Modifier) -> Modifier {
40        Modifier(self.0 | rhs.0)
41    }
42}
43
44impl std::ops::BitOrAssign for Modifier {
45    fn bitor_assign(&mut self, rhs: Modifier) {
46        self.0 |= rhs.0;
47    }
48}
49
50/// A foreground colour, background colour, and attribute set. `None` colours
51/// mean "inherit whatever is already there" when patched onto another style.
52#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
53pub struct Style {
54    pub fg: Option<Color>,
55    pub bg: Option<Color>,
56    pub mods: Modifier,
57}
58
59impl Style {
60    pub const fn new() -> Self {
61        Style {
62            fg: None,
63            bg: None,
64            mods: Modifier::NONE,
65        }
66    }
67
68    pub const fn fg(mut self, c: Color) -> Self {
69        self.fg = Some(c);
70        self
71    }
72
73    pub const fn bg(mut self, c: Color) -> Self {
74        self.bg = Some(c);
75        self
76    }
77
78    pub const fn add(mut self, m: Modifier) -> Self {
79        self.mods = Modifier(self.mods.0 | m.0);
80        self
81    }
82
83    pub const fn bold(self) -> Self {
84        self.add(Modifier::BOLD)
85    }
86
87    pub const fn dim(self) -> Self {
88        self.add(Modifier::DIM)
89    }
90
91    pub const fn italic(self) -> Self {
92        self.add(Modifier::ITALIC)
93    }
94
95    /// Overlay `other` on top of `self`: its set colours win, its modifiers are
96    /// added. Used to resolve a span's style against a surface default.
97    pub fn patch(mut self, other: Style) -> Self {
98        if other.fg.is_some() {
99            self.fg = other.fg;
100        }
101        if other.bg.is_some() {
102            self.bg = other.bg;
103        }
104        self.mods |= other.mods;
105        self
106    }
107}