use std::io::{self, Write};
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum Support {
Supported,
Unsupported,
Inferred,
#[default]
Unknown,
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct TerminalCapabilities {
pub kitty: Support,
pub sixel: Support,
pub iterm2: Support,
pub terminal: Option<String>,
pub background: Option<[u8; 3]>,
}
#[derive(Debug, Default)]
pub struct TerminalProbe {
capabilities: TerminalCapabilities,
state: InputState,
pending: Vec<u8>,
oversized: bool,
kitty_replied: bool,
complete: bool,
}
#[derive(Debug, Default)]
enum InputState {
#[default]
Ground,
Escape,
Csi,
String {
osc: bool,
escaped: bool,
},
}
impl TerminalProbe {
pub fn new() -> Self {
Self::default()
}
pub fn write_query(&self, output: &mut dyn Write) -> io::Result<()> {
output.write_all(
b"\x1b[>0q\x1b_Gi=31,s=1,v=1,a=q,t=d,f=32;AAAAAA==\x1b\\\x1b]11;?\x1b\\\x1b[c",
)?;
output.flush()
}
pub fn feed(&mut self, input: &[u8], unhandled: &mut Vec<u8>) {
for &byte in input {
if byte == 0x1b && matches!(self.state, InputState::Escape | InputState::Csi) {
unhandled.extend_from_slice(&self.pending);
self.pending.clear();
self.oversized = false;
self.state = InputState::Ground;
}
if matches!(self.state, InputState::Ground) && byte != 0x1b {
unhandled.push(byte);
continue;
}
if self.oversized {
unhandled.push(byte);
} else {
self.pending.push(byte);
}
let ended = match &mut self.state {
InputState::Ground => {
self.state = InputState::Escape;
false
}
InputState::Escape => {
self.state = match byte {
b'[' => InputState::Csi,
b']' => InputState::String {
osc: true,
escaped: false,
},
b'P' | b'_' | b'^' | b'X' => InputState::String {
osc: false,
escaped: false,
},
_ => InputState::Ground,
};
matches!(self.state, InputState::Ground)
}
InputState::Csi => (0x40..=0x7e).contains(&byte),
InputState::String { osc, escaped } => {
let ended = (*escaped && byte == b'\\') || (*osc && byte == 7);
*escaped = byte == 0x1b;
ended
}
};
if ended {
if !self.oversized
&& !parse_reply(
&self.pending,
&mut self.capabilities,
&mut self.kitty_replied,
&mut self.complete,
)
{
unhandled.extend_from_slice(&self.pending);
}
self.pending.clear();
self.oversized = false;
self.state = InputState::Ground;
} else if self.pending.len() == 4096 {
unhandled.extend_from_slice(&self.pending);
self.pending.clear();
self.oversized = true;
}
}
}
pub fn is_complete(&self) -> bool {
self.complete
}
pub fn finish(self, unhandled: &mut Vec<u8>) -> TerminalCapabilities {
unhandled.extend_from_slice(&self.pending);
self.capabilities
}
}
fn parse_reply(
bytes: &[u8],
capabilities: &mut TerminalCapabilities,
kitty_replied: &mut bool,
complete: &mut bool,
) -> bool {
let Ok(reply) = std::str::from_utf8(bytes) else {
return false;
};
if let Some(color) = reply
.strip_prefix("\x1b]11;rgb:")
.and_then(|s| s.strip_suffix("\x1b\\").or_else(|| s.strip_suffix('\x07')))
{
let mut components = color.split('/');
let mut rgb = [0; 3];
for channel in &mut rgb {
let Some(component) = components.next() else {
return false;
};
if !(1..=4).contains(&component.len())
|| !component.bytes().all(|byte| byte.is_ascii_hexdigit())
{
return false;
}
let value = u32::from_str_radix(component, 16).unwrap();
let maximum = (1u32 << (4 * component.len())) - 1;
*channel = ((value * 255 + maximum / 2) / maximum) as u8;
}
if components.next().is_some() {
return false;
}
capabilities.background = Some(rgb);
return true;
}
if let Some(body) = reply
.strip_prefix("\x1b_G")
.and_then(|s| s.strip_suffix("\x1b\\"))
{
let Some((parameters, message)) = body.split_once(';') else {
return false;
};
if parameters != "i=31" || message.is_empty() {
return false;
}
*kitty_replied = true;
capabilities.kitty = if message == "OK" {
Support::Supported
} else {
Support::Unknown
};
return true;
}
if let Some(body) = reply
.strip_prefix("\x1b[?")
.and_then(|s| s.strip_suffix('c'))
{
if !body
.bytes()
.all(|byte| byte.is_ascii_digit() || byte == b';')
{
return false;
}
let Ok(parameters) = body
.split(';')
.map(str::parse::<u16>)
.collect::<Result<Vec<_>, _>>()
else {
return false;
};
if (62..=65).contains(¶meters[0]) {
capabilities.sixel = if parameters[1..].contains(&4) {
Support::Supported
} else {
Support::Unsupported
};
}
if !*kitty_replied {
capabilities.kitty = Support::Unsupported;
}
*complete = true;
return true;
}
if let Some(name) = reply
.strip_prefix("\x1bP>|")
.and_then(|s| s.strip_suffix("\x1b\\"))
{
if name.is_empty() || name.chars().any(char::is_control) {
return false;
}
capabilities.iterm2 = if known_inline_images(name) {
Support::Inferred
} else {
Support::Unknown
};
capabilities.terminal = Some(name.into());
return true;
}
false
}
fn known_inline_images(name: &str) -> bool {
let Some((terminal, version)) = name.split_once(' ') else {
return false;
};
let mut parts = version.split('.');
let mut numbers = [0u32; 3];
for number in &mut numbers {
let Some(part) = parts.next() else {
return false;
};
if !part.bytes().all(|byte| byte.is_ascii_digit()) {
return false;
}
let Ok(value) = part.parse() else {
return false;
};
*number = value;
}
if parts.next().is_some() {
return false;
}
match terminal {
"Konsole" => numbers >= [23, 8, 5],
"iTerm2" => numbers >= [3, 0, 0],
_ => false,
}
}