Skip to main content

nms/
graphics.rs

1//! Inline kitty graphics support for the `nms` REPL / one-shot
2//! evaluator.
3//!
4//! When the user evaluates a form whose value is a `Value::Bytes`
5//! that sniffs as an image AND stdout is connected to a kitty-graphics
6//! capable terminal, the value-printer emits a kitty APC sequence
7//! containing the image. The image renders inline at the cursor;
8//! subsequent text lines below sit beneath it.
9//!
10//! Capability detection is `rpc::chart::env_speaks_kitty`, so an
11//! `nms` invocation and a TUI session inside the same terminal agree
12//! on what to emit. The `--no-graphics` CLI flag short-circuits the
13//! detection for CI captures and for users whose terminal the
14//! heuristics misidentify.
15
16use base64::Engine;
17use base64::engine::general_purpose::STANDARD;
18
19/// Image format the kitty graphics protocol can transmit directly.
20/// `f=100` corresponds to PNG; `f=24`/`f=32` would be raw RGB/RGBA.
21/// We never auto-convert SVG → PNG inline (that lives in the
22/// `plotting` crate's `:format png` keyword path); SVG bytes fall
23/// through to the textual `#u8(...)` printer.
24#[derive(Debug, Clone, Copy, PartialEq, Eq)]
25pub enum ImageFormat {
26    Png,
27    Jpeg,
28}
29
30impl ImageFormat {
31    fn kitty_format_code(self) -> &'static str {
32        match self {
33            // Kitty's f=100 covers both PNG and JPEG decode; the
34            // protocol picks the right decoder via libpng/libjpeg.
35            ImageFormat::Png | ImageFormat::Jpeg => "100",
36        }
37    }
38}
39
40/// Detect the image format by magic bytes. Returns `None` for any
41/// payload that isn't a known inline-renderable raster.
42#[must_use]
43pub fn sniff(bytes: &[u8]) -> Option<ImageFormat> {
44    if bytes.len() >= 8 && bytes[0..8] == [0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A] {
45        return Some(ImageFormat::Png);
46    }
47    if bytes.len() >= 3 && bytes[0..3] == [0xFF, 0xD8, 0xFF] {
48        return Some(ImageFormat::Jpeg);
49    }
50    None
51}
52
53/// Wrap `bytes` of a known image format into a single kitty graphics
54/// APC sequence. The sequence is appended to `out`, which keeps
55/// callers in control of stdout buffering — `nms` prints it through
56/// the normal value-formatter, and tests can capture the bytes for
57/// comparison.
58///
59/// For payloads above 4096 bytes the protocol recommends chunking with
60/// the `m=1`/`m=0` continuation markers. We chunk at 4096 base64
61/// characters (≈ 3072 raw bytes) so even multi-MB charts transmit
62/// without exceeding terminal buffer limits.
63pub fn encode_kitty(format: ImageFormat, bytes: &[u8], out: &mut String) {
64    let encoded = STANDARD.encode(bytes);
65    const CHUNK: usize = 4096;
66    let f = format.kitty_format_code();
67
68    if encoded.len() <= CHUNK {
69        out.push_str("\x1b_Ga=T,f=");
70        out.push_str(f);
71        out.push(';');
72        out.push_str(&encoded);
73        out.push_str("\x1b\\");
74        return;
75    }
76
77    let mut i = 0;
78    let mut first = true;
79    while i < encoded.len() {
80        let end = (i + CHUNK).min(encoded.len());
81        let last = end == encoded.len();
82        out.push_str("\x1b_G");
83        if first {
84            out.push_str("a=T,f=");
85            out.push_str(f);
86            out.push(',');
87            first = false;
88        }
89        out.push_str(if last { "m=0;" } else { "m=1;" });
90        out.push_str(&encoded[i..end]);
91        out.push_str("\x1b\\");
92        i = end;
93    }
94}
95
96/// Convenience entry that returns the kitty APC payload as a String
97/// when the bytes are a known image and the terminal supports kitty
98/// graphics, otherwise `None`. The caller falls back to the textual
99/// `#u8(...)` printer when this returns `None`.
100#[must_use]
101pub fn try_render_inline<F>(bytes: &[u8], env_lookup: F) -> Option<String>
102where
103    F: Fn(&str) -> Option<String>,
104{
105    let format = sniff(bytes)?;
106    if !rpc::chart::env_speaks_kitty(env_lookup) {
107        return None;
108    }
109    let mut out = String::with_capacity(bytes.len() * 4 / 3 + 32);
110    encode_kitty(format, bytes, &mut out);
111    Some(out)
112}
113
114#[cfg(test)]
115mod tests {
116    use super::*;
117    use std::collections::HashMap;
118
119    fn env_from(pairs: &[(&str, &str)]) -> impl Fn(&str) -> Option<String> {
120        let map: HashMap<String, String> = pairs
121            .iter()
122            .map(|(k, v)| ((*k).to_string(), (*v).to_string()))
123            .collect();
124        move |k: &str| map.get(k).cloned()
125    }
126
127    #[test]
128    fn sniff_recognises_png_magic() {
129        let png = [0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, 0, 0];
130        assert_eq!(sniff(&png), Some(ImageFormat::Png));
131    }
132
133    #[test]
134    fn sniff_recognises_jpeg_magic() {
135        let jpeg = [0xFF, 0xD8, 0xFF, 0xE0, 0, 0];
136        assert_eq!(sniff(&jpeg), Some(ImageFormat::Jpeg));
137    }
138
139    #[test]
140    fn sniff_returns_none_for_random_bytes() {
141        assert_eq!(sniff(&[1, 2, 3, 4]), None);
142        assert_eq!(sniff(b"<svg ..."), None);
143        assert_eq!(sniff(&[]), None);
144    }
145
146    #[test]
147    fn encode_kitty_short_payload_uses_single_chunk() {
148        let mut out = String::new();
149        encode_kitty(ImageFormat::Png, &[0x89, 0x50, 0x4E, 0x47], &mut out);
150        // Single-chunk sequence: ESC _ G a=T,f=100;<b64>ESC\
151        assert!(out.starts_with("\x1b_Ga=T,f=100;"));
152        assert!(out.ends_with("\x1b\\"));
153        // Exactly one APC start sequence.
154        assert_eq!(out.matches("\x1b_G").count(), 1);
155    }
156
157    #[test]
158    fn encode_kitty_long_payload_chunks() {
159        let bytes = vec![0xABu8; 10_000];
160        let mut out = String::new();
161        encode_kitty(ImageFormat::Png, &bytes, &mut out);
162        // Expect multiple APC chunks; the first carries the format
163        // header, the last has m=0 (terminator).
164        let starts = out.matches("\x1b_G").count();
165        assert!(starts > 1, "got {starts} chunks");
166        assert!(
167            out.ends_with(
168                "m=0;"
169                    .chars()
170                    .chain("".chars())
171                    .collect::<String>()
172                    .as_str()
173            ) || out.contains("m=0;")
174        );
175    }
176
177    #[test]
178    fn try_render_inline_returns_none_for_non_image() {
179        let env = env_from(&[("KITTY_WINDOW_ID", "1")]);
180        assert!(try_render_inline(b"not an image", env).is_none());
181    }
182
183    #[test]
184    fn try_render_inline_returns_none_when_terminal_lacks_kitty() {
185        let env = env_from(&[("TERM", "xterm-256color")]);
186        let png = [0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A];
187        assert!(try_render_inline(&png, env).is_none());
188    }
189
190    #[test]
191    fn try_render_inline_returns_some_when_png_and_kitty() {
192        let env = env_from(&[("KITTY_WINDOW_ID", "1")]);
193        let png = [0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A];
194        let rendered = try_render_inline(&png, env).expect("should encode");
195        assert!(rendered.contains("\x1b_G"));
196    }
197}