1#[cfg(feature = "ratatui")]
4use super::{VariantDef, dist, nearest_256};
5#[cfg(feature = "ratatui")]
6use ratatui::style::Color;
7
8#[derive(Debug, Clone, Copy, PartialEq, Eq)]
10pub enum ColorDepth {
11 TrueColor,
12 Ansi256,
13 Ansi16,
14}
15
16impl ColorDepth {
17 pub fn detect() -> Self {
18 let ct = std::env::var("COLORTERM").unwrap_or_default().to_ascii_lowercase();
19 if ct.contains("truecolor") || ct.contains("24bit") {
20 return ColorDepth::TrueColor;
21 }
22 let term = std::env::var("TERM").unwrap_or_default();
23 if term == "linux" || term.contains("16color") || term == "xterm" || term == "vt100" {
24 ColorDepth::Ansi16
25 } else if term.contains("256") {
26 ColorDepth::Ansi256
27 } else {
28 ColorDepth::TrueColor
29 }
30 }
31}
32
33#[cfg(feature = "ratatui")]
34const ANSI16: [(u8, u8, u8); 16] = [
35 (0, 0, 0),
36 (128, 0, 0),
37 (0, 128, 0),
38 (128, 128, 0),
39 (0, 0, 128),
40 (128, 0, 128),
41 (0, 128, 128),
42 (192, 192, 192),
43 (128, 128, 128),
44 (255, 0, 0),
45 (0, 255, 0),
46 (255, 255, 0),
47 (0, 0, 255),
48 (255, 0, 255),
49 (0, 255, 255),
50 (255, 255, 255),
51];
52
53#[cfg(feature = "ratatui")]
54pub fn to_color(c: (u8, u8, u8), depth: ColorDepth) -> Color {
55 match depth {
56 ColorDepth::TrueColor => Color::Rgb(c.0, c.1, c.2),
57 ColorDepth::Ansi256 => Color::Indexed(nearest_256(c)),
58 ColorDepth::Ansi16 => {
59 let i = ANSI16.iter().enumerate().min_by_key(|(_, a)| dist(c, **a)).map(|(i, _)| i).unwrap_or(7);
60 Color::Indexed(i as u8)
61 }
62 }
63}
64
65#[cfg(feature = "ratatui")]
66#[derive(Debug, Clone, PartialEq)]
68pub struct Theme {
69 pub bg: Color,
70 pub fg: Color,
71 pub muted: Color,
72 pub border: Color,
73 pub border_focus: Color,
74 pub selection_bg: Color,
75 pub selection_fg: Color,
76 pub accent: Color,
77 pub header: Color,
78 pub up: Color,
79 pub down: Color,
80 pub warning: Color,
81 pub error: Color,
82 pub success: Color,
83 pub info: Color,
84 pub charts: [Color; 6],
85}
86
87#[cfg(feature = "ratatui")]
88impl Theme {
89 pub fn from_variant(v: &VariantDef) -> Self {
90 Self::from_variant_depth(v, ColorDepth::detect())
91 }
92
93 pub fn from_variant_depth(v: &VariantDef, depth: ColorDepth) -> Self {
94 let c = |r: &str| to_color(v.resolve(r).unwrap_or((128, 128, 128)), depth);
95 Theme {
96 bg: c("bg"),
97 fg: c("fg"),
98 muted: c("muted"),
99 border: c("border"),
100 border_focus: c("border_focus"),
101 selection_bg: c("selection_bg"),
102 selection_fg: c("selection_fg"),
103 accent: c("accent"),
104 header: c("header"),
105 up: c("up"),
106 down: c("down"),
107 warning: c("warning"),
108 error: c("error"),
109 success: c("success"),
110 info: c("info"),
111 charts: [c("chart_1"), c("chart_2"), c("chart_3"), c("chart_4"), c("chart_5"), c("chart_6")],
112 }
113 }
114}