返回 CodeWhale
osc11.rs
根目录 / crates / palette / src / osc11.rs
1 //! OSC 11 terminal-background query.
2 //!
3 //! `COLORFGBG` is the only background signal the palette had before this
4 //! module, and most modern terminals never set it — Windows Terminal, conhost,
5 //! VS Code, GNOME Terminal, Alacritty and Ghostty all omit it. Without it a
6 //! white terminal was indistinguishable from a black one, so detection fell
7 //! back to `Dark` and painted dark-tuned text onto a light surface (#4833).
8 //!
9 //! OSC 11 (`ESC ] 11 ; ? BEL`) asks the terminal for its actual background
10 //! color and is answered by every terminal listed above. The reply is an
11 //! `xterm`-style color spec, e.g.
12 //!
13 //! ```text
14 //! ESC ] 11 ; rgb:ffff/ffff/ffff ESC \
15 //! ```
16 //!
17 //! The parse is a pure function so it can be tested without a terminal; the
18 //! query itself is Unix-only, bounded by a short deadline, and never runs when
19 //! stdin/stdout are not both TTYs.
20
21 /// Upper bound on how long startup will wait for a terminal that never
22 /// answers. A terminal that supports OSC 11 replies in well under a
23 /// millisecond; anything past this is a terminal that will never reply, and
24 /// startup latency matters more than the answer.
25 pub const OSC11_QUERY_TIMEOUT: std::time::Duration = std::time::Duration::from_millis(120);
26
27 /// The query sequence. `ESC \` (ST) is the terminator we prefer in the reply,
28 /// but terminals may answer with BEL instead, so the reader accepts both.
29 ///
30 /// Only the Unix query path writes it — see the note on [`parse_osc11_reply`].
31 const OSC11_QUERY: &[u8] = b"\x1b]11;?\x1b\\";
32
33 /// Extract an RGB triple from an OSC 11 reply body.
34 ///
35 /// Accepts the shapes terminals actually emit:
36 /// - `rgb:RRRR/GGGG/BBBB` (xterm, 1–4 hex digits per channel, any width)
37 /// - `#RRGGBB` / `#RGB` / `#RRRRGGGGBBBB`
38 ///
39 /// Leading `ESC ] 11 ;` and the trailing BEL/ST are optional — anything
40 /// outside the color spec is ignored, so a reply that arrived interleaved with
41 /// other terminal chatter still parses.
42 ///
43 /// Returns `None` when no color spec is present or a channel is malformed.
44 /// Channels wider than 8 bits are scaled down, not truncated, so `ffff` is
45 /// `255` rather than `0`.
46 #[must_use]
47 pub fn parse_osc11_reply(reply: &str) -> Option<(u8, u8, u8)> {
48 if let Some(idx) = reply.find("rgb:") {
49 return parse_slash_separated(&reply[idx + 4..]);
50 }
51 if let Some(idx) = reply.find('#') {
52 return parse_hash_hex(&reply[idx + 1..]);
53 }
54 None
55 }
56
57 fn parse_slash_separated(spec: &str) -> Option<(u8, u8, u8)> {
58 let spec: String = spec
59 .chars()
60 .take_while(|c| c.is_ascii_hexdigit() || *c == '/')
61 .collect();
62 let mut parts = spec.split('/');
63 let r = scale_hex_channel(parts.next()?)?;
64 let g = scale_hex_channel(parts.next()?)?;
65 let b = scale_hex_channel(parts.next()?)?;
66 if parts.next().is_some() {
67 return None;
68 }
69 Some((r, g, b))
70 }
71
72 fn parse_hash_hex(spec: &str) -> Option<(u8, u8, u8)> {
73 let digits: String = spec.chars().take_while(char::is_ascii_hexdigit).collect();
74 if !digits.len().is_multiple_of(3) || digits.is_empty() || digits.len() > 12 {
75 return None;
76 }
77 let width = digits.len() / 3;
78 let r = scale_hex_channel(&digits[..width])?;
79 let g = scale_hex_channel(&digits[width..width * 2])?;
80 let b = scale_hex_channel(&digits[width * 2..])?;
81 Some((r, g, b))
82 }
83
84 /// Normalize a hex channel of arbitrary width (1–4 digits) to 8 bits by
85 /// rescaling across the channel's full range: `f` → `255`, `ffff` → `255`,
86 /// `8000` → `128`.
87 fn scale_hex_channel(digits: &str) -> Option<u8> {
88 if digits.is_empty() || digits.len() > 4 || !digits.chars().all(|c| c.is_ascii_hexdigit()) {
89 return None;
90 }
91 let value = u32::from_str_radix(digits, 16).ok()?;
92 let max = (1u32 << (4 * digits.len() as u32)) - 1;
93 Some(((value * 255 + max / 2) / max) as u8)
94 }
95
96 /// Ask the terminal for its background color, giving up after `timeout`.
97 ///
98 /// Returns `None` — never blocks past `timeout`, never panics — when:
99 /// - stdin and stdout are not both TTYs (piped output, CI, `codewhale < file`),
100 /// - the platform has no supported query path (non-Unix; see the module docs),
101 /// - the terminal does not answer, or answers with something unparsable.
102 ///
103 /// # Caveat
104 ///
105 /// This reads from stdin, so it must only be called while the terminal is in
106 /// raw mode and before the event loop starts. Bytes that arrive during the
107 /// window and are not part of the reply are *not* discarded: they are the
108 /// user's type-ahead, and are handed to
109 /// [`carry_typed_ahead`] for the event loop to
110 /// replay in order (#5925).
111 #[must_use]
112 pub fn query_terminal_background(timeout: std::time::Duration) -> Option<(u8, u8, u8)> {
113 let reply = query_terminal(OSC11_QUERY, timeout)?;
114 parse_osc11_reply(&String::from_utf8_lossy(&reply))
115 }
116
117 /// Write `query` to the terminal and read back one reply, giving up after
118 /// `timeout`. The reply is the bytes up to (not including) its BEL or `ESC \`
119 /// terminator; an `ESC` that opens the reply is kept. Shared by the OSC 11
120 /// background query and the kitty graphics probe (`tui::mark`), under the
121 /// same caveat as [`query_terminal_background`]: raw mode on, event loop not
122 /// yet reading stdin.
123 #[cfg(unix)]
124 pub fn query_terminal(query: &[u8], timeout: std::time::Duration) -> Option<Vec<u8>> {
125 query_terminal_inner(query, timeout, false)
126 }
127
128 /// CSI-terminated variant of [`query_terminal`] for the sixel probe
129 /// (`tui::mark`): a primary-DA reply ends at its alphabetic final byte
130 /// (`c`), which is neither BEL nor `ESC \`, so the plain reader would keep
131 /// swallowing input — including the user's own typed-ahead keystrokes —
132 /// until its byte cap. Stops after the final byte of a reply that opened
133 /// with `ESC [` and keeps the same raw-mode caveat.
134 #[cfg(unix)]
135 pub fn query_terminal_csi(query: &[u8], timeout: std::time::Duration) -> Option<Vec<u8>> {
136 query_terminal_inner(query, timeout, true)
137 }
138
139 /// Largest reply any of the three probes can produce. Past this the answer
140 /// is not one of ours.
141 #[cfg(any(unix, test))]
142 const MAX_REPLY_BYTES: usize = 128;
143
144 // ---------------------------------------------------------------------------
145 // Type-ahead carried across the probe window (#5925).
146 //
147 // The probe readers below are the only readers of the tty between raw-mode
148 // entry and the input pump, so anything the user typed at launch arrives in
149 // the same stream as the replies. The reader keeps its reply and parks every
150 // other byte here; `tui::startup_input` drains this and replays it into the
151 // composer. The buffers live in this module rather than with the replay
152 // logic because `src/palette/` is `#[path]`-included by test harnesses that
153 // do not compile the `tui` module tree.
154 // ---------------------------------------------------------------------------
155
156 /// Upper bound on carried type-ahead. A terminal that answers a probe does
157 /// so in well under a millisecond, so this only ever holds a line or two;
158 /// the cap stops a wedged tty from growing the buffer without limit.
159 pub const MAX_CARRIED_BYTES: usize = 4096;
160
161 /// Bytes a probe consumed that were not part of its reply.
162 static CARRIED_TYPE_AHEAD: std::sync::Mutex<Vec<u8>> = std::sync::Mutex::new(Vec::new());
163 /// Bytes a probe consumed that cannot be replayed as keystrokes.
164 static CONSUMED_UNREPLAYABLE: std::sync::Mutex<Vec<u8>> = std::sync::Mutex::new(Vec::new());
165
166 /// Park non-reply bytes for the event loop to replay.
167 pub fn carry_typed_ahead(bytes: &[u8]) {
168 if bytes.is_empty() {
169 return;
170 }
171 let Ok(mut carried) = CARRIED_TYPE_AHEAD.lock() else {
172 note_consumed_unreplayable(bytes);
173 return;
174 };
175 let room = MAX_CARRIED_BYTES.saturating_sub(carried.len());
176 let (keep, overflow) = bytes.split_at(room.min(bytes.len()));
177 carried.extend_from_slice(keep);
178 drop(carried);
179 note_consumed_unreplayable(overflow);
180 }
181
182 /// Record bytes startup consumed and cannot hand back.
183 pub fn note_consumed_unreplayable(bytes: &[u8]) {
184 if bytes.is_empty() {
185 return;
186 }
187 if let Ok(mut dropped) = CONSUMED_UNREPLAYABLE.lock() {
188 let room = MAX_CARRIED_BYTES.saturating_sub(dropped.len());
189 dropped.extend_from_slice(&bytes[..room.min(bytes.len())]);
190 }
191 }
192
193 /// Take everything parked by [`carry_typed_ahead`].
194 pub fn take_carried_type_ahead() -> Vec<u8> {
195 CARRIED_TYPE_AHEAD
196 .lock()
197 .map(|mut carried| std::mem::take(&mut *carried))
198 .unwrap_or_default()
199 }
200
201 /// Take everything recorded by [`note_consumed_unreplayable`].
202 pub fn take_consumed_unreplayable() -> Vec<u8> {
203 CONSUMED_UNREPLAYABLE
204 .lock()
205 .map(|mut dropped| std::mem::take(&mut *dropped))
206 .unwrap_or_default()
207 }
208
209 /// What the caller should do after feeding one byte to [`ProbeSplit`].
210 #[cfg(any(unix, test))]
211 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
212 pub(crate) enum ProbeStep {
213 /// Keep reading.
214 Continue,
215 /// The reply is complete.
216 Done,
217 /// The reply ended with the `ESC` of an `ESC \` string terminator: read
218 /// one more byte and give it to [`ProbeSplit::finish_string_terminator`].
219 AwaitStringTerminator,
220 /// Carried type-ahead hit its cap; stop reading.
221 Overflow,
222 }
223
224 /// Splits one probe stream into the terminal's reply and the user's
225 /// type-ahead (#5925).
226 ///
227 /// Pure and byte-driven so the split — the actual defect in #5925, where
228 /// everything that was not the reply was thrown away — is testable without a
229 /// terminal. The reply always opens with the same two bytes the query did
230 /// (`ESC ]` for OSC 11, `ESC _` for the kitty graphics query, `ESC [` for the
231 /// sixel primary-DA query); anything before that introducer is input the user
232 /// typed, and an `ESC` that does not go on to match it is theirs too.
233 #[cfg(any(unix, test))]
234 #[derive(Debug)]
235 pub(crate) struct ProbeSplit<'a> {
236 introducer: &'a [u8],
237 stop_at_csi_final: bool,
238 carried: Vec<u8>,
239 /// A partial introducer match, still undecided between reply and input.
240 undecided: Vec<u8>,
241 reply: Vec<u8>,
242 in_reply: bool,
243 }
244
245 #[cfg(any(unix, test))]
246 impl<'a> ProbeSplit<'a> {
247 /// `query` is the sequence just written; its first two bytes are the
248 /// introducer the reply will open with.
249 pub(crate) fn for_query(query: &'a [u8], stop_at_csi_final: bool) -> Self {
250 Self {
251 introducer: if query.len() >= 2 && query[0] == 0x1b {
252 &query[..2]
253 } else {
254 &[]
255 },
256 stop_at_csi_final,
257 carried: Vec::new(),
258 undecided: Vec::new(),
259 reply: Vec::new(),
260 in_reply: false,
261 }
262 }
263
264 pub(crate) fn feed(&mut self, byte: u8) -> ProbeStep {
265 if !self.in_reply {
266 self.feed_before_reply(byte);
267 if self.carried.len() >= MAX_CARRIED_BYTES {
268 return ProbeStep::Overflow;
269 }
270 return ProbeStep::Continue;
271 }
272 // BEL, or the ESC of an `ESC \` string terminator, ends the reply.
273 if byte == 0x07 {
274 return ProbeStep::Done;
275 }
276 if byte == 0x1b {
277 return ProbeStep::AwaitStringTerminator;
278 }
279 self.reply.push(byte);
280 // A CSI reply (`ESC [` …) ends at its first final byte (`@..=~`):
281 // keep the final and stop, so a DA answer never eats past itself.
282 if self.stop_at_csi_final
283 && self.reply.len() >= 3
284 && self.reply[0] == 0x1b
285 && self.reply[1] == b'['
286 && (0x40..=0x7e).contains(&byte)
287 {
288 return ProbeStep::Done;
289 }
290 if self.reply.len() >= MAX_REPLY_BYTES {
291 return ProbeStep::Overflow;
292 }
293 ProbeStep::Continue
294 }
295
296 fn feed_before_reply(&mut self, byte: u8) {
297 if self.undecided.is_empty() {
298 if byte == 0x1b && !self.introducer.is_empty() {
299 self.undecided.push(byte);
300 } else {
301 self.carried.push(byte);
302 }
303 return;
304 }
305 self.undecided.push(byte);
306 if self.introducer.starts_with(&self.undecided) {
307 if self.undecided.len() == self.introducer.len() {
308 self.in_reply = true;
309 self.reply = std::mem::take(&mut self.undecided);
310 }
311 return;
312 }
313 // Not our reply after all — an `Esc` keypress, or an escape sequence
314 // from some other source. Everything held is the user's, except a
315 // fresh `ESC` which may still open the reply we are waiting for.
316 let restarts = byte == 0x1b;
317 if restarts {
318 self.undecided.pop();
319 }
320 self.carried.append(&mut self.undecided);
321 if restarts {
322 self.undecided.push(byte);
323 }
324 }
325
326 /// The byte read after an [`ProbeStep::AwaitStringTerminator`]. The `\`
327 /// of `ESC \` belongs to the reply; anything else is the user's next
328 /// keystroke and must not vanish with the terminator.
329 pub(crate) fn finish_string_terminator(&mut self, byte: u8) {
330 if byte != b'\\' {
331 self.carried.push(byte);
332 }
333 }
334
335 /// Consume the split: `(reply, carried type-ahead)`. An undecided
336 /// introducer is input the terminal never claimed.
337 pub(crate) fn finish(mut self) -> (Vec<u8>, Vec<u8>) {
338 self.carried.append(&mut self.undecided);
339 (self.reply, self.carried)
340 }
341 }
342
343 /// Read a probe reply off stdin without eating the user's type-ahead.
344 ///
345 /// The reply always opens with the same two bytes the query did (`ESC ]` for
346 /// OSC 11, `ESC _` for the kitty graphics query, `ESC [` for the sixel
347 /// primary-DA query), so every byte before that introducer — and the one
348 /// lookahead byte after an `ESC` that turned out not to open `ESC \` — is
349 /// input the user typed, not terminal chatter. Those bytes are carried to
350 /// [`carry_typed_ahead`] for replay instead of being dropped on the
351 /// floor (#5925). Bytes this reader consumed but cannot hand back (a reply
352 /// the terminal never terminated) are recorded as dropped so the startup
353 /// receipt names them.
354 #[cfg(unix)]
355 fn query_terminal_inner(
356 query: &[u8],
357 timeout: std::time::Duration,
358 stop_at_csi_final: bool,
359 ) -> Option<Vec<u8>> {
360 use std::io::Write;
361 use std::os::fd::AsRawFd;
362
363 let stdin = std::io::stdin();
364 let stdout = std::io::stdout();
365 let in_fd = stdin.as_raw_fd();
366 let out_fd = stdout.as_raw_fd();
367
368 // SAFETY: `isatty` only inspects the descriptor; both fds are owned by the
369 // std handles held above for the duration of the call.
370 let both_tty = unsafe { libc::isatty(in_fd) == 1 && libc::isatty(out_fd) == 1 };
371 if !both_tty {
372 return None;
373 }
374
375 {
376 let mut out = stdout.lock();
377 out.write_all(query).ok()?;
378 out.flush().ok()?;
379 }
380
381 let (answered, reply, carried) = read_terminal_reply(in_fd, query, timeout, stop_at_csi_final);
382 carry_typed_ahead(&carried);
383 if !answered {
384 // An incomplete control reply is not safe to replay as typing.
385 note_consumed_unreplayable(&reply);
386 return None;
387 }
388 Some(reply)
389 }
390
391 #[cfg(unix)]
392 fn read_terminal_reply(
393 in_fd: std::os::fd::RawFd,
394 query: &[u8],
395 timeout: std::time::Duration,
396 stop_at_csi_final: bool,
397 ) -> (bool, Vec<u8>, Vec<u8>) {
398 use std::time::Instant;
399
400 let deadline = Instant::now() + timeout;
401 let mut split = ProbeSplit::for_query(query, stop_at_csi_final);
402 let answered = loop {
403 let Some(byte) = read_terminal_byte(in_fd, deadline) else {
404 break false;
405 };
406 match split.feed(byte) {
407 ProbeStep::Continue => {}
408 ProbeStep::Done => break true,
409 ProbeStep::Overflow => break false,
410 ProbeStep::AwaitStringTerminator => {
411 // Consume the `\` of an `ESC \` terminator so it cannot
412 // surface later as a keypress once the event loop owns
413 // stdin. Anything else is the user's next keystroke.
414 let terminator_deadline = Instant::now() + std::time::Duration::from_millis(5);
415 if let Some(byte) = read_terminal_byte(in_fd, terminator_deadline) {
416 split.finish_string_terminator(byte);
417 }
418 break true;
419 }
420 }
421 };
422
423 let (reply, carried) = split.finish();
424 (answered, reply, carried)
425 }
426
427 /// Poll and read the same unbuffered descriptor. `StdinLock` reads ahead into
428 /// Rust's shared buffer: polling the tty afterward misses those bytes, and
429 /// crossterm's later fd reader cannot recover them either.
430 #[cfg(unix)]
431 fn read_terminal_byte(fd: std::os::fd::RawFd, deadline: std::time::Instant) -> Option<u8> {
432 loop {
433 let remaining = deadline.saturating_duration_since(std::time::Instant::now());
434 if remaining.is_zero() || !wait_readable(fd, remaining) {
435 return None;
436 }
437 let mut byte = 0u8;
438 // SAFETY: the caller owns the open fd throughout the startup probe;
439 // `byte` is writable for exactly the single byte requested. The input
440 // pump has not started, so there is no competing reader.
441 let count = unsafe { libc::read(fd, std::ptr::addr_of_mut!(byte).cast(), 1) };
442 if count == 1 {
443 return Some(byte);
444 }
445 if count != -1 || std::io::Error::last_os_error().kind() != std::io::ErrorKind::Interrupted
446 {
447 return None;
448 }
449 }
450 }
451
452 #[cfg(all(test, unix))]
453 #[path = "osc11_tests.rs"]
454 mod tests;
455
456 /// Block until `fd` has data or `timeout` elapses. `true` means readable.
457 #[cfg(unix)]
458 fn wait_readable(fd: std::os::fd::RawFd, timeout: std::time::Duration) -> bool {
459 let mut pollfd = libc::pollfd {
460 fd,
461 events: libc::POLLIN,
462 revents: 0,
463 };
464 let millis = i32::try_from(timeout.as_millis())
465 .unwrap_or(i32::MAX)
466 .max(1);
467 // SAFETY: `pollfd` is a live, correctly-initialized single-element array
468 // and the count matches.
469 let rc = unsafe { libc::poll(std::ptr::addr_of_mut!(pollfd), 1, millis) };
470 rc > 0 && (pollfd.revents & libc::POLLIN) != 0
471 }
472
473 /// Non-Unix platforms have no portable way to read a raw OSC reply back off
474 /// the console handle, so detection falls through to the environment-based
475 /// sources. Callers treat `None` as "no evidence", never as "dark".
476 #[cfg(not(unix))]
477 pub fn query_terminal(_query: &[u8], _timeout: std::time::Duration) -> Option<Vec<u8>> {
478 None
479 }
480
481 /// Non-Unix twin of [`query_terminal_csi`]: no console to ask, no evidence.
482 #[cfg(not(unix))]
483 pub fn query_terminal_csi(_query: &[u8], _timeout: std::time::Duration) -> Option<Vec<u8>> {
484 None
485 }
486
486 lines RUST