Skip to main content

oomtop_cli/
termprobe.rs

1//! Live terminal capability queries (UX §12.10), done once, only when stdin and stdout are both a TTY:
2//!
3//! | Query | Sent | Answer |
4//! |---|---|---|
5//! | background color | `OSC 11 ; ? ST` | `OSC 11 ; rgb:RRRR/GGGG/BBBB` (BEL or ST) |
6//! | Kitty keyboard protocol | `CSI ? u` | `CSI ? <flags> u` |
7//! | synchronized output | `CSI ? 2026 $ p` (DECRQM) | `CSI ? 2026 ; <1-4> $ y` |
8//! | SGR mouse | `CSI ? 1006 $ p` | `CSI ? 1006 ; <1-4> $ y` |
9//! | focus events | `CSI ? 1004 $ p` | `CSI ? 1004 ; <1-4> $ y` |
10//! | truecolor | `CSI 38;2;1;2;3 m` + `DCS $ q m ST` (DECRQSS) + `CSI 0 m` | `DCS 1 $ r …38:2:1:2:3 m ST` if kept |
11//! | sentinel | `CSI c` (DA1) | `CSI ? … c` — every terminal answers, so we stop waiting early |
12//!
13//! The truecolor query sets a foreground color, asks the terminal to report the current SGR, and resets it; a
14//! terminal that can't show 24-bit color reports a downsampled `38;5;n` (or nothing). No text is printed
15//! while the color is set, so nothing visible changes. Not sent on the Linux VT console (`TERM=linux`),
16//! whose parser treats `ESC P` as a palette command.
17//!
18//! The terminal is put in non-canonical, no-echo mode on `/dev/tty` for at most [`TIMEOUT`] and always
19//! restored. Parsing is a pure function ([`parse_replies`]) so it is unit-tested without a terminal.
20
21use serde::Serialize;
22use std::time::Duration;
23
24/// Upper bound for the whole probe (terminals answer in < 10 ms locally; SSH adds a round trip). 200 ms keeps
25/// the first frame under 300 ms (SPEC §14) even when the terminal never answers; a later answer is flushed.
26pub const TIMEOUT: Duration = Duration::from_millis(200);
27
28/// The full query, sentinel last.
29pub const QUERY: &[u8] =
30    b"\x1b]11;?\x1b\\\x1b[?u\x1b[?2026$p\x1b[?1006$p\x1b[?1004$p\x1b[38;2;1;2;3m\x1bP$qm\x1b\\\x1b[0m\x1b[c";
31
32/// For terminals that *print* queries they don't parse. Apple Terminal renders the final byte of each
33/// DECRQM (`CSI ? … $ p` → "p") and the body of DECRQSS (`DCS $ q m ST` → "$qm") as text — the `ppp$qm`
34/// seen before `oomtop doctor` output. It answers OSC 11 and DA1, so only those are asked.
35pub const QUERY_MINIMAL: &[u8] = b"\x1b]11;?\x1b\\\x1b[c";
36
37/// Returned to column 0 and cleared after the probe: wipes anything a terminal printed for a query it
38/// didn't understand (a terminal we don't know about, or Apple Terminal reached over SSH, where
39/// `TERM_PROGRAM` isn't forwarded). Runs before anything else is written, so the line holds nothing else.
40pub const WIPE_LINE: &[u8] = b"\r\x1b[2K";
41
42/// The query to send for `TERM_PROGRAM`, and whether it asks the DECRQM/kitty/DECRQSS questions.
43pub fn query_for(term_program: &str) -> (&'static [u8], bool) {
44    match term_program {
45        "Apple_Terminal" => (QUERY_MINIMAL, false),
46        _ => (QUERY, true),
47    }
48}
49
50/// DECRQM answer for one private mode.
51#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
52#[serde(rename_all = "snake_case")]
53pub enum ModeState {
54    /// 0: the terminal doesn't recognize the mode.
55    NotRecognized,
56    /// 1 / 2 / 3: supported (set, reset, permanently set).
57    Supported,
58    /// 4: permanently reset.
59    PermanentlyReset,
60}
61
62impl ModeState {
63    fn from_code(c: u32) -> Self {
64        match c {
65            1..=3 => ModeState::Supported,
66            4 => ModeState::PermanentlyReset,
67            _ => ModeState::NotRecognized,
68        }
69    }
70    pub fn supported(self) -> bool {
71        self == ModeState::Supported
72    }
73}
74
75/// What the terminal answered. `None` = no answer (unsupported, or swallowed by a multiplexer).
76#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)]
77pub struct Probe {
78    /// Background color from OSC 11.
79    pub background: Option<(u8, u8, u8)>,
80    /// Kitty keyboard protocol flags (`Some` = supported).
81    pub kitty_keyboard: Option<u32>,
82    pub sync_output: Option<ModeState>,
83    pub sgr_mouse: Option<ModeState>,
84    pub focus_events: Option<ModeState>,
85    /// DECRQSS answer to the 24-bit test color: `Some(true)` = kept exactly (truecolor), `Some(false)` =
86    /// downsampled or refused.
87    pub truecolor: Option<bool>,
88    /// DA1 answered (the probe completed; missing answers above are real "no"s).
89    pub da1: bool,
90    /// Raw DA1 attributes, e.g. "62;22".
91    pub da1_attrs: Option<String>,
92    /// Whether the DECRQM / kitty / DECRQSS questions were asked ([`query_for`]); when not, their missing
93    /// answers mean "unknown", not "no".
94    pub modes_queried: bool,
95}
96
97impl Probe {
98    /// `"#rrggbb"` of the background, if known.
99    pub fn background_hex(&self) -> Option<String> {
100        self.background.map(|(r, g, b)| format!("#{r:02x}{g:02x}{b:02x}"))
101    }
102}
103
104fn scale_hex(component: &str) -> Option<u8> {
105    if component.is_empty() || component.len() > 4 || !component.chars().all(|c| c.is_ascii_hexdigit()) {
106        return None;
107    }
108    let v = u32::from_str_radix(component, 16).ok()?;
109    let max = (1u32 << (4 * component.len() as u32)) - 1;
110    Some(((v * 255 + max / 2) / max) as u8)
111}
112
113/// Parses `rgb:RRRR/GGGG/BBBB` (1–4 hex digits per component) or `#rrggbb`.
114pub fn parse_osc_color(s: &str) -> Option<(u8, u8, u8)> {
115    if let Some(rest) = s.strip_prefix("rgb:").or_else(|| s.strip_prefix("rgba:")) {
116        let mut it = rest.split('/');
117        let r = scale_hex(it.next()?)?;
118        let g = scale_hex(it.next()?)?;
119        let b = scale_hex(it.next()?)?;
120        return Some((r, g, b));
121    }
122    let hex = s.strip_prefix('#')?;
123    if hex.len() == 6 {
124        let p = |i: usize| u8::from_str_radix(&hex[i..i + 2], 16).ok();
125        return Some((p(0)?, p(2)?, p(4)?));
126    }
127    None
128}
129
130/// DECRQSS reply body (between `ESC P` and ST) for the SGR query: `1$r<sgr>m` (valid) or `0$r` (refused).
131/// Accepts both `38;2;1;2;3` and the colon forms `38:2:1:2:3` / `38:2::1:2:3` (xterm's empty color space).
132pub fn truecolor_from_decrqss(body: &str) -> Option<bool> {
133    if body.starts_with("0$r") {
134        return Some(false);
135    }
136    let sgr = body.strip_prefix("1$r")?;
137    let sgr = sgr.strip_suffix('m').unwrap_or(sgr);
138    let toks: Vec<&str> = sgr.split([';', ':']).collect();
139    for i in 0..toks.len() {
140        if toks[i] == "38" && toks.get(i + 1) == Some(&"2") {
141            let rgb: Vec<&str> = toks[i + 2..]
142                .iter()
143                .copied()
144                .filter(|t| !t.is_empty())
145                .take(3)
146                .collect();
147            return Some(rgb == ["1", "2", "3"]);
148        }
149    }
150    Some(false)
151}
152
153/// Parses everything the terminal wrote back (in any order, possibly interleaved with nothing else).
154pub fn parse_replies(buf: &[u8]) -> Probe {
155    // Replies to the full [`QUERY`]; `probe_tty` overrides this for [`QUERY_MINIMAL`].
156    let mut p = Probe {
157        modes_queried: true,
158        ..Default::default()
159    };
160    let mut i = 0;
161    while i < buf.len() {
162        if buf[i] != 0x1b || i + 1 >= buf.len() {
163            i += 1;
164            continue;
165        }
166        match buf[i + 1] {
167            b']' => {
168                // OSC ... terminated by BEL or ESC \
169                let start = i + 2;
170                let mut j = start;
171                let mut end = None;
172                while j < buf.len() {
173                    if buf[j] == 0x07 {
174                        end = Some((j, j + 1));
175                        break;
176                    }
177                    if buf[j] == 0x1b && j + 1 < buf.len() && buf[j + 1] == b'\\' {
178                        end = Some((j, j + 2));
179                        break;
180                    }
181                    j += 1;
182                }
183                let Some((body_end, next)) = end else { break };
184                let body = String::from_utf8_lossy(&buf[start..body_end]);
185                if let Some(color) = body.strip_prefix("11;") {
186                    p.background = parse_osc_color(color.trim());
187                }
188                i = next;
189            }
190            b'P' => {
191                // DCS ... ST (only DECRQSS answers are expected)
192                let start = i + 2;
193                let Some(off) = buf[start..].windows(2).position(|w| w == b"\x1b\\") else {
194                    break;
195                };
196                let body = String::from_utf8_lossy(&buf[start..start + off]);
197                if body.contains("$r") {
198                    p.truecolor = truecolor_from_decrqss(&body);
199                }
200                i = start + off + 2;
201            }
202            b'[' => {
203                // CSI params final
204                let start = i + 2;
205                let mut j = start;
206                while j < buf.len() && !(0x40..=0x7e).contains(&buf[j]) {
207                    j += 1;
208                }
209                if j >= buf.len() {
210                    break;
211                }
212                let params = String::from_utf8_lossy(&buf[start..j]).into_owned();
213                let fin = buf[j];
214                if let Some(q) = params.strip_prefix('?') {
215                    match fin {
216                        b'u' => p.kitty_keyboard = q.parse().ok().or(Some(0)),
217                        b'c' => {
218                            p.da1 = true;
219                            p.da1_attrs = Some(q.to_string());
220                        }
221                        b'y' => {
222                            // DECRPM: ?<mode>;<state>$y
223                            if let Some(body) = q.strip_suffix('$') {
224                                if let Some((mode, state)) = body.split_once(';') {
225                                    let st = ModeState::from_code(state.parse().unwrap_or(0));
226                                    match mode {
227                                        "2026" => p.sync_output = Some(st),
228                                        "1006" => p.sgr_mouse = Some(st),
229                                        "1004" => p.focus_events = Some(st),
230                                        _ => {}
231                                    }
232                                }
233                            }
234                        }
235                        _ => {}
236                    }
237                }
238                i = j + 1;
239            }
240            _ => i += 1,
241        }
242    }
243    p
244}
245
246/// True when both stdin and stdout are terminals (the only case in which we query).
247pub fn interactive() -> bool {
248    use std::io::IsTerminal;
249    std::io::stdin().is_terminal() && std::io::stdout().is_terminal()
250}
251
252/// Terminals that must not be queried: `dumb` answers nothing, and the Linux VT console (`linux`) parses
253/// `ESC P` / `ESC ]` as palette commands.
254pub fn skip_probe_for(term: &str) -> bool {
255    term == "dumb" || term == "linux" || term.is_empty()
256}
257
258/// Queries the controlling terminal. `None` when not interactive, `TERM` is `dumb`/`linux`/unset, or
259/// `/dev/tty` can't be used.
260#[cfg(unix)]
261pub fn probe() -> Option<Probe> {
262    if !interactive() || skip_probe_for(&std::env::var("TERM").unwrap_or_default()) {
263        return None;
264    }
265    probe_tty(TIMEOUT, &std::env::var("TERM_PROGRAM").unwrap_or_default())
266}
267
268#[cfg(not(unix))]
269pub fn probe() -> Option<Probe> {
270    None
271}
272
273/// Waits until `fd` is readable or `timeout` passes. Uses `select(2)`: on macOS `poll(2)` on `/dev/tty`
274/// returns `POLLNVAL` at once (tty devices don't support poll there), which made the probe give up before
275/// the terminal answered — the answers then arrived in cooked mode, were echoed, and read as keystrokes.
276#[cfg(unix)]
277pub(crate) fn wait_readable(fd: i32, timeout: Duration) -> bool {
278    if fd < 0 || fd as usize >= libc::FD_SETSIZE {
279        return false;
280    }
281    // SAFETY: fd_set is plain data; FD_ZERO/FD_SET write inside it for fd < FD_SETSIZE.
282    let mut set: libc::fd_set = unsafe { std::mem::zeroed() };
283    unsafe {
284        libc::FD_ZERO(&mut set);
285        libc::FD_SET(fd, &mut set);
286    }
287    let mut tv = libc::timeval {
288        tv_sec: timeout.as_secs() as libc::time_t,
289        tv_usec: timeout.subsec_micros() as libc::suseconds_t,
290    };
291    loop {
292        // SAFETY: valid fd_set and timeval; the other sets are null.
293        let n = unsafe {
294            libc::select(
295                fd + 1,
296                &mut set,
297                std::ptr::null_mut(),
298                std::ptr::null_mut(),
299                &mut tv,
300            )
301        };
302        if n < 0 && std::io::Error::last_os_error().raw_os_error() == Some(libc::EINTR) {
303            continue;
304        }
305        // SAFETY: `set` was filled by select.
306        return n > 0 && unsafe { libc::FD_ISSET(fd, &set) };
307    }
308}
309
310#[cfg(unix)]
311fn probe_tty(timeout: Duration, term_program: &str) -> Option<Probe> {
312    use std::io::{Read, Write};
313    use std::os::fd::AsRawFd;
314    use std::time::Instant;
315
316    let mut tty = std::fs::OpenOptions::new()
317        .read(true)
318        .write(true)
319        .open("/dev/tty")
320        .ok()?;
321    let fd = tty.as_raw_fd();
322    // SAFETY: termios is plain data; tcgetattr fills it for a valid fd.
323    let mut orig: libc::termios = unsafe { std::mem::zeroed() };
324    if unsafe { libc::tcgetattr(fd, &mut orig) } != 0 {
325        return None;
326    }
327    let mut raw = orig;
328    raw.c_lflag &= !(libc::ICANON | libc::ECHO);
329    raw.c_cc[libc::VMIN] = 0;
330    raw.c_cc[libc::VTIME] = 0;
331    // SAFETY: valid fd and termios.
332    if unsafe { libc::tcsetattr(fd, libc::TCSANOW, &raw) } != 0 {
333        return None;
334    }
335    struct Restore(i32, libc::termios);
336    impl Drop for Restore {
337        fn drop(&mut self) {
338            // SAFETY: restoring the attributes read above on the same fd.
339            unsafe {
340                libc::tcsetattr(self.0, libc::TCSANOW, &self.1);
341            }
342        }
343    }
344    let _restore = Restore(fd, orig);
345
346    let (query, modes_queried) = query_for(term_program);
347    if tty.write_all(query).and_then(|_| tty.flush()).is_err() {
348        return None;
349    }
350    let deadline = Instant::now() + timeout;
351    let mut buf = Vec::with_capacity(256);
352    let mut chunk = [0u8; 256];
353    loop {
354        let left = deadline.saturating_duration_since(Instant::now());
355        if left.is_zero() {
356            break;
357        }
358        if !wait_readable(fd, left) {
359            break;
360        }
361        match tty.read(&mut chunk) {
362            Ok(0) => break,
363            Ok(k) => {
364                buf.extend_from_slice(&chunk[..k]);
365                if parse_replies(&buf).da1 || buf.len() > 4096 {
366                    break;
367                }
368            }
369            Err(_) => break,
370        }
371    }
372    let mut p = parse_replies(&buf);
373    p.modes_queried = modes_queried;
374    let _ = tty.write_all(WIPE_LINE).and_then(|_| tty.flush());
375    if !p.da1 {
376        // Timed out: drop whatever part of the answers already arrived so it isn't read as keystrokes.
377        // SAFETY: valid fd; TCIFLUSH only discards unread input.
378        unsafe {
379            libc::tcflush(fd, libc::TCIFLUSH);
380        }
381    }
382    Some(p)
383}
384
385#[cfg(test)]
386mod tests {
387    use super::*;
388
389    /// Apple Terminal prints DECRQM finals and DECRQSS bodies ("ppp$qm"); it is only asked OSC 11 + DA1.
390    #[test]
391    fn apple_terminal_gets_only_queries_it_parses() {
392        let (q, modes) = query_for("Apple_Terminal");
393        assert!(!modes);
394        let q = String::from_utf8_lossy(q);
395        assert!(!q.contains("$p"), "no DECRQM: {q:?}");
396        assert!(!q.contains("\x1bP"), "no DCS/DECRQSS: {q:?}");
397        assert!(!q.contains("[?u"), "no kitty query: {q:?}");
398        assert!(
399            q.starts_with("\x1b]11;?") && q.ends_with("\x1b[c"),
400            "OSC 11 then the DA1 sentinel"
401        );
402        let (full, modes) = query_for("ghostty");
403        assert!(modes);
404        assert_eq!(full, QUERY);
405        assert_eq!(WIPE_LINE, b"\r\x1b[2K");
406    }
407
408    #[test]
409    fn parses_a_full_ghostty_style_answer() {
410        let reply =
411            b"\x1b]11;rgb:1e1e/1e1e/2e2e\x1b\\\x1b[?1u\x1b[?2026;2$y\x1b[?1006;2$y\x1b[?1004;2$y\x1b[?62;22c";
412        let p = parse_replies(reply);
413        assert_eq!(p.background, Some((0x1e, 0x1e, 0x2e)));
414        assert_eq!(p.background_hex().as_deref(), Some("#1e1e2e"));
415        assert_eq!(p.kitty_keyboard, Some(1));
416        assert_eq!(p.sync_output, Some(ModeState::Supported));
417        assert_eq!(p.sgr_mouse, Some(ModeState::Supported));
418        assert_eq!(p.focus_events, Some(ModeState::Supported));
419        assert!(p.da1);
420        assert_eq!(p.da1_attrs.as_deref(), Some("62;22"));
421    }
422
423    #[test]
424    fn terminal_app_style_minimal_answer() {
425        // Only DA1 and a BEL-terminated OSC 11 with 2-digit components; no Kitty, DECRQM unknown.
426        let reply = b"\x1b]11;rgb:ff/ff/ff\x07\x1b[?2026;0$y\x1b[?1;2c";
427        let p = parse_replies(reply);
428        assert_eq!(p.background, Some((255, 255, 255)));
429        assert_eq!(p.kitty_keyboard, None);
430        assert_eq!(p.sync_output, Some(ModeState::NotRecognized));
431        assert!(!p.sync_output.unwrap().supported());
432        assert_eq!(p.sgr_mouse, None);
433        assert!(p.da1);
434    }
435
436    #[test]
437    fn garbage_and_truncation_never_panic() {
438        for b in [
439            &b""[..],
440            b"\x1b",
441            b"\x1b]11;rgb:zz/zz/zz\x07",
442            b"\x1b]11;rgb:1234",
443            b"\x1b[?2026;",
444            b"\x1b[?u",
445            b"hello\x1b[?1;2c",
446        ] {
447            let _ = parse_replies(b);
448        }
449        assert_eq!(parse_replies(b"\x1b[?u").kitty_keyboard, Some(0));
450        assert_eq!(parse_replies(b"\x1b]11;rgb:zz/zz/zz\x07").background, None);
451    }
452
453    #[test]
454    fn truecolor_via_decrqss() {
455        // kitty / WezTerm / Ghostty style (colon form), xterm style (empty color space), semicolon form.
456        for body in ["1$r38:2:1:2:3m", "1$r0;38:2::1:2:3m", "1$r38;2;1;2;3m"] {
457            assert_eq!(truecolor_from_decrqss(body), Some(true), "{body}");
458        }
459        // Downsampled to the 256 palette, refused, or unrelated.
460        assert_eq!(truecolor_from_decrqss("1$r38;5;16m"), Some(false));
461        assert_eq!(truecolor_from_decrqss("1$r38:2::0:0:0m"), Some(false));
462        assert_eq!(truecolor_from_decrqss("0$r"), Some(false));
463        assert_eq!(truecolor_from_decrqss("1$r0m"), Some(false));
464        assert_eq!(truecolor_from_decrqss("garbage"), None);
465        let p = parse_replies(b"\x1b[?1u\x1bP1$r0;38:2::1:2:3m\x1b\\\x1b[?62;22c");
466        assert_eq!(p.truecolor, Some(true));
467        assert_eq!(p.kitty_keyboard, Some(1), "parsing continues after the DCS");
468        assert!(p.da1);
469        let p = parse_replies(b"\x1bP1$r38;5;16m\x1b\\\x1b[?1;2c");
470        assert_eq!(p.truecolor, Some(false));
471        // Unterminated DCS never panics.
472        assert_eq!(parse_replies(b"\x1bP1$r38:2").truecolor, None);
473    }
474
475    #[test]
476    fn the_query_resets_the_test_color_and_ends_with_da1() {
477        let q = String::from_utf8_lossy(QUERY);
478        let set = q.find("\x1b[38;2;1;2;3m").unwrap();
479        let ask = q.find("\x1bP$qm\x1b\\").unwrap();
480        let reset = q.find("\x1b[0m").unwrap();
481        assert!(set < ask && ask < reset, "set → ask → reset");
482        assert!(q.ends_with("\x1b[c"), "DA1 sentinel last");
483        assert!(skip_probe_for("linux") && skip_probe_for("dumb") && skip_probe_for(""));
484        assert!(!skip_probe_for("xterm-ghostty"));
485    }
486
487    #[test]
488    fn osc_color_scaling() {
489        assert_eq!(parse_osc_color("rgb:f/0/8"), Some((255, 0, 136)));
490        assert_eq!(parse_osc_color("rgb:ffff/0000/8080"), Some((255, 0, 128)));
491        assert_eq!(parse_osc_color("#102030"), Some((16, 32, 48)));
492        assert_eq!(parse_osc_color("rgb:12345/0/0"), None);
493    }
494}