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;
10const FILE_QUERY_ID: u32 = 32;
12#[cfg(unix)]
13const REPLY_TIMEOUT: Duration = Duration::from_millis(250);
14const 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 files: bool,
34}
35
36#[derive(Clone, Copy, PartialEq, Eq)]
38enum Asking {
39 Terminal,
41 Tmux,
43 TmuxPassthrough,
45}
46
47#[cfg(any(unix, test))]
53fn questions(asking: Asking, files: &str) -> String {
54 let (cell, graphics) = match asking {
55 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
73fn 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
85const ASK_TMUX_BACKGROUND: &str = "\x1b]11;?\x1b\\\x1b[c";
87
88pub 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
118pub 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
131pub 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
153fn 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 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#[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#[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#[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#[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 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 let ready = unsafe { libc::poll(&mut pollfd, 1, left.as_millis() as libc::c_int) };
255 if ready <= 0 {
256 break;
257 }
258 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
277fn 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
292fn 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#[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
314pub 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 if let Some(files) = files {
322 files.answered(false);
323 }
324 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 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 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 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 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}