rho-coding-agent 3.8.0

A fast Rust agent harness with a small footprint and opinionated defaults
Documentation
//! Whether the terminal draws Nerd Font symbols whatever font the user
//! picked, which `icons = "auto"` turns icons on for. Only terminals that
//! bundle the symbols qualify; any other may have them through a patched
//! font, which no query can tell, so it stays plain unless set to `nerd`.
//!
//! The terminal names itself in its XTVERSION reply (`CSI > q`), which the
//! startup probe asks for and which also works over SSH. A terminal that
//! does not answer is named by `TERM_PROGRAM`. Inside tmux or screen the
//! multiplexer draws through some other terminal it cannot vouch for.

use std::env;

use super::TerminalScreen;
use crate::config::IconMode;

#[cfg(test)]
#[path = "terminal_icons_tests.rs"]
mod tests;

/// WezTerm `20220319-142410-0fcdea07` bundled `Symbols Nerd Font Mono` as a
/// default fallback font. Source: wezterm `docs/changelog.md`, and
/// <https://wezterm.org/config/fonts.html> ("WezTerm bundles ... Nerd Font
/// Symbols").
const WEZTERM_NERD_FONT_SINCE: u32 = 20_220_319;

/// kitty 0.36.0 (2024-08-17) added a builtin NERD font for symbols the
/// system fonts lack. Source: kitty `docs/changelog.rst`, 0.36.0.
const KITTY_NERD_FONT_SINCE: (u32, u32, u32) = (0, 36, 0);

/// What the TUI's screen means for icons, as the startup probe found.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum IconScreen {
    /// A terminal that bundles Nerd Font symbols, outside tmux and screen.
    BundledSymbols,
    /// Any other terminal: symbols show only if its font has them.
    FontDependent,
    /// Minimal mode: rows already in scrollback cannot reflow, and an icon
    /// arriving with a finished path check would widen them.
    Scrollback,
}

impl IconScreen {
    /// Where the TUI draws, and in which terminal: `xtversion` is the
    /// startup probe's XTVERSION reply, if one came.
    pub(super) fn probe(
        screen: TerminalScreen,
        env: &TerminalEnv,
        xtversion: Option<&str>,
    ) -> Self {
        match screen {
            TerminalScreen::Main => Self::Scrollback,
            TerminalScreen::Alternate if ships_nerd_font(env, xtversion) => Self::BundledSymbols,
            TerminalScreen::Alternate => Self::FontDependent,
        }
    }

    /// Whether `mode` shows icons on this screen.
    pub(super) fn shows_icons(self, mode: IconMode) -> bool {
        match (mode, self) {
            (_, Self::Scrollback) | (IconMode::Plain, _) => false,
            (IconMode::Auto, Self::BundledSymbols) | (IconMode::Nerd, _) => true,
            (IconMode::Auto, Self::FontDependent) => false,
        }
    }
}

/// What the environment says about the terminal and any multiplexer.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub(super) struct TerminalEnv {
    term_program: Option<String>,
    term_program_version: Option<String>,
    /// tmux or screen runs this session: `TMUX` or `STY` is set, or `TERM`
    /// names one.
    multiplexed: bool,
}

impl TerminalEnv {
    pub(super) fn from_process() -> Self {
        Self::from_vars(|name| env::var(name).ok())
    }

    /// Reads the variables through `var`, which tests stub.
    fn from_vars(var: impl Fn(&str) -> Option<String>) -> Self {
        let multiplexer_term =
            var("TERM").is_some_and(|term| term.starts_with("screen") || term.starts_with("tmux"));
        Self {
            term_program: var("TERM_PROGRAM"),
            term_program_version: var("TERM_PROGRAM_VERSION"),
            multiplexed: multiplexer_term || var("TMUX").is_some() || var("STY").is_some(),
        }
    }
}

/// A terminal as far as icons go.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Terminal {
    /// Ghostty embeds Nerd Font symbols in every release. Source:
    /// <https://ghostty.org/docs/config> ("has built-in nerd fonts").
    Ghostty,
    /// The `YYYYMMDD` its version starts with, when it has one.
    WezTerm(Option<u32>),
    Kitty(Option<(u32, u32, u32)>),
    /// rho-ui's terminal, which bundles a Nerd Font for the symbols the
    /// code font lacks.
    RhoUi,
    Multiplexer,
    Other,
}

impl Terminal {
    /// The terminal an XTVERSION reply's text names: `ghostty 1.2.3`,
    /// `WezTerm 20240203-110809-5046fc22`, `kitty(0.36.4)`, `rho-ui 0.5.0`,
    /// or `tmux 3.4`.
    fn from_xtversion(reply: &str) -> Self {
        let reply = reply.trim();
        let split = reply.find([' ', '(']).unwrap_or(reply.len());
        let (name, version) = reply.split_at(split);
        let version = version.trim_matches(|ch: char| ch == ' ' || ch == '(' || ch == ')');
        Self::named(name, Some(version))
    }

    /// The terminal `TERM_PROGRAM` names, with `TERM_PROGRAM_VERSION`. kitty
    /// sets neither, so only its XTVERSION reply names it.
    fn from_env(env: &TerminalEnv) -> Self {
        env.term_program.as_deref().map_or(Self::Other, |name| {
            Self::named(name, env.term_program_version.as_deref())
        })
    }

    fn named(name: &str, version: Option<&str>) -> Self {
        match name.to_ascii_lowercase().as_str() {
            "ghostty" => Self::Ghostty,
            "wezterm" => Self::WezTerm(version.and_then(wezterm_date)),
            "kitty" => Self::Kitty(version.and_then(dotted_version)),
            "rho-ui" => Self::RhoUi,
            "tmux" | "screen" => Self::Multiplexer,
            _ => Self::Other,
        }
    }

    fn ships_nerd_font(self) -> bool {
        match self {
            Self::Ghostty | Self::RhoUi => true,
            Self::WezTerm(date) => date.is_some_and(|date| date >= WEZTERM_NERD_FONT_SINCE),
            Self::Kitty(version) => version.is_some_and(|version| version >= KITTY_NERD_FONT_SINCE),
            Self::Multiplexer | Self::Other => false,
        }
    }
}

/// Whether the terminal draws Nerd Font symbols out of the box, from its
/// environment and its XTVERSION reply, if it sent one.
fn ships_nerd_font(env: &TerminalEnv, xtversion: Option<&str>) -> bool {
    !env.multiplexed
        && xtversion
            .map_or_else(|| Terminal::from_env(env), Terminal::from_xtversion)
            .ships_nerd_font()
}

/// `20240203` from a WezTerm version such as `20240203-110809-5046fc22`.
fn wezterm_date(version: &str) -> Option<u32> {
    let date = version.get(..8)?;
    date.bytes()
        .all(|byte| byte.is_ascii_digit())
        .then(|| date.parse().ok())
        .flatten()
}

/// `(0, 36, 4)` from `0.36.4`; a missing part is `0`.
fn dotted_version(version: &str) -> Option<(u32, u32, u32)> {
    let mut parts = version.split('.').map(str::parse::<u32>);
    let major = parts.next()?.ok()?;
    let minor = parts.next().unwrap_or(Ok(0)).ok()?;
    let patch = parts.next().unwrap_or(Ok(0)).ok()?;
    Some((major, minor, patch))
}