use std::env;
use std::io::Read;
use std::process::{Child, Command, ExitStatus, Stdio};
use std::thread;
use std::time::{Duration, Instant};
const TIMEOUT: Duration = Duration::from_millis(500);
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
pub struct Features {
pub sixel: bool,
pub hyperlinks: bool,
}
pub fn features() -> Option<Features> {
let pane = env::var("TMUX_PANE").ok()?;
env::var_os("TMUX")?;
let mut child = Command::new("tmux")
.args([
"display-message",
"-p",
"-t",
&pane,
"#{client_termfeatures}",
])
.stdin(Stdio::null())
.stdout(Stdio::piped())
.stderr(Stdio::null())
.spawn()
.ok()?;
let status = wait_within(&mut child, TIMEOUT)?;
if !status.success() {
return None;
}
let mut out = String::new();
child.stdout.take()?.read_to_string(&mut out).ok()?;
Some(parse(&out))
}
pub(crate) fn wait_within(child: &mut Child, timeout: Duration) -> Option<ExitStatus> {
let start = Instant::now();
loop {
match child.try_wait() {
Ok(Some(status)) => return Some(status),
Ok(None) if start.elapsed() < timeout => thread::sleep(Duration::from_millis(5)),
_ => {
let _ = child.kill();
let _ = child.wait();
return None;
}
}
}
}
pub fn parse(list: &str) -> Features {
let mut features = Features::default();
for name in list.trim().split(',') {
match name.trim() {
"sixel" => features.sixel = true,
"hyperlinks" => features.hyperlinks = true,
_ => {}
}
}
features
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn reads_the_features_we_care_about() {
let f = parse("bpaste,ccolour,clipboard,hyperlinks,cstyle,focus,RGB,sixel,title\n");
assert_eq!(
f,
Features {
sixel: true,
hyperlinks: true
}
);
}
#[test]
fn a_terminal_without_them_is_not_promoted() {
let f = parse("bpaste,ccolour,clipboard,cstyle,focus,RGB,title\n");
assert_eq!(f, Features::default());
}
#[test]
fn nothing_at_all_is_not_a_yes() {
assert_eq!(parse(""), Features::default());
assert_eq!(parse("\n"), Features::default());
}
#[test]
#[cfg(unix)]
fn a_process_that_does_not_finish_is_killed() {
let mut slow = Command::new("sleep")
.arg("30")
.stdin(Stdio::null())
.spawn()
.unwrap();
let start = Instant::now();
assert_eq!(wait_within(&mut slow, Duration::from_millis(50)), None);
assert!(start.elapsed() < Duration::from_secs(5), "did not give up");
assert!(matches!(slow.try_wait(), Ok(Some(_))));
let mut quick = Command::new("true").spawn().unwrap();
assert!(wait_within(&mut quick, Duration::from_secs(5)).is_some_and(|s| s.success()));
}
#[test]
fn a_feature_is_matched_whole() {
assert_eq!(parse("nosixel,hyperlinksextra"), Features::default());
}
}