use std::fmt;
use std::io::IsTerminal as _;
use std::str::FromStr;
use std::sync::OnceLock;
use std::time::Duration;
use anyhow::Result;
use ratatui::style::{Color, Modifier, Style};
use serde::{Deserialize, Serialize};
const DETECT_TIMEOUT: Duration = Duration::from_millis(30);
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub(crate) enum ThemeSetting {
#[default]
Auto,
Light,
Dark,
}
impl ThemeSetting {
pub(crate) fn as_str(self) -> &'static str {
match self {
Self::Auto => "auto",
Self::Light => "light",
Self::Dark => "dark",
}
}
}
impl fmt::Display for ThemeSetting {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.as_str())
}
}
impl FromStr for ThemeSetting {
type Err = anyhow::Error;
fn from_str(s: &str) -> Result<Self> {
match s {
"auto" => Ok(Self::Auto),
"light" => Ok(Self::Light),
"dark" => Ok(Self::Dark),
other => anyhow::bail!("unknown theme {other:?}; expected auto, light or dark"),
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Theme {
Dark,
Light,
}
impl Theme {
fn palette(self) -> &'static Palette {
match self {
Self::Dark => &DARK,
Self::Light => &LIGHT,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct Palette {
pub(crate) block_bg: Color,
pub(crate) toolbar_bg: Color,
pub(crate) idle_fg: Color,
pub(crate) comment_bg: Color,
pub(crate) approve_bg: Color,
pub(crate) cursor: Style,
pub(crate) selection: Style,
}
pub(crate) static DARK: Palette = Palette {
block_bg: Color::Indexed(236),
toolbar_bg: Color::Indexed(238),
idle_fg: Color::Gray,
comment_bg: Color::Indexed(58),
approve_bg: Color::Indexed(22),
cursor: Style::new().bg(Color::Indexed(240)),
selection: Style::new().add_modifier(Modifier::REVERSED),
};
pub(crate) static LIGHT: Palette = Palette {
block_bg: Color::Indexed(254),
toolbar_bg: Color::Indexed(252),
idle_fg: Color::DarkGray,
comment_bg: Color::Indexed(222),
approve_bg: Color::Indexed(157),
cursor: Style::new().bg(Color::Indexed(238)).fg(Color::White),
selection: Style::new().bg(Color::Indexed(153)),
};
static PALETTE: OnceLock<&'static Palette> = OnceLock::new();
pub(crate) fn palette() -> &'static Palette {
PALETTE.get().copied().unwrap_or(&DARK)
}
pub(crate) fn install(theme: Theme) {
let _ = PALETTE.set(theme.palette());
}
pub(crate) fn detect() -> Option<Theme> {
if !std::io::stdout().is_terminal() {
return None;
}
#[allow(
clippy::field_reassign_with_default,
reason = "QueryOptions is #[non_exhaustive]; struct-update syntax is not available to us"
)]
let options = {
let mut options = terminal_colorsaurus::QueryOptions::default();
options.timeout = DETECT_TIMEOUT;
options
};
match terminal_colorsaurus::theme_mode(options) {
Ok(terminal_colorsaurus::ThemeMode::Light) => Some(Theme::Light),
Ok(terminal_colorsaurus::ThemeMode::Dark) => Some(Theme::Dark),
Err(_) => None,
}
}
fn setting_from_env(env: &impl Fn(&str) -> Option<String>) -> Result<Option<ThemeSetting>> {
match env("PLANNOTATOR_TUI_THEME").filter(|value| !value.is_empty()) {
Some(value) => value.parse().map(Some),
None => Ok(None),
}
}
pub(crate) fn effective_setting(
env: impl Fn(&str) -> Option<String>,
configured: ThemeSetting,
) -> Result<ThemeSetting> {
Ok(setting_from_env(&env)?.unwrap_or(configured))
}
pub(crate) fn resolve(
env: impl Fn(&str) -> Option<String>,
configured: ThemeSetting,
detect: impl FnOnce() -> Option<Theme>,
) -> Result<Theme> {
Ok(match effective_setting(env, configured)? {
ThemeSetting::Light => Theme::Light,
ThemeSetting::Dark => Theme::Dark,
ThemeSetting::Auto => detect().unwrap_or(Theme::Dark),
})
}
#[cfg(test)]
#[allow(clippy::expect_used, reason = "tests assert by panicking")]
mod tests {
use super::*;
fn env(vars: &'static [(&'static str, &'static str)]) -> impl Fn(&str) -> Option<String> {
move |key: &str| vars.iter().find(|(name, _)| *name == key).map(|(_, v)| (*v).to_owned())
}
#[test]
fn the_environment_beats_the_config_file() {
let vars = env(&[("PLANNOTATOR_TUI_THEME", "light")]);
assert_eq!(resolve(vars, ThemeSetting::Dark, || None).expect("resolves"), Theme::Light);
}
#[test]
fn the_config_file_beats_detection() {
let detect = || Some(Theme::Light);
assert_eq!(resolve(env(&[]), ThemeSetting::Dark, detect).expect("resolves"), Theme::Dark);
}
#[test]
fn auto_in_the_environment_reopens_the_question_a_configured_theme_closed() {
let vars = env(&[("PLANNOTATOR_TUI_THEME", "auto")]);
let resolved = resolve(vars, ThemeSetting::Dark, || Some(Theme::Light)).expect("resolves");
assert_eq!(resolved, Theme::Light);
}
#[test]
fn auto_uses_the_terminals_answer_and_falls_back_to_dark_without_one() {
let auto = ThemeSetting::Auto;
assert_eq!(resolve(env(&[]), auto, || Some(Theme::Light)).expect("resolves"), Theme::Light);
assert_eq!(resolve(env(&[]), auto, || None).expect("resolves"), Theme::Dark);
}
#[test]
fn an_empty_environment_variable_is_not_a_choice() {
let vars = env(&[("PLANNOTATOR_TUI_THEME", "")]);
assert_eq!(resolve(vars, ThemeSetting::Light, || None).expect("resolves"), Theme::Light);
}
#[test]
fn an_unreadable_environment_variable_is_an_error_naming_the_value() {
let vars = env(&[("PLANNOTATOR_TUI_THEME", "solarized")]);
let err = resolve(vars, ThemeSetting::Auto, || None).expect_err("rejected");
assert!(err.to_string().contains("solarized"), "{err}");
}
#[test]
fn the_dark_palette_is_unchanged() {
assert_eq!(DARK.block_bg, Color::Indexed(236));
assert_eq!(DARK.toolbar_bg, Color::Indexed(238));
assert_eq!(DARK.idle_fg, Color::Gray);
assert_eq!(DARK.comment_bg, Color::Indexed(58));
assert_eq!(DARK.approve_bg, Color::Indexed(22));
assert_eq!(DARK.cursor, Style::new().bg(Color::Indexed(240)));
assert_eq!(DARK.selection, Style::new().add_modifier(Modifier::REVERSED));
}
#[test]
fn the_palette_is_dark_until_something_installs_one() {
assert_eq!(*palette(), DARK);
}
#[test]
fn no_light_role_reuses_its_dark_value() {
assert_ne!(LIGHT.block_bg, DARK.block_bg);
assert_ne!(LIGHT.toolbar_bg, DARK.toolbar_bg);
assert_ne!(LIGHT.comment_bg, DARK.comment_bg);
assert_ne!(LIGHT.approve_bg, DARK.approve_bg);
assert_ne!(LIGHT.cursor, DARK.cursor);
assert_ne!(LIGHT.selection, DARK.selection);
}
#[test]
fn the_light_selection_is_a_background_not_a_reversal() {
assert!(!LIGHT.selection.add_modifier.contains(Modifier::REVERSED));
assert!(LIGHT.selection.bg.is_some());
}
#[test]
fn a_theme_setting_roundtrips_through_its_own_name() {
for setting in [ThemeSetting::Auto, ThemeSetting::Light, ThemeSetting::Dark] {
assert_eq!(setting.as_str().parse::<ThemeSetting>().expect("parses"), setting);
}
}
}