anitty 0.1.0

Anime character animation rendering for terminals
Documentation
//! Optional terminal capability probing, independent of rendering and playback.
//!
//! The host sends queries, owns terminal modes and deadlines, and supplies input.
//! Nothing in this module opens a TTY, reads stdin, or inspects the environment.

use std::io::{self, Write};

/// Evidence for a protocol on the queried terminal connection.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum Support {
    /// The terminal positively answered the protocol query.
    Supported,
    /// The terminal's device attributes do not advertise the protocol.
    Unsupported,
    /// A known terminal version suggests support; not a protocol confirmation.
    Inferred,
    /// No conclusive reply, including timeouts and graphics query errors.
    #[default]
    Unknown,
}

/// Results describe protocol availability, not complete backend compatibility.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct TerminalCapabilities {
    /// Direct RGBA transmission via the Kitty graphics protocol.
    pub kitty: Support,
    pub sixel: Support,
    /// Currently inferred only from known Konsole and iTerm2 versions.
    pub iterm2: Support,
    /// XTVERSION reply, when available.
    pub terminal: Option<String>,
    /// Default terminal background from OSC 11, rounded to RGB8.
    /// This is not the background of an arbitrary cell, image or translucent window.
    /// Missing or unrecognized replies leave this as `None`.
    pub background: Option<[u8; 3]>,
}

/// An explicitly driven, single-use capability probe.
///
/// Serialize queries with the host's terminal traffic. The Kitty query uses ID
/// 31 without storing or displaying an image; do not overlap it with another
/// outstanding query for that ID. Feed raw 7-bit terminal replies before the
/// host's key decoder. Unrecognized input is returned unchanged in `unhandled`.
/// The host must distinguish replies from pasted text before feeding this probe.
///
/// Stop after [`Self::is_complete`] or a host-chosen deadline, then call
/// [`Self::finish`] to recover any unfinished input. A timeout is not a negative
/// capability result. Multiplexer passthrough is the host's responsibility.
#[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()
    }

    /// Explicitly query XTVERSION, RGBA support and the default background, then DA.
    /// Call once on the same terminal connection that supplies replies.
    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()
    }

    /// Accept arbitrary input chunks. Append non-query input to `unhandled`.
    /// Partial control sequences are retained until completed or `finish`ed.
    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 {
                // Bound storage for unterminated/untrusted terminal strings,
                // while forwarding their remaining bytes through the terminator.
                unhandled.extend_from_slice(&self.pending);
                self.pending.clear();
                self.oversized = true;
            }
        }
    }

    /// Primary DA has arrived after the queries. Unknown fields may remain.
    pub fn is_complete(&self) -> bool {
        self.complete
    }

    /// Return results and any partial control sequence, without further I/O.
    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(&parameters[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;
    }
    // Conservative known versions, not claims about the earliest support.
    match terminal {
        "Konsole" => numbers >= [23, 8, 5],
        "iTerm2" => numbers >= [3, 0, 0],
        _ => false,
    }
}