1type Rgb = (u8, u8, u8);
21
22use crate::palette_generated::{
25 AMBER, AMBER_256, AMBER_DEEP, AMBER_LIGHT, CHARCOAL, CHARCOAL_256, DANGER, DANGER_256, HEADING,
26 HEADING_256, MUTED, MUTED_256, ON_AMBER, ON_AMBER_256, SUCCESS, SUCCESS_256, WARNING,
27 WARNING_256,
28};
29
30const SPIN_UNICODE: &[&str] = &["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"];
32const SPIN_ASCII: &[&str] = &["-", "\\", "|", "/"];
34
35#[derive(Debug, Clone, Copy, PartialEq, Eq)]
37pub enum ColorTier {
38 Truecolor,
40 Ansi256,
42 Basic,
44 None,
46}
47
48pub struct BoxChars {
50 pub tl: &'static str,
52 pub tr: &'static str,
54 pub bl: &'static str,
56 pub br: &'static str,
58 pub h: &'static str,
60 pub v: &'static str,
62}
63
64#[derive(Debug, Clone, Copy)]
66pub struct Theme {
67 pub ascii: bool,
69 pub tier: ColorTier,
71}
72
73impl Theme {
74 pub fn detect(no_color_flag: bool, ascii_flag: bool) -> Theme {
78 let no_color = std::env::var_os("NO_COLOR").is_some() || no_color_flag;
79 Theme {
80 ascii: ascii_flag || !locale_is_utf8(),
81 tier: detect_tier(no_color),
82 }
83 }
84
85 pub fn paints_background(&self) -> bool {
88 matches!(self.tier, ColorTier::Truecolor | ColorTier::Ansi256)
89 }
90
91 pub fn background_prefix(&self) -> String {
94 match self.tier {
95 ColorTier::Truecolor => bg_rgb(CHARCOAL),
96 ColorTier::Ansi256 => format!("\x1b[48;5;{CHARCOAL_256}m"),
97 _ => String::new(),
98 }
99 }
100
101 fn fg(&self, rgb: Rgb, idx: u8, basic: u8, s: &str) -> String {
104 match self.tier {
105 ColorTier::Truecolor => format!("\x1b[38;2;{};{};{}m{s}\x1b[39m", rgb.0, rgb.1, rgb.2),
106 ColorTier::Ansi256 => format!("\x1b[38;5;{idx}m{s}\x1b[39m"),
107 ColorTier::Basic => format!("\x1b[{basic}m{s}\x1b[39m"),
108 ColorTier::None => s.to_string(),
109 }
110 }
111
112 pub fn ok(&self, s: &str) -> String {
114 self.fg(SUCCESS, SUCCESS_256, 32, s)
115 }
116 pub fn fail(&self, s: &str) -> String {
118 self.fg(DANGER, DANGER_256, 31, s)
119 }
120 pub fn accent(&self, s: &str) -> String {
122 self.fg(AMBER, AMBER_256, 33, s)
123 }
124 pub fn warn(&self, s: &str) -> String {
126 self.fg(WARNING, WARNING_256, 33, s)
127 }
128 pub fn dim(&self, s: &str) -> String {
130 self.fg(MUTED, MUTED_256, 90, s)
131 }
132 pub fn heading(&self, s: &str) -> String {
134 self.bold(&self.fg(HEADING, HEADING_256, 97, s))
135 }
136 pub fn bold(&self, s: &str) -> String {
138 if self.tier == ColorTier::None {
139 s.to_string()
140 } else {
141 format!("\x1b[1m{s}\x1b[22m")
142 }
143 }
144
145 pub fn amber_gradient(&self, row: usize, s: &str) -> String {
149 match self.tier {
150 ColorTier::Truecolor => {
151 let rgb = match row {
152 0 => AMBER_LIGHT,
153 1 => AMBER,
154 _ => AMBER_DEEP,
155 };
156 self.bold(&format!(
157 "\x1b[38;2;{};{};{}m{s}\x1b[39m",
158 rgb.0, rgb.1, rgb.2
159 ))
160 }
161 _ => self.bold(&self.accent(s)),
162 }
163 }
164
165 pub fn selection_bar(&self, content: &str, width: usize) -> String {
170 let body = pad_or_clip(content, width);
171 match self.tier {
172 ColorTier::Truecolor => format!(
173 "{}{}{body}{}",
174 bg_rgb(AMBER),
175 fg_rgb(ON_AMBER),
176 self.restore_base()
177 ),
178 ColorTier::Ansi256 => format!(
179 "\x1b[48;5;{AMBER_256}m\x1b[38;5;{ON_AMBER_256}m{body}{}",
180 self.restore_base()
181 ),
182 ColorTier::Basic => self.bold(&self.accent(content)),
184 ColorTier::None => content.to_string(),
185 }
186 }
187
188 fn restore_base(&self) -> String {
192 match self.tier {
193 ColorTier::Truecolor => format!("{}\x1b[39m", bg_rgb(CHARCOAL)),
194 ColorTier::Ansi256 => format!("\x1b[48;5;{CHARCOAL_256}m\x1b[39m"),
195 _ => "\x1b[39m".to_string(),
196 }
197 }
198
199 pub fn spinner(&self, frame: usize) -> &'static str {
203 if self.ascii {
204 SPIN_ASCII[frame % SPIN_ASCII.len()]
205 } else {
206 SPIN_UNICODE[frame % SPIN_UNICODE.len()]
207 }
208 }
209 pub fn glyph_ok(&self) -> &'static str {
211 if self.ascii {
212 "+"
213 } else {
214 "✓"
215 }
216 }
217 pub fn glyph_fail(&self) -> &'static str {
219 if self.ascii {
220 "x"
221 } else {
222 "✗"
223 }
224 }
225 pub fn glyph_pending(&self) -> &'static str {
227 if self.ascii {
228 "."
229 } else {
230 "•"
231 }
232 }
233 pub fn dot_filled(&self) -> &'static str {
235 if self.ascii {
236 "#"
237 } else {
238 "●"
239 }
240 }
241 pub fn dot_empty(&self) -> &'static str {
243 if self.ascii {
244 "."
245 } else {
246 "○"
247 }
248 }
249 pub fn box_checked(&self) -> &'static str {
251 if self.ascii {
252 "#"
253 } else {
254 "■"
255 }
256 }
257 pub fn box_unchecked(&self) -> &'static str {
259 if self.ascii {
260 "."
261 } else {
262 "□"
263 }
264 }
265
266 pub fn box_chars(&self) -> BoxChars {
268 if self.ascii {
269 BoxChars {
270 tl: "+",
271 tr: "+",
272 bl: "+",
273 br: "+",
274 h: "-",
275 v: "|",
276 }
277 } else {
278 BoxChars {
279 tl: "╭",
280 tr: "╮",
281 bl: "╰",
282 br: "╯",
283 h: "─",
284 v: "│",
285 }
286 }
287 }
288}
289
290fn fg_rgb(rgb: Rgb) -> String {
292 format!("\x1b[38;2;{};{};{}m", rgb.0, rgb.1, rgb.2)
293}
294
295fn bg_rgb(rgb: Rgb) -> String {
297 format!("\x1b[48;2;{};{};{}m", rgb.0, rgb.1, rgb.2)
298}
299
300fn pad_or_clip(content: &str, width: usize) -> String {
303 let n = content.chars().count();
304 if n == width {
305 content.to_string()
306 } else if n < width {
307 format!("{content}{}", " ".repeat(width - n))
308 } else if width == 0 {
309 String::new()
310 } else {
311 let mut out: String = content.chars().take(width.saturating_sub(1)).collect();
312 out.push('…');
313 out
314 }
315}
316
317fn detect_tier(no_color: bool) -> ColorTier {
321 if no_color {
322 return ColorTier::None;
323 }
324 let term = std::env::var("TERM").unwrap_or_default();
325 if term == "dumb" {
326 return ColorTier::None;
327 }
328 let colorterm = std::env::var("COLORTERM")
329 .unwrap_or_default()
330 .to_lowercase();
331 if colorterm.contains("truecolor") || colorterm.contains("24bit") {
332 return ColorTier::Truecolor;
333 }
334 if term.contains("256color") {
335 return ColorTier::Ansi256;
336 }
337 ColorTier::Basic
338}
339
340fn locale_is_utf8() -> bool {
343 for key in ["LC_ALL", "LC_CTYPE", "LANG"] {
346 if let Ok(v) = std::env::var(key) {
347 if v.is_empty() {
348 continue;
349 }
350 let v = v.to_ascii_lowercase();
351 return v.contains("utf-8") || v.contains("utf8");
352 }
353 }
354 true
355}
356
357#[cfg(test)]
358mod tests {
359 use super::*;
360
361 fn plain() -> Theme {
362 Theme {
363 ascii: false,
364 tier: ColorTier::None,
365 }
366 }
367
368 #[test]
369 fn no_color_tier_emits_plain_text() {
370 let t = plain();
371 assert_eq!(t.ok("✓"), "✓");
372 assert_eq!(t.dim("x"), "x");
373 assert_eq!(t.accent("a"), "a");
374 assert_eq!(t.bold("b"), "b");
375 assert_eq!(t.heading("h"), "h");
376 assert_eq!(t.selection_bar("row", 3), "row");
377 }
378
379 #[test]
380 fn truecolor_amber_accent_uses_rgb_sgr() {
381 let t = Theme {
382 ascii: false,
383 tier: ColorTier::Truecolor,
384 };
385 let a = t.accent("x");
386 assert!(
387 a.contains("\x1b[38;2;235;193;87m"),
388 "amber rgb missing: {a:?}"
389 );
390 assert!(a.ends_with("\x1b[39m"), "fg not reset: {a:?}");
391 assert!(!a.contains("\x1b[0m"), "must not full-reset: {a:?}");
393 }
394
395 #[test]
396 fn selection_bar_is_full_width_amber_with_dark_text() {
397 let t = Theme {
398 ascii: false,
399 tier: ColorTier::Truecolor,
400 };
401 let bar = t.selection_bar("● Drone", 20);
402 assert!(
404 bar.contains("\x1b[48;2;235;193;87m"),
405 "amber bg missing: {bar:?}"
406 );
407 assert!(
408 bar.contains("\x1b[38;2;26;26;26m"),
409 "dark fg missing: {bar:?}"
410 );
411 assert!(
413 bar.contains("\x1b[48;2;31;31;31m"),
414 "charcoal restore missing: {bar:?}"
415 );
416 assert_eq!(super::pad_or_clip("● Drone", 20).chars().count(), 20);
417 }
418
419 #[test]
420 fn background_prefix_only_on_painting_tiers() {
421 let tc = Theme {
422 ascii: false,
423 tier: ColorTier::Truecolor,
424 };
425 assert_eq!(tc.background_prefix(), "\x1b[48;2;31;31;31m");
426 assert!(tc.paints_background());
427 let basic = Theme {
428 ascii: false,
429 tier: ColorTier::Basic,
430 };
431 assert!(basic.background_prefix().is_empty());
432 assert!(!basic.paints_background());
433 assert!(plain().background_prefix().is_empty());
434 }
435
436 #[test]
437 fn ascii_tier_uses_ascii_glyphs() {
438 let t = Theme {
439 ascii: true,
440 tier: ColorTier::None,
441 };
442 assert_eq!(t.glyph_ok(), "+");
443 assert_eq!(t.glyph_fail(), "x");
444 assert_eq!(t.spinner(0), "-");
445 assert_eq!(t.box_chars().h, "-");
446 assert_eq!(t.dot_filled(), "#");
447 assert_eq!(t.box_checked(), "#");
448 }
449
450 #[test]
451 fn unicode_glyphs_are_single_column() {
452 let t = plain();
453 for g in [
454 t.glyph_ok(),
455 t.glyph_fail(),
456 t.glyph_pending(),
457 t.spinner(2),
458 t.dot_filled(),
459 t.dot_empty(),
460 t.box_checked(),
461 t.box_unchecked(),
462 ] {
463 assert_eq!(g.chars().count(), 1, "glyph {g:?} must be one column");
464 }
465 }
466}