Skip to main content

uncurses/color/
profile.rs

1//! Terminal color profile detection and color downsampling.
2//!
3//! ## Detection inputs
4//!
5//! Detection combines TTY state with environment variables and `TERM`
6//! heuristics:
7//!
8//! * Non-TTY output is [`Profile::Disabled`] unless `TTY_FORCE` or
9//!   `CLICOLOR_FORCE` is set.
10//! * `NO_COLOR` clamps a TTY to [`Profile::Ascii`]: colors are disabled, but
11//!   text decoration may still be emitted.
12//! * `CLICOLOR_FORCE` forces at least [`Profile::Ansi`] and can still be
13//!   upgraded by other environment evidence.
14//! * `CLICOLOR` bumps a non-dumb TTY to at least [`Profile::Ansi`].
15//! * `COLORTERM=truecolor|24bit|yes|true` upgrades to [`Profile::TrueColor`],
16//!   except inside `screen`.
17//! * `TERM_PROGRAM=Apple_Terminal` with major
18//!   `TERM_PROGRAM_VERSION >= 470` upgrades to [`Profile::TrueColor`], unless
19//!   `TERM` starts with `screen`.
20//! * `TERM=dumb` starts as [`Profile::Disabled`]; `*-256color` upgrades to
21//!   [`Profile::Ansi256`]; `*-direct` upgrades to [`Profile::TrueColor`];
22//!   selected known true-color terminal names are recognized by substring.
23//! * `WT_SESSION`, `GOOGLE_CLOUD_SHELL`, and `CI` upgrade to
24//!   [`Profile::TrueColor`].
25//!
26//! ## Downsampling
27//!
28//! [`Profile::convert`] maps any [`Color`] into the best representation this
29//! profile should emit:
30//!
31//! ```text
32//! TrueColor ─────────► Some(original Color)
33//! Ansi256   ─────────► Some(nearest Color::Indexed(_))
34//! Ansi      ─────────► Some(nearest named Color)
35//! Ascii     ─┐
36//! Disabled  ─┴──────► None
37//! ```
38
39use super::Color;
40use crate::terminal::{Env, ProcessEnv, is_apple_terminal};
41
42/// Terminal color capability profile.
43///
44/// Profiles are ordered by increasing capability:
45/// `Disabled < Ascii < Ansi < Ansi256 < TrueColor`. Use this ordering when
46/// clamping or choosing the maximum capability discovered from multiple
47/// sources.
48#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
49pub enum Profile {
50    /// No styling output at all.
51    ///
52    /// Used for non-TTY output and terminals that should not receive escape
53    /// sequences. Color conversion returns `None`; callers that convert whole
54    /// styles drop colors, attributes, and underline state.
55    /// Renderers and surface encoders also suppress hyperlinks.
56    Disabled,
57    /// ASCII/no-color profile where text decoration is still allowed.
58    ///
59    /// Color conversion returns `None`, but higher-level style conversion may
60    /// preserve non-color SGR attributes such as bold or underline.
61    Ascii,
62    /// Standard 16-color ANSI palette.
63    ///
64    /// Color conversion returns the nearest named [`Color`](super::Color)
65    /// using weighted RGB distance against the xterm palette entries `0..=15`.
66    Ansi,
67    /// xterm 256-color palette.
68    ///
69    /// Color conversion returns the nearest
70    /// [`Color::Indexed`](super::Color::Indexed), choosing between the 6×6×6
71    /// color cube and grayscale ramp by weighted RGB distance.
72    Ansi256,
73    /// 24-bit true color.
74    ///
75    /// Color conversion returns the original [`Color`] unchanged.
76    #[default]
77    TrueColor,
78}
79
80impl Profile {
81    /// Downsample a color to fit this profile.
82    ///
83    /// Returns `Some(color)` when this profile supports color output and
84    /// `None` for [`Profile::Disabled`] or [`Profile::Ascii`]. `TrueColor`
85    /// preserves the original value; `Ansi256` and `Ansi` resolve the input to
86    /// RGB and quantize to the nearest supported palette.
87    #[inline]
88    pub fn convert(self, color: Color) -> Option<Color> {
89        use super::convert::*;
90        match self {
91            Profile::Disabled | Profile::Ascii => None,
92            Profile::Ansi => Some(rgb_to_ansi16(color.to_rgb())),
93            Profile::Ansi256 => Some(rgb_to_ansi256(color.to_rgb())),
94            Profile::TrueColor => Some(color),
95        }
96    }
97
98    /// Detect the color profile from the current process environment.
99    ///
100    /// This assumes the output stream is a TTY. For explicit TTY state or
101    /// deterministic tests, use [`Profile::detect_from`].
102    pub fn detect() -> Self {
103        Self::detect_from(&ProcessEnv, true)
104    }
105
106    /// Detect the color profile from an explicit environment.
107    ///
108    /// `is_tty` should be `true` if the output stream is a terminal. A false
109    /// value clamps to [`Profile::Disabled`] unless `TTY_FORCE` makes the
110    /// stream act like a TTY or `CLICOLOR_FORCE` forces color. `TERM=dumb` and,
111    /// on non-Windows platforms, an empty `TERM` start as disabled before other
112    /// forcing/upgrading rules are applied.
113    pub fn detect_from(env: &dyn Env, is_tty: bool) -> Self {
114        let is_tty = is_tty || is_truthy(env, "TTY_FORCE");
115        let term = env.get("TERM").unwrap_or_default();
116
117        // `env_color_profile` is responsible for translating the
118        // environment to a profile, including the empty-or-`dumb` TERM
119        // case: on Unix that means Disabled, on Windows it falls back
120        // to a platform-specific probe (e.g. WT_SESSION → TrueColor)
121        // because Windows shells routinely leave TERM unset. The only
122        // unconditional clamp here is non-TTY output.
123        let envp = env_color_profile(env, &term);
124        let mut p = if !is_tty { Profile::Disabled } else { envp };
125
126        // NO_COLOR: clamp to Ascii (decoration still allowed). The spec is
127        // presence-based, not boolean: any non-empty value disables color,
128        // including `0` and `false`. `has` is exactly that test.
129        if env.has("NO_COLOR") && is_tty {
130            if p > Profile::Ascii {
131                p = Profile::Ascii;
132            }
133            return p;
134        }
135
136        // CLICOLOR_FORCE: at least Ansi, take max of env-derived.
137        if is_truthy(env, "CLICOLOR_FORCE") {
138            if p < Profile::Ansi {
139                p = Profile::Ansi;
140            }
141            if envp > p {
142                p = envp;
143            }
144            return p;
145        }
146
147        let is_dumb = term.is_empty() || term == DUMB_TERM;
148        // CLICOLOR: bump non-dumb TTY to at least Ansi.
149        if is_truthy(env, "CLICOLOR") && is_tty && !is_dumb && p < Profile::Ansi {
150            p = Profile::Ansi;
151        }
152
153        p
154    }
155}
156
157const DUMB_TERM: &str = "dumb";
158
159/// Return whether an environment variable reads as a truthy boolean.
160///
161/// Accepts `1`, `t`, `T`, `TRUE`, `true`, and `True` — the values Go's
162/// `strconv.ParseBool` reads as true. Anything else, including an empty or
163/// absent value, is false.
164fn is_truthy(env: &dyn Env, key: &str) -> bool {
165    matches!(
166        env.get(key).as_deref().unwrap_or_default(),
167        "1" | "t" | "T" | "TRUE" | "true" | "True"
168    )
169}
170
171/// Environment-driven profile inference. Knows nothing about TTY-ness.
172fn env_color_profile(env: &dyn Env, term: &str) -> Profile {
173    let mut p = if term == DUMB_TERM {
174        // An explicit `dumb` terminal opts out of styling everywhere.
175        Profile::Disabled
176    } else if term.is_empty() {
177        // On Windows, the lack of TERM is normal — Windows Terminal and
178        // cmd.exe don't set it. Defer to a Windows-specific fallback when
179        // we know we're on Windows; otherwise treat as Disabled.
180        #[cfg(windows)]
181        {
182            windows_color_profile(env).unwrap_or(Profile::Disabled)
183        }
184        #[cfg(not(windows))]
185        {
186            let _ = env;
187            Profile::Disabled
188        }
189    } else {
190        Profile::Ansi
191    };
192
193    // Known-good terminals: full TrueColor.
194    if KNOWN_TRUECOLOR_TERMS.iter().any(|t| term.contains(t)) {
195        return Profile::TrueColor;
196    }
197
198    // Screen can inherit these variables from its outer Terminal.app, so
199    // they do not establish whether the screen session supports true color.
200    if !term.starts_with("screen") && apple_terminal_supports_truecolor(env) {
201        return Profile::TrueColor;
202    }
203
204    if term.starts_with("tmux") || term.starts_with("screen") {
205        if p < Profile::Ansi256 {
206            p = Profile::Ansi256;
207        }
208    } else if term.starts_with("xterm") && p < Profile::Ansi {
209        p = Profile::Ansi;
210    }
211
212    // Windows Terminal session variable — set even when TERM isn't.
213    if env.has("WT_SESSION") {
214        return Profile::TrueColor;
215    }
216
217    if is_truthy(env, "GOOGLE_CLOUD_SHELL") {
218        return Profile::TrueColor;
219    }
220
221    // CI runners advertise themselves with CI=true and render ANSI
222    // color in their logs even though TERM is usually unset or `dumb`.
223    if is_truthy(env, "CI") {
224        return Profile::TrueColor;
225    }
226
227    // Screen can inherit COLORTERM from its outer terminal, so it does not
228    // establish the screen session's color support. Modern tmux (3.2+)
229    // forwards COLORTERM to its panes.
230    if colorterm_says_truecolor(env) && !term.starts_with("screen") {
231        return Profile::TrueColor;
232    }
233
234    if term.ends_with("256color") && p < Profile::Ansi256 {
235        p = Profile::Ansi256;
236    }
237
238    if term.ends_with("direct") {
239        return Profile::TrueColor;
240    }
241
242    p
243}
244
245/// Terminals known to support TrueColor regardless of `TERM` suffix.
246const KNOWN_TRUECOLOR_TERMS: &[&str] = &[
247    "alacritty",
248    "contour",
249    "foot",
250    "ghostty",
251    "kitty",
252    "rio",
253    "st",
254    "wezterm",
255];
256
257fn colorterm_says_truecolor(env: &dyn Env) -> bool {
258    let v = env
259        .get("COLORTERM")
260        .unwrap_or_default()
261        .to_ascii_lowercase();
262    matches!(v.as_str(), "truecolor" | "24bit" | "yes" | "true")
263}
264
265fn apple_terminal_supports_truecolor(env: &dyn Env) -> bool {
266    if !is_apple_terminal(env) {
267        return false;
268    }
269    env.get("TERM_PROGRAM_VERSION")
270        .and_then(|version| {
271            version
272                .split('.')
273                .next()
274                .and_then(|major| major.trim().parse::<u32>().ok())
275        })
276        .is_some_and(|major| major >= 470)
277}
278
279#[cfg(windows)]
280fn windows_color_profile(env: &dyn Env) -> Option<Profile> {
281    // Windows 10+ conhost and Windows Terminal both support virtual
282    // terminal sequences. WT_SESSION pins TrueColor; otherwise assume
283    // ANSI256 (conhost's legacy floor) — TrueColor support arrived in
284    // build 14931 and is universally available on supported Windows
285    // versions, but we stay conservative without further probing.
286    if env.has("WT_SESSION") {
287        return Some(Profile::TrueColor);
288    }
289    Some(Profile::Ansi256)
290}
291
292#[cfg(test)]
293mod tests {
294    use super::*;
295    use crate::terminal::EnvList;
296
297    fn env(pairs: &[(&str, &str)]) -> EnvList {
298        EnvList::from_pairs(pairs.iter().map(|(k, v)| (*k, *v)))
299    }
300
301    #[test]
302    fn default_is_truecolor() {
303        assert_eq!(Profile::default(), Profile::TrueColor);
304    }
305
306    #[test]
307    fn ordering_is_capability_ascending() {
308        assert!(Profile::Disabled < Profile::Ascii);
309        assert!(Profile::Ascii < Profile::Ansi);
310        assert!(Profile::Ansi < Profile::Ansi256);
311        assert!(Profile::Ansi256 < Profile::TrueColor);
312    }
313
314    #[test]
315    fn no_tty_clamps_to_notty() {
316        let e = env(&[("TERM", "xterm-256color")]);
317        assert_eq!(Profile::detect_from(&e, false), Profile::Disabled);
318    }
319
320    #[test]
321    fn dumb_term_is_notty() {
322        let e = env(&[("TERM", "dumb")]);
323        assert_eq!(Profile::detect_from(&e, true), Profile::Disabled);
324    }
325
326    /// NO_COLOR is presence-based: any non-empty value disables color,
327    /// however little it reads as a boolean. Only an absent or empty value
328    /// leaves color on.
329    #[test]
330    fn no_color_clamps_for_any_non_empty_value() {
331        for v in ["1", "0", "false", "no", "yes", "please", " "] {
332            let e = env(&[("TERM", "xterm-256color"), ("NO_COLOR", v)]);
333            assert_eq!(
334                Profile::detect_from(&e, true),
335                Profile::Ascii,
336                "NO_COLOR={v:?} should disable color"
337            );
338        }
339        let e = env(&[("TERM", "xterm-256color"), ("NO_COLOR", "")]);
340        assert!(Profile::detect_from(&e, true) > Profile::Ascii);
341    }
342
343    #[test]
344    fn no_color_does_not_apply_off_tty() {
345        // off-tty + no_color: still Disabled (no_color clamp only applies when isatty).
346        let e = env(&[("TERM", "xterm-256color"), ("NO_COLOR", "1")]);
347        assert_eq!(Profile::detect_from(&e, false), Profile::Disabled);
348    }
349
350    #[test]
351    fn clicolor_force_overrides_notty() {
352        let e = env(&[("TERM", "dumb"), ("CLICOLOR_FORCE", "1")]);
353        // CLICOLOR_FORCE guarantees at least Ansi; the platform/env floor may
354        // be higher (e.g. Ansi256 on Windows conhost).
355        assert!(Profile::detect_from(&e, true) >= Profile::Ansi);
356    }
357
358    #[test]
359    fn clicolor_preserves_screen_ansi256_on_tty() {
360        let e = env(&[("CLICOLOR", "1"), ("TERM", "screen")]);
361        let p = Profile::detect_from(&e, true);
362        assert_eq!(p, Profile::Ansi256);
363    }
364
365    #[test]
366    fn colorterm_truecolor_upgrades() {
367        let e = env(&[("TERM", "xterm"), ("COLORTERM", "truecolor")]);
368        assert_eq!(Profile::detect_from(&e, true), Profile::TrueColor);
369    }
370
371    #[test]
372    fn colorterm_24bit_upgrades() {
373        let e = env(&[("TERM", "xterm"), ("COLORTERM", "24bit")]);
374        assert_eq!(Profile::detect_from(&e, true), Profile::TrueColor);
375    }
376
377    #[test]
378    fn colorterm_does_not_upgrade_inside_screen() {
379        let e = env(&[("TERM", "screen-256color"), ("COLORTERM", "truecolor")]);
380        let p = Profile::detect_from(&e, true);
381        assert!(p < Profile::TrueColor);
382    }
383
384    #[test]
385    fn colorterm_upgrades_inside_tmux() {
386        let e = env(&[("TERM", "tmux-256color"), ("COLORTERM", "truecolor")]);
387        // Modern tmux forwards COLORTERM, so the upgrade applies.
388        assert_eq!(Profile::detect_from(&e, true), Profile::TrueColor);
389    }
390
391    #[test]
392    fn apple_terminal_version_upgrades_to_truecolor() {
393        for (version, expected) in [
394            ("469", Profile::Ansi256),
395            ("470", Profile::TrueColor),
396            ("470.1", Profile::TrueColor),
397            ("invalid", Profile::Ansi256),
398        ] {
399            let e = env(&[
400                ("TERM", "xterm-256color"),
401                ("TERM_PROGRAM", "Apple_Terminal"),
402                ("TERM_PROGRAM_VERSION", version),
403            ]);
404            assert_eq!(Profile::detect_from(&e, true), expected, "{version}");
405        }
406    }
407
408    #[test]
409    fn apple_terminal_hint_respects_screen_terminal_type() {
410        for (term, expected) in [
411            ("screen-256color", Profile::Ansi256),
412            ("screen", Profile::Ansi256),
413            ("screen-direct", Profile::TrueColor),
414        ] {
415            let e = env(&[
416                ("TERM", term),
417                ("TERM_PROGRAM", "Apple_Terminal"),
418                ("TERM_PROGRAM_VERSION", "470"),
419            ]);
420            assert_eq!(Profile::detect_from(&e, true), expected, "TERM={term}");
421        }
422    }
423
424    #[test]
425    fn apple_terminal_truecolor_respects_color_clamps() {
426        let no_color = env(&[
427            ("TERM", "xterm-256color"),
428            ("TERM_PROGRAM", "Apple_Terminal"),
429            ("TERM_PROGRAM_VERSION", "470"),
430            ("NO_COLOR", "1"),
431        ]);
432        assert_eq!(Profile::detect_from(&no_color, true), Profile::Ascii);
433
434        let not_tty = env(&[
435            ("TERM", "xterm-256color"),
436            ("TERM_PROGRAM", "Apple_Terminal"),
437            ("TERM_PROGRAM_VERSION", "470"),
438        ]);
439        assert_eq!(Profile::detect_from(&not_tty, false), Profile::Disabled);
440    }
441
442    #[test]
443    fn known_terminal_is_truecolor() {
444        for name in [
445            "alacritty",
446            "wezterm",
447            "ghostty",
448            "kitty-direct",
449            "xterm-kitty",
450        ] {
451            let e = env(&[("TERM", name)]);
452            assert_eq!(
453                Profile::detect_from(&e, true),
454                Profile::TrueColor,
455                "TERM={name} should detect as TrueColor",
456            );
457        }
458    }
459
460    #[test]
461    fn term_256color_suffix_is_ansi256() {
462        let e = env(&[("TERM", "xterm-256color")]);
463        assert_eq!(Profile::detect_from(&e, true), Profile::Ansi256);
464    }
465
466    #[test]
467    fn term_direct_suffix_is_truecolor() {
468        let e = env(&[("TERM", "tmux-direct")]);
469        assert_eq!(Profile::detect_from(&e, true), Profile::TrueColor);
470    }
471
472    #[test]
473    fn screen_floor_is_ansi256() {
474        let e = env(&[("TERM", "screen")]);
475        assert_eq!(Profile::detect_from(&e, true), Profile::Ansi256);
476    }
477
478    #[test]
479    fn tmux_floor_is_ansi256() {
480        let e = env(&[("TERM", "tmux")]);
481        assert_eq!(Profile::detect_from(&e, true), Profile::Ansi256);
482    }
483
484    #[test]
485    fn wt_session_implies_truecolor() {
486        let e = env(&[("TERM", "xterm"), ("WT_SESSION", "1234")]);
487        assert_eq!(Profile::detect_from(&e, true), Profile::TrueColor);
488    }
489
490    #[cfg(windows)]
491    #[test]
492    fn wt_session_without_term_is_truecolor_on_windows() {
493        // Windows shells (PowerShell, cmd, Windows Terminal) routinely
494        // leave TERM unset. WT_SESSION must still pin TrueColor.
495        let e = env(&[("WT_SESSION", "1234")]);
496        assert_eq!(Profile::detect_from(&e, true), Profile::TrueColor);
497    }
498
499    #[cfg(windows)]
500    #[test]
501    fn empty_term_falls_back_to_ansi256_on_windows() {
502        // Without WT_SESSION, conhost still supports VT sequences on
503        // supported Windows versions; floor is Ansi256.
504        let e = env(&[]);
505        assert_eq!(Profile::detect_from(&e, true), Profile::Ansi256);
506    }
507
508    #[test]
509    fn google_cloud_shell_implies_truecolor() {
510        let e = env(&[("GOOGLE_CLOUD_SHELL", "true"), ("TERM", "xterm")]);
511        assert_eq!(Profile::detect_from(&e, true), Profile::TrueColor);
512    }
513
514    #[test]
515    fn ci_implies_truecolor() {
516        let e = env(&[("CI", "true"), ("TERM", "dumb")]);
517        assert_eq!(Profile::detect_from(&e, true), Profile::TrueColor);
518    }
519
520    #[test]
521    fn xterm_plain_is_ansi() {
522        let e = env(&[("TERM", "xterm")]);
523        assert_eq!(Profile::detect_from(&e, true), Profile::Ansi);
524    }
525
526    #[test]
527    fn env_bool_parses_truthy_values() {
528        let cases = [
529            ("1", true),
530            ("0", false),
531            ("true", true),
532            ("True", true),
533            ("TRUE", true),
534            ("t", true),
535            ("T", true),
536            ("false", false),
537            ("False", false),
538            ("FALSE", false),
539            ("", false),
540            ("yes", false),
541            ("garbage", false),
542        ];
543        for (v, want) in cases {
544            let e = env(&[("X", v)]);
545            assert_eq!(is_truthy(&e, "X"), want, "bool({v:?})");
546        }
547    }
548
549    #[test]
550    fn convert_to_each_profile() {
551        let red = Color::Rgb(255, 0, 0);
552        assert!(Profile::Disabled.convert(red).is_none());
553        assert!(Profile::Ascii.convert(red).is_none());
554        assert!(Profile::Ansi.convert(red).is_some());
555        assert!(Profile::Ansi256.convert(red).is_some());
556        assert_eq!(Profile::TrueColor.convert(red), Some(red));
557    }
558}