返回 CodeWhale
color_compat.rs
根目录 / crates / tui / src / tui / color_compat.rs
1 //! Terminal color compatibility shim.
2 //!
3 //! Ratatui's crossterm backend emits truecolor SGR for every `Color::Rgb`
4 //! cell. That is correct for truecolor terminals, but macOS Terminal.app often
5 //! advertises only `xterm-256color`; sending `38;2` / `48;2` there can render
6 //! as stray green/cyan backgrounds. This backend adapts every cell to the
7 //! detected color depth before handing it to crossterm.
8
9 use std::fmt::Write as _;
10 use std::fs::{self, File, OpenOptions};
11 use std::io::{self, Write};
12
13 use ratatui::{
14 backend::{Backend, ClearType, CrosstermBackend, WindowSize},
15 buffer::Cell,
16 layout::{Position, Size},
17 };
18
19 use codewhale_palette::{self as palette, ColorDepth, PaletteMode, ThemeId, UiTheme};
20 use codewhale_tui_kit::osc8;
21
22 const RENDER_DEBUG_ENV: &str = "CODEWHALE_TUI_DEBUG";
23 const ASCII_SAFE_ENV: &str = "CODEWHALE_ASCII_SAFE";
24 const RENDER_DEBUG_SAMPLE_LIMIT: usize = 24;
25
26 #[derive(Debug)]
27 pub(crate) struct ColorCompatBackend<W: Write> {
28 inner: CrosstermBackend<W>,
29 depth: ColorDepth,
30 palette_mode: PaletteMode,
31 /// Currently active named theme. `System`/`Whale`/`WhaleLight` make the
32 /// theme remap a no-op (those rely on the dark/light pipeline); the
33 /// community presets (Catppuccin, Tokyo Night, Dracula, Gruvbox) trigger
34 /// a per-cell rewrite of dark-palette constants → preset slots.
35 theme_id: ThemeId,
36 /// Resolved active `UiTheme`, *including* any user `background_color`
37 /// override (`UiTheme::with_background_color`). The cell remap reads
38 /// target slots from this struct, not from `theme_id.ui_theme()`, so
39 /// `theme = "tokyo-night"` + `background_color = "#000000"` lands as a
40 /// pure-black surface instead of being overwritten back to
41 /// tokyo-night's `#16161e` by the remap.
42 active_ui_theme: UiTheme,
43 /// During a resize event the terminal emulator may report stale dimensions
44 /// for a brief window (observed on macOS Terminal.app and Windows ConHost).
45 /// Forcing the expected size prevents ratatui's internal `autoresize` from
46 /// shrinking the viewport back to the stale dimension inside `draw()`.
47 forced_size: Option<Size>,
48 /// Cached terminal size from `crossterm::terminal::size()`, set after
49 /// re-entering alt-screen to avoid stale buffer dimensions on Windows.
50 /// Used as the primary fallback in `size()` before falling through to
51 /// the live crossterm query.
52 terminal_size: Option<Size>,
53 /// The last position the cursor was explicitly moved to.
54 ///
55 /// ratatui-core >= 0.1.1 issues a CPR query inside `Terminal::clear()`
56 /// (`backend.get_cursor_position()` → `ESC[6n`) to snapshot and restore
57 /// the cursor. With our input event loop already reading stdin, the
58 /// reply is consumed as input and the query times out —
59 /// ratatui/ratatui#2483, #2640. #2640's workaround for apps with a live
60 /// event loop is to answer from tracked state, which this backend does:
61 /// `get_cursor_position()` never touches the terminal. Only
62 /// `set_cursor_position()` updates the tracker; raw writes that move
63 /// the cursor out-of-band leave it behind, but every such path is
64 /// followed by a full repaint that repositions the cursor itself.
65 tracked_cursor: Position,
66 render_debug: Option<RenderDebugLog>,
67 ascii_safe: bool,
68 /// The terminal's own background, when detection measured one
69 /// (`BackgroundSource::Osc11` or a resolvable `COLORFGBG` index). This is
70 /// the surface a `Color::Reset` cell is really drawn on, so it is what the
71 /// contrast floor reasons against. `None` means "no evidence": an
72 /// unpainted cell then keeps the terminal's own ink, and a painted cell is
73 /// left alone rather than guessed at.
74 detected_background: Option<ratatui::style::Color>,
75 previous_frame_links: Vec<osc8::LinkRegion>,
76 }
77
78 impl<W: Write> ColorCompatBackend<W> {
79 pub(crate) fn new(writer: W, depth: ColorDepth, palette_mode: PaletteMode) -> Self {
80 Self {
81 inner: CrosstermBackend::new(writer),
82 depth,
83 palette_mode,
84 theme_id: ThemeId::System,
85 // Default to whatever System resolves to right now — it stays a
86 // no-op for the remap since `theme_id` is also System, so this
87 // initial value only matters once `set_theme` flips both fields
88 // to a community preset.
89 active_ui_theme: UiTheme::detect(),
90 forced_size: None,
91 terminal_size: None,
92 tracked_cursor: Position::ORIGIN,
93 render_debug: RenderDebugLog::from_env(),
94 ascii_safe: ascii_safe_enabled(),
95 detected_background: None,
96 previous_frame_links: Vec::new(),
97 }
98 }
99
100 /// Immutable frame input from this backend's already negotiated facts.
101 /// Unknown terminal background stays unknown; an explicitly painted pane
102 /// may separately establish its own known ground at the finishing boundary.
103 pub(crate) fn native_ocean_caps(&self) -> codewhale_ratatui::Caps {
104 use codewhale_ratatui::{Caps, color::ColorDepth as NativeDepth, detect::Appearance};
105 Caps {
106 depth: match self.depth {
107 ColorDepth::Monochrome => NativeDepth::Monochrome,
108 ColorDepth::Ansi16 => NativeDepth::Ansi16,
109 ColorDepth::Ansi256 => NativeDepth::Ansi256,
110 ColorDepth::TrueColor => NativeDepth::TrueColor,
111 },
112 ascii: self.ascii_safe,
113 appearance: self
114 .detected_background
115 .and_then(codewhale_ratatui::detect::appearance_for_background)
116 .unwrap_or(Appearance::Unknown),
117 }
118 }
119
120 /// Record the measured terminal background. See the field docs.
121 pub(crate) fn set_detected_background(&mut self, color: Option<ratatui::style::Color>) {
122 self.detected_background = color;
123 }
124
125 pub(crate) fn detected_background(&self) -> Option<ratatui::style::Color> {
126 self.detected_background
127 }
128
129 pub(crate) fn force_size(&mut self, size: Size) {
130 self.forced_size = Some(size);
131 }
132
133 pub(crate) fn clear_forced_size(&mut self) {
134 self.forced_size = None;
135 }
136
137 pub(crate) fn set_terminal_size(&mut self, size: Size) {
138 self.terminal_size = Some(size);
139 }
140
141 pub(super) fn take_previous_frame_links(&mut self) -> Vec<osc8::LinkRegion> {
142 std::mem::take(&mut self.previous_frame_links)
143 }
144
145 pub(crate) fn set_palette_mode(&mut self, palette_mode: PaletteMode) {
146 self.palette_mode = palette_mode;
147 }
148
149 pub(crate) fn set_theme(&mut self, theme_id: ThemeId, ui_theme: UiTheme) {
150 self.theme_id = theme_id;
151 self.active_ui_theme = ui_theme;
152 }
153 }
154
155 impl<W: Write> Write for ColorCompatBackend<W> {
156 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
157 self.inner.write(buf)
158 }
159
160 fn flush(&mut self) -> io::Result<()> {
161 Write::flush(&mut self.inner)
162 }
163 }
164
165 impl<W: Write> Backend for ColorCompatBackend<W> {
166 type Error = io::Error;
167
168 fn draw<'a, I>(&mut self, content: I) -> io::Result<()>
169 where
170 I: Iterator<Item = (u16, u16, &'a Cell)>,
171 {
172 let adapted = content
173 .map(|(x, y, cell)| {
174 let mut cell = cell.clone();
175 adapt_cell_colors(
176 &mut cell,
177 self.depth,
178 self.palette_mode,
179 self.theme_id,
180 &self.active_ui_theme,
181 self.detected_background,
182 );
183 if self.ascii_safe {
184 adapt_cell_symbol_for_ascii(&mut cell);
185 }
186 (x, y, cell)
187 })
188 .collect::<Vec<_>>();
189 let viewport = if self.render_debug.is_some() {
190 self.size().ok()
191 } else {
192 None
193 };
194 if let Some(render_debug) = &mut self.render_debug {
195 render_debug.record(viewport, &adapted);
196 }
197 // #3029: Emit OSC 8 hyperlinks out-of-band through the backend's
198 // Write impl. ratatui's buffer pipeline strips ESC bytes, so the
199 // open/close sequences must be interleaved with the cell stream
200 // here. OSC 8 is stateful and last-writer-wins: every cell painted
201 // between an open and the next close links to that open's target,
202 // so each region's cells must be bracketed by their OWN open/close
203 // pair — never batched.
204 let mut frame_links = osc8::take_frame_links();
205 if frame_links.is_empty() || !osc8::enabled() {
206 self.inner
207 .draw(adapted.iter().map(|(x, y, cell)| (*x, *y, cell)))?;
208 self.previous_frame_links.clear();
209 return Ok(());
210 }
211 // Deterministic region lookup when regions are adjacent/overlapping:
212 // the first (top-left-most) region wins.
213 frame_links.sort_unstable_by_key(|link| (link.row, link.col_start));
214 let region_for = |x: u16, y: u16| -> Option<usize> {
215 frame_links
216 .iter()
217 .position(|link| y == link.row && x >= link.col_start && x <= link.col_end)
218 };
219
220 // Walk the diff in its original order and split it into runs at
221 // region boundaries, so the visible byte stream stays identical to
222 // a no-link render apart from the inserted OSC 8 sequences.
223 let mut idx = 0;
224 while idx < adapted.len() {
225 let current_region = region_for(adapted[idx].0, adapted[idx].1);
226 let run_start = idx;
227 while idx < adapted.len()
228 && region_for(adapted[idx].0, adapted[idx].1) == current_region
229 {
230 idx += 1;
231 }
232 let run = &adapted[run_start..idx];
233 if let Some(region_idx) = current_region
234 && osc8::target_within_limit(&frame_links[region_idx].target)
235 {
236 osc8::write_osc8_open(self, &frame_links[region_idx].target)?;
237 self.inner
238 .draw(run.iter().map(|(x, y, cell)| (*x, *y, cell)))?;
239 osc8::write_osc8_close(self)?;
240 } else {
241 self.inner
242 .draw(run.iter().map(|(x, y, cell)| (*x, *y, cell)))?;
243 }
244 }
245 self.previous_frame_links = frame_links;
246 Ok(())
247 }
248
249 fn append_lines(&mut self, n: u16) -> io::Result<()> {
250 self.inner.append_lines(n)
251 }
252
253 fn hide_cursor(&mut self) -> io::Result<()> {
254 self.inner.hide_cursor()
255 }
256
257 fn show_cursor(&mut self) -> io::Result<()> {
258 self.inner.show_cursor()
259 }
260
261 fn get_cursor_position(&mut self) -> io::Result<Position> {
262 // Answer from tracked state instead of issuing a CPR query that
263 // races the input event loop — see `tracked_cursor`.
264 Ok(self.tracked_cursor)
265 }
266
267 fn set_cursor_position<P: Into<Position>>(&mut self, position: P) -> io::Result<()> {
268 let position = position.into();
269 self.tracked_cursor = position;
270 self.inner.set_cursor_position(position)
271 }
272
273 fn clear(&mut self) -> io::Result<()> {
274 self.inner.clear()
275 }
276
277 fn clear_region(&mut self, clear_type: ClearType) -> io::Result<()> {
278 self.inner.clear_region(clear_type)
279 }
280
281 fn size(&self) -> io::Result<Size> {
282 // forced_size takes priority: it is set during resize events to prevent
283 // ratatui's autoresize from shrinking the viewport back to a stale
284 // dimension. terminal_size is the cached real terminal size used as a
285 // fallback after alt-screen re-entry (Windows buffer width workaround).
286 if let Some(size) = self.forced_size.or(self.terminal_size) {
287 return Ok(size);
288 }
289 self.inner.size()
290 }
291
292 fn window_size(&mut self) -> io::Result<WindowSize> {
293 self.inner.window_size()
294 }
295
296 fn flush(&mut self) -> io::Result<()> {
297 Backend::flush(&mut self.inner)
298 }
299 }
300
301 #[derive(Debug)]
302 struct RenderDebugLog {
303 file: File,
304 frame: u64,
305 }
306
307 impl RenderDebugLog {
308 fn from_env() -> Option<Self> {
309 if !render_debug_enabled_from_value(std::env::var(RENDER_DEBUG_ENV).ok().as_deref()) {
310 return None;
311 }
312
313 let log_dir = codewhale_runtime::runtime_log::log_directory()?;
314 if let Err(err) = fs::create_dir_all(&log_dir) {
315 tracing::debug!(?err, "failed to create TUI render debug log directory");
316 return None;
317 }
318 let path = log_dir.join("tui-render.log");
319 let file = OpenOptions::new()
320 .create(true)
321 .append(true)
322 .open(&path)
323 .map_err(|err| {
324 tracing::debug!(?err, path = %path.display(), "failed to open TUI render debug log");
325 err
326 })
327 .ok()?;
328
329 Some(Self { file, frame: 0 })
330 }
331
332 fn record(&mut self, viewport: Option<Size>, diff: &[(u16, u16, Cell)]) {
333 self.frame = self.frame.saturating_add(1);
334 let sample = diff
335 .iter()
336 .take(RENDER_DEBUG_SAMPLE_LIMIT)
337 .map(|(x, y, _)| (*x, *y))
338 .collect::<Vec<_>>();
339 let line = render_debug_line(self.frame, viewport, diff.len(), &sample);
340 let _ = self.file.write_all(line.as_bytes());
341 }
342 }
343
344 fn render_debug_enabled_from_value(value: Option<&str>) -> bool {
345 env_flag_enabled(value)
346 }
347
348 fn env_flag_enabled(value: Option<&str>) -> bool {
349 matches!(
350 value.map(str::trim).map(str::to_ascii_lowercase).as_deref(),
351 Some("1" | "true" | "yes" | "on")
352 )
353 }
354
355 /// Whether terminal chrome must use portable ASCII spellings. Text producers
356 /// that would otherwise compose multi-cell Unicode labels share this decision
357 /// with the backend's single-cell glyph adapter.
358 #[must_use]
359 pub(crate) fn ascii_safe_enabled() -> bool {
360 env_flag_enabled(std::env::var(ASCII_SAFE_ENV).ok().as_deref())
361 }
362
363 /// Narrow every CodeWhale-authored decorative glyph to a semantic ASCII
364 /// alternative. Scope is deliberate: box drawing, block elements (whale
365 /// mark, meters, rails), braille state markers, geometric role/state marks,
366 /// arrows, and typographic chrome. Language text — CJK labels, accented
367 /// letters, user and model content outside those decorative classes —
368 /// passes through untouched.
369 pub(crate) fn adapt_cell_symbol_for_ascii(cell: &mut Cell) {
370 // Braille: preserve the rising-fill signal instead of collapsing every
371 // working/verifying frame to one glyph.
372 let mut chars = cell.symbol().chars();
373 if let (Some(ch), None) = (chars.next(), chars.next())
374 && let Some(replacement) = codewhale_tui_kit::glyphs::braille_ascii_fallback(ch)
375 {
376 cell.set_symbol(replacement);
377 return;
378 }
379 if let Some(replacement) = codewhale_tui_kit::glyphs::ascii_fallback(cell.symbol()) {
380 cell.set_symbol(replacement);
381 }
382 }
383
384 fn render_debug_line(
385 frame: u64,
386 viewport: Option<Size>,
387 diff_cells: usize,
388 sample: &[(u16, u16)],
389 ) -> String {
390 let mut line = String::new();
391 match viewport {
392 Some(size) => {
393 let _ = write!(
394 &mut line,
395 "frame={frame} size={}x{} diff_cells={diff_cells} sample=",
396 size.width, size.height
397 );
398 }
399 None => {
400 let _ = write!(
401 &mut line,
402 "frame={frame} size=unknown diff_cells={diff_cells} sample="
403 );
404 }
405 }
406 for (index, (x, y)) in sample.iter().enumerate() {
407 if index > 0 {
408 line.push(',');
409 }
410 let _ = write!(&mut line, "{x}:{y}");
411 }
412 line.push('\n');
413 line
414 }
415
416 /// Apply the WCAG contrast floor to a cell that is about to be drawn.
417 ///
418 /// This runs *after* the palette-mode remap and *before* depth downsampling,
419 /// because the floor has to reason about the color the user will actually see
420 /// while it is still full-precision RGB.
421 ///
422 /// Unset text ink on painted ground uses the active theme body color.
423 ///
424 /// - Explicit preset colors (`theme_remap_active`: Terminal,
425 /// Catppuccin, Matrix, …) are exempt. Their authors tuned those pairs, some
426 /// deliberately below 4.5:1, and a user who typed `/theme matrix` asked for
427 /// that. The floor guards the auto-detected default path.
428 /// - Only text cells are clamped; frame chrome keeps its intended weight.
429 /// See [`palette::symbol_needs_text_contrast`].
430 ///
431 /// A third case has no surface to measure against: an unpainted cell on a
432 /// terminal that reported no background keeps the terminal's own ink, because
433 /// that is the one colour guaranteed to read on the ground the terminal drew.
434 fn enforce_cell_contrast(
435 cell: &mut Cell,
436 depth: ColorDepth,
437 theme_id: ThemeId,
438 ui_theme: &UiTheme,
439 detected_background: Option<ratatui::style::Color>,
440 ) {
441 if !palette::symbol_needs_text_contrast(cell.symbol()) {
442 return;
443 }
444 if matches!(depth, ColorDepth::TrueColor | ColorDepth::Ansi256)
445 && cell.fg == ratatui::style::Color::Reset
446 && !cell.modifier.contains(ratatui::style::Modifier::REVERSED)
447 && palette::resolvable_rgb(cell.bg).is_some()
448 {
449 cell.fg = if palette::theme_remap_active(theme_id) {
450 ui_theme.text_body
451 } else {
452 palette::enforce_contrast(ui_theme.text_body, cell.bg, palette::AA_BODY_CONTRAST)
453 };
454 return;
455 }
456 if palette::theme_remap_active(theme_id) {
457 return;
458 }
459 let Some(surface) = palette::effective_surface(cell.bg, detected_background) else {
460 if cell.bg == ratatui::style::Color::Reset && cell.fg == palette::TEXT_BODY {
461 cell.fg = ratatui::style::Color::Reset;
462 }
463 return;
464 };
465 cell.fg = palette::enforce_contrast(cell.fg, surface, palette::AA_BODY_CONTRAST);
466 }
467
468 pub(crate) fn adapt_cell_colors(
469 cell: &mut Cell,
470 depth: ColorDepth,
471 palette_mode: PaletteMode,
472 theme_id: ThemeId,
473 ui_theme: &UiTheme,
474 detected_background: Option<ratatui::style::Color>,
475 ) {
476 let source_fg = cell.fg;
477 // Stage 1: community-theme remap (dark palette → preset slots). No-op
478 // for System / Whale / WhaleLight so legacy dark/light flows are
479 // untouched. Runs *before* the palette-mode remap so a light terminal
480 // running e.g. Catppuccin still routes the preset colors through the
481 // light adaptation below (rare combo, but the sequencing is the same).
482 cell.fg = palette::adapt_fg_for_theme(cell.fg, theme_id, ui_theme);
483 cell.bg = palette::adapt_bg_for_theme(cell.bg, theme_id, ui_theme);
484 // Stage 2: legacy dark↔light remap.
485 let original_bg = cell.bg;
486 cell.fg = palette::adapt_fg_for_palette_mode(cell.fg, original_bg, palette_mode);
487 cell.bg = palette::adapt_bg_for_palette_mode(cell.bg, palette_mode);
488 // Stage 2.5: contrast floor. Stages 1 and 2 are equality whitelists — a
489 // token nobody listed reaches here unadapted, which is exactly how
490 // near-white body text ends up on a near-white terminal (#4833). This
491 // stage is membership-independent: it looks at the pair that will be
492 // rendered and lifts it if the numbers fail.
493 enforce_cell_contrast(cell, depth, theme_id, ui_theme, detected_background);
494 // Stage 3: depth (truecolor / 256 / 16) downsampling.
495 cell.fg = palette::adapt_fg_for_depth(source_fg, cell.fg, depth, ui_theme);
496 cell.bg = palette::adapt_bg(cell.bg, depth);
497 if depth == ColorDepth::Monochrome {
498 cell.underline_color = ratatui::style::Color::Reset;
499 }
500 }
501
502 /// Exact backend-visible proposed ink, reused by native Ocean's guard.
503 pub(crate) fn project_ocean_ink(
504 cell: &Cell,
505 water: ratatui::style::Color,
506 depth: codewhale_ratatui::color::ColorDepth,
507 theme: &UiTheme,
508 ) -> ratatui::style::Color {
509 use codewhale_ratatui::color::ColorDepth as NativeDepth;
510 let depth = match depth {
511 NativeDepth::Monochrome => ColorDepth::Monochrome,
512 NativeDepth::Ansi16 => ColorDepth::Ansi16,
513 NativeDepth::Ansi256 => ColorDepth::Ansi256,
514 NativeDepth::TrueColor => ColorDepth::TrueColor,
515 };
516 let mut proposed = cell.clone();
517 proposed.set_bg(water);
518 adapt_cell_colors(
519 &mut proposed,
520 depth,
521 theme.mode,
522 ThemeId::Underwater,
523 theme,
524 None,
525 );
526 proposed.fg
527 }
528
529 #[cfg(test)]
530 mod tests {
531 use std::{cell::RefCell, env, ffi::OsString, fs, io::Write, rc::Rc};
532
533 use ratatui::backend::Backend;
534 use ratatui::{buffer::Cell, style::Color};
535
536 use super::*;
537 use crate::test_support::lock_test_env;
538
539 #[derive(Clone, Default)]
540 struct SharedWriter(Rc<RefCell<Vec<u8>>>);
541
542 impl Write for SharedWriter {
543 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
544 self.0.borrow_mut().extend_from_slice(buf);
545 Ok(buf.len())
546 }
547
548 fn flush(&mut self) -> io::Result<()> {
549 Ok(())
550 }
551 }
552
553 struct EnvRestore {
554 key: &'static str,
555 value: Option<OsString>,
556 }
557
558 impl EnvRestore {
559 fn capture(key: &'static str) -> Self {
560 Self {
561 key,
562 value: env::var_os(key),
563 }
564 }
565 }
566
567 impl Drop for EnvRestore {
568 fn drop(&mut self) {
569 // SAFETY: environment mutation is serialized by lock_test_env.
570 unsafe {
571 match &self.value {
572 Some(value) => env::set_var(self.key, value),
573 None => env::remove_var(self.key),
574 }
575 }
576 }
577 }
578
579 #[test]
580 fn adapts_rgb_cells_to_indexed_on_ansi256() {
581 let mut cell = Cell::default();
582 cell.set_fg(Color::Rgb(53, 120, 229));
583 cell.set_bg(Color::Rgb(11, 21, 38));
584
585 adapt_cell_colors(
586 &mut cell,
587 ColorDepth::Ansi256,
588 PaletteMode::Dark,
589 ThemeId::System,
590 &palette::UI_THEME,
591 None,
592 );
593
594 assert!(matches!(cell.fg, Color::Indexed(_)));
595 assert!(matches!(cell.bg, Color::Indexed(_)));
596 }
597
598 #[test]
599 fn leaves_truecolor_cells_unchanged() {
600 let mut cell = Cell::default();
601 cell.set_fg(Color::Rgb(53, 120, 229));
602 cell.set_bg(Color::Rgb(11, 21, 38));
603
604 adapt_cell_colors(
605 &mut cell,
606 ColorDepth::TrueColor,
607 PaletteMode::Dark,
608 ThemeId::System,
609 &palette::UI_THEME,
610 None,
611 );
612
613 assert_eq!(cell.fg, Color::Rgb(53, 120, 229));
614 assert_eq!(cell.bg, Color::Rgb(11, 21, 38));
615 }
616
617 #[test]
618 fn ascii_safe_symbol_adapter_preserves_meaning_with_narrow_glyphs() {
619 for (rich, safe) in [
620 ("─", "-"),
621 ("│", "|"),
622 ("┌", "+"),
623 ("▶", ">"),
624 ("▷", ">"),
625 ("▼", "v"),
626 ("✓", "Y"),
627 ("✕", "X"),
628 ] {
629 let mut cell = Cell::default();
630 cell.set_symbol(rich);
631 adapt_cell_symbol_for_ascii(&mut cell);
632 assert_eq!(cell.symbol(), safe, "{rich} should map to {safe}");
633 assert!(cell.symbol().is_ascii());
634 }
635 }
636
637 #[test]
638 fn monochrome_backend_suppresses_every_color_but_keeps_text_modifiers() {
639 use ratatui::style::{Modifier, Style};
640
641 let sgr = regex::Regex::new(r"\x1b\[([0-9;:]*)m").unwrap();
642 for theme_id in palette::SELECTABLE_THEMES {
643 let theme = theme_id.ui_theme();
644 let writer = SharedWriter::default();
645 let capture = writer.0.clone();
646 let mut backend = ColorCompatBackend::new(writer, ColorDepth::Monochrome, theme.mode);
647 backend.set_theme(*theme_id, theme);
648 let modifiers = Modifier::BOLD | Modifier::UNDERLINED | Modifier::REVERSED;
649 let mut cell = Cell::default();
650 cell.set_symbol("x").set_style(
651 Style::default()
652 .fg(theme.accent_primary)
653 .bg(Color::Indexed(4))
654 .underline_color(Color::Red)
655 .add_modifier(modifiers),
656 );
657 let mut adapted = cell.clone();
658 adapt_cell_colors(
659 &mut adapted,
660 ColorDepth::Monochrome,
661 theme.mode,
662 *theme_id,
663 &theme,
664 None,
665 );
666 assert_eq!(
667 (adapted.fg, adapted.bg, adapted.underline_color),
668 (Color::Reset, Color::Reset, Color::Reset)
669 );
670 assert_eq!(adapted.modifier, modifiers);
671
672 backend.draw(std::iter::once((0, 0, &cell))).unwrap();
673 let output = String::from_utf8_lossy(&capture.borrow()).to_string();
674 assert!(output.contains('x'), "{theme_id:?}: {output:?}");
675 for codes in sgr.captures_iter(&output) {
676 for code in codes[1]
677 .split([';', ':'])
678 .filter_map(|code| code.parse::<u16>().ok())
679 {
680 assert!(
681 !matches!(code, 30..=38 | 40..=48 | 58 | 90..=97 | 100..=107),
682 "{theme_id:?} emitted color SGR: {output:?}"
683 );
684 }
685 }
686 }
687 }
688
689 #[test]
690 fn ansi256_backend_output_does_not_emit_truecolor_sgr() {
691 let writer = SharedWriter::default();
692 let capture = writer.0.clone();
693 let mut backend = ColorCompatBackend::new(writer, ColorDepth::Ansi256, PaletteMode::Dark);
694 let mut cell = Cell::default();
695 cell.set_symbol("x")
696 .set_fg(Color::Rgb(53, 120, 229))
697 .set_bg(Color::Rgb(11, 21, 38));
698
699 backend.draw(std::iter::once((0, 0, &cell))).unwrap();
700
701 let output = String::from_utf8_lossy(&capture.borrow()).to_string();
702 assert!(!output.contains("38;2;"), "{output:?}");
703 assert!(!output.contains("48;2;"), "{output:?}");
704 }
705
706 #[test]
707 fn light_palette_maps_dark_cells_before_depth_adaptation() {
708 let mut cell = Cell::default();
709 cell.set_fg(Color::White);
710 cell.set_bg(palette::WHALE_BG);
711
712 adapt_cell_colors(
713 &mut cell,
714 ColorDepth::TrueColor,
715 PaletteMode::Light,
716 ThemeId::WhaleLight,
717 &palette::LIGHT_UI_THEME,
718 None,
719 );
720
721 assert_eq!(cell.fg, palette::LIGHT_TEXT_BODY);
722 // The whale pair's shell is terminal-owned: a direct WHALE_BG paint
723 // follows LIGHT_UI_THEME.surface_bg (Reset), not a painted surface.
724 assert_eq!(cell.bg, Color::Reset);
725 }
726
727 #[test]
728 fn grayscale_palette_maps_hued_cells_before_depth_adaptation() {
729 let mut cell = Cell::default();
730 cell.set_fg(palette::WHALE_ACTION);
731 cell.set_bg(palette::WHALE_BG);
732
733 adapt_cell_colors(
734 &mut cell,
735 ColorDepth::TrueColor,
736 PaletteMode::Grayscale,
737 ThemeId::Grayscale,
738 &palette::GRAYSCALE_UI_THEME,
739 None,
740 );
741
742 assert_eq!(cell.fg, palette::GRAYSCALE_TEXT_SOFT);
743 assert_eq!(cell.bg, palette::GRAYSCALE_SURFACE);
744 }
745
746 #[test]
747 fn community_theme_remap_honors_background_color_override() {
748 // Tokyo Night + a custom black surface: the remap must rewrite
749 // `palette::WHALE_BG` to the *active* UiTheme's overridden
750 // surface, not to tokyo-night's default surface.
751 let active = palette::TOKYO_NIGHT_UI_THEME.with_background_color(Color::Rgb(0, 0, 0));
752 let mut cell = Cell::default();
753 cell.set_bg(palette::WHALE_BG);
754
755 adapt_cell_colors(
756 &mut cell,
757 ColorDepth::TrueColor,
758 PaletteMode::Dark,
759 ThemeId::TokyoNight,
760 &active,
761 None,
762 );
763
764 assert_eq!(cell.bg, Color::Rgb(0, 0, 0));
765 }
766
767 #[test]
768 fn terminal_and_matrix_cells_keep_effective_mode_colors() {
769 for (theme_id, theme) in [
770 (ThemeId::Terminal, palette::TERMINAL_UI_THEME),
771 (ThemeId::Matrix, palette::MATRIX_UI_THEME),
772 ] {
773 for (source, expected, role) in [
774 (palette::MODE_AGENT, theme.mode_agent, "agent"),
775 (palette::MODE_PLAN, theme.mode_plan, "plan"),
776 (palette::MODE_OPERATE, theme.mode_operate, "operate"),
777 (palette::MODE_YOLO, theme.mode_yolo, "full access"),
778 ] {
779 let mut cell = Cell::default();
780 cell.set_fg(source);
781 adapt_cell_colors(
782 &mut cell,
783 ColorDepth::TrueColor,
784 theme.mode,
785 theme_id,
786 &theme,
787 None,
788 );
789 assert_eq!(
790 cell.fg,
791 expected,
792 "theme '{}' rendered the {role} token through the wrong slot",
793 theme_id.name(),
794 );
795 }
796 }
797 }
798
799 fn rendered_foreground(
800 source: Color,
801 depth: ColorDepth,
802 theme_id: ThemeId,
803 theme: &UiTheme,
804 ) -> Color {
805 let mut cell = Cell::default();
806 cell.set_fg(source);
807 adapt_cell_colors(&mut cell, depth, theme.mode, theme_id, theme, None);
808 cell.fg
809 }
810
811 #[test]
812 fn grayscale_modes_are_identity_safe_for_raw_and_direct_cells() {
813 let theme = palette::GRAYSCALE_UI_THEME;
814 let roles = [
815 ("act", palette::MODE_AGENT, theme.mode_agent, Color::Blue),
816 ("plan", palette::MODE_PLAN, theme.mode_plan, Color::Magenta),
817 (
818 "operate",
819 palette::MODE_OPERATE,
820 theme.mode_operate,
821 Color::LightMagenta,
822 ),
823 (
824 "full access",
825 palette::MODE_YOLO,
826 theme.mode_yolo,
827 Color::Red,
828 ),
829 ];
830
831 for depth in [
832 ColorDepth::TrueColor,
833 ColorDepth::Ansi256,
834 ColorDepth::Ansi16,
835 ] {
836 let mut outputs = Vec::new();
837 for (name, raw, direct, ansi16) in roles {
838 let expected = if depth == ColorDepth::Ansi16 {
839 ansi16
840 } else {
841 palette::adapt_color(direct, depth)
842 };
843 let raw_output = rendered_foreground(raw, depth, ThemeId::Grayscale, &theme);
844 let direct_output = rendered_foreground(direct, depth, ThemeId::Grayscale, &theme);
845 assert_eq!(raw_output, expected, "raw {name} at {depth:?}");
846 assert_eq!(direct_output, expected, "direct {name} at {depth:?}");
847 outputs.push((name, raw_output));
848 }
849 for (index, (left_name, left)) in outputs.iter().enumerate() {
850 for (right_name, right) in outputs.iter().skip(index + 1) {
851 assert_ne!(
852 left, right,
853 "grayscale {depth:?} merged {left_name} and {right_name}"
854 );
855 }
856 }
857 }
858 }
859
860 #[test]
861 fn ansi16_uses_complete_semantic_role_matrix_for_whale_dark_and_light() {
862 let dark_expected = [
863 ("action", Color::LightBlue),
864 ("live", Color::LightCyan),
865 ("human", Color::LightYellow),
866 ("warning", Color::Yellow),
867 ("danger", Color::LightRed),
868 ("success", Color::LightGreen),
869 ("act mode", Color::Blue),
870 ("plan mode", Color::Magenta),
871 ("operate mode", Color::LightMagenta),
872 ("full-access mode", Color::Red),
873 ];
874 let light_expected = [
875 ("action", Color::Blue),
876 ("live", Color::Cyan),
877 ("human", Color::Yellow),
878 ("warning", Color::Yellow),
879 ("danger", Color::Red),
880 ("success", Color::Green),
881 ("act mode", Color::Blue),
882 ("plan mode", Color::Magenta),
883 ("operate mode", Color::Magenta),
884 ("full-access mode", Color::Red),
885 ];
886 let raw = [
887 palette::WHALE_ACTION,
888 palette::WHALE_LIVE,
889 palette::WHALE_HUMAN,
890 palette::STATUS_WARNING,
891 palette::WHALE_ERROR,
892 palette::STATUS_SUCCESS,
893 palette::MODE_AGENT,
894 palette::MODE_PLAN,
895 palette::MODE_OPERATE,
896 palette::MODE_YOLO,
897 ];
898
899 for (theme_id, theme, expected, check_all_distinct) in [
900 (ThemeId::Whale, palette::UI_THEME, dark_expected, true),
901 (
902 ThemeId::WhaleLight,
903 palette::LIGHT_UI_THEME,
904 light_expected,
905 false,
906 ),
907 ] {
908 let direct = [
909 theme.accent_primary,
910 theme.status_working,
911 theme.accent_action,
912 theme.warning,
913 theme.error_fg,
914 theme.success,
915 theme.mode_agent,
916 theme.mode_plan,
917 theme.mode_operate,
918 theme.mode_yolo,
919 ];
920 for (source_kind, sources) in [("raw", raw), ("direct", direct)] {
921 let outputs = sources
922 .into_iter()
923 .zip(expected)
924 .map(|(source, (name, expected_color))| {
925 let output =
926 rendered_foreground(source, ColorDepth::Ansi16, theme_id, &theme);
927 assert_eq!(
928 output,
929 expected_color,
930 "{} {source_kind} {name}",
931 theme_id.name(),
932 );
933 (name, output)
934 })
935 .collect::<Vec<_>>();
936 if check_all_distinct {
937 for (index, (left_name, left)) in outputs.iter().enumerate() {
938 for (right_name, right) in outputs.iter().skip(index + 1) {
939 assert_ne!(
940 left,
941 right,
942 "{} {source_kind} matrix merged {left_name} and {right_name}",
943 theme_id.name(),
944 );
945 }
946 }
947 } else {
948 for pair_group in [&[0usize, 1, 3, 4, 5][..], &[6usize, 7, 9][..]] {
949 for (pos, &left_idx) in pair_group.iter().enumerate() {
950 for &right_idx in &pair_group[pos + 1..] {
951 let (left_name, left) = outputs[left_idx];
952 let (right_name, right) = outputs[right_idx];
953 assert_ne!(
954 left,
955 right,
956 "{} {source_kind} matrix merged {left_name} and {right_name}",
957 theme_id.name(),
958 );
959 }
960 }
961 }
962 }
963 }
964 }
965 }
966
967 #[test]
968 fn backend_palette_mode_can_follow_runtime_theme_changes() {
969 let writer = SharedWriter::default();
970 let mut backend = ColorCompatBackend::new(writer, ColorDepth::TrueColor, PaletteMode::Dark);
971
972 assert_eq!(backend.palette_mode, PaletteMode::Dark);
973 backend.set_palette_mode(PaletteMode::Light);
974 assert_eq!(backend.palette_mode, PaletteMode::Light);
975 backend.set_palette_mode(PaletteMode::Grayscale);
976 assert_eq!(backend.palette_mode, PaletteMode::Grayscale);
977 }
978
979 #[test]
980 fn render_debug_env_parser_accepts_truthy_values_only() {
981 assert!(!render_debug_enabled_from_value(None));
982 assert!(!render_debug_enabled_from_value(Some("")));
983 assert!(!render_debug_enabled_from_value(Some("0")));
984 assert!(!render_debug_enabled_from_value(Some("false")));
985 assert!(render_debug_enabled_from_value(Some("1")));
986 assert!(render_debug_enabled_from_value(Some("true")));
987 assert!(render_debug_enabled_from_value(Some("YES")));
988 assert!(render_debug_enabled_from_value(Some("on")));
989 }
990
991 #[test]
992 fn render_debug_line_records_frame_size_and_diff_sample() {
993 let line = render_debug_line(7, Some(Size::new(80, 24)), 42, &[(0, 0), (12, 3), (79, 23)]);
994
995 assert_eq!(
996 line,
997 "frame=7 size=80x24 diff_cells=42 sample=0:0,12:3,79:23\n"
998 );
999 }
1000
1001 #[test]
1002 fn backend_writes_render_debug_log_when_enabled() {
1003 let _lock = lock_test_env();
1004 let tmp = tempfile::tempdir().expect("tempdir");
1005 let _home = EnvRestore::capture("HOME");
1006 let _userprofile = EnvRestore::capture("USERPROFILE");
1007 let _debug = EnvRestore::capture(RENDER_DEBUG_ENV);
1008
1009 // SAFETY: environment mutation is serialized by lock_test_env.
1010 unsafe {
1011 env::set_var("HOME", tmp.path());
1012 env::set_var("USERPROFILE", "");
1013 env::set_var(RENDER_DEBUG_ENV, "1");
1014 }
1015
1016 let writer = SharedWriter::default();
1017 let mut backend = ColorCompatBackend::new(writer, ColorDepth::TrueColor, PaletteMode::Dark);
1018 let mut cell = Cell::default();
1019 cell.set_symbol("x");
1020 backend.draw(std::iter::once((3, 4, &cell))).unwrap();
1021
1022 let log_path = tmp
1023 .path()
1024 .join(".codewhale")
1025 .join("logs")
1026 .join("tui-render.log");
1027 let body = fs::read_to_string(log_path).expect("render debug log");
1028 assert!(body.contains("frame=1"), "{body}");
1029 assert!(body.contains("diff_cells=1"), "{body}");
1030 assert!(body.contains("sample=3:4"), "{body}");
1031 }
1032
1033 #[test]
1034 fn size_returns_terminal_size_when_set() {
1035 let writer = SharedWriter::default();
1036 let mut backend = ColorCompatBackend::new(writer, ColorDepth::TrueColor, PaletteMode::Dark);
1037
1038 backend.set_terminal_size(Size::new(120, 40));
1039 assert_eq!(backend.size().unwrap(), Size::new(120, 40));
1040 }
1041
1042 #[test]
1043 fn forced_size_takes_priority_over_terminal_size() {
1044 let writer = SharedWriter::default();
1045 let mut backend = ColorCompatBackend::new(writer, ColorDepth::TrueColor, PaletteMode::Dark);
1046
1047 // forced_size is set during resize events to temporarily override the
1048 // cached terminal_size — it must win to prevent viewport shrinking.
1049 backend.set_terminal_size(Size::new(120, 40));
1050 backend.force_size(Size::new(80, 25));
1051 assert_eq!(backend.size().unwrap(), Size::new(80, 25));
1052 }
1053
1054 #[test]
1055 fn size_falls_back_to_forced_size_when_terminal_size_unset() {
1056 let writer = SharedWriter::default();
1057 let mut backend = ColorCompatBackend::new(writer, ColorDepth::TrueColor, PaletteMode::Dark);
1058
1059 backend.force_size(Size::new(80, 25));
1060 assert_eq!(backend.size().unwrap(), Size::new(80, 25));
1061 }
1062
1063 // ── #3029: OSC 8 emission through the backend byte stream ──────────────
1064
1065 fn row_cells(symbols: &str) -> Vec<(u16, u16, Cell)> {
1066 symbols
1067 .chars()
1068 .enumerate()
1069 .map(|(i, ch)| {
1070 let mut cell = Cell::default();
1071 cell.set_symbol(&ch.to_string());
1072 (u16::try_from(i).unwrap(), 0u16, cell)
1073 })
1074 .collect()
1075 }
1076
1077 #[test]
1078 fn osc8_open_close_bracket_only_their_region_cells() {
1079 use codewhale_tui_kit::osc8::LinkRegion;
1080
1081 // Baseline: identical cells, no link regions.
1082 let baseline_writer = SharedWriter::default();
1083 let baseline_capture = baseline_writer.0.clone();
1084 let mut baseline =
1085 ColorCompatBackend::new(baseline_writer, ColorDepth::TrueColor, PaletteMode::Dark);
1086 let cells = row_cells("ABCDE");
1087 baseline
1088 .draw(cells.iter().map(|(x, y, cell)| (*x, *y, cell)))
1089 .unwrap();
1090 let baseline_out = String::from_utf8_lossy(&baseline_capture.borrow()).to_string();
1091
1092 // Linked render: columns 2..=3 ("CD") carry one link region.
1093 codewhale_tui_kit::osc8::set_frame_links(vec![LinkRegion {
1094 row: 0,
1095 col_start: 2,
1096 col_end: 3,
1097 target: "https://example.test/1".to_string(),
1098 }]);
1099 let writer = SharedWriter::default();
1100 let capture = writer.0.clone();
1101 let mut backend = ColorCompatBackend::new(writer, ColorDepth::TrueColor, PaletteMode::Dark);
1102 let cells = row_cells("ABCDE");
1103 backend
1104 .draw(cells.iter().map(|(x, y, cell)| (*x, *y, cell)))
1105 .unwrap();
1106 let out = String::from_utf8_lossy(&capture.borrow()).to_string();
1107
1108 let open = "\x1b]8;;https://example.test/1\x1b\\";
1109 let close = "\x1b]8;;\x1b\\";
1110 assert_eq!(out.matches(open).count(), 1, "exactly one open: {out:?}");
1111 assert_eq!(out.matches(close).count(), 1, "exactly one close: {out:?}");
1112
1113 // The open must precede the first linked glyph and the close must sit
1114 // between the last linked glyph and the first glyph after the region.
1115 let open_at = out.find(open).expect("open present");
1116 let close_at = out.find(close).expect("close present");
1117 let c_at = out.find('C').expect("glyph C");
1118 let d_at = out.find('D').expect("glyph D");
1119 let e_at = out.find('E').expect("glyph E");
1120 assert!(open_at < c_at, "open before linked cells: {out:?}");
1121 assert!(d_at < close_at, "close after linked cells: {out:?}");
1122 assert!(
1123 close_at < e_at,
1124 "cells after the region must not inherit the link: {out:?}"
1125 );
1126
1127 // Visible glyph stream is unchanged by link insertion.
1128 let mut baseline_visible = String::new();
1129 codewhale_sanitize::sanitize::strip_ansi_into(&baseline_out, &mut baseline_visible);
1130 let mut linked_visible = String::new();
1131 codewhale_sanitize::sanitize::strip_ansi_into(&out, &mut linked_visible);
1132 assert_eq!(
1133 baseline_visible, linked_visible,
1134 "link emission must not move or alter visible cells"
1135 );
1136 }
1137
1138 #[test]
1139 fn osc8_two_regions_link_to_their_own_targets() {
1140 use codewhale_tui_kit::osc8::LinkRegion;
1141
1142 codewhale_tui_kit::osc8::set_frame_links(vec![
1143 LinkRegion {
1144 row: 0,
1145 col_start: 0,
1146 col_end: 1,
1147 target: "https://example.test/first".to_string(),
1148 },
1149 LinkRegion {
1150 row: 0,
1151 col_start: 3,
1152 col_end: 4,
1153 target: "https://example.test/second".to_string(),
1154 },
1155 ]);
1156 let writer = SharedWriter::default();
1157 let capture = writer.0.clone();
1158 let mut backend = ColorCompatBackend::new(writer, ColorDepth::TrueColor, PaletteMode::Dark);
1159 let cells = row_cells("ABZCD");
1160 backend
1161 .draw(cells.iter().map(|(x, y, cell)| (*x, *y, cell)))
1162 .unwrap();
1163 let out = String::from_utf8_lossy(&capture.borrow()).to_string();
1164
1165 let first = "\x1b]8;;https://example.test/first\x1b\\";
1166 let second = "\x1b]8;;https://example.test/second\x1b\\";
1167 let close = "\x1b]8;;\x1b\\";
1168 assert_eq!(out.matches(first).count(), 1, "{out:?}");
1169 assert_eq!(out.matches(second).count(), 1, "{out:?}");
1170 assert_eq!(out.matches(close).count(), 2, "{out:?}");
1171
1172 // Pre-#3029-audit bug: both opens were emitted before any cell, so
1173 // the whole frame linked to the LAST region's target. Each region's
1174 // open must close before the next region's open begins.
1175 let first_at = out.find(first).expect("first open");
1176 let first_close_at = out[first_at..].find(close).expect("first close") + first_at;
1177 let second_at = out.find(second).expect("second open");
1178 assert!(
1179 first_close_at < second_at,
1180 "region one must close before region two opens: {out:?}"
1181 );
1182 // The unlinked middle glyph sits between the two link spans.
1183 let z_at = out.find('Z').expect("unlinked glyph");
1184 assert!(first_close_at < z_at && z_at < second_at, "{out:?}");
1185 }
1186
1187 /// #3029 end-to-end: a long bare URL hard-wraps at narrow width while its
1188 /// full target travels beside every visible chunk. No escape payload enters
1189 /// the buffer, and the backend re-emits one OSC 8 pair per row without
1190 /// altering the visible byte stream.
1191 #[test]
1192 fn osc8_metadata_feeds_backend_for_every_wrapped_url_chunk() {
1193 use codewhale_tui_kit::{markdown_render, osc8};
1194 use ratatui::buffer::Buffer;
1195 use ratatui::layout::Rect;
1196 use ratatui::style::Style;
1197 use ratatui::widgets::{Paragraph, Widget};
1198 use unicode_width::UnicodeWidthStr;
1199
1200 let target = "https://example.test/a/very/long/path/that/wraps/across/rows";
1201 let rendered = markdown_render::render_markdown_tagged(target, 12, Style::default());
1202 assert!(rendered.len() > 2, "fixture must wrap at narrow width");
1203 let lines = rendered
1204 .iter()
1205 .map(|rendered| rendered.line.clone())
1206 .collect::<Vec<_>>();
1207 let line_links = rendered
1208 .iter()
1209 .map(|rendered| rendered.links.clone())
1210 .collect::<Vec<_>>();
1211 let visible = lines
1212 .iter()
1213 .map(|line| {
1214 line.spans
1215 .iter()
1216 .map(|span| span.content.as_ref())
1217 .collect::<String>()
1218 })
1219 .collect::<Vec<_>>();
1220 assert_eq!(visible.concat(), target);
1221
1222 let area = Rect::new(3, 2, 12, u16::try_from(lines.len()).unwrap());
1223 let mut buf = Buffer::empty(area);
1224 Paragraph::new(lines).render(area, &mut buf);
1225
1226 // Visible cells start at the area's real x offset and contain exactly
1227 // the URL chunks — never the historical `]8;;` payload bytes.
1228 for (row_index, text) in visible.iter().enumerate() {
1229 let y = area.y + u16::try_from(row_index).unwrap();
1230 let row = (0..u16::try_from(text.width()).unwrap())
1231 .map(|offset| buf[(area.x + offset, y)].symbol().to_string())
1232 .collect::<String>();
1233 assert_eq!(row, *text);
1234 }
1235 assert!((area.y..area.bottom()).all(|y| {
1236 (area.x..area.right()).all(|x| {
1237 let symbol = buf[(x, y)].symbol();
1238 !symbol.contains('\x1b') && !symbol.contains("]8;;")
1239 })
1240 }));
1241
1242 let regions = osc8::link_regions_for_lines(area, &line_links);
1243 assert_eq!(regions.len(), rendered.len());
1244 for ((region, text), row_index) in regions.iter().zip(&visible).zip(0u16..) {
1245 assert_eq!(region.row, area.y + row_index);
1246 assert_eq!(region.col_start, area.x);
1247 assert_eq!(
1248 region.col_end,
1249 area.x + u16::try_from(text.width()).unwrap() - 1
1250 );
1251 assert_eq!(region.target, target);
1252 }
1253
1254 let buf_ref = &buf;
1255 let cells = (area.y..area.bottom())
1256 .flat_map(|y| (area.x..area.right()).map(move |x| (x, y, buf_ref[(x, y)].clone())))
1257 .collect::<Vec<_>>();
1258
1259 // Capture an unlinked baseline from the exact same cells.
1260 let _ = osc8::take_frame_links();
1261 let baseline_writer = SharedWriter::default();
1262 let baseline_capture = baseline_writer.0.clone();
1263 let mut baseline =
1264 ColorCompatBackend::new(baseline_writer, ColorDepth::TrueColor, PaletteMode::Dark);
1265 baseline
1266 .draw(cells.iter().map(|(x, y, cell)| (*x, *y, cell)))
1267 .unwrap();
1268
1269 osc8::set_frame_links(regions);
1270 let writer = SharedWriter::default();
1271 let capture = writer.0.clone();
1272 let mut backend = ColorCompatBackend::new(writer, ColorDepth::TrueColor, PaletteMode::Dark);
1273 backend
1274 .draw(cells.iter().map(|(x, y, cell)| (*x, *y, cell)))
1275 .unwrap();
1276 let out = String::from_utf8_lossy(&capture.borrow()).to_string();
1277
1278 let open = format!("\x1b]8;;{target}\x1b\\");
1279 let close = "\x1b]8;;\x1b\\";
1280 assert_eq!(
1281 out.matches(open.as_str()).count(),
1282 rendered.len(),
1283 "each row reopens the full target: {out:?}"
1284 );
1285 assert_eq!(out.matches(close).count(), rendered.len());
1286
1287 let baseline_out = String::from_utf8_lossy(&baseline_capture.borrow()).to_string();
1288 let mut baseline_visible = String::new();
1289 codewhale_sanitize::sanitize::strip_ansi_into(&baseline_out, &mut baseline_visible);
1290 let mut linked_visible = String::new();
1291 codewhale_sanitize::sanitize::strip_ansi_into(&out, &mut linked_visible);
1292 assert_eq!(
1293 linked_visible, baseline_visible,
1294 "OSC 8 insertion must not move or alter any rendered cell"
1295 );
1296 }
1297
1298 /// Render one cell the way `draw()` does and hand back the foreground.
1299 fn cell_fg_after_adaptation(
1300 symbol: &str,
1301 fg: Color,
1302 bg: Color,
1303 palette_mode: PaletteMode,
1304 theme_id: ThemeId,
1305 detected_background: Option<Color>,
1306 ) -> Color {
1307 let mut cell = Cell::default();
1308 cell.set_symbol(symbol).set_fg(fg).set_bg(bg);
1309 adapt_cell_colors(
1310 &mut cell,
1311 ColorDepth::TrueColor,
1312 palette_mode,
1313 theme_id,
1314 &theme_id.ui_theme(),
1315 detected_background,
1316 );
1317 cell.fg
1318 }
1319
1320 /// #4833. A white terminal that reports no `COLORFGBG` was detected as
1321 /// Dark, so the light whitelist never ran and ivory body text landed on a
1322 /// near-white surface. With the background measured, the contrast floor
1323 /// catches it even when the palette mode is still Dark.
1324 #[test]
1325 fn measured_light_background_lifts_body_text_off_the_surface() {
1326 let white = Color::Rgb(0xFF, 0xFF, 0xFF);
1327 let rendered = cell_fg_after_adaptation(
1328 "x",
1329 palette::TEXT_BODY,
1330 Color::Reset,
1331 PaletteMode::Dark,
1332 ThemeId::System,
1333 Some(white),
1334 );
1335
1336 assert_ne!(
1337 rendered,
1338 palette::TEXT_BODY,
1339 "body text must not pass through unadapted onto a white surface"
1340 );
1341 let ratio = palette::contrast_ratio(rendered, white).unwrap();
1342 assert!(
1343 ratio >= palette::AA_BODY_CONTRAST,
1344 "rendered body text is {ratio}:1 against the measured surface"
1345 );
1346 }
1347
1348 /// The no-regression half of #4833: on a measured dark terminal every
1349 /// rendered cell comes out byte-identical to what v0.9.1 emitted.
1350 #[test]
1351 fn measured_dark_background_changes_nothing() {
1352 for surface in [
1353 Color::Rgb(0x00, 0x00, 0x00),
1354 Color::Rgb(0x1E, 0x1E, 0x1E),
1355 palette::WHALE_BG,
1356 ] {
1357 for token in [
1358 palette::TEXT_BODY,
1359 palette::TEXT_HINT,
1360 palette::TEXT_TOOL_OUTPUT,
1361 palette::WHALE_ACTION,
1362 palette::WHALE_HUMAN,
1363 palette::STATUS_ERROR,
1364 palette::DIFF_ADDED,
1365 // Frame chrome sits below 4.5:1 by design and must survive.
1366 palette::BORDER_COLOR,
1367 ] {
1368 let symbol = if token == palette::BORDER_COLOR {
1369 "\u{2500}"
1370 } else {
1371 "x"
1372 };
1373 assert_eq!(
1374 cell_fg_after_adaptation(
1375 symbol,
1376 token,
1377 Color::Reset,
1378 PaletteMode::Dark,
1379 ThemeId::System,
1380 Some(surface),
1381 ),
1382 token,
1383 "{token:?} was rewritten on measured dark surface {surface:?}"
1384 );
1385 }
1386 }
1387 }
1388
1389 /// No measurement and no painted ground means the terminal's own ink is
1390 /// the only colour guaranteed to read on the ground it actually drew.
1391 #[test]
1392 fn unknown_background_gives_unpainted_body_text_the_terminal_ink() {
1393 assert_eq!(
1394 cell_fg_after_adaptation(
1395 "x",
1396 palette::TEXT_BODY,
1397 Color::Reset,
1398 PaletteMode::Dark,
1399 ThemeId::System,
1400 None,
1401 ),
1402 Color::Reset
1403 );
1404 }
1405
1406 /// Frame chrome keeps its intended weight even where the floor is active.
1407 #[test]
1408 fn contrast_floor_skips_frame_chrome_on_a_light_surface() {
1409 let white = Color::Rgb(0xFF, 0xFF, 0xFF);
1410 assert_eq!(
1411 cell_fg_after_adaptation(
1412 "\u{2502}",
1413 palette::LIGHT_BORDER,
1414 Color::Reset,
1415 PaletteMode::Light,
1416 ThemeId::WhaleLight,
1417 Some(white),
1418 ),
1419 palette::LIGHT_BORDER
1420 );
1421 }
1422
1423 /// Presets own their palette. A user who chose Matrix asked for its
1424 /// deliberately dim greens; the floor must not repaint them.
1425 #[test]
1426 fn explicit_presets_are_exempt_from_the_floor() {
1427 let matrix = ThemeId::Matrix.ui_theme();
1428 assert_eq!(
1429 cell_fg_after_adaptation(
1430 "x",
1431 matrix.text_muted,
1432 Color::Reset,
1433 PaletteMode::Dark,
1434 ThemeId::Matrix,
1435 Some(Color::Rgb(0x00, 0x00, 0x00)),
1436 ),
1437 matrix.text_muted
1438 );
1439 }
1440 }
1441
1441 lines RUST