Lines
100 %
Functions
94.23 %
Branches
//! Named styles for every role the interface draws, read from a theme file.
mod cga;
mod depth;
#[cfg(test)]
mod override_tests;
mod role;
mod tests;
use crate::error::ParseError;
use cga::Cga;
pub use depth::ColorDepth;
pub use role::Role;
use ratatui::style::{Color, Modifier, Style};
#[derive(Debug, Clone, Copy, Default)]
struct Entry {
fg: Cga,
bg: Cga,
modifiers: Modifier,
}
/// The style of every [`Role`].
#[derive(Debug, Clone)]
pub struct Theme {
entries: [Entry; Role::ALL.len()],
depth: ColorDepth,
/// The preset a theme starts from unless one is chosen.
pub const DEFAULT_PRESET: &str = "dn";
const PRESETS: [(&str, &str); 2] = [
("dn", include_str!("theme/presets/dn.theme")),
("turbo", include_str!("theme/presets/turbo.theme")),
];
impl Theme {
/// Parse `role = fg on bg [bold] [underline] [reverse]` entries, one per line or
/// separated by `;`; every role exactly once.
///
/// # Errors
/// The first malformed entry, a duplicated role, or a role left undefined.
pub fn parse(text: &str) -> Result<Theme, ParseError> {
let mut theme = Theme {
entries: [Entry::default(); Role::ALL.len()],
depth: ColorDepth::Rgb,
};
let defined = theme.apply(text)?;
match Role::ALL.iter().zip(defined).find(|(_, done)| !done) {
Some((role, _)) => Err(ParseError::whole(format!("missing role `{}`", role.name()))),
None => Ok(theme),
/// This theme with the roles `text` defines replaced; same grammar as [`Theme::parse`].
/// The first malformed entry or a role defined twice in `text`.
pub fn overridden(&self, text: &str) -> Result<Theme, ParseError> {
let mut theme = self.clone();
theme.apply(text)?;
Ok(theme)
/// A built-in theme: `dn` or `turbo`.
/// An unknown name, which the message answers with the known ones.
pub fn preset(name: &str) -> Result<Theme, ParseError> {
match PRESETS.iter().find(|(known, _)| *known == name) {
Some((_, text)) => Theme::parse(text),
None => {
let known: Vec<&str> = PRESETS.iter().map(|(known, _)| *known).collect();
let message = format!("unknown preset `{name}`; known: {}", known.join(", "));
Err(ParseError::whole(message))
/// The names of the built-in themes.
pub fn preset_names() -> impl Iterator<Item = &'static str> {
PRESETS.iter().map(|(name, _)| *name)
/// Writes the entries of `text` into `self`; returns which roles it defined.
fn apply(&mut self, text: &str) -> Result<[bool; Role::ALL.len()], ParseError> {
let mut defined = [false; Role::ALL.len()];
let comment_free = text
.lines()
.enumerate()
.filter(|(_, line)| !line.trim_start().starts_with('#'));
for (index, line) in comment_free {
for entry in line.split(';').map(str::trim).filter(|e| !e.is_empty()) {
let (role, parsed) = parse_definition(index + 1, entry)?;
if std::mem::replace(&mut defined[role.index()], true) {
let message = format!("duplicate role `{}`", role.name());
return Err(ParseError::at(index + 1, message));
self.entries[role.index()] = parsed;
Ok(defined)
/// The same theme rendered at `depth`.
#[must_use]
pub fn with_depth(self, depth: ColorDepth) -> Theme {
Theme { depth, ..self }
pub fn depth(&self) -> ColorDepth {
self.depth
pub fn style(&self, role: Role) -> Style {
let Entry { fg, bg, modifiers } = self.entries[role.index()];
Style::new()
.fg(fg.color(self.depth))
.bg(bg.background(self.depth))
.add_modifier(modifiers)
/// The RGB the cells of `role` show as background at this depth, for a picture that must
/// match the cells under it.
pub fn bg_rgb(&self, role: Role) -> [u8; 3] {
self.entries[role.index()].bg.background_rgb(self.depth)
/// The background colour of `role`.
pub fn bg(&self, role: Role) -> Color {
self.entries[role.index()].bg.background(self.depth)
fn parse_definition(number: usize, line: &str) -> Result<(Role, Entry), ParseError> {
let (name, rest) = line
.split_once('=')
.ok_or_else(|| ParseError::at(number, "expected `role = fg on bg`"))?;
let name = name.trim();
let role = Role::from_name(name)
.ok_or_else(|| ParseError::at(number, format!("unknown role `{name}`")))?;
let mut words = rest.split_whitespace();
let fg = parse_colour(number, words.next())?;
if words.next() != Some("on") {
return Err(ParseError::at(number, "expected `on` after the foreground"));
let bg = parse_colour(number, words.next())?;
let modifiers = words.try_fold(Modifier::empty(), |all, word| {
parse_modifier(number, word).map(|one| all | one)
})?;
Ok((role, Entry { fg, bg, modifiers }))
fn parse_colour(number: usize, word: Option<&str>) -> Result<Cga, ParseError> {
let word = word.ok_or_else(|| ParseError::at(number, "expected `role = fg on bg`"))?;
Cga::from_name(word).ok_or_else(|| ParseError::at(number, format!("unknown colour `{word}`")))
fn parse_modifier(number: usize, word: &str) -> Result<Modifier, ParseError> {
match word {
"bold" => Ok(Modifier::BOLD),
"underline" => Ok(Modifier::UNDERLINED),
"reverse" => Ok(Modifier::REVERSED),
other => Err(ParseError::at(
number,
format!("unknown modifier `{other}`"),
)),