1use serde::Serialize;
22use std::time::Duration;
23
24pub const TIMEOUT: Duration = Duration::from_millis(200);
27
28pub 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
32pub const QUERY_MINIMAL: &[u8] = b"\x1b]11;?\x1b\\\x1b[c";
36
37pub const WIPE_LINE: &[u8] = b"\r\x1b[2K";
41
42pub 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#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
52#[serde(rename_all = "snake_case")]
53pub enum ModeState {
54 NotRecognized,
56 Supported,
58 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#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)]
77pub struct Probe {
78 pub background: Option<(u8, u8, u8)>,
80 pub kitty_keyboard: Option<u32>,
82 pub sync_output: Option<ModeState>,
83 pub sgr_mouse: Option<ModeState>,
84 pub focus_events: Option<ModeState>,
85 pub truecolor: Option<bool>,
88 pub da1: bool,
90 pub da1_attrs: Option<String>,
92 pub modes_queried: bool,
95}
96
97impl Probe {
98 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
113pub 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
130pub 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
153pub fn parse_replies(buf: &[u8]) -> Probe {
155 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 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 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 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 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
246pub fn interactive() -> bool {
248 use std::io::IsTerminal;
249 std::io::stdin().is_terminal() && std::io::stdout().is_terminal()
250}
251
252pub fn skip_probe_for(term: &str) -> bool {
255 term == "dumb" || term == "linux" || term.is_empty()
256}
257
258#[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#[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 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 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 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 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 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 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 unsafe {
379 libc::tcflush(fd, libc::TCIFLUSH);
380 }
381 }
382 Some(p)
383}
384
385#[cfg(test)]
386mod tests {
387 use super::*;
388
389 #[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 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 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 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 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}