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

            
16
use base64::Engine;
17
use 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)]
25
pub enum ImageFormat {
26
    Png,
27
    Jpeg,
28
}
29

            
30
impl ImageFormat {
31
3
    fn kitty_format_code(self) -> &'static str {
32
3
        match self {
33
            // Kitty's f=100 covers both PNG and JPEG decode; the
34
            // protocol picks the right decoder via libpng/libjpeg.
35
3
            ImageFormat::Png | ImageFormat::Jpeg => "100",
36
        }
37
3
    }
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]
43
8
pub fn sniff(bytes: &[u8]) -> Option<ImageFormat> {
44
8
    if bytes.len() >= 8 && bytes[0..8] == [0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A] {
45
3
        return Some(ImageFormat::Png);
46
5
    }
47
5
    if bytes.len() >= 3 && bytes[0..3] == [0xFF, 0xD8, 0xFF] {
48
1
        return Some(ImageFormat::Jpeg);
49
4
    }
50
4
    None
51
8
}
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.
63
3
pub fn encode_kitty(format: ImageFormat, bytes: &[u8], out: &mut String) {
64
3
    let encoded = STANDARD.encode(bytes);
65
    const CHUNK: usize = 4096;
66
3
    let f = format.kitty_format_code();
67

            
68
3
    if encoded.len() <= CHUNK {
69
2
        out.push_str("\x1b_Ga=T,f=");
70
2
        out.push_str(f);
71
2
        out.push(';');
72
2
        out.push_str(&encoded);
73
2
        out.push_str("\x1b\\");
74
2
        return;
75
1
    }
76

            
77
1
    let mut i = 0;
78
1
    let mut first = true;
79
5
    while i < encoded.len() {
80
4
        let end = (i + CHUNK).min(encoded.len());
81
4
        let last = end == encoded.len();
82
4
        out.push_str("\x1b_G");
83
4
        if first {
84
1
            out.push_str("a=T,f=");
85
1
            out.push_str(f);
86
1
            out.push(',');
87
1
            first = false;
88
3
        }
89
4
        out.push_str(if last { "m=0;" } else { "m=1;" });
90
4
        out.push_str(&encoded[i..end]);
91
4
        out.push_str("\x1b\\");
92
4
        i = end;
93
    }
94
3
}
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]
101
3
pub fn try_render_inline<F>(bytes: &[u8], env_lookup: F) -> Option<String>
102
3
where
103
3
    F: Fn(&str) -> Option<String>,
104
{
105
3
    let format = sniff(bytes)?;
106
2
    if !rpc::chart::env_speaks_kitty(env_lookup) {
107
1
        return None;
108
1
    }
109
1
    let mut out = String::with_capacity(bytes.len() * 4 / 3 + 32);
110
1
    encode_kitty(format, bytes, &mut out);
111
1
    Some(out)
112
3
}
113

            
114
#[cfg(test)]
115
mod tests {
116
    use super::*;
117
    use std::collections::HashMap;
118

            
119
3
    fn env_from(pairs: &[(&str, &str)]) -> impl Fn(&str) -> Option<String> {
120
3
        let map: HashMap<String, String> = pairs
121
3
            .iter()
122
3
            .map(|(k, v)| ((*k).to_string(), (*v).to_string()))
123
            .collect();
124
5
        move |k: &str| map.get(k).cloned()
125
3
    }
126

            
127
    #[test]
128
1
    fn sniff_recognises_png_magic() {
129
1
        let png = [0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, 0, 0];
130
1
        assert_eq!(sniff(&png), Some(ImageFormat::Png));
131
1
    }
132

            
133
    #[test]
134
1
    fn sniff_recognises_jpeg_magic() {
135
1
        let jpeg = [0xFF, 0xD8, 0xFF, 0xE0, 0, 0];
136
1
        assert_eq!(sniff(&jpeg), Some(ImageFormat::Jpeg));
137
1
    }
138

            
139
    #[test]
140
1
    fn sniff_returns_none_for_random_bytes() {
141
1
        assert_eq!(sniff(&[1, 2, 3, 4]), None);
142
1
        assert_eq!(sniff(b"<svg ..."), None);
143
1
        assert_eq!(sniff(&[]), None);
144
1
    }
145

            
146
    #[test]
147
1
    fn encode_kitty_short_payload_uses_single_chunk() {
148
1
        let mut out = String::new();
149
1
        encode_kitty(ImageFormat::Png, &[0x89, 0x50, 0x4E, 0x47], &mut out);
150
        // Single-chunk sequence: ESC _ G a=T,f=100;<b64>ESC\
151
1
        assert!(out.starts_with("\x1b_Ga=T,f=100;"));
152
1
        assert!(out.ends_with("\x1b\\"));
153
        // Exactly one APC start sequence.
154
1
        assert_eq!(out.matches("\x1b_G").count(), 1);
155
1
    }
156

            
157
    #[test]
158
1
    fn encode_kitty_long_payload_chunks() {
159
1
        let bytes = vec![0xABu8; 10_000];
160
1
        let mut out = String::new();
161
1
        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
1
        let starts = out.matches("\x1b_G").count();
165
1
        assert!(starts > 1, "got {starts} chunks");
166
1
        assert!(
167
1
            out.ends_with(
168
1
                "m=0;"
169
1
                    .chars()
170
1
                    .chain("".chars())
171
1
                    .collect::<String>()
172
1
                    .as_str()
173
1
            ) || out.contains("m=0;")
174
        );
175
1
    }
176

            
177
    #[test]
178
1
    fn try_render_inline_returns_none_for_non_image() {
179
1
        let env = env_from(&[("KITTY_WINDOW_ID", "1")]);
180
1
        assert!(try_render_inline(b"not an image", env).is_none());
181
1
    }
182

            
183
    #[test]
184
1
    fn try_render_inline_returns_none_when_terminal_lacks_kitty() {
185
1
        let env = env_from(&[("TERM", "xterm-256color")]);
186
1
        let png = [0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A];
187
1
        assert!(try_render_inline(&png, env).is_none());
188
1
    }
189

            
190
    #[test]
191
1
    fn try_render_inline_returns_some_when_png_and_kitty() {
192
1
        let env = env_from(&[("KITTY_WINDOW_ID", "1")]);
193
1
        let png = [0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A];
194
1
        let rendered = try_render_inline(&png, env).expect("should encode");
195
1
        assert!(rendered.contains("\x1b_G"));
196
1
    }
197
}