1use base64::Engine;
17use base64::engine::general_purpose::STANDARD;
18
19#[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 ImageFormat::Png | ImageFormat::Jpeg => "100",
36 }
37 }
38}
39
40#[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
53pub 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#[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 assert!(out.starts_with("\x1b_Ga=T,f=100;"));
152 assert!(out.ends_with("\x1b\\"));
153 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 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}