use std::env;
use std::io::IsTerminal;
use super::style::Rgb;
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Default)]
pub enum ColorDepth {
None,
Ansi16,
#[default]
Ansi256,
TrueColor,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum GraphicsProtocol {
Kitty,
ITerm2,
Sixel,
Blocks,
#[default]
None,
}
impl GraphicsProtocol {
pub fn name(self) -> &'static str {
match self {
Self::Kitty => "kitty",
Self::ITerm2 => "iterm2",
Self::Sixel => "sixel",
Self::Blocks => "blocks",
Self::None => "none",
}
}
pub fn is_pixel_exact(self) -> bool {
matches!(self, Self::Kitty | Self::ITerm2 | Self::Sixel)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Default)]
pub enum UnicodeLevel {
Ascii,
#[default]
Extended,
Full,
}
#[derive(Debug, Clone)]
pub struct Capabilities {
pub color: ColorDepth,
pub graphics: GraphicsProtocol,
pub hyperlinks: bool,
pub unicode: UnicodeLevel,
pub cols: u16,
pub rows: u16,
pub cell_px: Option<(u16, u16)>,
pub background: Option<Rgb>,
pub is_tty: bool,
pub italic_broken: bool,
pub multiplexed: bool,
}
impl Default for Capabilities {
fn default() -> Self {
Self {
color: ColorDepth::None,
graphics: GraphicsProtocol::None,
hyperlinks: false,
unicode: UnicodeLevel::Ascii,
cols: 80,
rows: 24,
cell_px: None,
background: None,
is_tty: false,
italic_broken: false,
multiplexed: false,
}
}
}
impl Capabilities {
pub fn detect(allow_probe: bool) -> Self {
let mut caps = Self::from_env();
if caps.is_tty && allow_probe {
super::probe::refine(&mut caps);
}
caps
}
pub fn from_env() -> Self {
let is_tty = std::io::stdout().is_terminal();
let term = env::var("TERM").unwrap_or_default();
let term_program = env::var("TERM_PROGRAM").unwrap_or_default();
let dumb = term == "dumb" || term.is_empty();
let multiplexed = env::var_os("TMUX").is_some() || term.starts_with("screen");
let color = Self::detect_color(is_tty, &term, &term_program, dumb);
let (cols, rows) = terminal_size();
let mut caps = Self {
color,
graphics: GraphicsProtocol::None,
hyperlinks: is_tty && !dumb && Self::hyperlinks_from_env(&term, &term_program),
unicode: Self::unicode_from_env(dumb),
cols,
rows,
cell_px: cell_size_px(),
background: None,
is_tty,
italic_broken: term_program == "Apple_Terminal" || term == "linux",
multiplexed,
};
caps.graphics = Self::graphics_from_env(&caps, &term, &term_program);
caps
}
fn detect_color(is_tty: bool, term: &str, term_program: &str, dumb: bool) -> ColorDepth {
if env::var_os("NO_COLOR").is_some_and(|v| !v.is_empty()) {
return ColorDepth::None;
}
let forced = env::var_os("CLICOLOR_FORCE").is_some_and(|v| v != "0")
|| env::var("FORCE_COLOR").is_ok_and(|v| v != "0" && v != "false");
if !is_tty && !forced {
return ColorDepth::None;
}
if dumb {
return ColorDepth::None;
}
let colorterm = env::var("COLORTERM").unwrap_or_default();
if colorterm == "truecolor" || colorterm == "24bit" {
return ColorDepth::TrueColor;
}
const TRUECOLOR_PROGRAMS: &[&str] = &[
"iTerm.app",
"WezTerm",
"ghostty",
"vscode",
"Hyper",
"rio",
"Tabby",
"warp",
];
if TRUECOLOR_PROGRAMS
.iter()
.any(|p| p.eq_ignore_ascii_case(term_program))
{
return ColorDepth::TrueColor;
}
if env::var_os("KITTY_WINDOW_ID").is_some() || term.contains("kitty") {
return ColorDepth::TrueColor;
}
if term.contains("direct") {
return ColorDepth::TrueColor;
}
if term.contains("256") {
return ColorDepth::Ansi256;
}
if term_program == "Apple_Terminal" {
return ColorDepth::Ansi256;
}
ColorDepth::Ansi16
}
fn graphics_from_env(caps: &Self, term: &str, term_program: &str) -> GraphicsProtocol {
let kitty_marker = env::var_os("KITTY_WINDOW_ID").is_some()
|| env::var_os("GHOSTTY_RESOURCES_DIR").is_some();
Self::choose_graphics(caps, term, term_program, kitty_marker)
}
fn choose_graphics(
caps: &Self,
term: &str,
term_program: &str,
kitty_marker: bool,
) -> GraphicsProtocol {
if !caps.is_tty {
return GraphicsProtocol::None;
}
if caps.multiplexed {
return GraphicsProtocol::Blocks;
}
match term_program {
"iTerm.app" => return GraphicsProtocol::ITerm2,
"ghostty" | "Ghostty" => return GraphicsProtocol::Kitty,
"WezTerm" => return GraphicsProtocol::Kitty,
"Apple_Terminal" => return GraphicsProtocol::Blocks,
_ => {}
}
if term.contains("kitty") || kitty_marker {
return GraphicsProtocol::Kitty;
}
if term.contains("mlterm") || term.contains("yaft") || term.contains("foot") {
return GraphicsProtocol::Sixel;
}
if caps.color >= ColorDepth::Ansi256 {
GraphicsProtocol::Blocks
} else {
GraphicsProtocol::None
}
}
fn hyperlinks_from_env(term: &str, term_program: &str) -> bool {
if term == "linux" {
return false;
}
if let Ok(v) = env::var("VTE_VERSION") {
if let Ok(n) = v.parse::<u32>() {
return n >= 5000;
}
}
const KNOWN: &[&str] = &[
"iTerm.app",
"WezTerm",
"ghostty",
"vscode",
"Hyper",
"rio",
"kitty",
];
KNOWN.iter().any(|p| p.eq_ignore_ascii_case(term_program))
|| term.contains("kitty")
|| term.contains("foot")
|| term.contains("alacritty")
|| env::var_os("WT_SESSION").is_some()
|| env::var_os("KITTY_WINDOW_ID").is_some()
}
fn unicode_from_env(dumb: bool) -> UnicodeLevel {
if dumb {
return UnicodeLevel::Ascii;
}
let utf8 = ["LC_ALL", "LC_CTYPE", "LANG"]
.iter()
.filter_map(|k| env::var(k).ok())
.any(|v| {
v.to_ascii_lowercase().contains("utf-8") || v.to_ascii_lowercase().contains("utf8")
});
if utf8 || cfg!(windows) {
UnicodeLevel::Full
} else {
UnicodeLevel::Ascii
}
}
pub fn prefers_dark(&self) -> bool {
self.background
.map(|b| b.luminance() < 0.35)
.unwrap_or(true)
}
pub fn cell_px_or_guess(&self) -> (u16, u16) {
self.cell_px.unwrap_or((8, 16))
}
}
pub fn terminal_size() -> (u16, u16) {
if let (Ok(c), Ok(r)) = (env::var("COLUMNS"), env::var("LINES")) {
if let (Ok(c), Ok(r)) = (c.parse(), r.parse()) {
return (c, r);
}
}
crossterm::terminal::size().unwrap_or((80, 24))
}
fn cell_size_px() -> Option<(u16, u16)> {
let ws = crossterm::terminal::window_size().ok()?;
if ws.width == 0 || ws.height == 0 || ws.columns == 0 || ws.rows == 0 {
return None;
}
Some((ws.width / ws.columns, ws.height / ws.rows))
}
#[cfg(test)]
mod tests {
use super::*;
fn graphics_for(term: &str, term_program: &str, kitty_marker: bool) -> GraphicsProtocol {
let caps = Capabilities {
is_tty: true,
color: ColorDepth::TrueColor,
..Default::default()
};
Capabilities::choose_graphics(&caps, term, term_program, kitty_marker)
}
#[test]
fn term_program_outranks_the_marker_variables() {
assert_eq!(
graphics_for("xterm-256color", "iTerm.app", true),
GraphicsProtocol::ITerm2
);
assert_eq!(
graphics_for("xterm-256color", "Apple_Terminal", true),
GraphicsProtocol::Blocks
);
assert_eq!(
graphics_for("xterm-256color", "", true),
GraphicsProtocol::Kitty
);
}
#[test]
fn known_terminals_get_their_protocol() {
assert_eq!(
graphics_for("xterm-ghostty", "ghostty", false),
GraphicsProtocol::Kitty
);
assert_eq!(
graphics_for("xterm-kitty", "", false),
GraphicsProtocol::Kitty
);
assert_eq!(
graphics_for("wezterm", "WezTerm", false),
GraphicsProtocol::Kitty
);
assert_eq!(graphics_for("foot", "", false), GraphicsProtocol::Sixel);
assert_eq!(
graphics_for("xterm-256color", "", false),
GraphicsProtocol::Blocks
);
}
#[test]
fn a_multiplexer_falls_back_to_blocks() {
let caps = Capabilities {
is_tty: true,
multiplexed: true,
color: ColorDepth::TrueColor,
..Default::default()
};
assert_eq!(
Capabilities::choose_graphics(&caps, "xterm-kitty", "ghostty", true),
GraphicsProtocol::Blocks
);
}
#[test]
fn graphics_names_are_stable() {
assert_eq!(GraphicsProtocol::Kitty.name(), "kitty");
assert!(GraphicsProtocol::Sixel.is_pixel_exact());
assert!(!GraphicsProtocol::Blocks.is_pixel_exact());
}
#[test]
fn unknown_background_is_treated_as_dark() {
let caps = Capabilities::default();
assert!(caps.prefers_dark());
}
#[test]
fn light_background_is_detected() {
let caps = Capabilities {
background: Some(Rgb(250, 250, 250)),
..Default::default()
};
assert!(!caps.prefers_dark());
}
#[test]
fn color_depth_orders_by_fidelity() {
assert!(ColorDepth::TrueColor > ColorDepth::Ansi256);
assert!(ColorDepth::Ansi16 > ColorDepth::None);
}
}