use std::path::PathBuf;
use std::str::FromStr;
use anyhow::{Context, Result, bail};
use ratatui::style::Color;
use ratatui::widgets::BorderType;
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(untagged)]
pub enum ColorSpec {
Index(u8),
Name(String),
}
impl ColorSpec {
fn to_color(&self) -> Result<Color> {
match self {
ColorSpec::Index(n) => Ok(Color::Indexed(*n)),
ColorSpec::Name(raw) => {
let raw = raw.trim();
if let Ok(c) = Color::from_str(raw) {
return Ok(c);
}
let squashed: String = raw
.to_lowercase()
.chars()
.filter(|c| !matches!(c, ' ' | '-' | '_'))
.collect();
Color::from_str(&squashed).map_err(|_| {
anyhow::anyhow!(
"unrecognized color {raw:?} (use a name like \"light-blue\", \
\"#rrggbb\" hex, or a 0-255 palette index)"
)
})
}
}
}
}
#[derive(Debug, Clone, Default, Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
pub struct ThemeConfig {
#[serde(skip_serializing_if = "Option::is_none")]
pub max_width: Option<u16>,
#[serde(skip_serializing_if = "Option::is_none")]
pub max_height: Option<u16>,
#[serde(skip_serializing_if = "Option::is_none")]
pub margin: Option<u16>,
#[serde(skip_serializing_if = "Option::is_none")]
pub margin_x: Option<u16>,
#[serde(skip_serializing_if = "Option::is_none")]
pub margin_y: Option<u16>,
#[serde(skip_serializing_if = "Option::is_none")]
pub align_x: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub align_y: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub pin_title: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
pub title_gap: Option<u16>,
#[serde(skip_serializing_if = "Option::is_none")]
pub border_type: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub accent: Option<ColorSpec>,
#[serde(skip_serializing_if = "Option::is_none")]
pub muted: Option<ColorSpec>,
#[serde(skip_serializing_if = "Option::is_none")]
pub term_border: Option<ColorSpec>,
#[serde(skip_serializing_if = "Option::is_none")]
pub snapshot_border: Option<ColorSpec>,
#[serde(skip_serializing_if = "Option::is_none")]
pub status_bg: Option<ColorSpec>,
#[serde(skip_serializing_if = "Option::is_none")]
pub status_fg: Option<ColorSpec>,
#[serde(skip_serializing_if = "Option::is_none")]
pub h1_style: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub h1: Option<ColorSpec>,
#[serde(skip_serializing_if = "Option::is_none")]
pub h2: Option<ColorSpec>,
#[serde(skip_serializing_if = "Option::is_none")]
pub bullet: Option<ColorSpec>,
#[serde(skip_serializing_if = "Option::is_none")]
pub quote: Option<ColorSpec>,
#[serde(skip_serializing_if = "Option::is_none")]
pub link: Option<ColorSpec>,
#[serde(skip_serializing_if = "Option::is_none")]
pub inline_code: Option<ColorSpec>,
#[serde(skip_serializing_if = "Option::is_none")]
pub code_bg: Option<ColorSpec>,
#[serde(skip_serializing_if = "Option::is_none")]
pub code_fg: Option<ColorSpec>,
#[serde(skip_serializing_if = "Option::is_none")]
pub code_keyword: Option<ColorSpec>,
#[serde(skip_serializing_if = "Option::is_none")]
pub code_string: Option<ColorSpec>,
#[serde(skip_serializing_if = "Option::is_none")]
pub code_comment: Option<ColorSpec>,
#[serde(skip_serializing_if = "Option::is_none")]
pub code_literal: Option<ColorSpec>,
#[serde(skip_serializing_if = "Option::is_none")]
pub code_function: Option<ColorSpec>,
#[serde(skip_serializing_if = "Option::is_none")]
pub code_type: Option<ColorSpec>,
#[serde(skip_serializing_if = "Option::is_none")]
pub qr_dark: Option<ColorSpec>,
#[serde(skip_serializing_if = "Option::is_none")]
pub qr_light: Option<ColorSpec>,
}
impl ThemeConfig {
pub fn merged(self, over: ThemeConfig) -> ThemeConfig {
ThemeConfig {
max_width: over.max_width.or(self.max_width),
max_height: over.max_height.or(self.max_height),
margin: over.margin.or(self.margin),
margin_x: over.margin_x.or(self.margin_x),
margin_y: over.margin_y.or(self.margin_y),
align_x: over.align_x.or(self.align_x),
align_y: over.align_y.or(self.align_y),
pin_title: over.pin_title.or(self.pin_title),
title_gap: over.title_gap.or(self.title_gap),
border_type: over.border_type.or(self.border_type),
accent: over.accent.or(self.accent),
muted: over.muted.or(self.muted),
term_border: over.term_border.or(self.term_border),
snapshot_border: over.snapshot_border.or(self.snapshot_border),
status_bg: over.status_bg.or(self.status_bg),
status_fg: over.status_fg.or(self.status_fg),
h1_style: over.h1_style.or(self.h1_style),
h1: over.h1.or(self.h1),
h2: over.h2.or(self.h2),
bullet: over.bullet.or(self.bullet),
quote: over.quote.or(self.quote),
link: over.link.or(self.link),
inline_code: over.inline_code.or(self.inline_code),
code_bg: over.code_bg.or(self.code_bg),
code_fg: over.code_fg.or(self.code_fg),
code_keyword: over.code_keyword.or(self.code_keyword),
code_string: over.code_string.or(self.code_string),
code_comment: over.code_comment.or(self.code_comment),
code_literal: over.code_literal.or(self.code_literal),
code_function: over.code_function.or(self.code_function),
code_type: over.code_type.or(self.code_type),
qr_dark: over.qr_dark.or(self.qr_dark),
qr_light: over.qr_light.or(self.qr_light),
}
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum VAlign {
Center,
Top,
Bottom,
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum HAlign {
Center,
Left,
Right,
}
#[derive(Debug, Clone, Copy)]
pub struct Theme {
pub max_width: u16,
pub max_height: u16,
pub margin_x: u16,
pub margin_y: u16,
pub align_x: HAlign,
pub align_y: VAlign,
pub pin_title: bool,
pub title_gap: u16,
pub border_type: BorderType,
pub accent: Color,
pub muted: Color,
pub term_border: Color,
pub snapshot_border: Option<Color>,
pub status_bg: Color,
pub status_fg: Color,
pub h1_banner: bool,
pub h1: Color,
pub h2: Color,
pub bullet: Color,
pub quote: Color,
pub link: Color,
pub inline_code: Color,
pub code_bg: Color,
pub code_fg: Color,
pub code_keyword: Color,
pub code_string: Color,
pub code_comment: Color,
pub code_literal: Color,
pub code_function: Color,
pub code_type: Color,
pub qr_dark: Color,
pub qr_light: Color,
}
impl Default for Theme {
fn default() -> Self {
Theme {
max_width: 96,
max_height: u16::MAX,
margin_x: 2,
margin_y: 0,
align_x: HAlign::Center,
align_y: VAlign::Center,
pin_title: false,
title_gap: 1,
border_type: BorderType::Plain,
accent: Color::Cyan,
muted: Color::Indexed(244),
term_border: Color::Indexed(244),
snapshot_border: None,
status_bg: Color::Indexed(236),
status_fg: Color::Indexed(250),
h1_banner: false,
h1: Color::Cyan,
h2: Color::LightBlue,
bullet: Color::Cyan,
quote: Color::Green,
link: Color::Blue,
inline_code: Color::Yellow,
code_bg: Color::Indexed(235),
code_fg: Color::Indexed(252),
code_keyword: Color::Rgb(0xc6, 0x78, 0xdd),
code_string: Color::Rgb(0x98, 0xc3, 0x79),
code_comment: Color::Rgb(0x7f, 0x84, 0x90),
code_literal: Color::Rgb(0xd1, 0x9a, 0x66),
code_function: Color::Rgb(0x61, 0xaf, 0xef),
code_type: Color::Rgb(0xe5, 0xc0, 0x7b),
qr_dark: Color::Indexed(16),
qr_light: Color::Indexed(231),
}
}
}
impl Theme {
pub fn snapshot_border(&self) -> Color {
self.snapshot_border.unwrap_or(self.term_border)
}
pub fn resolve(configs: Vec<ThemeConfig>) -> Result<Theme> {
let cfg = configs
.into_iter()
.fold(ThemeConfig::default(), ThemeConfig::merged);
let mut t = Theme::default();
if let Some(w) = cfg.max_width {
t.max_width = w.max(20);
}
if let Some(h) = cfg.max_height {
t.max_height = h.max(5);
}
if let Some(m) = cfg.margin {
t.margin_x = m.min(30);
t.margin_y = m.min(30);
}
if let Some(m) = cfg.margin_x {
t.margin_x = m.min(30);
}
if let Some(m) = cfg.margin_y {
t.margin_y = m.min(30);
}
if let Some(a) = cfg.align_x {
t.align_x = match a.as_str() {
"center" => HAlign::Center,
"left" => HAlign::Left,
"right" => HAlign::Right,
other => {
bail!(
"theme.align_x: expected \"left\", \"center\", or \"right\", got {other:?}"
)
}
};
}
if let Some(a) = cfg.align_y {
t.align_y = match a.as_str() {
"center" => VAlign::Center,
"top" => VAlign::Top,
"bottom" => VAlign::Bottom,
other => {
bail!(
"theme.align_y: expected \"top\", \"center\", or \"bottom\", got {other:?}"
)
}
};
}
if let Some(p) = cfg.pin_title {
t.pin_title = p;
}
if let Some(g) = cfg.title_gap {
t.title_gap = g.min(20);
}
if let Some(s) = cfg.h1_style {
t.h1_banner = match s.as_str() {
"normal" => false,
"banner" => true,
other => {
bail!("theme.h1_style: expected \"normal\" or \"banner\", got {other:?}")
}
};
}
if let Some(b) = cfg.border_type {
t.border_type = match b.as_str() {
"plain" => BorderType::Plain,
"rounded" => BorderType::Rounded,
"double" => BorderType::Double,
"thick" => BorderType::Thick,
other => bail!(
"theme.border_type: expected \"plain\", \"rounded\", \"double\", or \"thick\", got {other:?}"
),
};
}
macro_rules! color {
($field:ident) => {
if let Some(c) = &cfg.$field {
t.$field = c
.to_color()
.with_context(|| concat!("theme.", stringify!($field)))?;
}
};
}
color!(accent);
color!(muted);
color!(term_border);
if let Some(c) = &cfg.snapshot_border {
t.snapshot_border = Some(c.to_color().context("theme.snapshot_border")?);
}
color!(status_bg);
color!(status_fg);
color!(h1);
color!(h2);
color!(bullet);
color!(quote);
color!(link);
color!(inline_code);
color!(code_bg);
color!(code_fg);
color!(code_keyword);
color!(code_string);
color!(code_comment);
color!(code_literal);
color!(code_function);
color!(code_type);
color!(qr_dark);
color!(qr_light);
Ok(t)
}
}
pub fn user_config_path() -> Option<PathBuf> {
if let Ok(xdg) = std::env::var("XDG_CONFIG_HOME")
&& !xdg.is_empty()
{
return Some(PathBuf::from(xdg).join("deckhand").join("theme.json"));
}
std::env::var("HOME").ok().map(|h| {
PathBuf::from(h)
.join(".config")
.join("deckhand")
.join("theme.json")
})
}
pub fn user_config() -> Result<Option<ThemeConfig>> {
let Some(path) = user_config_path() else {
return Ok(None);
};
if !path.exists() {
return Ok(None);
}
let src = std::fs::read_to_string(&path)
.with_context(|| format!("reading theme {}", path.display()))?;
let cfg =
serde_json::from_str(&src).with_context(|| format!("parsing theme {}", path.display()))?;
Ok(Some(cfg))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn defaults_when_empty() {
let t = Theme::resolve(vec![]).unwrap();
assert_eq!(t.max_width, 96);
assert_eq!(t.accent, Color::Cyan);
}
#[test]
fn merge_precedence() {
let user: ThemeConfig =
serde_json::from_str(r#"{ "accent": "magenta", "max_width": 80 }"#).unwrap();
let deck: ThemeConfig =
serde_json::from_str(r#"{ "max_width": 60, "max_height": 25 }"#).unwrap();
let t = Theme::resolve(vec![user, deck]).unwrap();
assert_eq!(t.max_width, 60); assert_eq!(t.max_height, 25);
assert_eq!(t.accent, Color::Magenta); }
#[test]
fn color_forms() {
let cfg: ThemeConfig = serde_json::from_str(
r##"{ "h1": "#ff8800", "code_bg": 17, "bullet": "light-green" }"##,
)
.unwrap();
let t = Theme::resolve(vec![cfg]).unwrap();
assert_eq!(t.h1, Color::Rgb(255, 136, 0));
assert_eq!(t.code_bg, Color::Indexed(17));
assert_eq!(t.bullet, Color::LightGreen);
}
#[test]
fn snapshot_border_supersedes_term_border() {
let t = Theme::resolve(vec![]).unwrap();
assert_eq!(t.snapshot_border(), t.term_border);
let cfg: ThemeConfig =
serde_json::from_str(r#"{ "term_border": "blue", "snapshot_border": "yellow" }"#)
.unwrap();
let t = Theme::resolve(vec![cfg]).unwrap();
assert_eq!(t.term_border, Color::Blue);
assert_eq!(t.snapshot_border(), Color::Yellow);
}
#[test]
fn margin_shorthand_and_axis_overrides() {
let t = Theme::resolve(vec![]).unwrap();
assert_eq!((t.margin_x, t.margin_y), (2, 0));
let cfg: ThemeConfig = serde_json::from_str(r#"{ "margin": 4 }"#).unwrap();
let t = Theme::resolve(vec![cfg]).unwrap();
assert_eq!((t.margin_x, t.margin_y), (4, 4));
let user: ThemeConfig = serde_json::from_str(r#"{ "margin_y": 3 }"#).unwrap();
let deck: ThemeConfig = serde_json::from_str(r#"{ "margin": 1 }"#).unwrap();
let t = Theme::resolve(vec![user, deck]).unwrap();
assert_eq!((t.margin_x, t.margin_y), (1, 3));
}
#[test]
fn align_axes_resolve() {
let t = Theme::resolve(vec![]).unwrap();
assert_eq!(t.align_x, HAlign::Center);
assert_eq!(t.align_y, VAlign::Center);
let cfg: ThemeConfig =
serde_json::from_str(r#"{ "align_x": "right", "align_y": "bottom" }"#).unwrap();
let t = Theme::resolve(vec![cfg]).unwrap();
assert_eq!(t.align_x, HAlign::Right);
assert_eq!(t.align_y, VAlign::Bottom);
let cfg: ThemeConfig = serde_json::from_str(r#"{ "align_y": "middle" }"#).unwrap();
assert!(Theme::resolve(vec![cfg]).is_err());
}
#[test]
fn pin_title_resolves_and_merges() {
let t = Theme::resolve(vec![]).unwrap();
assert!(!t.pin_title);
let user: ThemeConfig = serde_json::from_str(r#"{ "pin_title": true }"#).unwrap();
let deck: ThemeConfig = serde_json::from_str(r#"{ "accent": "red" }"#).unwrap();
let t = Theme::resolve(vec![user, deck]).unwrap();
assert!(t.pin_title); }
#[test]
fn qr_colors_default_to_true_black_on_white() {
let t = Theme::resolve(vec![]).unwrap();
assert_eq!(t.qr_dark, Color::Indexed(16));
assert_eq!(t.qr_light, Color::Indexed(231));
let cfg: ThemeConfig =
serde_json::from_str(r##"{ "qr_dark": "#102040", "qr_light": "#fdf6e3" }"##).unwrap();
let t = Theme::resolve(vec![cfg]).unwrap();
assert_eq!(t.qr_dark, Color::Rgb(0x10, 0x20, 0x40));
assert_eq!(t.qr_light, Color::Rgb(0xfd, 0xf6, 0xe3));
}
#[test]
fn bad_values_error() {
let cfg: ThemeConfig = serde_json::from_str(r#"{ "accent": "chartreuse" }"#).unwrap();
assert!(Theme::resolve(vec![cfg]).is_err());
let cfg: ThemeConfig = serde_json::from_str(r#"{ "border_type": "wavy" }"#).unwrap();
assert!(Theme::resolve(vec![cfg]).is_err());
}
}