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