1
//! Named styles for every role the interface draws, read from a theme file.
2

            
3
mod cga;
4
mod depth;
5
#[cfg(test)]
6
mod override_tests;
7
mod role;
8
#[cfg(test)]
9
mod tests;
10

            
11
use crate::error::ParseError;
12
use cga::Cga;
13
pub use depth::ColorDepth;
14
pub use role::Role;
15

            
16
use ratatui::style::{Color, Modifier, Style};
17

            
18
#[derive(Debug, Clone, Copy, Default)]
19
struct Entry {
20
    fg: Cga,
21
    bg: Cga,
22
    modifiers: Modifier,
23
}
24

            
25
/// The style of every [`Role`].
26
#[derive(Debug, Clone)]
27
pub struct Theme {
28
    entries: [Entry; Role::ALL.len()],
29
    depth: ColorDepth,
30
}
31

            
32
/// The preset a theme starts from unless one is chosen.
33
pub const DEFAULT_PRESET: &str = "dn";
34

            
35
const PRESETS: [(&str, &str); 2] = [
36
    ("dn", include_str!("theme/presets/dn.theme")),
37
    ("turbo", include_str!("theme/presets/turbo.theme")),
38
];
39

            
40
impl 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
12378
    pub fn parse(text: &str) -> Result<Theme, ParseError> {
47
12378
        let mut theme = Theme {
48
12378
            entries: [Entry::default(); Role::ALL.len()],
49
12378
            depth: ColorDepth::Rgb,
50
12378
        };
51
12378
        let defined = theme.apply(text)?;
52
507107
        match Role::ALL.iter().zip(defined).find(|(_, done)| !done) {
53
2
            Some((role, _)) => Err(ParseError::whole(format!("missing role `{}`", role.name()))),
54
12368
            None => Ok(theme),
55
        }
56
12378
    }
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
345
    pub fn overridden(&self, text: &str) -> Result<Theme, ParseError> {
63
345
        let mut theme = self.clone();
64
345
        theme.apply(text)?;
65
21
        Ok(theme)
66
345
    }
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
12376
    pub fn preset(name: &str) -> Result<Theme, ParseError> {
73
12614
        match PRESETS.iter().find(|(known, _)| *known == name) {
74
12366
            Some((_, text)) => Theme::parse(text),
75
            None => {
76
20
                let known: Vec<&str> = PRESETS.iter().map(|(known, _)| *known).collect();
77
10
                let message = format!("unknown preset `{name}`; known: {}", known.join(", "));
78
10
                Err(ParseError::whole(message))
79
            }
80
        }
81
12376
    }
82

            
83
    /// The names of the built-in themes.
84
97
    pub fn preset_names() -> impl Iterator<Item = &'static str> {
85
130
        PRESETS.iter().map(|(name, _)| *name)
86
97
    }
87

            
88
    /// Writes the entries of `text` into `self`; returns which roles it defined.
89
12723
    fn apply(&mut self, text: &str) -> Result<[bool; Role::ALL.len()], ParseError> {
90
12723
        let mut defined = [false; Role::ALL.len()];
91
12723
        let comment_free = text
92
12723
            .lines()
93
12723
            .enumerate()
94
643136
            .filter(|(_, line)| !line.trim_start().starts_with('#'));
95
12723
        for (index, line) in comment_free {
96
507602
            for entry in line.split(';').map(str::trim).filter(|e| !e.is_empty()) {
97
507595
                let (role, parsed) = parse_definition(index + 1, entry)?;
98
507265
                if std::mem::replace(&mut defined[role.index()], true) {
99
2
                    let message = format!("duplicate role `{}`", role.name());
100
2
                    return Err(ParseError::at(index + 1, message));
101
507263
                }
102
507263
                self.entries[role.index()] = parsed;
103
            }
104
        }
105
12391
        Ok(defined)
106
12723
    }
107

            
108
    /// The same theme rendered at `depth`.
109
    #[must_use]
110
7018
    pub fn with_depth(self, depth: ColorDepth) -> Theme {
111
7018
        Theme { depth, ..self }
112
7018
    }
113

            
114
    #[must_use]
115
34
    pub fn depth(&self) -> ColorDepth {
116
34
        self.depth
117
34
    }
118

            
119
    #[must_use]
120
161532
    pub fn style(&self, role: Role) -> Style {
121
161532
        let Entry { fg, bg, modifiers } = self.entries[role.index()];
122
161532
        Style::new()
123
161532
            .fg(fg.color(self.depth))
124
161532
            .bg(bg.background(self.depth))
125
161532
            .add_modifier(modifiers)
126
161532
    }
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
1361
    pub fn bg_rgb(&self, role: Role) -> [u8; 3] {
132
1361
        self.entries[role.index()].bg.background_rgb(self.depth)
133
1361
    }
134

            
135
    /// The background colour of `role`.
136
    #[must_use]
137
491
    pub fn bg(&self, role: Role) -> Color {
138
491
        self.entries[role.index()].bg.background(self.depth)
139
491
    }
140
}
141

            
142
507595
fn parse_definition(number: usize, line: &str) -> Result<(Role, Entry), ParseError> {
143
507595
    let (name, rest) = line
144
507595
        .split_once('=')
145
163
        .ok_or_else(|| ParseError::at(number, "expected `role = fg on bg`"))?;
146
507432
    let name = name.trim();
147
507432
    let role = Role::from_name(name)
148
2
        .ok_or_else(|| ParseError::at(number, format!("unknown role `{name}`")))?;
149
507430
    let mut words = rest.split_whitespace();
150
507430
    let fg = parse_colour(number, words.next())?;
151
507354
    if words.next() != Some("on") {
152
37
        return Err(ParseError::at(number, "expected `on` after the foreground"));
153
507317
    }
154
507317
    let bg = parse_colour(number, words.next())?;
155
507266
    let modifiers = words.try_fold(Modifier::empty(), |all, word| {
156
24752
        parse_modifier(number, word).map(|one| all | one)
157
24752
    })?;
158
507265
    Ok((role, Entry { fg, bg, modifiers }))
159
507595
}
160

            
161
1014747
fn parse_colour(number: usize, word: Option<&str>) -> Result<Cga, ParseError> {
162
1014747
    let word = word.ok_or_else(|| ParseError::at(number, "expected `role = fg on bg`"))?;
163
1014698
    Cga::from_name(word).ok_or_else(|| ParseError::at(number, format!("unknown colour `{word}`")))
164
1014747
}
165

            
166
24752
fn parse_modifier(number: usize, word: &str) -> Result<Modifier, ParseError> {
167
24752
    match word {
168
24742
        "bold" => Ok(Modifier::BOLD),
169
5
        "underline" => Ok(Modifier::UNDERLINED),
170
4
        "reverse" => Ok(Modifier::REVERSED),
171
1
        other => Err(ParseError::at(
172
1
            number,
173
1
            format!("unknown modifier `{other}`"),
174
1
        )),
175
    }
176
24752
}