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);
11const 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#[derive(Clone, Copy, PartialEq, Eq)]
33enum Asking {
34 Terminal,
36 Tmux,
38 TmuxPassthrough,
40}
41
42#[cfg(any(unix, test))]
47fn questions(asking: Asking) -> String {
48 let (cell, graphics) = match asking {
49 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
67fn 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
79const ASK_TMUX_BACKGROUND: &str = "\x1b]11;?\x1b\\\x1b[c";
81
82pub 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
115pub 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
137fn query_terminal(out: &mut impl Write, asking: Asking) -> io::Result<Reply> {
141 let mut reply = ask(out, asking)?;
142 if asking == Asking::TmuxPassthrough {
143 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#[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#[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#[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 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 let ready = unsafe { libc::poll(&mut pollfd, 1, left.as_millis() as libc::c_int) };
217 if ready <= 0 {
218 break;
219 }
220 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
238fn 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
252fn 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#[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
274pub fn detect(var: impl Fn(&str) -> Option<String>) -> io::Result<Env> {
276 let multiplexer = Multiplexer::detect(var);
277 if multiplexer == Multiplexer::Tmux {
278 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 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 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 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 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}