1use std::str::FromStr;
4use std::time::Duration;
5
6use ratatui::style::{Color, Modifier, Style};
7
8#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
20pub enum ThemeChoice {
21 #[default]
23 Auto,
24 Light,
26 Dark,
28}
29
30impl FromStr for ThemeChoice {
31 type Err = String;
32
33 fn from_str(value: &str) -> Result<Self, Self::Err> {
34 match value.trim().to_ascii_lowercase().as_str() {
35 "auto" => Ok(Self::Auto),
36 "light" => Ok(Self::Light),
37 "dark" => Ok(Self::Dark),
38 other => Err(format!("unknown theme '{other}': use auto, light or dark")),
39 }
40 }
41}
42
43#[derive(Debug, Clone, Copy, PartialEq, Eq)]
53pub enum Appearance {
54 Light,
56 Dark,
58}
59
60impl ThemeChoice {
61 pub fn resolve(self) -> Appearance {
64 match self {
65 Self::Light => Appearance::Light,
66 Self::Dark => Appearance::Dark,
67 Self::Auto => detect(),
68 }
69 }
70}
71
72fn detect() -> Appearance {
73 let mut options = terminal_colorsaurus::QueryOptions::default();
74 options.timeout = Duration::from_millis(300);
75 match terminal_colorsaurus::theme_mode(options) {
76 Ok(terminal_colorsaurus::ThemeMode::Light) => return Appearance::Light,
77 Ok(terminal_colorsaurus::ThemeMode::Dark) => return Appearance::Dark,
78 Err(error) => tracing::debug!(error = %error, "the terminal did not report its background"),
79 }
80 if let Ok(value) = std::env::var("COLORFGBG")
82 && let Some(background) = value.rsplit(';').next()
83 {
84 return match background.trim() {
85 "7" | "15" => Appearance::Light,
86 _ => Appearance::Dark,
87 };
88 }
89 Appearance::Dark
90}
91
92#[derive(Debug, Clone, Copy, PartialEq, Eq)]
94pub(crate) struct Palette {
95 pub background: (u8, u8, u8),
96 pub raised: (u8, u8, u8),
97 pub border: (u8, u8, u8),
98 pub text: (u8, u8, u8),
99 pub secondary: (u8, u8, u8),
100 pub label: (u8, u8, u8),
101 pub brand: (u8, u8, u8),
102 pub accent: (u8, u8, u8),
103 pub button: (u8, u8, u8),
104 pub button_text: (u8, u8, u8),
105 pub decision: (u8, u8, u8),
106 pub decision_strong: (u8, u8, u8),
108 pub stop: (u8, u8, u8),
109 pub stop_text: (u8, u8, u8),
110 pub working: (u8, u8, u8),
111 pub done: (u8, u8, u8),
112 pub failed: (u8, u8, u8),
113}
114
115const fn rgb(hex: u32) -> (u8, u8, u8) {
116 (((hex >> 16) & 0xff) as u8, ((hex >> 8) & 0xff) as u8, (hex & 0xff) as u8)
117}
118
119const LIGHT: Palette = Palette {
121 background: rgb(0xFFFFFF),
122 raised: rgb(0xF4F4F1),
123 border: rgb(0xE7E6E2),
124 text: rgb(0x18181B),
125 secondary: rgb(0x4B4B53),
126 label: rgb(0x6B6B74),
127 brand: rgb(0xF74C00),
128 accent: rgb(0xC2410C),
129 button: rgb(0xC2410C),
130 button_text: rgb(0xFFFFFF),
131 decision: rgb(0xFFF7F1),
132 decision_strong: rgb(0xFFEDE1),
133 stop: rgb(0x18181B),
134 stop_text: rgb(0xFFFFFF),
135 working: rgb(0x15803D),
136 done: rgb(0x1D4ED8),
137 failed: rgb(0xB91C1C),
138};
139
140const DARK: Palette = Palette {
142 background: rgb(0x0E0F11),
143 raised: rgb(0x1E1F23),
144 border: rgb(0x2C2D32),
145 text: rgb(0xEDEDEF),
146 secondary: rgb(0xB5B5BD),
147 label: rgb(0x8E8E97),
148 brand: rgb(0xFF6A1F),
149 accent: rgb(0xFF8A4C),
150 button: rgb(0xFF8A4C),
151 button_text: rgb(0x1A0D05),
152 decision: rgb(0x1F1610),
153 decision_strong: rgb(0x2A1D13),
154 stop: rgb(0xEDEDEF),
155 stop_text: rgb(0x0E0F11),
156 working: rgb(0x4ADE80),
157 done: rgb(0x93B4FF),
158 failed: rgb(0xFCA5A5),
159};
160
161#[derive(Debug, Clone, Copy, PartialEq, Eq)]
173pub struct Theme {
174 appearance: Appearance,
175 truecolor: bool,
176 palette: Palette,
177}
178
179impl Theme {
180 pub fn new(appearance: Appearance, truecolor: bool) -> Self {
183 let palette = match appearance {
184 Appearance::Light => LIGHT,
185 Appearance::Dark => DARK,
186 };
187 Self { appearance, truecolor, palette }
188 }
189
190 pub fn detect(choice: ThemeChoice) -> Self {
192 Self::new(choice.resolve(), truecolor())
193 }
194
195 pub fn appearance(&self) -> Appearance {
197 self.appearance
198 }
199
200 pub(crate) fn palette(&self) -> &Palette {
201 &self.palette
202 }
203
204 pub(crate) fn color(&self, (r, g, b): (u8, u8, u8)) -> Color {
205 if self.truecolor { Color::Rgb(r, g, b) } else { Color::Indexed(xterm_index(r, g, b)) }
206 }
207
208 pub(crate) fn base(&self) -> Style {
210 Style::new().fg(self.color(self.palette.text)).bg(self.color(self.palette.background))
211 }
212
213 pub(crate) fn fg(&self, token: (u8, u8, u8)) -> Style {
214 Style::new().fg(self.color(token))
215 }
216
217 pub(crate) fn text(&self) -> Style {
218 self.fg(self.palette.text)
219 }
220
221 pub(crate) fn secondary(&self) -> Style {
222 self.fg(self.palette.secondary)
223 }
224
225 pub(crate) fn label(&self) -> Style {
226 self.fg(self.palette.label)
227 }
228
229 pub(crate) fn heading(&self) -> Style {
230 self.label().add_modifier(Modifier::BOLD)
231 }
232
233 pub(crate) fn accent(&self) -> Style {
234 self.fg(self.palette.accent)
235 }
236
237 pub(crate) fn border(&self) -> Style {
238 self.fg(self.palette.border)
239 }
240
241 pub(crate) fn keycap(&self) -> Style {
243 Style::new().fg(self.color(self.palette.background)).bg(self.color(self.palette.text))
244 }
245
246 pub(crate) fn badge(&self) -> Style {
248 Style::new()
249 .fg(self.color(self.palette.button_text))
250 .bg(self.color(self.palette.button))
251 .add_modifier(Modifier::BOLD)
252 }
253
254 pub(crate) fn stop(&self) -> Style {
256 Style::new().fg(self.color(self.palette.stop_text)).bg(self.color(self.palette.stop))
257 }
258}
259
260fn truecolor() -> bool {
262 let colorterm = std::env::var("COLORTERM").unwrap_or_default().to_ascii_lowercase();
263 colorterm == "truecolor"
264 || colorterm == "24bit"
265 || std::env::var_os("WT_SESSION").is_some()
266 || matches!(
267 std::env::var("TERM_PROGRAM").as_deref(),
268 Ok("iTerm.app" | "WezTerm" | "vscode" | "ghostty")
269 )
270}
271
272fn xterm_index(r: u8, g: u8, b: u8) -> u8 {
274 const LEVELS: [u8; 6] = [0, 95, 135, 175, 215, 255];
275 let level = |v: u8| -> usize {
276 LEVELS
277 .iter()
278 .enumerate()
279 .min_by_key(|(_, l)| (i32::from(**l) - i32::from(v)).abs())
280 .map_or(0, |(i, _)| i)
281 };
282 let (ri, gi, bi) = (level(r), level(g), level(b));
283 let cube = (LEVELS[ri], LEVELS[gi], LEVELS[bi]);
284 let grey_step = ((u32::from(r) + u32::from(g) + u32::from(b)) / 3).saturating_sub(8) / 10;
285 let grey_step = grey_step.min(23) as u8;
286 let grey = 8 + 10 * grey_step;
287 let distance = |(a, b2, c): (u8, u8, u8)| -> i32 {
288 let d = |x: u8, y: u8| (i32::from(x) - i32::from(y)).pow(2);
289 d(a, r) + d(b2, g) + d(c, b)
290 };
291 if distance((grey, grey, grey)) < distance(cube) {
292 232 + grey_step
293 } else {
294 16 + 36 * ri as u8 + 6 * gi as u8 + bi as u8
295 }
296}
297
298#[cfg(test)]
299mod tests {
300 use super::*;
301
302 #[test]
303 fn the_tokens_of_section_9() {
304 assert_eq!(LIGHT.background, (0xFF, 0xFF, 0xFF));
305 assert_eq!(LIGHT.decision, (0xFF, 0xF7, 0xF1));
306 assert_eq!(LIGHT.accent, (0xC2, 0x41, 0x0C));
307 assert_eq!(DARK.background, (0x0E, 0x0F, 0x11));
308 assert_eq!(DARK.decision, (0x1F, 0x16, 0x10));
309 assert_eq!(DARK.accent, (0xFF, 0x8A, 0x4C));
310 assert_eq!(LIGHT.brand, (0xF7, 0x4C, 0x00));
312 assert_eq!(DARK.brand, (0xFF, 0x6A, 0x1F));
313 }
314
315 #[test]
316 fn indexed_colours_are_the_nearest() {
317 assert_eq!(xterm_index(255, 255, 255), 231);
318 assert_eq!(xterm_index(0, 0, 0), 16);
319 assert_eq!(xterm_index(0x80, 0x80, 0x80), 244);
320 let theme = Theme::new(Appearance::Light, false);
321 assert!(matches!(theme.color(LIGHT.accent), Color::Indexed(_)));
322 assert_eq!(
323 Theme::new(Appearance::Dark, true).color(DARK.text),
324 Color::Rgb(0xED, 0xED, 0xEF)
325 );
326 }
327}