1#[derive(Debug, Clone, Copy, PartialEq, Eq)]
3pub enum ColorDepth {
4 Rgb,
5 Indexed256,
6 Ansi16,
7}
8
9const TRUECOLOR_TERMS: [&str; 5] = ["kitty", "ghostty", "wezterm", "foot", "alacritty"];
10
11impl ColorDepth {
12 #[must_use]
14 pub fn name(self) -> &'static str {
15 match self {
16 ColorDepth::Rgb => "rgb",
17 ColorDepth::Indexed256 => "256",
18 ColorDepth::Ansi16 => "16",
19 }
20 }
21
22 #[must_use]
24 pub fn detect(term: Option<&str>, colorterm: Option<&str>) -> ColorDepth {
25 let colorterm = colorterm.map(str::to_ascii_lowercase);
26 let term = term.map(str::to_ascii_lowercase).unwrap_or_default();
27 let truecolor_terminal = TRUECOLOR_TERMS.iter().any(|name| term.contains(name))
28 || term.ends_with("-direct")
29 || term.ends_with("-truecolor");
30 match colorterm.as_deref() {
31 Some("truecolor" | "24bit") => ColorDepth::Rgb,
32 _ if truecolor_terminal => ColorDepth::Rgb,
33 _ if term.ends_with("-256color") => ColorDepth::Indexed256,
34 _ => ColorDepth::Ansi16,
35 }
36 }
37}
38
39impl std::str::FromStr for ColorDepth {
40 type Err = String;
41
42 fn from_str(s: &str) -> Result<ColorDepth, String> {
43 match s.to_ascii_lowercase().as_str() {
44 "rgb" => Ok(ColorDepth::Rgb),
45 "256" => Ok(ColorDepth::Indexed256),
46 "16" => Ok(ColorDepth::Ansi16),
47 _ => Err(format!("unknown colour depth `{s}`; known: rgb, 256, 16")),
48 }
49 }
50}