Skip to main content

tvui/
theme.rs

1//! Named styles for every role the interface draws, read from a theme file.
2
3mod cga;
4mod depth;
5#[cfg(test)]
6mod override_tests;
7mod role;
8#[cfg(test)]
9mod tests;
10
11use crate::error::ParseError;
12use cga::Cga;
13pub use depth::ColorDepth;
14pub use role::Role;
15
16use ratatui::style::{Color, Modifier, Style};
17
18#[derive(Debug, Clone, Copy, Default)]
19struct Entry {
20    fg: Cga,
21    bg: Cga,
22    modifiers: Modifier,
23}
24
25/// The style of every [`Role`].
26#[derive(Debug, Clone)]
27pub struct Theme {
28    entries: [Entry; Role::ALL.len()],
29    depth: ColorDepth,
30}
31
32/// The preset a theme starts from unless one is chosen.
33pub const DEFAULT_PRESET: &str = "dn";
34
35const PRESETS: [(&str, &str); 2] = [
36    ("dn", include_str!("theme/presets/dn.theme")),
37    ("turbo", include_str!("theme/presets/turbo.theme")),
38];
39
40impl Theme {
41    /// Parse `role = fg on bg [bold] [underline] [reverse]` entries, one per line or
42    /// separated by `;`; every role exactly once.
43    ///
44    /// # Errors
45    /// The first malformed entry, a duplicated role, or a role left undefined.
46    pub fn parse(text: &str) -> Result<Theme, ParseError> {
47        let mut theme = Theme {
48            entries: [Entry::default(); Role::ALL.len()],
49            depth: ColorDepth::Rgb,
50        };
51        let defined = theme.apply(text)?;
52        match Role::ALL.iter().zip(defined).find(|(_, done)| !done) {
53            Some((role, _)) => Err(ParseError::whole(format!("missing role `{}`", role.name()))),
54            None => Ok(theme),
55        }
56    }
57
58    /// This theme with the roles `text` defines replaced; same grammar as [`Theme::parse`].
59    ///
60    /// # Errors
61    /// The first malformed entry or a role defined twice in `text`.
62    pub fn overridden(&self, text: &str) -> Result<Theme, ParseError> {
63        let mut theme = self.clone();
64        theme.apply(text)?;
65        Ok(theme)
66    }
67
68    /// A built-in theme: `dn` or `turbo`.
69    ///
70    /// # Errors
71    /// An unknown name, which the message answers with the known ones.
72    pub fn preset(name: &str) -> Result<Theme, ParseError> {
73        match PRESETS.iter().find(|(known, _)| *known == name) {
74            Some((_, text)) => Theme::parse(text),
75            None => {
76                let known: Vec<&str> = PRESETS.iter().map(|(known, _)| *known).collect();
77                let message = format!("unknown preset `{name}`; known: {}", known.join(", "));
78                Err(ParseError::whole(message))
79            }
80        }
81    }
82
83    /// The names of the built-in themes.
84    pub fn preset_names() -> impl Iterator<Item = &'static str> {
85        PRESETS.iter().map(|(name, _)| *name)
86    }
87
88    /// Writes the entries of `text` into `self`; returns which roles it defined.
89    fn apply(&mut self, text: &str) -> Result<[bool; Role::ALL.len()], ParseError> {
90        let mut defined = [false; Role::ALL.len()];
91        let comment_free = text
92            .lines()
93            .enumerate()
94            .filter(|(_, line)| !line.trim_start().starts_with('#'));
95        for (index, line) in comment_free {
96            for entry in line.split(';').map(str::trim).filter(|e| !e.is_empty()) {
97                let (role, parsed) = parse_definition(index + 1, entry)?;
98                if std::mem::replace(&mut defined[role.index()], true) {
99                    let message = format!("duplicate role `{}`", role.name());
100                    return Err(ParseError::at(index + 1, message));
101                }
102                self.entries[role.index()] = parsed;
103            }
104        }
105        Ok(defined)
106    }
107
108    /// The same theme rendered at `depth`.
109    #[must_use]
110    pub fn with_depth(self, depth: ColorDepth) -> Theme {
111        Theme { depth, ..self }
112    }
113
114    #[must_use]
115    pub fn depth(&self) -> ColorDepth {
116        self.depth
117    }
118
119    #[must_use]
120    pub fn style(&self, role: Role) -> Style {
121        let Entry { fg, bg, modifiers } = self.entries[role.index()];
122        Style::new()
123            .fg(fg.color(self.depth))
124            .bg(bg.background(self.depth))
125            .add_modifier(modifiers)
126    }
127
128    /// The RGB the cells of `role` show as background at this depth, for a picture that must
129    /// match the cells under it.
130    #[must_use]
131    pub fn bg_rgb(&self, role: Role) -> [u8; 3] {
132        self.entries[role.index()].bg.background_rgb(self.depth)
133    }
134
135    /// The background colour of `role`.
136    #[must_use]
137    pub fn bg(&self, role: Role) -> Color {
138        self.entries[role.index()].bg.background(self.depth)
139    }
140}
141
142fn parse_definition(number: usize, line: &str) -> Result<(Role, Entry), ParseError> {
143    let (name, rest) = line
144        .split_once('=')
145        .ok_or_else(|| ParseError::at(number, "expected `role = fg on bg`"))?;
146    let name = name.trim();
147    let role = Role::from_name(name)
148        .ok_or_else(|| ParseError::at(number, format!("unknown role `{name}`")))?;
149    let mut words = rest.split_whitespace();
150    let fg = parse_colour(number, words.next())?;
151    if words.next() != Some("on") {
152        return Err(ParseError::at(number, "expected `on` after the foreground"));
153    }
154    let bg = parse_colour(number, words.next())?;
155    let modifiers = words.try_fold(Modifier::empty(), |all, word| {
156        parse_modifier(number, word).map(|one| all | one)
157    })?;
158    Ok((role, Entry { fg, bg, modifiers }))
159}
160
161fn parse_colour(number: usize, word: Option<&str>) -> Result<Cga, ParseError> {
162    let word = word.ok_or_else(|| ParseError::at(number, "expected `role = fg on bg`"))?;
163    Cga::from_name(word).ok_or_else(|| ParseError::at(number, format!("unknown colour `{word}`")))
164}
165
166fn parse_modifier(number: usize, word: &str) -> Result<Modifier, ParseError> {
167    match word {
168        "bold" => Ok(Modifier::BOLD),
169        "underline" => Ok(Modifier::UNDERLINED),
170        "reverse" => Ok(Modifier::REVERSED),
171        other => Err(ParseError::at(
172            number,
173            format!("unknown modifier `{other}`"),
174        )),
175    }
176}