cellix-term 0.16.3

Terminal probing and presentation backends for Cellix
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
use std::io::{self, Write};
use std::process::Command;
#[cfg(unix)]
use std::time::{Duration, Instant};

use crate::files::TileFiles;
use crate::probe::{Env, Multiplexer};

const QUERY_ID: u32 = 31;
/// The answer to whether the terminal takes a tile as a file.
const FILE_QUERY_ID: u32 = 32;
#[cfg(unix)]
const REPLY_TIMEOUT: Duration = Duration::from_millis(250);
/// Terminals known to speak Kitty graphics, for when tmux hides the terminal from us.
const KITTY_TERMINALS: [&str; 3] = ["ghostty", "kitty", "wezterm"];

fn tmux_output(args: &[&str]) -> Option<String> {
    let output = Command::new("tmux").args(args).output().ok()?;
    output
        .status
        .success()
        .then(|| String::from_utf8_lossy(&output.stdout).trim().to_string())
}

struct Reply {
    kitty: bool,
    cell: Option<(usize, usize)>,
    pixel_mouse: bool,
    paste_events: bool,
    light: Option<bool>,
    background: Option<(u8, u8, u8)>,
    /// It said it took the file it was asked about.
    files: bool,
}

/// Where the questions go.
#[derive(Clone, Copy, PartialEq, Eq)]
enum Asking {
    /// The terminal itself.
    Terminal,
    /// tmux, which answers for the terminal from what it knows.
    Tmux,
    /// tmux, with passthrough, so the cell size can be asked of the terminal outside it.
    TmuxPassthrough,
}

/// What to ask a terminal. The graphics query goes only where it reaches the terminal
/// itself: tmux takes that kind of sequence as a window title and shows it in its status bar.
/// tmux makes up a cell size when its own terminal gives none (16 by 32, over a console), and
/// images sized for that are letterboxed, so with passthrough the cell size goes past it.
/// `files` is the question whether it takes a tile as a file, asked of the terminal itself.
#[cfg(any(unix, test))]
fn questions(asking: Asking, files: &str) -> String {
    let (cell, graphics) = match asking {
        // Whether it has paste events is asked with the graphics: only the terminal itself
        // can say, and only it would send them.
        Asking::Terminal => (
            "\x1b[16t".to_string(),
            format!(
                "\x1b_Gi={QUERY_ID},s=1,v=1,a=q,t=d,f=24;AAAA\x1b\\{files}{}",
                crate::clipboard::ASK_PASTE_EVENTS
            ),
        ),
        Asking::Tmux => (String::new(), String::new()),
        Asking::TmuxPassthrough => ("\x1bPtmux;\x1b\x1b[16t\x1b\\".to_string(), String::new()),
    };
    format!(
        "{}{cell}\x1b[?1016$p{graphics}\x1b[c",
        background_question(asking)
    )
}

/// The question about the background. Inside tmux with passthrough it goes to the terminal
/// itself too: tmux keeps that answer rather than passing it on, but it's how tmux learns the
/// terminal's colour has changed since the client attached, so tmux's own answer, asked
/// afterwards, is current. It comes ahead of the cell size, which the terminal answers next and
/// tmux does pass on, so that answer arriving means tmux has the new colour.
fn background_question(asking: Asking) -> &'static str {
    match asking {
        Asking::TmuxPassthrough => "\x1bPtmux;\x1b\x1b]11;?\x07\x1b\\",
        Asking::Terminal | Asking::Tmux => "\x1b]11;?\x1b\\",
    }
}

/// tmux's own answer about the background, asked once the terminal has told it.
const ASK_TMUX_BACKGROUND: &str = "\x1b]11;?\x1b\\\x1b[c";

/// Asks the terminal for its background again, as when Cellix comes back into focus: it may
/// have turned from light to dark since Cellix started. Must run in raw mode, between reads
/// of input. Gives whether it's light, and its colour, when the terminal said.
pub fn background(multiplexer: Multiplexer, passthrough: bool) -> Option<(bool, (u8, u8, u8))> {
    let asking = match multiplexer {
        Multiplexer::Tmux if passthrough => Asking::TmuxPassthrough,
        Multiplexer::Tmux => Asking::Tmux,
        Multiplexer::None | Multiplexer::Zellij => Asking::Terminal,
    };
    let mut out = io::stdout();
    let reply = if asking == Asking::TmuxPassthrough {
        let refresh = format!(
            "{}\x1bPtmux;\x1b\x1b[16t\x1b\\\x1b[c",
            background_question(asking)
        );
        ask_for(&mut out, &refresh, asking, |reply| {
            parse_cell_size(reply).is_some()
        })
        .ok()?;
        ask_for(&mut out, ASK_TMUX_BACKGROUND, Asking::Tmux, |_| true).ok()?
    } else {
        let question = format!("{}\x1b[c", background_question(asking));
        ask_for(&mut out, &question, asking, |reply| {
            parse_background(reply).is_some()
        })
        .ok()?
    };
    colour_in(&reply)
}

/// Whether the background an answer that came after its wait gives is light, and its colour,
/// from the `rgb:…` that `Replies::take_background` hands over.
pub fn background_in(answer: &[u8]) -> Option<(bool, (u8, u8, u8))> {
    colour_in(&[b"]11;".as_slice(), answer].concat())
}

fn colour_in(reply: &[u8]) -> Option<(bool, (u8, u8, u8))> {
    let light = parse_background_is_light(reply)?;
    let (r, g, b) = parse_background(reply)?;
    let byte = |channel: f32| (channel * 255.0).round() as u8;
    Some((light, (byte(r), byte(g), byte(b))))
}

/// Asks the terminal how big a cell is, in pixels, as (width, height): what it says is
/// exact, where the window's pixels over its cells is a guess that takes its padding, and a
/// tab bar some terminals count, for part of every row. Asked when the window's size has
/// settled after a change. Must run in raw mode, between reads of input. `None` when the
/// terminal doesn't say, or under tmux without passthrough, which would answer for itself.
pub fn cell_size(multiplexer: Multiplexer, passthrough: bool) -> Option<(usize, usize)> {
    let (question, asking) = match multiplexer {
        Multiplexer::Tmux if passthrough => (
            "\x1bPtmux;\x1b\x1b[16t\x1b\\\x1b[c",
            Asking::TmuxPassthrough,
        ),
        Multiplexer::Tmux => return None,
        Multiplexer::None | Multiplexer::Zellij => ("\x1b[16t\x1b[c", Asking::Terminal),
    };
    let mut out = io::stdout();
    let reply = ask_for(&mut out, question, asking, |reply| {
        asking != Asking::TmuxPassthrough || parse_cell_size(reply).is_some()
    })
    .ok()?;
    parse_cell_size(&reply)
}

/// Asks for the cell size and for Kitty graphics, then device attributes, which every
/// terminal answers, so a terminal without graphics doesn't cost the full timeout.
/// Expects raw mode. `files` is asked as well, where it isn't empty.
fn query_terminal(out: &mut impl Write, asking: Asking, files: &str) -> io::Result<Reply> {
    let mut reply = ask(out, asking, files)?;
    if asking == Asking::TmuxPassthrough {
        // The terminal told tmux its colour; now tmux's answer is current.
        reply.extend(ask_for(out, ASK_TMUX_BACKGROUND, Asking::Tmux, |_| true)?);
    }
    Ok(Reply {
        kitty: reply_has(&reply, format!("_Gi={QUERY_ID};OK").as_bytes()),
        cell: parse_cell_size(&reply),
        pixel_mouse: reply_has(&reply, b"?1016;1$y") || reply_has(&reply, b"?1016;2$y"),
        paste_events: crate::clipboard::has_paste_events(&reply),
        light: parse_background_is_light(&reply),
        background: parse_background(&reply).map(|(r, g, b)| {
            let byte = |channel: f32| (channel * 255.0).round() as u8;
            (byte(r), byte(g), byte(b))
        }),
        files: reply_has(&reply, format!("_Gi={FILE_QUERY_ID};OK").as_bytes()),
    })
}

/// A Windows console hands its input over as key events, not bytes to poll, so nothing is
/// asked there: Cellix starts on the cell tier with its own colours, and nothing the terminal
/// would answer is left to arrive as keys.
#[cfg(not(unix))]
fn ask(_out: &mut impl Write, _asking: Asking, _files: &str) -> io::Result<Vec<u8>> {
    Ok(Vec::new())
}

#[cfg(not(unix))]
fn ask_for(
    _out: &mut impl Write,
    _question: &str,
    _asking: Asking,
    _done: impl Fn(&[u8]) -> bool,
) -> io::Result<Vec<u8>> {
    Ok(Vec::new())
}

/// Writes the questions and reads the replies until device attributes, or the timeout.
#[cfg(unix)]
fn ask(out: &mut impl Write, asking: Asking, files: &str) -> io::Result<Vec<u8>> {
    let outside = asking == Asking::TmuxPassthrough;
    ask_for(out, &questions(asking, files), asking, |reply| {
        !outside || parse_cell_size(reply).is_some()
    })
}

/// Writes `question`, which ends by asking for device attributes, and reads the replies
/// until those come and `done` is satisfied, or the timeout. What comes after that is read by
/// the loop, which drops it as answers (`replies.rs`): so a wait that runs out says so, with how
/// far into an answer it read. So does one asked while an earlier question's answers may still
/// come, since those may be what it read, and its own then come after it.
#[cfg(unix)]
fn ask_for(
    out: &mut impl Write,
    question: &str,
    asking: Asking,
    done: impl Fn(&[u8]) -> bool,
) -> io::Result<Vec<u8>> {
    let owing = crate::replies::owing(Instant::now());
    let mut read = crate::replies::Read::default();
    let reply = read_answers(out, question, asking, done, &mut read);
    if !matches!(reply, Ok((_, true))) || owing {
        crate::replies::owe(&read);
    }
    reply.map(|(reply, _)| reply)
}

/// The wait itself: the replies, and whether they were all there.
#[cfg(unix)]
fn read_answers(
    out: &mut impl Write,
    question: &str,
    asking: Asking,
    done: impl Fn(&[u8]) -> bool,
    read: &mut crate::replies::Read,
) -> io::Result<(Vec<u8>, bool)> {
    write!(out, "{question}")?;
    out.flush()?;
    // tmux answers device attributes at once, but the terminal outside answers through it a
    // round trip later, so that answer is waited for too, a little longer.
    let outside = asking == Asking::TmuxPassthrough;
    let timeout = if outside {
        REPLY_TIMEOUT * 3
    } else {
        REPLY_TIMEOUT
    };
    let deadline = Instant::now() + timeout;
    let mut reply = Vec::new();
    let mut buf = [0u8; 256];
    while Instant::now() < deadline {
        let left = deadline.saturating_duration_since(Instant::now());
        let mut pollfd = libc::pollfd {
            fd: libc::STDIN_FILENO,
            events: libc::POLLIN,
            revents: 0,
        };
        // SAFETY: pollfd is a valid, exclusively borrowed array of one element.
        let ready = unsafe { libc::poll(&mut pollfd, 1, left.as_millis() as libc::c_int) };
        if ready <= 0 {
            break;
        }
        // SAFETY: buf is valid for writes of buf.len() bytes.
        let n = unsafe { libc::read(libc::STDIN_FILENO, buf.as_mut_ptr().cast(), buf.len()) };
        if n <= 0 {
            break;
        }
        reply.extend_from_slice(&buf[..n as usize]);
        read.feed(&buf[..n as usize]);
        if ends_device_attributes(&reply) && done(&reply) {
            return Ok((reply, true));
        }
    }
    Ok((reply, false))
}

fn parse_background_is_light(reply: &[u8]) -> Option<bool> {
    let (r, g, b) = parse_background(reply)?;
    Some(0.2126 * r + 0.7152 * g + 0.0722 * b > 0.5)
}

/// Reads `ESC ] 11 ; rgb:RRRR/GGGG/BBBB`, as fractions of full brightness. The last such
/// answer: one before it may be an earlier question's, come late.
fn parse_background(reply: &[u8]) -> Option<(f32, f32, f32)> {
    let needle = b"]11;rgb:";
    let start = reply.windows(needle.len()).rposition(|w| w == needle)? + needle.len();
    let rest = std::str::from_utf8(&reply[start..]).ok()?;
    let mut channels = rest.split(['/', '\x1b', '\x07']).take(3).map(|part| {
        let digits = part.len().clamp(1, 4) as u32;
        u32::from_str_radix(part, 16)
            .ok()
            .map(|v| v as f32 / (16f32.powi(digits as i32) - 1.0))
    });
    Some((channels.next()??, channels.next()??, channels.next()??))
}

/// Finds a `ESC [ 6 ; height ; width t` reply, the last, as for the background.
fn parse_cell_size(reply: &[u8]) -> Option<(usize, usize)> {
    let start = reply.windows(4).rposition(|w| w == b"\x1b[6;")? + 4;
    let rest = std::str::from_utf8(&reply[start..]).ok()?;
    let (body, _) = rest.split_once('t')?;
    let (height, width) = body.split_once(';')?;
    Some((width.parse().ok()?, height.parse().ok()?))
}

fn reply_has(reply: &[u8], needle: &[u8]) -> bool {
    reply.windows(needle.len()).any(|w| w == needle)
}

/// A primary device attributes reply looks like `ESC [ ? ... c`.
#[cfg(any(unix, test))]
fn ends_device_attributes(reply: &[u8]) -> bool {
    let Some(start) = reply.windows(3).rposition(|w| w == b"\x1b[?") else {
        return false;
    };
    reply[start..].contains(&b'c')
}

/// Works out what this terminal can do. Must run in raw mode, before input is read. Where
/// `files` is given, the terminal itself is asked whether it takes a tile as a file, with the
/// other questions, and `files` is told what it said.
pub fn detect(var: impl Fn(&str) -> Option<String>, files: Option<&TileFiles>) -> io::Result<Env> {
    let multiplexer = Multiplexer::detect(var);
    if multiplexer == Multiplexer::Tmux {
        // Never past tmux: the terminal there may be on another machine.
        if let Some(files) = files {
            files.answered(false);
        }
        // tmux swallows replies from the terminal outside it, so ask tmux instead.
        // The terminal's own name where tmux heard it, as well as its TERM: over SSH, TERM is
        // often a stand-in like xterm-256color when the server lacks the terminal's terminfo.
        let client = tmux_output(&["display", "-p", "#{client_termname} #{client_termtype}"])
            .unwrap_or_default()
            .to_lowercase();
        let kitty_graphics = KITTY_TERMINALS.iter().any(|t| client.contains(t));
        let tmux_passthrough = tmux_output(&["show", "-Apv", "allow-passthrough"])
            .is_some_and(|v| v == "on" || v == "all");
        // tmux answers the colour query itself, from what it knows of the terminal, which with
        // passthrough is brought up to date first.
        let asking = if tmux_passthrough {
            Asking::TmuxPassthrough
        } else {
            Asking::Tmux
        };
        let reply = query_terminal(&mut io::stdout(), asking, "")?;
        return Ok(Env {
            multiplexer,
            kitty_graphics,
            tmux_passthrough,
            cell: reply.cell,
            pixel_mouse: false,
            paste_events: false,
            light: reply.light,
            background: reply.background,
        });
    }
    let question = files.and_then(|files| files.question(FILE_QUERY_ID));
    let reply = query_terminal(
        &mut io::stdout(),
        Asking::Terminal,
        question.as_deref().unwrap_or(""),
    )?;
    if let Some(files) = files {
        files.answered(question.is_some() && reply.files);
    }
    Ok(Env {
        multiplexer,
        kitty_graphics: reply.kitty,
        tmux_passthrough: false,
        cell: reply.cell,
        pixel_mouse: reply.pixel_mouse,
        paste_events: reply.paste_events && multiplexer == Multiplexer::None,
        light: reply.light,
        background: reply.background,
    })
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn inside_tmux_with_passthrough_the_terminal_itself_is_asked_its_colour() {
        // tmux's own answer is what it knew when the client attached, and goes stale.
        let asked = questions(Asking::TmuxPassthrough, "");
        assert!(asked.starts_with("\x1bPtmux;\x1b\x1b]11;?"), "{asked:?}");
        assert!(
            !asked.contains("\x1b]11;?\x1b\\\x1b["),
            "tmux isn't asked as well: {asked:?}"
        );
        assert!(questions(Asking::Terminal, "").starts_with("\x1b]11;?"));
        assert!(questions(Asking::Tmux, "").starts_with("\x1b]11;?"));
    }

    #[test]
    fn tmux_is_not_asked_about_graphics() {
        assert!(!questions(Asking::Tmux, "").contains("\x1b_G"));
        assert!(questions(Asking::Terminal, "").contains("\x1b_Gi=31"));
        assert!(questions(Asking::Tmux, "").ends_with("\x1b[c"));
    }

    #[test]
    fn the_cell_size_is_asked_past_tmux() {
        // tmux would answer a plain question with a size it made up.
        assert!(!questions(Asking::Tmux, "").contains("[16t"));
        let past = questions(Asking::TmuxPassthrough, "");
        assert!(past.contains("\x1bPtmux;\x1b\x1b[16t\x1b\\"), "{past:?}");
        assert!(!past.contains("\x1b_G"));
        // As tmux hands the outer terminal's answer back.
        assert_eq!(parse_cell_size(b"\x1b[?62c\x1b[6;36;17t"), Some((17, 36)));
    }

    #[test]
    fn device_attributes_reply_is_recognised() {
        assert!(ends_device_attributes(b"\x1b[?62;22c"));
        assert!(ends_device_attributes(b"\x1b_Gi=31;EBADF\x1b\\\x1b[?62c"));
        assert!(!ends_device_attributes(b"\x1b[?62"));
        assert!(!ends_device_attributes(b"\x1b_Gi=31;OK\x1b\\"));
    }

    #[test]
    fn cell_size_reply_is_parsed() {
        let zellij = b"\x1b[6;37;17t\x1b_Gi=31;OK\x1b\\\x1b[4;888;1394t\x1b[?62;52c";
        assert_eq!(parse_cell_size(zellij), Some((17, 37)));
        assert_eq!(parse_cell_size(b"\x1b[?62c"), None);
    }

    #[test]
    fn the_background_decides_light_or_dark() {
        let dark = b"\x1b]11;rgb:1e1e/1e1e/1e1e\x1b\\\x1b[?62c";
        assert_eq!(parse_background_is_light(dark), Some(false));
        assert_eq!(
            parse_background_is_light(b"\x1b]11;rgb:ffff/fefe/fdfd\x07"),
            Some(true)
        );
        assert_eq!(
            parse_background_is_light(b"\x1b]11;rgb:ee/ee/ee\x07"),
            Some(true)
        );
        assert_eq!(parse_background_is_light(b"\x1b[?62c"), None);
    }

    #[test]
    fn the_file_question_goes_to_the_terminal_before_device_attributes() {
        let probe = "\x1b_Gi=32,s=1,v=1,a=q,t=t,f=24;L3RtcA==\x1b\\";
        let asked = questions(Asking::Terminal, probe);
        let at = asked.find(probe).expect("asked");
        assert!(at > asked.find("\x1b_Gi=31").unwrap());
        assert!(
            at < asked.rfind("\x1b[c").unwrap(),
            "answered before the reply that ends it"
        );
        assert!(!questions(Asking::Tmux, "").contains("t=t"));
    }

    #[test]
    fn query_reply_is_recognised() {
        assert!(reply_has(b"\x1b_Gi=31;OK\x1b\\", b"_Gi=31;OK"));
        assert!(!reply_has(b"\x1b_Gi=31;EINVAL\x1b\\", b"_Gi=31;OK"));
    }
}