1#![forbid(unsafe_code)]
6
7pub mod detect;
8mod error;
9mod term;
10
11use serde::{Deserialize, Serialize};
12use std::collections::BTreeMap;
13use std::path::{Path, PathBuf};
14
15pub use error::{Result, ThemeError};
16pub use term::ColorDepth;
17#[cfg(feature = "ratatui")]
18pub use term::{Theme, to_color};
19
20pub const THEME_FILE: &str = "interface.toml";
22
23pub trait ThemeDirs {
26 fn themes_dir(&self) -> PathBuf;
28 fn theme_dir(&self, name: &str) -> PathBuf {
29 self.themes_dir().join(name)
30 }
31 fn ensure_dir(&self, dir: &Path) -> std::io::Result<()>;
33 fn write_private(&self, path: &Path, bytes: &[u8]) -> std::io::Result<()>;
35}
36
37#[derive(Debug, Clone, PartialEq, Eq)]
39pub struct PlainDir(pub PathBuf);
40
41impl ThemeDirs for PlainDir {
42 fn themes_dir(&self) -> PathBuf {
43 self.0.clone()
44 }
45 fn ensure_dir(&self, dir: &Path) -> std::io::Result<()> {
46 std::fs::create_dir_all(dir)
47 }
48 fn write_private(&self, path: &Path, bytes: &[u8]) -> std::io::Result<()> {
49 std::fs::write(path, bytes)
50 }
51}
52
53#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
55pub enum Mode {
56 Light,
57 Dark,
58 #[default]
59 System,
60}
61
62pub const ROLES: [&str; 21] = [
64 "bg",
65 "fg",
66 "muted",
67 "border",
68 "border_focus",
69 "selection_bg",
70 "selection_fg",
71 "accent",
72 "header",
73 "up",
74 "down",
75 "warning",
76 "error",
77 "success",
78 "info",
79 "chart_1",
80 "chart_2",
81 "chart_3",
82 "chart_4",
83 "chart_5",
84 "chart_6",
85];
86
87pub const DEFAULT_THEME: &str = "tokyo-night";
88
89pub const BUILTINS: &[(&str, &str)] = &[
91 ("tokyo-night", include_str!("../themes/tokyo-night.toml")),
92 ("catppuccin", include_str!("../themes/catppuccin.toml")),
93 ("gruvbox", include_str!("../themes/gruvbox.toml")),
94 ("dracula", include_str!("../themes/dracula.toml")),
95 ("nord", include_str!("../themes/nord.toml")),
96 ("one", include_str!("../themes/one.toml")),
97 ("solarized", include_str!("../themes/solarized.toml")),
98];
99
100#[derive(Debug, Clone, Copy, PartialEq, Eq)]
101pub enum Variant {
102 Dark,
103 Light,
104}
105
106impl Variant {
107 pub fn toggle(self) -> Self {
108 match self {
109 Variant::Dark => Variant::Light,
110 Variant::Light => Variant::Dark,
111 }
112 }
113 pub fn name(self) -> &'static str {
114 match self {
115 Variant::Dark => "dark",
116 Variant::Light => "light",
117 }
118 }
119}
120
121#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
122pub struct Meta {
123 pub name: String,
124 #[serde(default)]
125 pub display_name: Option<String>,
126 #[serde(default)]
127 pub author: Option<String>,
128 #[serde(default)]
129 pub base: Option<String>,
130}
131
132#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
133pub struct VariantDef {
134 #[serde(default, skip_serializing_if = "Option::is_none")]
135 pub variant_name: Option<String>,
136 #[serde(flatten)]
138 pub roles: BTreeMap<String, String>,
139 #[serde(default)]
140 pub palette: BTreeMap<String, String>,
141}
142
143#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
144pub struct ThemeFile {
145 pub meta: Meta,
146 pub dark: VariantDef,
147 pub light: VariantDef,
148}
149
150pub fn parse_hex(s: &str) -> Option<(u8, u8, u8)> {
151 let h = s.trim().strip_prefix('#')?;
152 if h.len() != 6 || !h.chars().all(|c| c.is_ascii_hexdigit()) {
153 return None;
154 }
155 let v = u32::from_str_radix(h, 16).ok()?;
156 Some(((v >> 16) as u8, (v >> 8) as u8, v as u8))
157}
158
159pub fn to_hex(c: (u8, u8, u8)) -> String {
160 format!("#{:02x}{:02x}{:02x}", c.0, c.1, c.2)
161}
162
163impl VariantDef {
164 pub fn resolve(&self, role: &str) -> Option<(u8, u8, u8)> {
166 let v = self.roles.get(role)?;
167 parse_hex(v).or_else(|| self.palette.get(v).and_then(|h| parse_hex(h)))
168 }
169
170 pub fn swatches(&self) -> Vec<(String, String)> {
172 let mut v: Vec<(String, String)> = self.palette.iter().map(|(k, h)| (k.clone(), h.clone())).collect();
173 for val in self.roles.values() {
174 if parse_hex(val).is_some() && !v.iter().any(|(_, h)| h.eq_ignore_ascii_case(val)) {
175 v.push((val.clone(), val.clone()));
176 }
177 }
178 v
179 }
180}
181
182impl ThemeFile {
183 pub fn parse(text: &str) -> Result<Self> {
184 let t: ThemeFile = toml::from_str(text).map_err(|e| {
185 let msg = e.to_string();
186 if msg.contains("missing field `light`") || msg.contains("missing field `dark`") {
187 ThemeError::invalid("theme", format!("every theme needs both [dark] and [light] tables ({})", msg.trim()))
188 } else {
189 ThemeError::invalid("theme", msg)
190 }
191 })?;
192 t.validate()?;
193 Ok(t)
194 }
195
196 pub fn validate(&self) -> Result<()> {
197 valid_name(&self.meta.name)?;
198 for (vn, v) in [("dark", &self.dark), ("light", &self.light)] {
199 for r in ROLES {
200 if !v.roles.contains_key(r) {
201 return Err(ThemeError::invalid("theme", format!("[{vn}] is missing role `{r}`")));
202 }
203 if v.resolve(r).is_none() {
204 return Err(ThemeError::invalid("theme", format!("[{vn}] role `{r}` = `{}` is neither #rrggbb nor a palette name", v.roles[r])));
205 }
206 }
207 for k in v.roles.keys() {
208 if !ROLES.contains(&k.as_str()) {
209 return Err(ThemeError::invalid("theme", format!("[{vn}] has unknown role `{k}`")));
210 }
211 }
212 }
213 Ok(())
214 }
215
216 pub fn to_toml(&self) -> Result<String> {
217 Ok(toml::to_string_pretty(self)?)
218 }
219
220 pub fn variant(&self, v: Variant) -> &VariantDef {
221 match v {
222 Variant::Dark => &self.dark,
223 Variant::Light => &self.light,
224 }
225 }
226
227 pub fn variant_mut(&mut self, v: Variant) -> &mut VariantDef {
228 match v {
229 Variant::Dark => &mut self.dark,
230 Variant::Light => &mut self.light,
231 }
232 }
233
234 pub fn display_name(&self) -> String {
235 self.meta.display_name.clone().unwrap_or_else(|| self.meta.name.clone())
236 }
237
238 pub fn generate_variant(&mut self, target: Variant) {
240 let src = self.variant(target.toggle()).clone();
241 let mut out = VariantDef { variant_name: Some(format!("{} (generated)", target.name())), ..Default::default() };
242 for r in ROLES {
243 if let Some(c) = src.resolve(r) {
244 out.roles.insert(r.to_string(), to_hex(invert_lightness(c)));
245 }
246 }
247 *self.variant_mut(target) = out;
248 }
249
250 #[cfg(feature = "ratatui")]
251 pub fn resolved(&self, v: Variant) -> Theme {
252 Theme::from_variant(self.variant(v))
253 }
254}
255
256pub fn valid_name(n: &str) -> Result<()> {
257 if n.is_empty() || !n.chars().all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_') {
258 return Err(ThemeError::invalid("theme name", format!("`{n}` (use letters, digits, - and _)")));
259 }
260 Ok(())
261}
262
263fn invert_lightness((r, g, b): (u8, u8, u8)) -> (u8, u8, u8) {
264 let l = (r as u16 + g as u16 + b as u16) / 3;
266 let shift = 255 - 2 * l as i32;
267 let f = |c: u8| (c as i32 + shift).clamp(0, 255) as u8;
268 (f(r), f(g), f(b))
269}
270
271pub fn luminance((r, g, b): (u8, u8, u8)) -> f64 {
273 let ch = |c: u8| {
274 let c = c as f64 / 255.0;
275 if c <= 0.03928 { c / 12.92 } else { ((c + 0.055) / 1.055).powf(2.4) }
276 };
277 0.2126 * ch(r) + 0.7152 * ch(g) + 0.0722 * ch(b)
278}
279
280pub fn contrast(a: (u8, u8, u8), b: (u8, u8, u8)) -> f64 {
282 let (la, lb) = (luminance(a), luminance(b));
283 let (hi, lo) = if la > lb { (la, lb) } else { (lb, la) };
284 (hi + 0.05) / (lo + 0.05)
285}
286
287pub const MIN_CONTRAST: f64 = 4.5;
288
289pub fn contrast_warnings(v: &VariantDef) -> Vec<String> {
291 let pairs = [("fg", "bg"), ("selection_fg", "selection_bg"), ("header", "bg")];
292 let mut out = vec![];
293 for (f, b) in pairs {
294 if let (Some(fc), Some(bc)) = (v.resolve(f), v.resolve(b)) {
295 let c = contrast(fc, bc);
296 if c < MIN_CONTRAST {
297 out.push(format!("{f}/{b} contrast {c:.2}:1 is below {MIN_CONTRAST}:1"));
298 }
299 }
300 }
301 out
302}
303
304#[cfg_attr(not(feature = "ratatui"), allow(dead_code))]
305pub(crate) fn dist(a: (u8, u8, u8), b: (u8, u8, u8)) -> i32 {
306 let d = |x: u8, y: u8| (x as i32 - y as i32).pow(2);
307 d(a.0, b.0) + d(a.1, b.1) + d(a.2, b.2)
308}
309
310pub fn nearest_256(c: (u8, u8, u8)) -> u8 {
312 let levels = [0u8, 95, 135, 175, 215, 255];
313 let idx = |v: u8| levels.iter().enumerate().min_by_key(|(_, l)| (v as i32 - **l as i32).abs()).map(|(i, _)| i).unwrap_or(0);
314 let (ri, gi, bi) = (idx(c.0), idx(c.1), idx(c.2));
315 let cube = (levels[ri], levels[gi], levels[bi]);
316 let cube_i = 16 + 36 * ri + 6 * gi + bi;
317 let avg = (c.0 as u32 + c.1 as u32 + c.2 as u32) / 3;
318 let gi2 = (((avg as i32 - 8).max(0)) / 10).min(23) as u8;
319 let gv = 8 + 10 * gi2;
320 if dist(c, (gv, gv, gv)) < dist(c, cube) { 232 + gi2 } else { cube_i as u8 }
321}
322
323pub fn builtin(name: &str) -> Option<ThemeFile> {
324 BUILTINS.iter().find(|(n, _)| *n == name).and_then(|(_, t)| ThemeFile::parse(t).ok())
325}
326
327pub fn materialize(paths: &(impl ThemeDirs + ?Sized)) -> Result<()> {
329 for (name, text) in BUILTINS {
330 let dir = paths.theme_dir(name);
331 if !dir.join(THEME_FILE).exists() {
332 paths.ensure_dir(&dir)?;
333 paths.ensure_dir(&dir.join("assets"))?;
334 paths.write_private(&dir.join(THEME_FILE), text.as_bytes())?;
335 }
336 }
337 Ok(())
338}
339
340pub fn reset(paths: &(impl ThemeDirs + ?Sized), name: &str) -> Result<()> {
342 let (_, text) =
343 BUILTINS.iter().find(|(n, _)| *n == name).ok_or_else(|| ThemeError::invalid("theme", format!("`{name}` is not a built-in theme")))?;
344 let dir = paths.theme_dir(name);
345 paths.ensure_dir(&dir)?;
346 paths.ensure_dir(&dir.join("assets"))?;
347 paths.write_private(&dir.join(THEME_FILE), text.as_bytes())?;
348 Ok(())
349}
350
351pub fn load(paths: &(impl ThemeDirs + ?Sized), name: &str) -> Result<ThemeFile> {
352 let p = paths.theme_dir(name).join(THEME_FILE);
353 if !p.exists() {
354 return builtin(name).ok_or_else(|| ThemeError::invalid("theme", format!("`{name}` not found in {}", paths.themes_dir().display())));
355 }
356 ThemeFile::parse(&std::fs::read_to_string(&p)?).map_err(|e| ThemeError::invalid("theme", format!("{}: {e}", p.display())))
357}
358
359pub fn save(paths: &(impl ThemeDirs + ?Sized), t: &ThemeFile) -> Result<()> {
360 t.validate()?;
361 let dir = paths.theme_dir(&t.meta.name);
362 paths.ensure_dir(&dir)?;
363 paths.ensure_dir(&dir.join("assets"))?;
364 paths.write_private(&dir.join(THEME_FILE), t.to_toml()?.as_bytes())?;
365 Ok(())
366}
367
368pub fn list(paths: &(impl ThemeDirs + ?Sized)) -> Result<Vec<String>> {
370 let mut v: Vec<String> = BUILTINS.iter().map(|(n, _)| n.to_string()).collect();
371 let mut extra = vec![];
372 if let Ok(rd) = std::fs::read_dir(paths.themes_dir()) {
373 for e in rd.flatten() {
374 let n = e.file_name().to_string_lossy().to_string();
375 if e.path().join(THEME_FILE).exists() && !v.contains(&n) {
376 extra.push(n);
377 }
378 }
379 }
380 extra.sort();
381 v.extend(extra);
382 Ok(v)
383}
384
385pub fn resolve_variant(mode: impl Into<Mode>) -> Variant {
387 match mode.into() {
388 Mode::Dark => Variant::Dark,
389 Mode::Light => Variant::Light,
390 Mode::System => detect::system_variant(),
391 }
392}
393
394pub fn active(paths: &(impl ThemeDirs + ?Sized), name: &str) -> (ThemeFile, Option<String>) {
396 match load(paths, name) {
397 Ok(t) => (t, None),
398 Err(e) => (builtin(DEFAULT_THEME).expect("default theme is valid"), Some(e.to_string())),
399 }
400}
401
402#[cfg(test)]
403mod tests {
404 use super::*;
405
406 #[test]
407 fn builtins_are_valid_and_complete() {
408 assert_eq!(BUILTINS.len(), 7);
409 for (n, t) in BUILTINS {
410 let th = ThemeFile::parse(t).unwrap_or_else(|e| panic!("{n}: {e}"));
411 assert_eq!(&th.meta.name, n);
412 for v in [Variant::Dark, Variant::Light] {
413 let var = th.variant(v);
414 let fg = var.resolve("fg").unwrap();
415 let bg = var.resolve("bg").unwrap();
416 let min = if *n == "solarized" && v == Variant::Light { 4.0 } else { MIN_CONTRAST };
419 assert!(contrast(fg, bg) >= min, "{n} {:?} fg/bg contrast {}", v, contrast(fg, bg));
420 assert_eq!(luminance(bg) < 0.2, v == Variant::Dark, "{n} {v:?}");
422 }
423 }
424 }
425
426 #[test]
427 fn known_palette_values() {
428 let t = builtin("tokyo-night").unwrap();
429 assert_eq!(t.dark.resolve("bg"), parse_hex("#1a1b26"));
430 assert_eq!(t.light.resolve("bg"), parse_hex("#e1e2e7"));
431 let d = builtin("dracula").unwrap();
432 assert_eq!(d.dark.resolve("accent"), parse_hex("#ff79c6"));
433 assert_eq!(builtin("solarized").unwrap().light.resolve("bg"), parse_hex("#fdf6e3"));
434 }
435
436 #[test]
437 fn missing_variant_fails() {
438 let t = BUILTINS[0].1;
439 let only_dark = &t[..t.find("[light]").unwrap()];
440 let e = ThemeFile::parse(only_dark).unwrap_err().to_string();
441 assert!(e.contains("[dark] and [light]"), "{e}");
442 let broken = t.replacen("bg = \"bg\"", "bg = \"nope\"", 1);
443 assert!(ThemeFile::parse(&broken).is_err());
444 }
445
446 #[test]
447 fn contrast_math() {
448 assert!((contrast((0, 0, 0), (255, 255, 255)) - 21.0).abs() < 0.01);
449 assert!((contrast((10, 10, 10), (10, 10, 10)) - 1.0).abs() < 1e-9);
450 assert_eq!(nearest_256((255, 0, 0)), 196);
451 assert_eq!(nearest_256((0, 0, 0)), 16);
452 }
453
454 #[test]
455 fn generate_and_round_trip() {
456 let mut t = builtin("gruvbox").unwrap();
457 t.generate_variant(Variant::Light);
458 t.validate().unwrap();
459 let s = t.to_toml().unwrap();
460 assert_eq!(ThemeFile::parse(&s).unwrap(), t);
461 }
462
463 #[test]
464 fn plain_dir_materialize_list_load_save() {
465 let tmp = tempfile::tempdir().unwrap();
466 let d = PlainDir(tmp.path().join("t"));
467 materialize(&d).unwrap();
468 assert!(d.theme_dir("nord").join("assets").is_dir());
469 assert_eq!(list(&d).unwrap(), BUILTINS.iter().map(|(n, _)| n.to_string()).collect::<Vec<_>>());
470 assert_eq!(std::fs::read_to_string(d.theme_dir("nord").join(THEME_FILE)).unwrap(), BUILTINS.iter().find(|(n, _)| *n == "nord").unwrap().1);
472 let mut t = load(&d, "nord").unwrap();
473 t.meta.name = "my-nord".into();
474 save(&d, &t).unwrap();
475 assert!(list(&d).unwrap().contains(&"my-nord".to_string()));
476 assert_eq!(load(&d, "my-nord").unwrap(), t);
477 assert_eq!(resolve_variant(Mode::Light), Variant::Light);
478 assert_eq!(resolve_variant(Mode::Dark), Variant::Dark);
479 }
480
481 #[test]
482 fn external_theme_errors_and_fallback() {
483 let tmp = tempfile::tempdir().unwrap();
484 let d = PlainDir(tmp.path().join("t"));
485 let e = load(&d, "nope").unwrap_err().to_string();
486 assert!(e.starts_with("invalid theme: `nope` not found in "), "{e}");
487 d.ensure_dir(&d.theme_dir("bad")).unwrap();
488 std::fs::write(d.theme_dir("bad").join(THEME_FILE), "[meta]\nname = \"bad\"\n").unwrap();
489 let e = load(&d, "bad").unwrap_err().to_string();
490 assert!(e.contains("every theme needs both [dark] and [light] tables"), "{e}");
491 let (t, warn) = active(&d, "bad");
492 assert_eq!(t.meta.name, DEFAULT_THEME);
493 assert!(warn.unwrap().contains("bad"));
494 assert_eq!(reset(&d, "my-own").unwrap_err().to_string(), "invalid theme: `my-own` is not a built-in theme");
495 assert_eq!(valid_name("a b").unwrap_err().to_string(), "invalid theme name: `a b` (use letters, digits, - and _)");
496 let mut t = builtin("one").unwrap();
497 t.dark.roles.remove("fg");
498 assert_eq!(save(&d, &t).unwrap_err().to_string(), "invalid theme: [dark] is missing role `fg`");
499 }
500
501 #[cfg(feature = "ratatui")]
502 #[test]
503 fn ratatui_colours_by_depth() {
504 use ratatui::style::Color;
505 let v = &builtin("tokyo-night").unwrap().dark;
506 assert_eq!(Theme::from_variant_depth(v, ColorDepth::TrueColor).bg, Color::Rgb(0x1a, 0x1b, 0x26));
507 assert!(matches!(Theme::from_variant_depth(v, ColorDepth::Ansi256).bg, Color::Indexed(_)));
508 assert_eq!(to_color((255, 0, 0), ColorDepth::Ansi16), Color::Indexed(9));
509 }
510}