1
/// How many colours the terminal can show.
2
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
3
pub enum ColorDepth {
4
    Rgb,
5
    Indexed256,
6
    Ansi16,
7
}
8

            
9
const TRUECOLOR_TERMS: [&str; 5] = ["kitty", "ghostty", "wezterm", "foot", "alacritty"];
10

            
11
impl ColorDepth {
12
    /// The word the config and the command line name this depth with.
13
    #[must_use]
14
330
    pub fn name(self) -> &'static str {
15
330
        match self {
16
97
            ColorDepth::Rgb => "rgb",
17
97
            ColorDepth::Indexed256 => "256",
18
136
            ColorDepth::Ansi16 => "16",
19
        }
20
330
    }
21

            
22
    /// The depth `TERM` and `COLORTERM` advertise.
23
    #[must_use]
24
54
    pub fn detect(term: Option<&str>, colorterm: Option<&str>) -> ColorDepth {
25
54
        let colorterm = colorterm.map(str::to_ascii_lowercase);
26
54
        let term = term.map(str::to_ascii_lowercase).unwrap_or_default();
27
116
        let truecolor_terminal = TRUECOLOR_TERMS.iter().any(|name| term.contains(name))
28
12
            || term.ends_with("-direct")
29
11
            || term.ends_with("-truecolor");
30
54
        match colorterm.as_deref() {
31
3
            Some("truecolor" | "24bit") => ColorDepth::Rgb,
32
51
            _ if truecolor_terminal => ColorDepth::Rgb,
33
6
            _ if term.ends_with("-256color") => ColorDepth::Indexed256,
34
4
            _ => ColorDepth::Ansi16,
35
        }
36
54
    }
37
}
38

            
39
impl std::str::FromStr for ColorDepth {
40
    type Err = String;
41

            
42
47
    fn from_str(s: &str) -> Result<ColorDepth, String> {
43
47
        match s.to_ascii_lowercase().as_str() {
44
5
            "rgb" => Ok(ColorDepth::Rgb),
45
8
            "256" => Ok(ColorDepth::Indexed256),
46
23
            "16" => Ok(ColorDepth::Ansi16),
47
11
            _ => Err(format!("unknown colour depth `{s}`; known: rgb, 256, 16")),
48
        }
49
47
    }
50
}