termosaic 0.2.2

Semantic, structured output for human, machine-text, and opaque-byte destinations
Documentation
//! Terminal background-brightness discovery.
//!
//! Discovery is never automatic. [`Console`](crate::Console) construction does
//! no terminal round-trips, because rendering a table must not depend on the
//! terminal answering a question. Applications that want background-adaptive
//! styling opt in by calling [`from_env`] or, behind the `background-probe`
//! feature, [`probe`], and feeding the result to
//! [`themes::for_background`](crate::themes::for_background).

/// Relative brightness of the terminal background.
///
/// `Unknown` is a first-class answer, not an error: an application that cannot
/// learn the background must still render, and the background-agnostic
/// [`themes::default`](crate::themes::default) is the correct choice when it
/// does not know.
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub enum Background {
    #[default]
    Unknown,
    Dark,
    Light,
}

/// Read the background from `COLORFGBG` without touching the terminal.
///
/// Free of I/O and side effects. Only some terminals export the variable
/// (rxvt, konsole, and a few others); iTerm2, Ghostty, and Apple Terminal do
/// not, so a `Unknown` result is common and expected.
pub fn from_env() -> Background {
    std::env::var("COLORFGBG")
        .ok()
        .as_deref()
        .map_or(Background::Unknown, from_colorfgbg)
}

/// Parse the background field of a `COLORFGBG` value.
///
/// The value is `foreground;background` or `foreground;<extra>;background`;
/// the background is always the last field, as an ANSI palette index. A value
/// with no separator carries no background field and yields `Unknown`.
fn from_colorfgbg(value: &str) -> Background {
    if !value.contains(';') {
        return Background::Unknown;
    }
    let Some(field) = value.rsplit(';').next() else {
        return Background::Unknown;
    };
    match field.trim().parse::<u8>() {
        // 7 is light gray and 9..=15 are the bright half; every other index in
        // the 16-color palette is a dark seat.
        Ok(7) | Ok(9..=15) => Background::Light,
        Ok(0..=6) | Ok(8) => Background::Dark,
        Ok(_) | Err(_) => Background::Unknown,
    }
}

/// Classify a background color by relative luminance (ITU-R BT.709).
#[cfg(feature = "background-probe")]
fn from_rgb(red: u8, green: u8, blue: u8) -> Background {
    let luminance = 0.2126 * f32::from(red) + 0.7152 * f32::from(green) + 0.0722 * f32::from(blue);
    if luminance > 127.5 {
        Background::Light
    } else {
        Background::Dark
    }
}

#[cfg(feature = "background-probe")]
pub use probe_impl::probe;

#[cfg(feature = "background-probe")]
mod probe_impl {
    use std::time::Duration;

    use super::{Background, from_env, from_rgb};

    /// Ask the terminal for its background color with an OSC 11 query.
    ///
    /// Checks `COLORFGBG` first and only queries when that is inconclusive.
    /// The query opens `/dev/tty` directly rather than using stdin or stdout,
    /// so it works when either is redirected and never writes the escape
    /// sequence into a pipe.
    ///
    /// Returns [`Background::Unknown`] when there is no controlling terminal,
    /// the terminal does not answer within `timeout`, or the reply is invalid.
    /// All three cases select the agnostic theme.
    ///
    /// The probe holds the terminal in raw mode for at most `timeout` and
    /// restores the previous settings on every exit path. Call it once during
    /// startup, before any concurrent terminal reader exists. A concurrent
    /// reader can consume the reply.
    pub fn probe(timeout: Duration) -> Background {
        match from_env() {
            Background::Unknown => query(timeout),
            known => known,
        }
    }

    #[cfg(not(unix))]
    fn query(_timeout: Duration) -> Background {
        // Windows uses `COLORFGBG`; OSC 11 probing is Unix-only.
        Background::Unknown
    }

    #[cfg(unix)]
    fn query(timeout: Duration) -> Background {
        use std::fs::OpenOptions;
        use std::io::{Read, Write};
        use std::os::fd::AsRawFd;

        const QUERY: &[u8] = b"\x1b]11;?\x1b\\";

        let Ok(mut tty) = OpenOptions::new().read(true).write(true).open("/dev/tty") else {
            return Background::Unknown;
        };
        let fd = tty.as_raw_fd();
        let Some(raw) = RawMode::enter(fd) else {
            return Background::Unknown;
        };
        if tty.write_all(QUERY).is_err() || tty.flush().is_err() {
            drop(raw);
            return Background::Unknown;
        }

        let mut reply = Vec::new();
        let mut byte = [0u8; 1];
        let deadline = std::time::Instant::now() + timeout;
        let background = loop {
            let remaining = deadline.saturating_duration_since(std::time::Instant::now());
            if remaining.is_zero() || !readable(fd, remaining) {
                break Background::Unknown;
            }
            match tty.read(&mut byte) {
                Ok(1) => {}
                // EOF or an error mid-reply leaves nothing further to wait for.
                Ok(_) | Err(_) => break Background::Unknown,
            }
            // BEL and ST both terminate an OSC reply; `\` closes the two-byte
            // ESC-backslash form whose ESC we have already consumed.
            if matches!(byte[0], 0x07 | b'\\') {
                break parse_reply(&reply);
            }
            reply.push(byte[0]);
            // A terminal that answers with something other than an OSC 11
            // reply must not make us read forever.
            if reply.len() > 64 {
                break Background::Unknown;
            }
        };
        drop(raw);
        background
    }

    /// Extract the background color from an OSC 11 reply body.
    ///
    /// The body is `]11;rgb:RRRR/GGGG/BBBB` with 1-to-4 hex digits per
    /// component; each component is scaled to 8 bits by its own width, so
    /// `rgb:0/0/0` and `rgb:0000/0000/0000` agree.
    #[cfg_attr(test, allow(clippy::missing_const_for_fn))]
    fn parse_reply(reply: &[u8]) -> Background {
        let Ok(text) = std::str::from_utf8(reply) else {
            return Background::Unknown;
        };
        let Some(spec) = text.split_once("rgb:").map(|(_, rest)| rest) else {
            return Background::Unknown;
        };
        let mut components = spec.trim().split('/');
        let (Some(red), Some(green), Some(blue), None) = (
            components.next(),
            components.next(),
            components.next(),
            components.next(),
        ) else {
            return Background::Unknown;
        };
        let (Some(red), Some(green), Some(blue)) = (
            scale_component(red),
            scale_component(green),
            scale_component(blue),
        ) else {
            return Background::Unknown;
        };
        from_rgb(red, green, blue)
    }

    /// Scale one 1-to-4 hex-digit component to 8 bits.
    fn scale_component(value: &str) -> Option<u8> {
        let digits = u32::try_from(value.len()).ok()?;
        if !(1..=4).contains(&digits) {
            return None;
        }
        let parsed = u32::from_str_radix(value, 16).ok()?;
        let full = (1u32 << (digits * 4)) - 1;
        u8::try_from(parsed.min(full) * 255 / full).ok()
    }

    #[cfg(unix)]
    fn readable(fd: std::os::fd::RawFd, timeout: std::time::Duration) -> bool {
        let mut poll = libc::pollfd {
            fd,
            events: libc::POLLIN,
            revents: 0,
        };
        let millis = i32::try_from(timeout.as_millis()).unwrap_or(i32::MAX);
        // SAFETY: `poll` points at one initialized `pollfd` that outlives the
        // call, and the count matches.
        unsafe { libc::poll(&raw mut poll, 1, millis) == 1 }
    }

    /// Puts the terminal in raw mode and restores the prior settings on drop,
    /// including on early return from every failure path in `query`.
    #[cfg(unix)]
    struct RawMode {
        fd: std::os::fd::RawFd,
        saved: libc::termios,
    }

    #[cfg(unix)]
    impl RawMode {
        fn enter(fd: std::os::fd::RawFd) -> Option<Self> {
            // SAFETY: `termios` is a plain-old-data struct that `tcgetattr`
            // fully initializes when it succeeds.
            let mut saved: libc::termios = unsafe { std::mem::zeroed() };
            if unsafe { libc::tcgetattr(fd, &raw mut saved) } != 0 {
                return None;
            }
            let mut raw = saved;
            // Canonical mode would withhold the reply until a newline the
            // terminal never sends, and echo would paint it on the screen.
            raw.c_lflag &= !(libc::ICANON | libc::ECHO);
            if unsafe { libc::tcsetattr(fd, libc::TCSANOW, &raw const raw) } != 0 {
                return None;
            }
            Some(Self { fd, saved })
        }
    }

    #[cfg(unix)]
    impl Drop for RawMode {
        fn drop(&mut self) {
            // SAFETY: `self.saved` was filled by a successful `tcgetattr` on
            // the same descriptor, which is still open.
            unsafe { libc::tcsetattr(self.fd, libc::TCSANOW, &raw const self.saved) };
        }
    }

    #[cfg(test)]
    mod tests {
        use super::{Background, parse_reply, scale_component};

        #[test]
        fn parses_four_digit_components() {
            assert_eq!(
                parse_reply(b"]11;rgb:0000/0000/0000"),
                Background::Dark,
                "black background"
            );
            assert_eq!(
                parse_reply(b"]11;rgb:ffff/ffff/ffff"),
                Background::Light,
                "white background"
            );
        }

        #[test]
        fn component_width_does_not_change_the_value() {
            assert_eq!(scale_component("f"), Some(255));
            assert_eq!(scale_component("ff"), Some(255));
            assert_eq!(scale_component("ffff"), Some(255));
            assert_eq!(scale_component("0"), Some(0));
            assert_eq!(scale_component("8080"), Some(128));
        }

        #[test]
        fn malformed_replies_are_unknown() {
            for reply in [
                &b"]11;rgb:0000/0000"[..],
                &b"]11;rgb:0000/0000/0000/0000"[..],
                &b"]11;0000/0000/0000"[..],
                &b"]11;rgb:zzzz/0000/0000"[..],
                &b"]11;rgb:00000/0/0"[..],
                &b""[..],
            ] {
                assert_eq!(
                    parse_reply(reply),
                    Background::Unknown,
                    "{}",
                    String::from_utf8_lossy(reply)
                );
            }
        }

        #[test]
        fn solarized_light_reads_as_light_and_dark_as_dark() {
            // base3 #fdf6e3 and base03 #002b36.
            assert_eq!(parse_reply(b"]11;rgb:fd/f6/e3"), Background::Light);
            assert_eq!(parse_reply(b"]11;rgb:00/2b/36"), Background::Dark);
        }
    }
}

#[cfg(test)]
mod tests {
    use super::{Background, from_colorfgbg};

    #[test]
    fn colorfgbg_background_is_the_last_field() {
        assert_eq!(from_colorfgbg("15;0"), Background::Dark);
        assert_eq!(from_colorfgbg("0;15"), Background::Light);
        assert_eq!(from_colorfgbg("15;default;0"), Background::Dark);
        assert_eq!(from_colorfgbg("0;default;7"), Background::Light);
    }

    #[test]
    fn colorfgbg_without_a_background_field_is_unknown() {
        // A bare index is a foreground, not a background; reading it as one
        // would report light for the common `COLORFGBG=15`.
        assert_eq!(from_colorfgbg("15"), Background::Unknown);
        assert_eq!(from_colorfgbg(""), Background::Unknown);
        assert_eq!(from_colorfgbg("15;default"), Background::Unknown);
        assert_eq!(from_colorfgbg("15;255"), Background::Unknown);
    }

    #[cfg(feature = "background-probe")]
    #[test]
    fn luminance_is_weighted_not_averaged() {
        // Pure green is bright and pure blue is not, though both have the
        // same mean channel value.
        assert_eq!(super::from_rgb(0, 255, 0), Background::Light);
        assert_eq!(super::from_rgb(0, 0, 255), Background::Dark);
    }
}