Skip to main content

cellix_term/
detect.rs

1use std::io::{self, Write};
2use std::process::Command;
3#[cfg(unix)]
4use std::time::{Duration, Instant};
5
6use crate::probe::{Env, Multiplexer};
7
8const QUERY_ID: u32 = 31;
9#[cfg(unix)]
10const REPLY_TIMEOUT: Duration = Duration::from_millis(250);
11/// Terminals known to speak Kitty graphics, for when tmux hides the terminal from us.
12const KITTY_TERMINALS: [&str; 3] = ["ghostty", "kitty", "wezterm"];
13
14fn tmux_output(args: &[&str]) -> Option<String> {
15    let output = Command::new("tmux").args(args).output().ok()?;
16    output
17        .status
18        .success()
19        .then(|| String::from_utf8_lossy(&output.stdout).trim().to_string())
20}
21
22struct Reply {
23    kitty: bool,
24    cell: Option<(usize, usize)>,
25    pixel_mouse: bool,
26    paste_events: bool,
27    light: Option<bool>,
28    background: Option<(u8, u8, u8)>,
29}
30
31/// Where the questions go.
32#[derive(Clone, Copy, PartialEq, Eq)]
33enum Asking {
34    /// The terminal itself.
35    Terminal,
36    /// tmux, which answers for the terminal from what it knows.
37    Tmux,
38    /// tmux, with passthrough, so the cell size can be asked of the terminal outside it.
39    TmuxPassthrough,
40}
41
42/// What to ask a terminal. The graphics query goes only where it reaches the terminal
43/// itself: tmux takes that kind of sequence as a window title and shows it in its status bar.
44/// tmux makes up a cell size when its own terminal gives none (16 by 32, over a console), and
45/// images sized for that are letterboxed, so with passthrough the cell size goes past it.
46#[cfg(any(unix, test))]
47fn questions(asking: Asking) -> String {
48    let (cell, graphics) = match asking {
49        // Whether it has paste events is asked with the graphics: only the terminal itself
50        // can say, and only it would send them.
51        Asking::Terminal => (
52            "\x1b[16t".to_string(),
53            format!(
54                "\x1b_Gi={QUERY_ID},s=1,v=1,a=q,t=d,f=24;AAAA\x1b\\{}",
55                crate::clipboard::ASK_PASTE_EVENTS
56            ),
57        ),
58        Asking::Tmux => (String::new(), String::new()),
59        Asking::TmuxPassthrough => ("\x1bPtmux;\x1b\x1b[16t\x1b\\".to_string(), String::new()),
60    };
61    format!(
62        "{}{cell}\x1b[?1016$p{graphics}\x1b[c",
63        background_question(asking)
64    )
65}
66
67/// The question about the background. Inside tmux with passthrough it goes to the terminal
68/// itself too: tmux keeps that answer rather than passing it on, but it's how tmux learns the
69/// terminal's colour has changed since the client attached, so tmux's own answer, asked
70/// afterwards, is current. It comes ahead of the cell size, which the terminal answers next and
71/// tmux does pass on, so that answer arriving means tmux has the new colour.
72fn background_question(asking: Asking) -> &'static str {
73    match asking {
74        Asking::TmuxPassthrough => "\x1bPtmux;\x1b\x1b]11;?\x07\x1b\\",
75        Asking::Terminal | Asking::Tmux => "\x1b]11;?\x1b\\",
76    }
77}
78
79/// tmux's own answer about the background, asked once the terminal has told it.
80const ASK_TMUX_BACKGROUND: &str = "\x1b]11;?\x1b\\\x1b[c";
81
82/// Asks the terminal for its background again, as when Cellix comes back into focus: it may
83/// have turned from light to dark since Cellix started. Must run in raw mode, between reads
84/// of input. Gives whether it's light, and its colour, when the terminal said.
85pub fn background(multiplexer: Multiplexer, passthrough: bool) -> Option<(bool, (u8, u8, u8))> {
86    let asking = match multiplexer {
87        Multiplexer::Tmux if passthrough => Asking::TmuxPassthrough,
88        Multiplexer::Tmux => Asking::Tmux,
89        Multiplexer::None | Multiplexer::Zellij => Asking::Terminal,
90    };
91    let mut out = io::stdout();
92    let reply = if asking == Asking::TmuxPassthrough {
93        let refresh = format!(
94            "{}\x1bPtmux;\x1b\x1b[16t\x1b\\\x1b[c",
95            background_question(asking)
96        );
97        ask_for(&mut out, &refresh, asking, |reply| {
98            parse_cell_size(reply).is_some()
99        })
100        .ok()?;
101        ask_for(&mut out, ASK_TMUX_BACKGROUND, Asking::Tmux, |_| true).ok()?
102    } else {
103        let question = format!("{}\x1b[c", background_question(asking));
104        ask_for(&mut out, &question, asking, |reply| {
105            parse_background(reply).is_some()
106        })
107        .ok()?
108    };
109    let light = parse_background_is_light(&reply)?;
110    let (r, g, b) = parse_background(&reply)?;
111    let byte = |channel: f32| (channel * 255.0).round() as u8;
112    Some((light, (byte(r), byte(g), byte(b))))
113}
114
115/// Asks the terminal how big a cell is, in pixels, as (width, height): what it says is
116/// exact, where the window's pixels over its cells is a guess that takes its padding, and a
117/// tab bar some terminals count, for part of every row. Asked when the window's size has
118/// settled after a change. Must run in raw mode, between reads of input. `None` when the
119/// terminal doesn't say, or under tmux without passthrough, which would answer for itself.
120pub fn cell_size(multiplexer: Multiplexer, passthrough: bool) -> Option<(usize, usize)> {
121    let (question, asking) = match multiplexer {
122        Multiplexer::Tmux if passthrough => (
123            "\x1bPtmux;\x1b\x1b[16t\x1b\\\x1b[c",
124            Asking::TmuxPassthrough,
125        ),
126        Multiplexer::Tmux => return None,
127        Multiplexer::None | Multiplexer::Zellij => ("\x1b[16t\x1b[c", Asking::Terminal),
128    };
129    let mut out = io::stdout();
130    let reply = ask_for(&mut out, question, asking, |reply| {
131        asking != Asking::TmuxPassthrough || parse_cell_size(reply).is_some()
132    })
133    .ok()?;
134    parse_cell_size(&reply)
135}
136
137/// Asks for the cell size and for Kitty graphics, then device attributes, which every
138/// terminal answers, so a terminal without graphics doesn't cost the full timeout.
139/// Expects raw mode. Returns (kitty graphics, cell size).
140fn query_terminal(out: &mut impl Write, asking: Asking) -> io::Result<Reply> {
141    let mut reply = ask(out, asking)?;
142    if asking == Asking::TmuxPassthrough {
143        // The terminal told tmux its colour; now tmux's answer is current.
144        reply.extend(ask_for(out, ASK_TMUX_BACKGROUND, Asking::Tmux, |_| true)?);
145    }
146    Ok(Reply {
147        kitty: reply_has(&reply, format!("_Gi={QUERY_ID};OK").as_bytes()),
148        cell: parse_cell_size(&reply),
149        pixel_mouse: reply_has(&reply, b"?1016;1$y") || reply_has(&reply, b"?1016;2$y"),
150        paste_events: crate::clipboard::has_paste_events(&reply),
151        light: parse_background_is_light(&reply),
152        background: parse_background(&reply).map(|(r, g, b)| {
153            let byte = |channel: f32| (channel * 255.0).round() as u8;
154            (byte(r), byte(g), byte(b))
155        }),
156    })
157}
158
159/// A Windows console hands its input over as key events, not bytes to poll, so nothing is
160/// asked there: Cellix starts on the cell tier with its own colours, and nothing the terminal
161/// would answer is left to arrive as keys.
162#[cfg(not(unix))]
163fn ask(_out: &mut impl Write, _asking: Asking) -> io::Result<Vec<u8>> {
164    Ok(Vec::new())
165}
166
167#[cfg(not(unix))]
168fn ask_for(
169    _out: &mut impl Write,
170    _question: &str,
171    _asking: Asking,
172    _done: impl Fn(&[u8]) -> bool,
173) -> io::Result<Vec<u8>> {
174    Ok(Vec::new())
175}
176
177/// Writes the questions and reads the replies until device attributes, or the timeout.
178#[cfg(unix)]
179fn ask(out: &mut impl Write, asking: Asking) -> io::Result<Vec<u8>> {
180    let outside = asking == Asking::TmuxPassthrough;
181    ask_for(out, &questions(asking), asking, |reply| {
182        !outside || parse_cell_size(reply).is_some()
183    })
184}
185
186/// Writes `question`, which ends by asking for device attributes, and reads the replies
187/// until those come and `done` is satisfied, or the timeout.
188#[cfg(unix)]
189fn ask_for(
190    out: &mut impl Write,
191    question: &str,
192    asking: Asking,
193    done: impl Fn(&[u8]) -> bool,
194) -> io::Result<Vec<u8>> {
195    write!(out, "{question}")?;
196    out.flush()?;
197    // tmux answers device attributes at once, but the terminal outside answers through it a
198    // round trip later, so that answer is waited for too, a little longer.
199    let outside = asking == Asking::TmuxPassthrough;
200    let timeout = if outside {
201        REPLY_TIMEOUT * 3
202    } else {
203        REPLY_TIMEOUT
204    };
205    let deadline = Instant::now() + timeout;
206    let mut reply = Vec::new();
207    let mut buf = [0u8; 256];
208    while Instant::now() < deadline {
209        let left = deadline.saturating_duration_since(Instant::now());
210        let mut pollfd = libc::pollfd {
211            fd: libc::STDIN_FILENO,
212            events: libc::POLLIN,
213            revents: 0,
214        };
215        // SAFETY: pollfd is a valid, exclusively borrowed array of one element.
216        let ready = unsafe { libc::poll(&mut pollfd, 1, left.as_millis() as libc::c_int) };
217        if ready <= 0 {
218            break;
219        }
220        // SAFETY: buf is valid for writes of buf.len() bytes.
221        let n = unsafe { libc::read(libc::STDIN_FILENO, buf.as_mut_ptr().cast(), buf.len()) };
222        if n <= 0 {
223            break;
224        }
225        reply.extend_from_slice(&buf[..n as usize]);
226        if ends_device_attributes(&reply) && done(&reply) {
227            break;
228        }
229    }
230    Ok(reply)
231}
232
233fn parse_background_is_light(reply: &[u8]) -> Option<bool> {
234    let (r, g, b) = parse_background(reply)?;
235    Some(0.2126 * r + 0.7152 * g + 0.0722 * b > 0.5)
236}
237
238/// Reads `ESC ] 11 ; rgb:RRRR/GGGG/BBBB`, as fractions of full brightness.
239fn parse_background(reply: &[u8]) -> Option<(f32, f32, f32)> {
240    let needle = b"]11;rgb:";
241    let start = reply.windows(needle.len()).position(|w| w == needle)? + needle.len();
242    let rest = std::str::from_utf8(&reply[start..]).ok()?;
243    let mut channels = rest.split(['/', '\x1b', '\x07']).take(3).map(|part| {
244        let digits = part.len().clamp(1, 4) as u32;
245        u32::from_str_radix(part, 16)
246            .ok()
247            .map(|v| v as f32 / (16f32.powi(digits as i32) - 1.0))
248    });
249    Some((channels.next()??, channels.next()??, channels.next()??))
250}
251
252/// Finds a `ESC [ 6 ; height ; width t` reply.
253fn parse_cell_size(reply: &[u8]) -> Option<(usize, usize)> {
254    let start = reply.windows(4).position(|w| w == b"\x1b[6;")? + 4;
255    let rest = std::str::from_utf8(&reply[start..]).ok()?;
256    let (body, _) = rest.split_once('t')?;
257    let (height, width) = body.split_once(';')?;
258    Some((width.parse().ok()?, height.parse().ok()?))
259}
260
261fn reply_has(reply: &[u8], needle: &[u8]) -> bool {
262    reply.windows(needle.len()).any(|w| w == needle)
263}
264
265/// A primary device attributes reply looks like `ESC [ ? ... c`.
266#[cfg(any(unix, test))]
267fn ends_device_attributes(reply: &[u8]) -> bool {
268    let Some(start) = reply.windows(3).rposition(|w| w == b"\x1b[?") else {
269        return false;
270    };
271    reply[start..].contains(&b'c')
272}
273
274/// Works out what this terminal can do. Must run in raw mode, before input is read.
275pub fn detect(var: impl Fn(&str) -> Option<String>) -> io::Result<Env> {
276    let multiplexer = Multiplexer::detect(var);
277    if multiplexer == Multiplexer::Tmux {
278        // tmux swallows replies from the terminal outside it, so ask tmux instead.
279        // The terminal's own name where tmux heard it, as well as its TERM: over SSH, TERM is
280        // often a stand-in like xterm-256color when the server lacks the terminal's terminfo.
281        let client = tmux_output(&["display", "-p", "#{client_termname} #{client_termtype}"])
282            .unwrap_or_default()
283            .to_lowercase();
284        let kitty_graphics = KITTY_TERMINALS.iter().any(|t| client.contains(t));
285        let tmux_passthrough = tmux_output(&["show", "-Apv", "allow-passthrough"])
286            .is_some_and(|v| v == "on" || v == "all");
287        // tmux answers the colour query itself, from what it knows of the terminal, which with
288        // passthrough is brought up to date first.
289        let asking = if tmux_passthrough {
290            Asking::TmuxPassthrough
291        } else {
292            Asking::Tmux
293        };
294        let reply = query_terminal(&mut io::stdout(), asking)?;
295        return Ok(Env {
296            multiplexer,
297            kitty_graphics,
298            tmux_passthrough,
299            cell: reply.cell,
300            pixel_mouse: false,
301            paste_events: false,
302            light: reply.light,
303            background: reply.background,
304        });
305    }
306    let reply = query_terminal(&mut io::stdout(), Asking::Terminal)?;
307    Ok(Env {
308        multiplexer,
309        kitty_graphics: reply.kitty,
310        tmux_passthrough: false,
311        cell: reply.cell,
312        pixel_mouse: reply.pixel_mouse,
313        paste_events: reply.paste_events && multiplexer == Multiplexer::None,
314        light: reply.light,
315        background: reply.background,
316    })
317}
318
319#[cfg(test)]
320mod tests {
321    use super::*;
322
323    #[test]
324    fn inside_tmux_with_passthrough_the_terminal_itself_is_asked_its_colour() {
325        // tmux's own answer is what it knew when the client attached, and goes stale.
326        let asked = questions(Asking::TmuxPassthrough);
327        assert!(asked.starts_with("\x1bPtmux;\x1b\x1b]11;?"), "{asked:?}");
328        assert!(
329            !asked.contains("\x1b]11;?\x1b\\\x1b["),
330            "tmux isn't asked as well: {asked:?}"
331        );
332        assert!(questions(Asking::Terminal).starts_with("\x1b]11;?"));
333        assert!(questions(Asking::Tmux).starts_with("\x1b]11;?"));
334    }
335
336    #[test]
337    fn tmux_is_not_asked_about_graphics() {
338        assert!(!questions(Asking::Tmux).contains("\x1b_G"));
339        assert!(questions(Asking::Terminal).contains("\x1b_Gi=31"));
340        assert!(questions(Asking::Tmux).ends_with("\x1b[c"));
341    }
342
343    #[test]
344    fn the_cell_size_is_asked_past_tmux() {
345        // tmux would answer a plain question with a size it made up.
346        assert!(!questions(Asking::Tmux).contains("[16t"));
347        let past = questions(Asking::TmuxPassthrough);
348        assert!(past.contains("\x1bPtmux;\x1b\x1b[16t\x1b\\"), "{past:?}");
349        assert!(!past.contains("\x1b_G"));
350        // As tmux hands the outer terminal's answer back.
351        assert_eq!(parse_cell_size(b"\x1b[?62c\x1b[6;36;17t"), Some((17, 36)));
352    }
353
354    #[test]
355    fn device_attributes_reply_is_recognised() {
356        assert!(ends_device_attributes(b"\x1b[?62;22c"));
357        assert!(ends_device_attributes(b"\x1b_Gi=31;EBADF\x1b\\\x1b[?62c"));
358        assert!(!ends_device_attributes(b"\x1b[?62"));
359        assert!(!ends_device_attributes(b"\x1b_Gi=31;OK\x1b\\"));
360    }
361
362    #[test]
363    fn cell_size_reply_is_parsed() {
364        let zellij = b"\x1b[6;37;17t\x1b_Gi=31;OK\x1b\\\x1b[4;888;1394t\x1b[?62;52c";
365        assert_eq!(parse_cell_size(zellij), Some((17, 37)));
366        assert_eq!(parse_cell_size(b"\x1b[?62c"), None);
367    }
368
369    #[test]
370    fn the_background_decides_light_or_dark() {
371        let dark = b"\x1b]11;rgb:1e1e/1e1e/1e1e\x1b\\\x1b[?62c";
372        assert_eq!(parse_background_is_light(dark), Some(false));
373        assert_eq!(
374            parse_background_is_light(b"\x1b]11;rgb:ffff/fefe/fdfd\x07"),
375            Some(true)
376        );
377        assert_eq!(
378            parse_background_is_light(b"\x1b]11;rgb:ee/ee/ee\x07"),
379            Some(true)
380        );
381        assert_eq!(parse_background_is_light(b"\x1b[?62c"), None);
382    }
383
384    #[test]
385    fn query_reply_is_recognised() {
386        assert!(reply_has(b"\x1b_Gi=31;OK\x1b\\", b"_Gi=31;OK"));
387        assert!(!reply_has(b"\x1b_Gi=31;EINVAL\x1b\\", b"_Gi=31;OK"));
388    }
389}