返回 CodeWhale
focus_texture.rs
根目录 / crates / tui / src / tui / focus_texture.rs
1 //! Focus-context texture prototype (#4823).
2 //!
3 //! When a modal view is open, the area *outside* the focused modal can get a
4 //! subtle treatment so the focused region stands out:
5 //!
6 //! - `scrim` dims the already-rendered background toward the theme surface;
7 //! - `grain` sprinkles sparse deterministic dots over blank cells.
8 //!
9 //! Scope and guarantees, by construction:
10 //!
11 //! - **Prototype, bounded to modal contexts.** The only consumer is
12 //! `ViewStack::render`, which passes the top view's `occupied_region` as the
13 //! focus rect. Nothing else in the shell opts in.
14 //! - **Default off.** `FocusTextureMode::Off` (the default) returns zeroed
15 //! stats and leaves the buffer untouched, so the render path stays
16 //! byte-identical to the pre-prototype path.
17 //! - **Static, not animated.** The grain pattern is a pure function of cell
18 //! coordinates with no time component, so it is motion-off-safe: the
19 //! `low_motion` / `MotionPolicy::allows_decorative` path needs no special
20 //! handling here, and two applications over the same buffer produce
21 //! identical output.
22 //! - **Explicit fallbacks.** Off is the fallback for unknown setting values;
23 //! cells whose background is `Color::Reset` (transparent terminals) are
24 //! skipped under Scrim — the terminal owns that background; the grain dot
25 //! falls back to `.` when ASCII-safe mode is on.
26 //! - **The focus rect is never painted** — the caller applies the texture
27 //! before painting the backdrop and views, so the focused modal is drawn
28 //! afterward at full strength and the texture can never overwrite it.
29 //! - **Text is never obscured.** Grain only writes blank/whitespace cells and
30 //! never touches a cell that carries a symbol. Scrim preserves the
31 //! WCAG AA body-text floor (4.5:1) whenever both colors are resolvable:
32 //! after blending, the foreground is lifted with
33 //! `palette::enforce_contrast` against the *new* background. Colors the
34 //! terminal owns (`Reset`, named ANSI) are left alone rather than guessed.
35 //!
36 //! Near-fullscreen focus regions (covering at least
37 //! `FOCUS_COVERAGE_NOOP_PERCENT`% of the frame) and frames smaller than
38 //! [`FOCUS_TEXTURE_MIN_WIDTH`]x[`FOCUS_TEXTURE_MIN_HEIGHT`] refuse the
39 //! treatment entirely: there is no meaningful outside left to texture.
40
41 use ratatui::{buffer::Buffer, layout::Rect, style::Color};
42
43 use codewhale_palette::{self as palette, AA_BODY_CONTRAST, UiTheme};
44
45 /// Minimum frame size that earns the texture. Below this, content and
46 /// controls own every cell. Mirrors the ambient-life floors.
47 pub const FOCUS_TEXTURE_MIN_WIDTH: u16 = crate::tui::ocean::AMBIENT_MIN_WIDTH;
48 pub const FOCUS_TEXTURE_MIN_HEIGHT: u16 = crate::tui::ocean::AMBIENT_MIN_HEIGHT;
49
50 /// Focus regions covering at least this share of the frame's cells leave no
51 /// meaningful outside to texture, so the pass is a no-op.
52 const FOCUS_COVERAGE_NOOP_PERCENT: u64 = 90;
53
54 /// Scrim background blend toward the theme surface.
55 const SCRIM_BG_BLEND: f32 = 0.5;
56 /// Scrim foreground blend toward the theme surface, before the contrast
57 /// floor lifts the result back to legibility.
58 const SCRIM_FG_BLEND: f32 = 0.25;
59
60 /// Grain dot glyph. Deterministic placement (see [`grain_dot_at`]) keeps the
61 /// texture static; `glyphs::ascii_fallback` maps this to `.` in ASCII-safe
62 /// mode.
63 const GRAIN_DOT: &str = "·";
64
65 /// Focus-context texture mode for modal views (#4823 prototype).
66 ///
67 /// Parsed from the `focus_texture` setting at the consumption point; unknown
68 /// values fall back to `Off` and never panic.
69 #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
70 pub enum FocusTextureMode {
71 /// No treatment. The render path is byte-identical to the pre-prototype
72 /// path in this mode.
73 #[default]
74 Off,
75 /// Dim cells outside the focused modal toward the theme surface.
76 Scrim,
77 /// Sparse deterministic dots on blank cells outside the focused modal.
78 Grain,
79 }
80
81 impl FocusTextureMode {
82 /// Parse a setting value; `None` for anything unknown (callers map that
83 /// to `Off`). Case-insensitive, surrounding whitespace ignored.
84 #[must_use]
85 pub fn parse(value: &str) -> Option<Self> {
86 match value.trim().to_ascii_lowercase().as_str() {
87 "off" => Some(Self::Off),
88 "scrim" => Some(Self::Scrim),
89 "grain" => Some(Self::Grain),
90 _ => None,
91 }
92 }
93 }
94
95 /// Accounting for one [`apply_focus_texture`] pass.
96 ///
97 /// Identity: `cells_examined == cells_scrimmed + cells_dotted
98 /// + cells_skipped_focus + cells_skipped_transparent + cells_skipped_text`.
99 ///
100 /// Scrim examines every cell of the area. Grain examines focus cells, text
101 /// cells, and deterministic dot candidates; blank cells that earn no dot are
102 /// left untouched and unexamined, which keeps the identity exact without a
103 /// "blank but not dotted" bucket.
104 #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
105 pub struct FocusTextureStats {
106 pub cells_examined: u32,
107 pub cells_scrimmed: u32,
108 pub cells_dotted: u32,
109 pub cells_skipped_focus: u32,
110 pub cells_skipped_transparent: u32,
111 pub cells_skipped_text: u32,
112 }
113
114 impl FocusTextureStats {
115 /// The accounting identity asserted by the unit tests.
116 #[cfg(test)]
117 #[must_use]
118 pub fn accounted(&self) -> bool {
119 self.cells_examined
120 == self.cells_scrimmed
121 + self.cells_dotted
122 + self.cells_skipped_focus
123 + self.cells_skipped_transparent
124 + self.cells_skipped_text
125 }
126 }
127
128 /// `true` when `(x, y)` lies inside `rect`.
129 fn rect_contains(rect: Rect, x: u16, y: u16) -> bool {
130 x >= rect.left() && x < rect.right() && y >= rect.top() && y < rect.bottom()
131 }
132
133 /// Deterministic grain placement: a pure function of the cell coordinates,
134 /// so the texture is static (motion-off-safe) and reproducible.
135 fn grain_dot_at(x: u16, y: u16) -> bool {
136 x.wrapping_mul(7)
137 .wrapping_add(y.wrapping_mul(13))
138 .is_multiple_of(11)
139 }
140
141 /// Apply the focus-context texture to `area`, treating `focus` as the
142 /// focused modal's occupied region. See the module docs for the guarantees.
143 ///
144 /// Returns zeroed stats and leaves the buffer untouched when the mode is
145 /// `Off`, the frame is below the minimum size, or the focus rect (clamped to
146 /// the area) covers at least `FOCUS_COVERAGE_NOOP_PERCENT`% of the frame.
147 pub fn apply_focus_texture(
148 area: Rect,
149 buf: &mut Buffer,
150 focus: Rect,
151 theme: &UiTheme,
152 mode: FocusTextureMode,
153 ascii_safe: bool,
154 ) -> FocusTextureStats {
155 let mut stats = FocusTextureStats::default();
156 if mode == FocusTextureMode::Off {
157 return stats;
158 }
159 if area.width < FOCUS_TEXTURE_MIN_WIDTH || area.height < FOCUS_TEXTURE_MIN_HEIGHT {
160 return stats;
161 }
162 let focus = focus.intersection(area);
163 // u64: a full u16-square frame already fits u32, but the *100 coverage
164 // compare would not.
165 let area_cells = u64::from(area.width) * u64::from(area.height);
166 let focus_cells = u64::from(focus.width) * u64::from(focus.height);
167 if area_cells == 0 || focus_cells * 100 >= area_cells * FOCUS_COVERAGE_NOOP_PERCENT {
168 return stats;
169 }
170
171 for y in area.top()..area.bottom() {
172 for x in area.left()..area.right() {
173 if rect_contains(focus, x, y) {
174 stats.cells_examined += 1;
175 stats.cells_skipped_focus += 1;
176 continue;
177 }
178 match mode {
179 FocusTextureMode::Off => unreachable!("off returns early"),
180 FocusTextureMode::Scrim => {
181 stats.cells_examined += 1;
182 let cell = &buf[(x, y)];
183 // Transparent-terminal fallback: the terminal owns this
184 // background, so dimming it would be a guess. Skip.
185 if cell.bg == Color::Reset {
186 stats.cells_skipped_transparent += 1;
187 continue;
188 }
189 let new_bg =
190 crate::tui::ocean::mix_colors(cell.bg, theme.surface_bg, SCRIM_BG_BLEND);
191 let blended_fg =
192 crate::tui::ocean::mix_colors(cell.fg, theme.surface_bg, SCRIM_FG_BLEND);
193 // Text is never obscured by construction: when both
194 // colors are resolvable this lifts the foreground back to
195 // the AA body floor against the *new* background; when
196 // either side is terminal-owned the color is left alone.
197 let new_fg = palette::enforce_contrast(blended_fg, new_bg, AA_BODY_CONTRAST);
198 let cell = &mut buf[(x, y)];
199 cell.bg = new_bg;
200 cell.fg = new_fg;
201 stats.cells_scrimmed += 1;
202 }
203 FocusTextureMode::Grain => {
204 let cell = &buf[(x, y)];
205 // Never write over a cell that carries a symbol: grain is
206 // a background texture, not an ink.
207 if !cell.symbol().trim().is_empty() {
208 stats.cells_examined += 1;
209 stats.cells_skipped_text += 1;
210 continue;
211 }
212 // Blank cells that earn no dot are left untouched and
213 // unexamined (see the stats docs).
214 if !grain_dot_at(x, y) {
215 continue;
216 }
217 stats.cells_examined += 1;
218 let dot = if ascii_safe {
219 codewhale_tui_kit::glyphs::ascii_fallback(GRAIN_DOT).unwrap_or(".")
220 } else {
221 GRAIN_DOT
222 };
223 let cell = &mut buf[(x, y)];
224 cell.set_symbol(dot);
225 // Set the dim ink only when it is resolvable; a
226 // terminal-owned `text_dim` (the Terminal theme) stays
227 // as-is rather than being guessed.
228 if palette::resolvable_rgb(theme.text_dim).is_some() {
229 cell.set_fg(theme.text_dim);
230 }
231 stats.cells_dotted += 1;
232 }
233 }
234 }
235 }
236 stats
237 }
238
239 #[cfg(test)]
240 mod tests {
241 use super::*;
242 use ratatui::style::Style;
243
244 /// A fully resolvable (Rgb) theme for the texture's color math.
245 ///
246 /// Whale Flat deliberately leaves its shell surface terminal-owned, so it
247 /// is not a valid fixture for tests that exercise RGB scrim blending.
248 fn theme() -> UiTheme {
249 let theme = codewhale_palette::ThemeId::Dracula.ui_theme();
250 assert!(palette::resolvable_rgb(theme.surface_bg).is_some());
251 assert!(palette::resolvable_rgb(theme.text_dim).is_some());
252 theme
253 }
254
255 /// A 60x20 frame: large enough for the texture, small enough to eyeball.
256 fn test_area() -> Rect {
257 Rect::new(0, 0, 60, 20)
258 }
259
260 /// A focus rect well under the 90% coverage threshold (200 of 1200).
261 fn test_focus() -> Rect {
262 Rect::new(10, 5, 20, 10)
263 }
264
265 fn blank_buffer(area: Rect) -> Buffer {
266 Buffer::empty(area)
267 }
268
269 fn assert_accounted(stats: FocusTextureStats) {
270 assert!(stats.accounted(), "accounting identity broken: {stats:?}");
271 }
272
273 #[test]
274 fn mode_parse_covers_every_setting_value() {
275 for (value, mode) in [
276 ("off", FocusTextureMode::Off),
277 ("scrim", FocusTextureMode::Scrim),
278 ("grain", FocusTextureMode::Grain),
279 ] {
280 assert_eq!(FocusTextureMode::parse(value), Some(mode));
281 }
282 assert_eq!(
283 FocusTextureMode::parse(" SCRIM "),
284 Some(FocusTextureMode::Scrim)
285 );
286 assert_eq!(
287 FocusTextureMode::parse("Grain"),
288 Some(FocusTextureMode::Grain)
289 );
290 assert_eq!(FocusTextureMode::parse("static"), None);
291 assert_eq!(FocusTextureMode::parse(""), None);
292 assert_eq!(FocusTextureMode::default(), FocusTextureMode::Off);
293 }
294
295 #[test]
296 fn off_leaves_buffer_untouched() {
297 let area = test_area();
298 let mut buf = blank_buffer(area);
299 buf[(0, 0)].set_symbol("a").set_fg(Color::White);
300 buf[(1, 0)].set_bg(Color::Reset);
301 let original = buf.clone();
302
303 let stats = apply_focus_texture(
304 area,
305 &mut buf,
306 test_focus(),
307 &theme(),
308 FocusTextureMode::Off,
309 false,
310 );
311
312 assert_eq!(stats, FocusTextureStats::default());
313 assert_eq!(buf, original);
314 }
315
316 #[test]
317 fn near_fullscreen_focus_is_noop() {
318 let area = test_area();
319 // 59x20 = 1180 of 1200 cells (98%): over the 90% threshold.
320 for focus in [area, Rect::new(0, 0, 59, 20)] {
321 let mut buf = blank_buffer(area);
322 let original = buf.clone();
323 let stats = apply_focus_texture(
324 area,
325 &mut buf,
326 focus,
327 &theme(),
328 FocusTextureMode::Scrim,
329 false,
330 );
331 assert_eq!(stats, FocusTextureStats::default(), "focus {focus:?}");
332 assert_eq!(buf, original, "focus {focus:?}");
333 }
334 }
335
336 #[test]
337 fn small_area_is_noop() {
338 for area in [Rect::new(0, 0, 39, 20), Rect::new(0, 0, 60, 9)] {
339 let mut buf = blank_buffer(area);
340 let original = buf.clone();
341 let stats = apply_focus_texture(
342 area,
343 &mut buf,
344 Rect::new(0, 0, 4, 2),
345 &theme(),
346 FocusTextureMode::Grain,
347 false,
348 );
349 assert_eq!(stats, FocusTextureStats::default(), "area {area:?}");
350 assert_eq!(buf, original, "area {area:?}");
351 }
352 }
353
354 #[test]
355 fn scrim_preserves_focus_and_transparent_cells() {
356 let area = test_area();
357 let focus = test_focus();
358 let mut buf = blank_buffer(area);
359 let focus_style = Style::default().fg(Color::White).bg(Color::Blue);
360 let mut reset_cells = 0_u32;
361 for y in area.top()..area.bottom() {
362 for x in area.left()..area.right() {
363 if rect_contains(focus, x, y) {
364 buf[(x, y)].set_symbol("F").set_style(focus_style);
365 } else if (x + y) % 2 == 0 {
366 // Transparent-terminal cells outside the focus.
367 buf[(x, y)].set_bg(Color::Reset);
368 reset_cells += 1;
369 } else {
370 buf[(x, y)]
371 .set_symbol("t")
372 .set_fg(Color::Rgb(200, 200, 200))
373 .set_bg(Color::Rgb(40, 40, 40));
374 }
375 }
376 }
377 let original = buf.clone();
378
379 let stats = apply_focus_texture(
380 area,
381 &mut buf,
382 focus,
383 &theme(),
384 FocusTextureMode::Scrim,
385 false,
386 );
387
388 assert_accounted(stats);
389 assert_eq!(stats.cells_examined, 60 * 20);
390 assert_eq!(stats.cells_skipped_focus, 20 * 10);
391 assert_eq!(stats.cells_skipped_transparent, reset_cells);
392 assert_eq!(stats.cells_dotted, 0);
393 for y in area.top()..area.bottom() {
394 for x in area.left()..area.right() {
395 if rect_contains(focus, x, y) {
396 assert_eq!(
397 buf[(x, y)],
398 original[(x, y)],
399 "focus cell ({x},{y}) must stay byte-identical"
400 );
401 } else if (x + y) % 2 == 0 {
402 assert_eq!(
403 buf[(x, y)],
404 original[(x, y)],
405 "Reset-bg cell ({x},{y}) must stay untouched"
406 );
407 }
408 }
409 }
410 }
411
412 #[test]
413 fn scrim_text_keeps_aa_contrast_when_resolvable() {
414 let area = test_area();
415 let focus = test_focus();
416 let theme = theme();
417 let combos = [
418 (Color::Rgb(255, 255, 255), Color::Rgb(30, 30, 30)),
419 (Color::Rgb(200, 200, 200), Color::Rgb(240, 240, 240)),
420 (Color::Rgb(120, 120, 120), Color::Rgb(110, 110, 110)),
421 (Color::Rgb(40, 80, 200), Color::Rgb(20, 20, 30)),
422 ];
423 for (row, (fg, bg)) in combos.iter().enumerate() {
424 let mut buf = blank_buffer(area);
425 let y = row as u16;
426 let mut seeded = Vec::new();
427 for x in area.left()..area.right() {
428 if rect_contains(focus, x, y) {
429 continue;
430 }
431 buf[(x, y)].set_symbol("t").set_fg(*fg).set_bg(*bg);
432 seeded.push(x);
433 }
434
435 let stats = apply_focus_texture(
436 area,
437 &mut buf,
438 focus,
439 &theme,
440 FocusTextureMode::Scrim,
441 false,
442 );
443
444 assert_accounted(stats);
445 for x in seeded {
446 let cell = &buf[(x, y)];
447 assert_eq!(cell.symbol(), "t", "glyph must survive the scrim");
448 let ratio = palette::contrast_ratio(cell.fg, cell.bg)
449 .expect("seeded colors are Rgb and stay resolvable");
450 assert!(
451 ratio >= AA_BODY_CONTRAST,
452 "combo {fg:?}/{bg:?} ended at {ratio}:1, below the AA floor"
453 );
454 }
455 }
456 }
457
458 #[test]
459 fn grain_never_overwrites_text_and_dots_are_deterministic() {
460 let area = test_area();
461 let focus = test_focus();
462 let theme = theme();
463 let mut buf = blank_buffer(area);
464 let mut text_cells = Vec::new();
465 for y in area.top()..area.bottom() {
466 for x in area.left()..area.right() {
467 if !rect_contains(focus, x, y) && (x + y) % 3 == 0 {
468 buf[(x, y)].set_symbol("a").set_fg(Color::White);
469 text_cells.push((x, y));
470 }
471 }
472 }
473 let original = buf.clone();
474
475 let stats = apply_focus_texture(
476 area,
477 &mut buf,
478 focus,
479 &theme,
480 FocusTextureMode::Grain,
481 false,
482 );
483
484 assert_accounted(stats);
485 assert_eq!(stats.cells_skipped_focus, 20 * 10);
486 assert_eq!(stats.cells_skipped_text, text_cells.len() as u32);
487 assert_eq!(stats.cells_scrimmed, 0);
488 // Every seeded text cell is untouched, byte for byte.
489 for (x, y) in &text_cells {
490 assert_eq!(
491 buf[(*x, *y)],
492 original[(*x, *y)],
493 "text cell ({x},{y}) must never be overwritten"
494 );
495 }
496 // Dots land exactly at the deterministic positions on blank cells.
497 let mut expected_dots = 0_u32;
498 for y in area.top()..area.bottom() {
499 for x in area.left()..area.right() {
500 if rect_contains(focus, x, y) || (x + y) % 3 == 0 {
501 continue;
502 }
503 if grain_dot_at(x, y) {
504 expected_dots += 1;
505 assert_eq!(buf[(x, y)].symbol(), GRAIN_DOT, "dot at ({x},{y})");
506 assert_eq!(buf[(x, y)].fg, theme.text_dim);
507 } else {
508 assert_eq!(
509 buf[(x, y)],
510 original[(x, y)],
511 "non-dot blank cell ({x},{y}) must stay untouched"
512 );
513 }
514 }
515 }
516 assert_eq!(stats.cells_dotted, expected_dots);
517 }
518
519 #[test]
520 fn grain_ascii_safe_uses_plain_dot() {
521 let area = test_area();
522 let focus = test_focus();
523 let mut buf = blank_buffer(area);
524
525 let stats = apply_focus_texture(
526 area,
527 &mut buf,
528 focus,
529 &theme(),
530 FocusTextureMode::Grain,
531 true,
532 );
533
534 assert_accounted(stats);
535 assert!(stats.cells_dotted > 0);
536 for y in area.top()..area.bottom() {
537 for x in area.left()..area.right() {
538 if !rect_contains(focus, x, y) && grain_dot_at(x, y) {
539 assert_eq!(buf[(x, y)].symbol(), ".", "ascii dot at ({x},{y})");
540 }
541 }
542 }
543 }
544
545 #[test]
546 fn grain_is_deterministic_across_applications() {
547 let area = test_area();
548 let focus = test_focus();
549 let theme = theme();
550 let mut first = blank_buffer(area);
551 let mut second = blank_buffer(area);
552
553 apply_focus_texture(
554 area,
555 &mut first,
556 focus,
557 &theme,
558 FocusTextureMode::Grain,
559 false,
560 );
561 apply_focus_texture(
562 area,
563 &mut second,
564 focus,
565 &theme,
566 FocusTextureMode::Grain,
567 false,
568 );
569
570 // Static texture: no time component, so motion-off needs no special
571 // path and repeated passes over the same buffer agree exactly.
572 assert_eq!(first, second);
573 }
574 }
575
575 lines RUST