From 3a31975f06c074cdbebb3c62afe9b5451bbcedc2 Mon Sep 17 00:00:00 2001 From: Wez Furlong Date: Tue, 17 Jul 2018 11:09:59 -0700 Subject: [PATCH] Add terminal capabilities struct --- Cargo.toml | 2 + src/caps/mod.rs | 434 ++++++++++++++++++++++++++++++++++++++++++++++++ src/lib.rs | 4 + 3 files changed, 440 insertions(+) create mode 100644 src/caps/mod.rs diff --git a/Cargo.toml b/Cargo.toml index 3054b6d40..ac2d829db 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -13,6 +13,8 @@ failure = "~0.1" vte = "0.3.2" num = "0.2.0" num-traits = "0.2.5" +derive_builder = "0.5.1" +semver = "0.9.0" [dependencies.num-derive] version = "~0.2" diff --git a/src/caps/mod.rs b/src/caps/mod.rs new file mode 100644 index 000000000..fdaf20578 --- /dev/null +++ b/src/caps/mod.rs @@ -0,0 +1,434 @@ +//! # Terminal Capabilities +//! +//! There are a few problems in the world of terminal capability +//! detection today; the terminal is typically local to a machine +//! running very up to date software, but applications may be running +//! on a remote system with relatively stale system software, or +//! even different operating systems. +//! +//! There are two well-specified standard approaches to querying terminal +//! capabilities: `termcap` and `terminfo`. The databases for the +//! capabilities are typically deployed with the operating system +//! software and suffers from splay and freshness issues: they may +//! be different on different systems and out of date. +//! +//! A further complication is that the terminal may be connected +//! via a series of intermediaries or multiplexers (mosh, tmux, screen) +//! which hides or perturbs the true capabilities of the terminal. +//! +//! `terminfo` and `termcap` both allow for the user to supply a local +//! override. `terminfo` needs a locally available compiled database, +//! and that database may have different binary representations on disk +//! depending on the operating system software, making it difficult for +//! users that need to login to many remote machines; the burden is on +//! the user to configure a local profile on many machines or solve the +//! challenge of having a `$HOME/.terminfo` directory that is NFS mountable +//! and readable to all potential machines. +//! +//! `termcap` defines a `TERMCAP` environment variable that can contain +//! overrides and be passed via SSH to the remote systems much more simply +//! than the `terminfo` database, but `termcap` is the old obsolete database +//! and lacks a way to express support for the newer, more interesting +//! features. +//! +//! It's a bit of a mess. +//! +//! There's more: `slang` defined the concept of `COLORTERM` to workaround +//! some of these concerns so that it was possible to influence the +//! availability of relatively recent higher color palette extensions. +//! This allows the user the ability to "know better" about their terminal +//! than the local configuration allows. `COLORTERM` has the advantage of +//! being able to be passed on to remote systems via SSH. +//! +//! Regarding environment variables: on macOS the two main terminal +//! emulators export `TERM_PROGRAM` and `TERM_PROGRAM_VERSION` into the +//! environment, and if this were transported via SSH and adopted by +//! more terminal emulators then newer software could potentially also +//! look at this information too. +//! +//! Is there or will there ever be an ideal solution to this stuff? +//! Probably not. +//! +//! With all this in mind, this module presents a `Capabilities` struct +//! that holds information about a terminal. The `new_from_env` method +//! implements some heuristics (a fancy word for guessing) to compute +//! the terminal capabilities, but also offers a `ProbeHintsBuilder` +//! that can be used by the embedding application to override those choices. +use failure::{err_msg, Error}; +use semver::Version; +use std::env::var; +use terminfo::{self, capability as cap}; + +/// Use the `ProbeHintsBuilder` to configure an instance of +/// the `ProbeHints` struct. +#[derive(Debug, Default, Builder, Clone)] +#[builder(default)] +pub struct ProbeHints { + /// The contents of the TERM environment variable + term: Option, + + /// The contents of the COLORTERM environment variable. + /// http://invisible-island.net/ncurses/ncurses-slang.html#env_COLORTERM + colorterm: Option, + + /// The contents of the TERM_PROGRAM environment variable + term_program: Option, + + /// Override the choice of the number of colors + color_level: Option, + + /// The contents of the TERM_PROGRAM_VERSION environment variable + term_program_version: Option, + + /// Definitively set whether hyperlinks are supported. + /// The default is to assume yes as this is mostly harmless. + hyperlinks: Option, + + /// Configure whether sixel graphics are supported. + sixel: Option, + + /// Configure whether iTerm2 style graphics embedding is supported + /// See https://www.iterm2.com/documentation-images.html + iterm2_image: Option, + + /// Specify whether `bce`, background color erase, is supported. + /// http://invisible-island.net/ncurses/ncurses-slang.html#env_COLORTERM_BCE + bce: Option, + + /// The contents of the COLORTERM_BCE environment variable + colorterm_bce: Option, + + /// A loaded terminfo database entry + terminfo_db: Option, +} + +/// Describes the level of color support available +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum ColorLevel { + /// Basic ANSI colors; 8 colors + bright versions + Sixteen, + /// In addition to the ANSI 16 colors, this has 24 levels of grey + /// and 216 colors typically 6x6x6 color cube with 5 bits. There + /// is some variance in implementations: the precise color cube is + /// different in different emulators. + TwoFiftySix, + /// Commonly accepted as 24-bit RGB color. The implementation may + /// display these exactly as specified or it may match to an internal + /// palette with fewer than the theoretical maximum 16 million colors. + /// What we care about here is whether the terminal supports the escape + /// sequence to specify RGB values rather than a palette index. + TrueColor, +} + +pub struct Capabilities { + color_level: ColorLevel, + hyperlinks: bool, + sixel: bool, + iterm2_image: bool, + bce: bool, + terminfo_db: Option, +} + +impl Capabilities { + /// Detect the capabilities of the terminal and return the + /// Capability object holding the outcome. + /// This function inspects the environment variables to build + /// up configuration hints. + pub fn new_from_env() -> Result { + let mut hints = ProbeHintsBuilder::default(); + hints.term(var("TERM").ok()); + hints.colorterm(var("COLORTERM").ok()); + hints.colorterm_bce(var("COLORTERM_BCE").ok()); + hints.term_program(var("TERM_PROGRAM").ok()); + hints.term_program_version(var("TERM_PROGRAM_VERSION").ok()); + hints.terminfo_db(terminfo::Database::from_env().ok()); + Self::new_with_hints(hints.build().map_err(|e| err_msg(e))?) + } + + /// Given some hints and a writable handle to the terminal output stream, + /// compute the available terminal capabilities. + pub fn new_with_hints(hints: ProbeHints) -> Result { + let color_level = hints.color_level.unwrap_or_else(|| { + // If set, COLORTERM overrides any other source of information + match hints.colorterm.as_ref().map(String::as_ref) { + Some("truecolor") | Some("24bit") => ColorLevel::TrueColor, + Some(_) => ColorLevel::TwoFiftySix, + _ => { + // COLORTERM isn't set, so look at the terminfo. + if let Some(ref db) = hints.terminfo_db.as_ref() { + let has_true_color = db.get::() + .unwrap_or(cap::TrueColor(false)) + .0; + if has_true_color { + ColorLevel::TrueColor + } else if let Some(cap::MaxColors(n)) = db.get::() { + if n >= 256 { + ColorLevel::TwoFiftySix + } else { + ColorLevel::Sixteen + } + } else { + ColorLevel::Sixteen + } + } else if let Some(ref term) = hints.term { + // if we don't have TERMINFO, use a somewhat awful + // substring test against the TERM name. + if term.contains("256color") { + ColorLevel::TwoFiftySix + } else { + ColorLevel::Sixteen + } + } else { + ColorLevel::Sixteen + } + } + } + }); + + // I don't know of a way to detect SIXEL support, so we + // assume no by default. + let sixel = hints.sixel.unwrap_or(false); + + // The use of OSC 8 for hyperlinks means that it is generally + // safe to assume yes: if the terminal doesn't support it, + // the text will look "OK", although some versions of VTE based + // terminals had a bug where it look like garbage. + let hyperlinks = hints.hyperlinks.unwrap_or(true); + + let bce = hints.bce.unwrap_or_else(|| { + // Use the COLORTERM_BCE variable to override any terminfo + match hints.colorterm_bce.as_ref().map(String::as_ref) { + Some("1") => true, + _ => { + // Look it up from terminfo + hints + .terminfo_db + .as_ref() + .map(|db| { + db.get::() + .unwrap_or(cap::BackColorErase(false)) + .0 + }) + .unwrap_or(false) + } + } + }); + + let iterm2_image = hints.iterm2_image.unwrap_or_else(|| { + match hints.term_program.as_ref().map(String::as_ref) { + Some("iTerm.app") => { + // We're testing whether it has animated gif support + // here because the iTerm2 docs don't say when the + // image protocol was first implemented, but do mention + // the gif version. + Version::parse( + hints + .term_program_version + .as_ref() + .unwrap_or(&"0.0.0".to_owned()), + ) >= Version::parse("2.9.20150512") + } + _ => false, + } + }); + + Ok(Self { + color_level, + sixel, + hyperlinks, + iterm2_image, + bce, + terminfo_db: hints.terminfo_db, + }) + } + + /// Indicates how many colors are supported + pub fn color_level(&self) -> ColorLevel { + self.color_level + } + + /// Does the terminal support SIXEL graphics? + pub fn sixel(&self) -> bool { + self.sixel + } + + /// Does the terminal support hyperlinks? + /// See https://gist.github.com/egmontkob/eb114294efbcd5adb1944c9f3cb5feda + pub fn hyperlinks(&self) -> bool { + self.hyperlinks + } + + /// Does the terminal support the iTerm2 image protocol? + /// See https://www.iterm2.com/documentation-images.html + pub fn iterm2_image(&self) -> bool { + self.iterm2_image + } + + /// Is `bce`, background color erase supported? + /// http://invisible-island.net/ncurses/ncurses-slang.html#env_COLORTERM_BCE + pub fn bce(&self) -> bool { + self.bce + } + + /// Returns a reference to the loaded terminfo, if any. + pub fn terminfo_db(&self) -> Option<&terminfo::Database> { + self.terminfo_db.as_ref() + } +} + +#[cfg(test)] +mod test { + use super::*; + + fn load_terminfo() -> terminfo::Database { + // Load our own compiled data so that the tests have an + // environment that doesn't vary machine by machine. + let data = include_bytes!("../../data/xterm-256color"); + terminfo::Database::from_buffer(data.as_ref()).unwrap() + } + + #[test] + fn empty_hint() { + let caps = + Capabilities::new_with_hints(ProbeHintsBuilder::default().build().unwrap()).unwrap(); + + assert_eq!(caps.color_level(), ColorLevel::Sixteen); + assert_eq!(caps.sixel(), false); + assert_eq!(caps.hyperlinks(), true); + assert_eq!(caps.iterm2_image(), false); + assert_eq!(caps.bce(), false); + } + + #[test] + fn bce() { + let caps = Capabilities::new_with_hints( + ProbeHintsBuilder::default() + .colorterm_bce(Some("1".into())) + .build() + .unwrap(), + ).unwrap(); + + assert_eq!(caps.bce(), true); + } + + #[test] + fn bce_terminfo() { + let caps = Capabilities::new_with_hints( + ProbeHintsBuilder::default() + .terminfo_db(Some(load_terminfo())) + .build() + .unwrap(), + ).unwrap(); + + assert_eq!(caps.bce(), true); + } + + #[test] + fn terminfo_color() { + let caps = Capabilities::new_with_hints( + ProbeHintsBuilder::default() + .terminfo_db(Some(load_terminfo())) + .build() + .unwrap(), + ).unwrap(); + + assert_eq!(caps.color_level(), ColorLevel::TrueColor); + } + + #[test] + fn term_but_not_colorterm() { + let caps = Capabilities::new_with_hints( + ProbeHintsBuilder::default() + .term(Some("xterm-256color".into())) + .build() + .unwrap(), + ).unwrap(); + + assert_eq!(caps.color_level(), ColorLevel::TwoFiftySix); + } + + #[test] + fn colorterm_but_no_term() { + let caps = Capabilities::new_with_hints( + ProbeHintsBuilder::default() + .colorterm(Some("24bit".into())) + .build() + .unwrap(), + ).unwrap(); + + assert_eq!(caps.color_level(), ColorLevel::TrueColor); + } + + #[test] + fn term_and_colorterm() { + let caps = Capabilities::new_with_hints( + ProbeHintsBuilder::default() + .term(Some("xterm-256color".into())) + // bogus value + .colorterm(Some("24bot".into())) + .build() + .unwrap(), + ).unwrap(); + + assert_eq!(caps.color_level(), ColorLevel::TwoFiftySix); + + let caps = Capabilities::new_with_hints( + ProbeHintsBuilder::default() + .term(Some("xterm-256color".into())) + .colorterm(Some("24bit".into())) + .build() + .unwrap(), + ).unwrap(); + + assert_eq!(caps.color_level(), ColorLevel::TrueColor); + + let caps = Capabilities::new_with_hints( + ProbeHintsBuilder::default() + .term(Some("xterm-256color".into())) + .colorterm(Some("truecolor".into())) + .build() + .unwrap(), + ).unwrap(); + + assert_eq!(caps.color_level(), ColorLevel::TrueColor); + } + + #[test] + fn iterm2_image() { + let caps = Capabilities::new_with_hints( + ProbeHintsBuilder::default() + .term_program(Some("iTerm.app".into())) + .term_program_version(Some("1.0.0".into())) + .build() + .unwrap(), + ).unwrap(); + assert_eq!(caps.iterm2_image(), false); + + let caps = Capabilities::new_with_hints( + ProbeHintsBuilder::default() + .term_program(Some("iTerm.app".into())) + .term_program_version(Some("2.9.0".into())) + .build() + .unwrap(), + ).unwrap(); + assert_eq!(caps.iterm2_image(), false); + + let caps = Capabilities::new_with_hints( + ProbeHintsBuilder::default() + .term_program(Some("iTerm.app".into())) + .term_program_version(Some("2.9.20150512".into())) + .build() + .unwrap(), + ).unwrap(); + assert_eq!(caps.iterm2_image(), true); + + let caps = Capabilities::new_with_hints( + ProbeHintsBuilder::default() + .term_program(Some("iTerm.app".into())) + .term_program_version(Some("3.2.0beta5".into())) + .build() + .unwrap(), + ).unwrap(); + assert_eq!(caps.iterm2_image(), true); + } +} diff --git a/src/lib.rs b/src/lib.rs index 06dc5c45e..832f23f83 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,6 +1,7 @@ #[macro_use] extern crate failure; extern crate palette; +extern crate semver; extern crate serde; extern crate terminfo; #[macro_use] @@ -9,7 +10,10 @@ extern crate num; extern crate vte; #[macro_use] extern crate num_derive; +#[macro_use] +extern crate derive_builder; +pub mod caps; pub mod cell; pub mod color; pub mod escape;