Skip to main content

qframe/
graphics.rs

1//! Which way the terminal can show a picture: the [`Graphics`] an [`Env`](crate::env::Env)
2//! reports, and the rules that decide it.
3//!
4//! The runtime asks the terminal once, as it starts (see
5//! [`Env::graphics`](crate::env::Env::graphics)); what the terminal answered is then weighed
6//! against what is known of the environment. This module holds the parts that need no terminal:
7//! reading the answers and applying the rules.
8
9/// The way a picture can be drawn in this terminal, sharpest first.
10#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
11pub enum Graphics {
12    /// The kitty graphics protocol: real pixels, sent once and placed again by number. Kitty,
13    /// WezTerm, Ghostty and Konsole answer to it.
14    Kitty,
15    /// DEC sixel: real pixels, written out whole each time. foot, WezTerm, mlterm, Windows
16    /// Terminal and a configured xterm answer to it.
17    Sixel,
18    /// Half blocks: each cell shows two pixels, the upper one as the colour of `▀`, the lower one
19    /// as the cell's ground. Every terminal with 256 or more colours shows it, over any link.
20    HalfBlock,
21    /// No picture at all: the terminal has 16 colours or draws in ASCII, where a picture cannot
22    /// be told apart from noise. A picture's place shows what it is instead.
23    None,
24}
25
26impl Graphics {
27    /// Every value, sharpest first.
28    pub const ALL: [Self; 4] = [Self::Kitty, Self::Sixel, Self::HalfBlock, Self::None];
29
30    /// The name the `QUVYTA_GRAPHICS` environment variable takes for this value: `kitty`,
31    /// `sixel`, `halfblock` or `none`.
32    #[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    /// The value `name` stands for, as [`Graphics::name`] writes it; case and surrounding space
43    /// do not matter. `None` for any other name.
44    #[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
51/// The environment variable that decides the graphics, whatever the terminal answered.
52pub(crate) const VARIABLE: &str = "QUVYTA_GRAPHICS";
53
54/// What the environment knows about pictures before the terminal is asked, and what it answered.
55#[derive(Debug, Clone, Copy, PartialEq, Eq)]
56pub(crate) struct GraphicsFacts {
57    /// What the terminal answered to the probe; [`Graphics::HalfBlock`] until it is asked, and
58    /// when it did not answer.
59    pub(crate) answer: Graphics,
60    /// What `QUVYTA_GRAPHICS` forces, if it is set to a known name.
61    pub(crate) forced: Option<Graphics>,
62    /// Whether the application runs inside tmux or GNU screen.
63    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    /// Reads `QUVYTA_GRAPHICS`, `TMUX` and `STY` through `lookup`. An unknown name in
74    /// `QUVYTA_GRAPHICS` is returned as the second value, so the caller can report it.
75    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    /// The graphics in force for a terminal of `depth` drawing in `glyphs`.
89    ///
90    /// `QUVYTA_GRAPHICS` wins over everything, because the person who set it knows their
91    /// terminal. Otherwise 16 colours and ASCII glyphs show no picture, a multiplexer turns kitty
92    /// and sixel into half blocks because it does not pass them through, and what the terminal
93    /// answered decides the rest.
94    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    /// Whether asking the terminal could change the result: not when the variable decides, not
108    /// inside a multiplexer, and not at 16 colours, which a running application never leaves.
109    /// ASCII glyphs do not count, because a settings screen can switch them off while it runs.
110    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
115/// The question the runtime sends as it starts: a kitty graphics query for a one-pixel image
116/// (`a=q` only asks, nothing is stored or shown), then a primary device attributes request (DA1).
117/// Every terminal answers DA1 and answers in order, so its reply marks the end of the answers.
118pub(crate) const QUERY: &str = "\x1b_Gi=31,s=1,v=1,a=q,t=d,f=24;AAAA\x1b\\\x1b[c";
119
120/// Reads the terminal's answers to [`QUERY`]: an `OK` to the kitty query means kitty, a DA1
121/// answer that lists attribute `4` means sixel, and anything else, no answer included, means half
122/// blocks. Kitty wins when both are there, being the sharper and the cheaper to redraw.
123pub(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
133/// Whether `replies` hold the terminal's primary device attributes in full, which is the last
134/// answer to [`QUERY`].
135pub(crate) fn answered(replies: &[u8]) -> bool {
136    primary_attributes(replies).is_some()
137}
138
139/// Whether `replies` hold `ESC _ G i=31 … ; OK ESC \`, the kitty answer to the query's image 31.
140fn 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
159/// The attributes of a DA1 answer, `ESC [ ? 62 ; 4 ; 22 c`, when `replies` hold a whole one.
160fn 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    /// What kitty itself answers to DA1: a VT220 without sixel.
186    const DA1_PLAIN: &[u8] = b"\x1b[?62;c";
187    /// What foot answers: a VT220 with sixel (4) and ANSI colour (22).
188    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}