1#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
11pub enum Graphics {
12 Kitty,
15 Sixel,
18 HalfBlock,
21 None,
24}
25
26impl Graphics {
27 pub const ALL: [Self; 4] = [Self::Kitty, Self::Sixel, Self::HalfBlock, Self::None];
29
30 #[must_use]
33 pub fn name(self) -> &'static str {
34 match self {
35 Self::Kitty => "kitty",
36 Self::Sixel => "sixel",
37 Self::HalfBlock => "halfblock",
38 Self::None => "none",
39 }
40 }
41
42 #[must_use]
45 pub fn from_name(name: &str) -> Option<Self> {
46 let name = name.trim();
47 Self::ALL.into_iter().find(|graphics| graphics.name().eq_ignore_ascii_case(name))
48 }
49}
50
51pub(crate) const VARIABLE: &str = "QUVYTA_GRAPHICS";
53
54#[derive(Debug, Clone, Copy, PartialEq, Eq)]
56pub(crate) struct GraphicsFacts {
57 pub(crate) answer: Graphics,
60 pub(crate) forced: Option<Graphics>,
62 pub(crate) multiplexed: bool,
64}
65
66impl Default for GraphicsFacts {
67 fn default() -> Self {
68 Self { answer: Graphics::HalfBlock, forced: None, multiplexed: false }
69 }
70}
71
72impl GraphicsFacts {
73 pub(crate) fn detect(lookup: impl Fn(&str) -> Option<String>) -> (Self, Option<String>) {
76 let set = |name: &str| lookup(name).filter(|value| !value.trim().is_empty());
77 let multiplexed = set("TMUX").is_some() || set("STY").is_some();
78 let (forced, unknown) = match set(VARIABLE) {
79 Some(value) => match Graphics::from_name(&value) {
80 Some(graphics) => (Some(graphics), None),
81 None => (None, Some(value)),
82 },
83 None => (None, None),
84 };
85 (Self { answer: Graphics::HalfBlock, forced, multiplexed }, unknown)
86 }
87
88 pub(crate) fn resolve(self, depth: crate::color::ColorDepth, glyphs: crate::icons::GlyphMode) -> Graphics {
95 if let Some(forced) = self.forced {
96 return forced;
97 }
98 if depth == crate::color::ColorDepth::Ansi16 || glyphs == crate::icons::GlyphMode::Ascii {
99 return Graphics::None;
100 }
101 match self.answer {
102 Graphics::Kitty | Graphics::Sixel if self.multiplexed => Graphics::HalfBlock,
103 answer => answer,
104 }
105 }
106
107 pub(crate) fn worth_asking(self, depth: crate::color::ColorDepth) -> bool {
111 self.forced.is_none() && !self.multiplexed && depth != crate::color::ColorDepth::Ansi16
112 }
113}
114
115pub(crate) const QUERY: &str = "\x1b_Gi=31,s=1,v=1,a=q,t=d,f=24;AAAA\x1b\\\x1b[c";
119
120pub(crate) fn classify(replies: &[u8]) -> Graphics {
124 if kitty_ok(replies) {
125 Graphics::Kitty
126 } else if primary_attributes(replies).is_some_and(|attributes| attributes.contains(&"4")) {
127 Graphics::Sixel
128 } else {
129 Graphics::HalfBlock
130 }
131}
132
133pub(crate) fn answered(replies: &[u8]) -> bool {
136 primary_attributes(replies).is_some()
137}
138
139fn kitty_ok(replies: &[u8]) -> bool {
141 let mut rest = replies;
142 while let Some(start) = find(rest, b"\x1b_G") {
143 let after = &rest[start + 3..];
144 let Some(end) = find(after, b"\x1b\\") else {
145 return false;
146 };
147 let body = &after[..end];
148 if let Some(split) = body.iter().position(|&byte| byte == b';') {
149 let (keys, message) = (&body[..split], &body[split + 1..]);
150 if keys.split(|&byte| byte == b',').any(|key| key == b"i=31") && message == b"OK" {
151 return true;
152 }
153 }
154 rest = &after[end + 2..];
155 }
156 false
157}
158
159fn primary_attributes(replies: &[u8]) -> Option<Vec<&str>> {
161 let mut rest = replies;
162 while let Some(start) = find(rest, b"\x1b[?") {
163 let body = &rest[start + 3..];
164 let length = body.iter().position(|&byte| !(byte.is_ascii_digit() || byte == b';'))?;
165 if body[length] == b'c' {
166 let text = std::str::from_utf8(&body[..length]).ok()?;
167 return Some(text.split(';').collect());
168 }
169 rest = &body[length..];
170 }
171 None
172}
173
174fn find(haystack: &[u8], needle: &[u8]) -> Option<usize> {
175 haystack.windows(needle.len()).position(|window| window == needle)
176}
177
178#[cfg(test)]
179mod tests {
180 use super::*;
181 use crate::color::ColorDepth;
182 use crate::icons::GlyphMode;
183
184 const KITTY_OK: &[u8] = b"\x1b_Gi=31;OK\x1b\\";
185 const DA1_PLAIN: &[u8] = b"\x1b[?62;c";
187 const DA1_SIXEL: &[u8] = b"\x1b[?62;4;22c";
189
190 #[test]
191 fn a_kitty_ok_before_the_attributes_means_kitty() {
192 assert_eq!(classify(&[KITTY_OK, DA1_PLAIN].concat()), Graphics::Kitty);
193 assert_eq!(classify(&[KITTY_OK, DA1_SIXEL].concat()), Graphics::Kitty, "the sharper of the two wins");
194 }
195
196 #[test]
197 fn attributes_listing_4_mean_sixel() {
198 assert_eq!(classify(DA1_SIXEL), Graphics::Sixel);
199 assert_eq!(classify(b"\x1b[?4c"), Graphics::Sixel, "4 alone");
200 assert_eq!(classify(b"\x1b[?64;1;2;4;6;9;15;18;21;22c"), Graphics::Sixel, "xterm as a VT340");
201 }
202
203 #[test]
204 fn attributes_without_4_mean_half_blocks() {
205 assert_eq!(classify(DA1_PLAIN), Graphics::HalfBlock);
206 assert_eq!(classify(b"\x1b[?1;2c"), Graphics::HalfBlock, "a VT100 with advanced video");
207 assert_eq!(classify(b"\x1b[?64;14;22c"), Graphics::HalfBlock, "14 is not 4");
208 }
209
210 #[test]
211 fn a_kitty_error_or_another_image_is_not_kitty() {
212 let refused = [&b"\x1b_Gi=31;ENOTSUPPORTED:no\x1b\\"[..], DA1_PLAIN].concat();
213 assert_eq!(classify(&refused), Graphics::HalfBlock);
214 let other = [&b"\x1b_Gi=7;OK\x1b\\"[..], DA1_PLAIN].concat();
215 assert_eq!(classify(&other), Graphics::HalfBlock);
216 }
217
218 #[test]
219 fn garbage_and_silence_mean_half_blocks() {
220 assert_eq!(classify(b""), Graphics::HalfBlock);
221 assert_eq!(classify(b"hello \x1b[?62;4"), Graphics::HalfBlock, "an unfinished answer");
222 assert_eq!(classify(b"\x1b_Gi=31;OK"), Graphics::HalfBlock, "an unterminated kitty answer");
223 assert_eq!(classify(b"\x1b[?6x4c\x1b\x1b_G;"), Graphics::HalfBlock);
224 assert_eq!(classify(&[0xff, 0x1b, b'[', b'?', 0xfe]), Graphics::HalfBlock);
225 }
226
227 #[test]
228 fn the_attributes_mark_the_end_of_the_answers() {
229 assert!(!answered(b""));
230 assert!(!answered(KITTY_OK), "the kitty answer comes first; the attributes are still due");
231 assert!(!answered(b"\x1b[?62;4"));
232 assert!(answered(&[KITTY_OK, DA1_PLAIN].concat()));
233 assert!(answered(DA1_SIXEL));
234 }
235
236 #[test]
237 fn a_multiplexer_turns_kitty_and_sixel_into_half_blocks() {
238 for variable in ["TMUX", "STY"] {
239 let lookup = |name: &str| (name == variable).then(|| "/tmp/tmux-1000/default,1234,0".to_owned());
240 let (mut facts, unknown) = GraphicsFacts::detect(lookup);
241 assert!(facts.multiplexed && unknown.is_none(), "{variable}");
242 for answer in [Graphics::Kitty, Graphics::Sixel, Graphics::HalfBlock] {
243 facts.answer = answer;
244 let graphics = facts.resolve(ColorDepth::TrueColor, GlyphMode::Unicode);
245 assert_eq!(graphics, Graphics::HalfBlock, "{variable} with {answer:?}");
246 }
247 assert!(!facts.worth_asking(ColorDepth::TrueColor), "a multiplexer needs no question");
248 }
249 let empty = |name: &str| (name == "TMUX").then(String::new);
250 assert!(!GraphicsFacts::detect(empty).0.multiplexed, "an empty variable is unset");
251 }
252
253 #[test]
254 fn outside_a_multiplexer_the_answer_decides() {
255 let (mut facts, _) = GraphicsFacts::detect(|_| None);
256 for answer in [Graphics::Kitty, Graphics::Sixel, Graphics::HalfBlock] {
257 facts.answer = answer;
258 assert_eq!(facts.resolve(ColorDepth::TrueColor, GlyphMode::Unicode), answer);
259 assert_eq!(facts.resolve(ColorDepth::Ansi256, GlyphMode::Nerd), answer);
260 }
261 assert!(facts.worth_asking(ColorDepth::Ansi256));
262 }
263
264 #[test]
265 fn sixteen_colours_and_ascii_show_no_picture() {
266 let facts = GraphicsFacts { answer: Graphics::Kitty, ..GraphicsFacts::default() };
267 assert_eq!(facts.resolve(ColorDepth::Ansi16, GlyphMode::Unicode), Graphics::None);
268 assert_eq!(facts.resolve(ColorDepth::TrueColor, GlyphMode::Ascii), Graphics::None);
269 assert!(!facts.worth_asking(ColorDepth::Ansi16), "16 colours never change while it runs");
270 assert!(facts.worth_asking(ColorDepth::TrueColor), "ASCII glyphs can be switched off while it runs");
271 }
272
273 #[test]
274 fn the_variable_wins_over_everything() {
275 for forced in Graphics::ALL {
276 let lookup = |name: &str| match name {
277 VARIABLE => Some(format!(" {} ", forced.name().to_uppercase())),
278 "TMUX" => Some("/tmp/tmux".to_owned()),
279 _ => None,
280 };
281 let (mut facts, unknown) = GraphicsFacts::detect(lookup);
282 assert_eq!((facts.forced, unknown), (Some(forced), None));
283 facts.answer = Graphics::Sixel;
284 assert_eq!(facts.resolve(ColorDepth::Ansi16, GlyphMode::Ascii), forced, "{forced:?}");
285 assert_eq!(facts.resolve(ColorDepth::TrueColor, GlyphMode::Unicode), forced, "{forced:?}");
286 assert!(!facts.worth_asking(ColorDepth::TrueColor), "the variable already decided");
287 }
288 }
289
290 #[test]
291 fn an_unknown_name_is_reported_and_ignored() {
292 let lookup = |name: &str| (name == VARIABLE).then(|| "pixels".to_owned());
293 let (facts, unknown) = GraphicsFacts::detect(lookup);
294 assert_eq!(facts.forced, None);
295 assert_eq!(unknown.as_deref(), Some("pixels"));
296 }
297
298 #[test]
299 fn names_read_back() {
300 for graphics in Graphics::ALL {
301 assert_eq!(Graphics::from_name(graphics.name()), Some(graphics));
302 }
303 assert_eq!(Graphics::from_name("half-block"), None);
304 }
305}