use super::caps::{Capabilities, GraphicsProtocol};
use super::style::Rgb;
use super::tmux;
#[cfg(unix)]
const TIMEOUT_MS: u64 = 300;
#[derive(Debug, Default, PartialEq)]
pub struct ProbeResult {
pub kitty_graphics: bool,
pub sixel: bool,
pub cell_px: Option<(u16, u16)>,
pub background: Option<Rgb>,
pub answered: bool,
}
fn apply_tmux(caps: &mut Capabilities, features: tmux::Features) {
if features.sixel && caps.graphics == GraphicsProtocol::Blocks {
caps.graphics = GraphicsProtocol::Sixel;
}
if features.hyperlinks {
caps.hyperlinks = true;
}
}
#[cfg(unix)]
fn queries() -> String {
let mut q = String::new();
q.push_str("\x1b_Gi=4294967295,s=1,v=1,a=q,t=d,f=24;AAAA\x1b\\");
q.push_str("\x1b]11;?\x1b\\");
q.push_str("\x1b[16t");
q.push_str("\x1b[c");
q
}
pub fn refine(caps: &mut Capabilities) {
if caps.multiplexed {
if let Some(features) = tmux::features() {
apply_tmux(caps, features);
}
}
let Some(result) = run() else { return };
if !result.answered {
return;
}
if let Some(px) = result.cell_px {
caps.cell_px = Some(px);
}
if result.background.is_some() {
caps.background = result.background;
}
if result.kitty_graphics && caps.graphics != GraphicsProtocol::Kitty && !caps.multiplexed {
caps.graphics = GraphicsProtocol::Kitty;
} else if result.sixel
&& !caps.multiplexed
&& matches!(
caps.graphics,
GraphicsProtocol::Blocks | GraphicsProtocol::None
)
{
caps.graphics = GraphicsProtocol::Sixel;
}
}
#[cfg(unix)]
pub fn run() -> Option<ProbeResult> {
let tty = unix::Tty::open()?;
let raw = tty.enter_raw()?;
let response = raw.exchange(queries().as_bytes(), TIMEOUT_MS);
drop(raw);
Some(parse(&response))
}
#[cfg(not(unix))]
pub fn run() -> Option<ProbeResult> {
None
}
pub fn parse(buf: &[u8]) -> ProbeResult {
let s = String::from_utf8_lossy(buf);
let mut out = ProbeResult::default();
if let Some(apc) = find_between(&s, "\x1b_G", "\x1b\\") {
if apc.contains(";OK") || apc.contains("i=4294967295") {
out.kitty_graphics = true;
out.answered = true;
}
}
if let Some(da) = find_between(&s, "\x1b[?", "c") {
out.answered = true;
out.sixel = da.split(';').any(|p| p.trim() == "4");
}
if let Some(t) = find_between(&s, "\x1b[6;", "t") {
let mut parts = t.split(';');
if let (Some(h), Some(w)) = (parts.next(), parts.next()) {
if let (Ok(h), Ok(w)) = (h.trim().parse::<u16>(), w.trim().parse::<u16>()) {
if h > 0 && w > 0 {
out.cell_px = Some((w, h));
out.answered = true;
}
}
}
}
if let Some(rgb) = s.split("\x1b]11;").nth(1) {
let payload = rgb.split(['\x07', '\x1b']).next().unwrap_or("");
if let Some(c) = parse_xparse_color(payload) {
out.background = Some(c);
out.answered = true;
}
}
out
}
fn parse_xparse_color(s: &str) -> Option<Rgb> {
let body = s.trim().strip_prefix("rgb:")?;
let mut it = body.split('/');
let mut next = || -> Option<u8> {
let part = it.next()?.trim();
if part.is_empty() || part.len() > 4 {
return None;
}
let v = u32::from_str_radix(part, 16).ok()?;
let max = (1u32 << (4 * part.len() as u32)) - 1;
Some(((v * 255 + max / 2) / max) as u8)
};
Some(Rgb(next()?, next()?, next()?))
}
fn find_between<'a>(haystack: &'a str, start: &str, end: &str) -> Option<&'a str> {
let i = haystack.find(start)? + start.len();
let rest = &haystack[i..];
let j = rest.find(end)?;
Some(&rest[..j])
}
#[cfg(unix)]
mod unix {
use std::fs::{File, OpenOptions};
use std::io::{Read, Write};
use std::os::unix::io::AsRawFd;
pub struct Tty(File);
impl Tty {
pub fn open() -> Option<Self> {
OpenOptions::new()
.read(true)
.write(true)
.open("/dev/tty")
.ok()
.map(Tty)
}
pub fn enter_raw(self) -> Option<RawTty> {
let fd = self.0.as_raw_fd();
unsafe {
let mut saved: libc::termios = std::mem::zeroed();
if libc::tcgetattr(fd, &mut saved) != 0 {
return None;
}
let mut raw = saved;
raw.c_lflag &= !(libc::ICANON | libc::ECHO);
raw.c_cc[libc::VMIN] = 0;
raw.c_cc[libc::VTIME] = 1;
if libc::tcsetattr(fd, libc::TCSANOW, &raw) != 0 {
return None;
}
Some(RawTty { tty: self, saved })
}
}
}
pub struct RawTty {
tty: Tty,
saved: libc::termios,
}
impl RawTty {
pub fn exchange(&self, query: &[u8], timeout_ms: u64) -> Vec<u8> {
let mut f = &self.tty.0;
if f.write_all(query).is_err() || f.flush().is_err() {
return Vec::new();
}
let deadline = std::time::Instant::now() + std::time::Duration::from_millis(timeout_ms);
let mut buf = Vec::with_capacity(256);
let mut chunk = [0u8; 256];
while std::time::Instant::now() < deadline {
match f.read(&mut chunk) {
Ok(0) => {
if sentinel_seen(&buf) {
break;
}
}
Ok(n) => {
buf.extend_from_slice(&chunk[..n]);
if sentinel_seen(&buf) {
break;
}
}
Err(_) => break,
}
}
buf
}
}
fn sentinel_seen(buf: &[u8]) -> bool {
let Some(start) = buf.windows(3).position(|w| w == b"\x1b[?") else {
return false;
};
buf[start..].contains(&b'c')
}
impl Drop for RawTty {
fn drop(&mut self) {
unsafe {
libc::tcsetattr(self.tty.0.as_raw_fd(), libc::TCSANOW, &self.saved);
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn detects_kitty_support() {
let r = parse(b"\x1b_Gi=4294967295;OK\x1b\\\x1b[?62;22c");
assert!(r.kitty_graphics);
assert!(r.answered);
}
#[test]
fn detects_sixel_from_device_attributes() {
let r = parse(b"\x1b[?62;1;2;4;6;9;22c");
assert!(r.sixel);
assert!(!r.kitty_graphics);
}
#[test]
fn does_not_mistake_other_attributes_for_sixel() {
let r = parse(b"\x1b[?65;14;40;22c");
assert!(!r.sixel);
}
#[test]
fn parses_cell_size_report() {
let r = parse(b"\x1b[6;34;15t\x1b[?62c");
assert_eq!(r.cell_px, Some((15, 34)));
}
#[test]
fn parses_background_color_at_several_depths() {
let r = parse(b"\x1b]11;rgb:1e1e/1e1e/2e2e\x1b\\\x1b[?62c");
assert_eq!(r.background, Some(Rgb(0x1e, 0x1e, 0x2e)));
let r = parse(b"\x1b]11;rgb:ff/ff/ff\x07\x1b[?62c");
assert_eq!(r.background, Some(Rgb(255, 255, 255)));
}
#[test]
fn silence_reports_nothing() {
let r = parse(b"");
assert!(!r.answered);
assert_eq!(r, ProbeResult::default());
}
#[test]
fn tmux_promotes_only_what_its_client_can_draw() {
let multiplexed = || Capabilities {
graphics: GraphicsProtocol::Blocks,
multiplexed: true,
is_tty: true,
..Default::default()
};
let mut caps = multiplexed();
apply_tmux(&mut caps, tmux::parse("bpaste,RGB,sixel,hyperlinks,title"));
assert_eq!(caps.graphics, GraphicsProtocol::Sixel);
assert!(caps.hyperlinks);
let mut caps = multiplexed();
apply_tmux(&mut caps, tmux::parse("bpaste,RGB,title"));
assert_eq!(
caps.graphics,
GraphicsProtocol::Blocks,
"half blocks are the only thing that survives everywhere"
);
assert!(!caps.hyperlinks);
}
#[test]
fn tmux_does_not_overrule_a_forced_protocol() {
for forced in [GraphicsProtocol::None, GraphicsProtocol::Kitty] {
let mut caps = Capabilities {
graphics: forced,
multiplexed: true,
is_tty: true,
..Default::default()
};
apply_tmux(&mut caps, tmux::parse("sixel"));
assert_eq!(caps.graphics, forced);
}
}
#[test]
fn probe_does_not_downgrade_a_known_good_terminal() {
let mut caps = Capabilities {
graphics: GraphicsProtocol::Kitty,
is_tty: true,
..Default::default()
};
let before = caps.graphics;
let result = ProbeResult::default();
if result.answered {
caps.graphics = GraphicsProtocol::None;
}
assert_eq!(caps.graphics, before);
}
}