返回 CodeWhale
ombre.rs
1 //! An opt-in atmosphere: one spatial ombre painted over a finished scene.
2 //!
3 //! A host paints its components through [`Theme`] as usual and then calls
4 //! [`Ombre::apply`] once, last, over the whole scene. That order is the whole
5 //! contract: every ground a component paints is already on the buffer, so
6 //! the pass repaints the cells whose background is one of the five structural
7 //! grounds (Sidebar, Background, Surface, Hover, Selected) and leaves glyphs,
8 //! every foreground, content and diff tints, action fills and any color the
9 //! tokens do not name exactly as they were painted.
10 //!
11 //! The wash is spatial, not a flat theme swatch: each cell is tinted toward
12 //! the blend of two token hues at its own position along the requested
13 //! [`Rect`], anchored to that rect even when only its visible intersection is
14 //! painted. The luminance the source ground was audited with is restored
15 //! afterwards ([`crate::color::tint_keeping_luminance`]), so every contrast
16 //! the tokens passed still holds. A nonblank cell is repainted only when the
17 //! result keeps its ink at `min(original contrast, the ink's audited floor)`;
18 //! blank cells carry the gradient without that proof, so the wash stays
19 //! continuous where nothing is written on it.
20 //!
21 //! | Palette | Runs between | Reads as |
22 //! |---|---|---|
23 //! | [`WaterPalette::Ocean`] | the logo ombre `#1E8FD8` → `#0B48BB` | deep water |
24 //! | [`WaterPalette::Lagoon`] | `Live` → `Primary` | the shallows |
25 //! | [`WaterPalette::Dusk`] | `Primary` → `Attention` | blue hour into a warm horizon |
26 //! | [`WaterPalette::Coral`] | `Danger` → `Attention` | a reef |
27 //! | [`WaterPalette::Graphite`] | the exact token grounds, no tint | graphite |
28 //!
29 //! In a light appearance the hues for Lagoon, Dusk and Coral are read from
30 //! the light token table, so paper gets pale washes of its own tokens; Ocean
31 //! keeps the logo pair, as a pale wash. Where a ground cannot hold a hue and
32 //! keep the luminance it was audited with (paper's pure white surface), it is
33 //! left exactly as the theme painted it.
34 //!
35 //! The pass runs at truecolor on a measured appearance only. At 256 colors,
36 //! 16 colors, `NO_COLOR`, ASCII-safe output and an unmeasured ground the
37 //! audited [`Theme`] is painted exactly as everywhere else.
38 //!
39 //! [`WaterPalette::Graphite`] does not tint: on a dark truecolor terminal it
40 //! remaps the five structural grounds to the graphite token grounds (the ones
41 //! the desktop app paints), so an Ocean-themed host can show real graphite.
42 //! On a light terminal it is pass-through, because paper already is the light
43 //! token table. A theme already at [`crate::Ground::Graphite`] is left alone.
44 //!
45 //! The palette is atmosphere, never state: no state word or mark is given a
46 //! new hue, and nothing here runs on a clock or animates by itself.
47
48 use std::time::Duration;
49
50 use ratatui::{
51 buffer::Buffer,
52 layout::Rect,
53 style::{Color, Modifier, Style},
54 };
55
56 use crate::{
57 MotionMode, Paint, Role, Theme,
58 color::{
59 ColorDepth, blend, mix_oklab, relative_luminance, rgb, tint_keeping_luminance,
60 tint_keeping_luminance_oklab,
61 },
62 detect::Appearance,
63 theme::{Ground, LOGO_BOTTOM, LOGO_TOP},
64 };
65
66 /// The five structural grounds this pass may repaint, in elevation order.
67 const GROUNDS: [Role; 5] = [
68 Role::Sidebar,
69 Role::Background,
70 Role::Surface,
71 Role::Hover,
72 Role::Selected,
73 ];
74
75 /// The dark wash: the audited strength [`crate::theme::OCEAN_TINT`] uses.
76 const OMBRE_TINT: f64 = 0.5;
77
78 /// Paper washes, strongest first. The pass takes the strongest one whose
79 /// result keeps the source ground's luminance; `0.0` means "leave it alone".
80 const PAPER_TINTS: [f64; 3] = [0.16, 0.10, 0.06];
81
82 /// How far a wash may move a ground's WCAG luminance: one 8-bit channel step
83 /// near the middle of the range. A wash that cannot stay inside this is not
84 /// offered for that ground.
85 const LUMINANCE_ROUNDING: f32 = 0.005;
86
87 /// Floating-point comparison tolerance; channel rounding never permits a
88 /// wash to cross an audited contrast floor.
89 const CONTRAST_ROUNDING: f32 = 1e-5;
90
91 /// The body-text floor the tokens audit (`generate.py`).
92 const TEXT_FLOOR: f32 = 4.5;
93
94 /// The control-edge floor the tokens audit.
95 const CONTROL_FLOOR: f32 = 3.0;
96
97 /// Samples across the ramp used to prove a wash strength before it is used.
98 const STRENGTH_SAMPLES: u32 = 32;
99
100 /// The five atmospheres a scene can be finished with.
101 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
102 pub enum WaterPalette {
103 /// The logo ombre: `#1E8FD8` into `#0B48BB`.
104 Ocean,
105 /// The shallows: `Live` into `Primary`.
106 Lagoon,
107 /// Blue hour: `Primary` into `Attention`.
108 Dusk,
109 /// A reef: `Danger` into `Attention`.
110 Coral,
111 /// The exact token grounds, no tint.
112 Graphite,
113 }
114
115 impl WaterPalette {
116 /// Every palette, in the order the gallery shows them.
117 pub const ALL: [WaterPalette; 5] = [
118 WaterPalette::Ocean,
119 WaterPalette::Lagoon,
120 WaterPalette::Dusk,
121 WaterPalette::Coral,
122 WaterPalette::Graphite,
123 ];
124
125 /// The palette's name, as a label reads it.
126 #[must_use]
127 pub const fn name(self) -> &'static str {
128 match self {
129 WaterPalette::Ocean => "Ocean",
130 WaterPalette::Lagoon => "Lagoon",
131 WaterPalette::Dusk => "Dusk",
132 WaterPalette::Coral => "Coral",
133 WaterPalette::Graphite => "Graphite",
134 }
135 }
136
137 /// The two hues this ombre runs between, read from the theme's own token
138 /// table so paper gets light-token washes. `None` for graphite, which
139 /// maps grounds instead of tinting them.
140 fn stops(self, theme: &Theme) -> Option<(u32, u32)> {
141 Some(match self {
142 WaterPalette::Graphite => return None,
143 // The logo pair is the brand ombre in both appearances.
144 WaterPalette::Ocean => (LOGO_TOP, LOGO_BOTTOM),
145 WaterPalette::Lagoon => (theme.token_hex(Role::Live), theme.token_hex(Role::Accent)),
146 WaterPalette::Dusk => (
147 theme.token_hex(Role::Accent),
148 theme.token_hex(Role::Attention),
149 ),
150 WaterPalette::Coral => (
151 theme.token_hex(Role::Danger),
152 theme.token_hex(Role::Attention),
153 ),
154 })
155 }
156 }
157
158 /// Which way the wash travels across the requested area.
159 #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
160 pub enum OmbreDirection {
161 /// Runs down the area: the same wash on every column.
162 Vertical,
163 /// Runs from the top-left corner to the bottom-right corner (the
164 /// default).
165 #[default]
166 Diagonal,
167 }
168
169 /// A finishing pass: one palette, one direction.
170 ///
171 /// ```no_run
172 /// use codewhale_ratatui::{Ombre, Theme, WaterPalette};
173 /// # fn draw(area: ratatui::layout::Rect, buf: &mut ratatui::buffer::Buffer) {
174 /// let theme = Theme::detect();
175 /// // ... the host paints its scene through `theme` first ...
176 /// Ombre::new(WaterPalette::Ocean).apply(area, buf, &theme);
177 /// # }
178 /// ```
179 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
180 pub struct Ombre {
181 pub palette: WaterPalette,
182 pub direction: OmbreDirection,
183 perceptual: bool,
184 }
185
186 impl Ombre {
187 /// The palette at its default [`OmbreDirection::Diagonal`].
188 #[must_use]
189 pub const fn new(palette: WaterPalette) -> Self {
190 Self {
191 palette,
192 direction: OmbreDirection::Diagonal,
193 perceptual: false,
194 }
195 }
196
197 /// Choose the direction the wash travels.
198 #[must_use]
199 pub const fn direction(mut self, direction: OmbreDirection) -> Self {
200 self.direction = direction;
201 self
202 }
203
204 /// Interpolate palette stops and washes in perceptual OKLab while keeping
205 /// each ground's audited WCAG luminance and contrast floors.
206 #[must_use]
207 pub const fn perceptual(mut self, enabled: bool) -> Self {
208 self.perceptual = enabled;
209 self
210 }
211
212 /// Repaint the recognized structural grounds in the buffer.
213 ///
214 /// Call this last, after the scene has been painted through `theme`.
215 /// `area` is the area the gradient is anchored to: callers that clip a
216 /// larger scene still pass the full rect, and the visible part keeps the
217 /// colors it would have had at full size. Areas that do not intersect the
218 /// buffer, zero-sized areas and `u16::MAX` extents are all safe.
219 pub fn apply(&self, area: Rect, buf: &mut Buffer, theme: &Theme) {
220 self.apply_at(area, buf, theme, Duration::ZERO, MotionMode::Still);
221 }
222
223 pub fn apply_at(
224 &self,
225 area: Rect,
226 buf: &mut Buffer,
227 theme: &Theme,
228 elapsed: Duration,
229 motion: MotionMode,
230 ) {
231 // Only truecolor on a measured appearance has audited grounds to
232 // move; every other profile keeps the theme exactly as it is.
233 if theme.depth() != ColorDepth::TrueColor || !theme.caps().paints_tokens() {
234 return;
235 }
236 let visible = area.intersection(*buf.area());
237 if visible.is_empty() {
238 return;
239 }
240 match self.palette {
241 // Paper is already the light token table.
242 WaterPalette::Graphite if matches!(theme.caps().appearance, Appearance::Light) => {}
243 WaterPalette::Graphite if theme.ground_kind() == Ground::Graphite => {}
244 WaterPalette::Graphite => remap_graphite(area, visible, buf, theme),
245 _ => {
246 let drift = if motion.animates() {
247 let seconds = (elapsed.as_secs() % 24) as f64
248 + f64::from(elapsed.subsec_nanos()) / 1_000_000_000.;
249 (seconds * std::f64::consts::TAU / 24.).sin() as f32 * 0.16
250 } else {
251 0.
252 };
253 self.wash(area, visible, buf, theme, drift);
254 }
255 }
256 }
257
258 /// Tint each structural ground toward the palette hue at its own ramp
259 /// position.
260 fn wash(&self, requested: Rect, visible: Rect, buf: &mut Buffer, theme: &Theme, drift: f32) {
261 let Some((start, end)) = self.palette.stops(theme) else {
262 return;
263 };
264 let light = matches!(theme.caps().appearance, Appearance::Light);
265 let mut present = [false; GROUNDS.len()];
266 for y in visible.top()..visible.bottom() {
267 for x in visible.left()..visible.right() {
268 if let Some(ground) = ground_index(buf[(x, y)].bg, theme) {
269 present[ground] = true;
270 }
271 }
272 }
273 let mut sources = [0_u32; GROUNDS.len()];
274 let mut grounds = [0.0_f32; GROUNDS.len()];
275 let mut strengths = [0.0_f64; GROUNDS.len()];
276 for (ground, on) in present.iter().enumerate() {
277 if !*on {
278 continue;
279 }
280 sources[ground] = theme.token_hex(GROUNDS[ground]);
281 grounds[ground] = relative_luminance(rgb(sources[ground])).unwrap_or(0.0);
282 strengths[ground] = wash_strength(sources[ground], start, end, light, self.perceptual);
283 }
284 let (base, rows) = ramp_rows(visible, requested, self.direction);
285 let den = ramp_den(requested, self.direction);
286 let mut table: Vec<[Option<Wash>; GROUNDS.len()]> = vec![[None; GROUNDS.len()]; rows];
287 for (ground, on) in present.iter().enumerate() {
288 if !*on || strengths[ground] == 0.0 {
289 continue;
290 }
291 for (row, washes) in table.iter_mut().enumerate() {
292 let sample = base + row as u32;
293 let t = if den == 0 {
294 0.0
295 } else {
296 sample.min(den) as f32 / den as f32
297 };
298 let t = if drift == 0. || t == 0. || t == 1. {
299 t
300 } else {
301 (t + drift * (std::f32::consts::PI * t).sin()).clamp(0., 1.)
302 };
303 let blended = if self.perceptual {
304 mix_oklab(rgb(start), rgb(end), t)
305 } else {
306 blend(rgb(end), rgb(start), t)
307 };
308 let Some(hue) = hex_of(blended) else {
309 continue;
310 };
311 let tinted = if self.perceptual {
312 tint_keeping_luminance_oklab(sources[ground], hue, strengths[ground])
313 } else {
314 tint_keeping_luminance(sources[ground], hue, strengths[ground])
315 };
316 washes[ground] = Wash::of(tinted);
317 }
318 }
319 repaint(
320 visible,
321 requested,
322 self.direction,
323 buf,
324 theme,
325 &Washes {
326 base,
327 rows: table,
328 grounds,
329 },
330 );
331 }
332 }
333
334 impl Paint for Ombre {
335 fn paint(&self, area: Rect, buf: &mut Buffer, theme: &Theme) {
336 self.apply(area, buf, theme);
337 }
338 }
339
340 /// Map the five structural grounds to the graphite token grounds, keeping
341 /// any cell whose ink would not survive the move.
342 fn remap_graphite(requested: Rect, visible: Rect, buf: &mut Buffer, theme: &Theme) {
343 let graphite = theme.ground(Ground::Graphite);
344 let mut entries: [Option<Wash>; GROUNDS.len()] = [None; GROUNDS.len()];
345 let mut grounds = [0.0_f32; GROUNDS.len()];
346 for (index, role) in GROUNDS.iter().enumerate() {
347 entries[index] = graphite.color(*role).and_then(hex_of).and_then(Wash::of);
348 grounds[index] = relative_luminance(rgb(theme.token_hex(*role))).unwrap_or(0.0);
349 }
350 let (base, rows) = ramp_rows(visible, requested, OmbreDirection::Vertical);
351 repaint(
352 visible,
353 requested,
354 OmbreDirection::Vertical,
355 buf,
356 theme,
357 &Washes {
358 base,
359 rows: vec![entries; rows],
360 grounds,
361 },
362 );
363 }
364
365 /// One repainted ground color and the luminance it carries.
366 #[derive(Clone, Copy)]
367 struct Wash {
368 hex: u32,
369 luminance: f32,
370 }
371
372 impl Wash {
373 fn of(hex: u32) -> Option<Self> {
374 Some(Self {
375 hex,
376 luminance: relative_luminance(rgb(hex))?,
377 })
378 }
379 }
380
381 /// The washes for one scene: one row per ramp sample, one entry per ground.
382 struct Washes {
383 /// The ramp sample row `0` stands for.
384 base: u32,
385 rows: Vec<[Option<Wash>; GROUNDS.len()]>,
386 /// The luminance each source ground was audited with.
387 grounds: [f32; GROUNDS.len()],
388 }
389
390 impl Washes {
391 /// The wash row for a cell inside `requested`.
392 fn at(&self, x: u16, y: u16, area: Rect, direction: OmbreDirection) -> Option<&[Option<Wash>]> {
393 let sample = ramp_offset(x, y, area, direction).checked_sub(self.base)?;
394 self.rows
395 .get(usize::try_from(sample).ok()?)
396 .map(|row| row.as_slice())
397 }
398 }
399
400 /// Repaint every visible cell of a recognized ground, keeping any cell whose
401 /// ink the wash would make unreadable.
402 fn repaint(
403 visible: Rect,
404 requested: Rect,
405 direction: OmbreDirection,
406 buf: &mut Buffer,
407 theme: &Theme,
408 washes: &Washes,
409 ) {
410 let mut ink = Ink::default();
411 for y in visible.top()..visible.bottom() {
412 for x in visible.left()..visible.right() {
413 let Some(ground) = ground_index(buf[(x, y)].bg, theme) else {
414 continue;
415 };
416 let Some(row) = washes.at(x, y, requested, direction) else {
417 continue;
418 };
419 let Some(wash) = row.get(ground).copied().flatten() else {
420 continue;
421 };
422 let cell = &buf[(x, y)];
423 // Reversed cells display the foreground as their background.
424 // Preserve that caller-authored selection instead of proving
425 // contrast against the wrong side of the swap.
426 if cell.modifier.contains(Modifier::REVERSED) {
427 continue;
428 }
429 if !cell.symbol().trim().is_empty()
430 && !ink.allows(theme, cell.fg, washes.grounds[ground], wash.luminance)
431 {
432 continue;
433 }
434 buf[(x, y)].set_style(Style::default().bg(rgb(wash.hex)));
435 }
436 }
437 }
438
439 /// The last ink examined: paintings come in runs, so one slot is enough and
440 /// the per-cell work stays a comparison.
441 #[derive(Default)]
442 struct Ink {
443 color: Option<Color>,
444 luminance: Option<f32>,
445 floor: f32,
446 }
447
448 impl Ink {
449 /// Whether replacing `old` with `new` keeps this ink at
450 /// `min(original contrast, the ink's floor)`, within rounding.
451 fn allows(&mut self, theme: &Theme, ink: Color, old: f32, new: f32) -> bool {
452 if self.color != Some(ink) {
453 self.color = Some(ink);
454 self.luminance = relative_luminance(ink);
455 self.floor = ink_floor(theme, ink);
456 }
457 // Ink the terminal owns (`Reset`, indices 0..=15, `None`) cannot be
458 // measured; its cell keeps the screen it already had.
459 let Some(luminance) = self.luminance else {
460 return false;
461 };
462 ratio(luminance, new) + CONTRAST_ROUNDING >= ratio(luminance, old).min(self.floor)
463 }
464 }
465
466 /// The floor an ink was audited against: body text, or a control edge for
467 /// the roles the tokens hold to 3:1. Ink the tokens do not name is held to
468 /// body text, the strictest default.
469 fn ink_floor(theme: &Theme, ink: Color) -> f32 {
470 let roles = theme.roles_of(ink, false);
471 if roles.is_empty() {
472 return TEXT_FLOOR;
473 }
474 roles
475 .iter()
476 .copied()
477 .map(|role| match role {
478 Role::Dim | Role::Border | Role::BorderStrong => CONTROL_FLOOR,
479 _ => TEXT_FLOOR,
480 })
481 .fold(0.0_f32, f32::max)
482 }
483
484 /// WCAG contrast from two relative luminances, as
485 /// [`crate::color::contrast_ratio`] computes it from colors; the pass already
486 /// holds both, so no channel math repeats per cell.
487 fn ratio(a: f32, b: f32) -> f32 {
488 let (hi, lo) = if a >= b { (a, b) } else { (b, a) };
489 (hi + 0.05) / (lo + 0.05)
490 }
491
492 /// The strongest wash `source` can take toward the `start` → `end` hues while
493 /// keeping the luminance it was audited with. `0.0` means the ground cannot
494 /// hold a hue at all and is left exactly as painted.
495 fn wash_strength(source: u32, start: u32, end: u32, light: bool, perceptual: bool) -> f64 {
496 let Some(want) = relative_luminance(rgb(source)) else {
497 return 0.0;
498 };
499 let ladder: &[f64] = if light { &PAPER_TINTS } else { &[OMBRE_TINT] };
500 for amount in ladder {
501 let keeps = (0..=STRENGTH_SAMPLES).all(|i| {
502 let t = i as f32 / STRENGTH_SAMPLES as f32;
503 let blended = if perceptual {
504 mix_oklab(rgb(start), rgb(end), t)
505 } else {
506 blend(rgb(end), rgb(start), t)
507 };
508 let Some(hue) = hex_of(blended) else {
509 return false;
510 };
511 let tinted = if perceptual {
512 tint_keeping_luminance_oklab(source, hue, *amount)
513 } else {
514 tint_keeping_luminance(source, hue, *amount)
515 };
516 relative_luminance(rgb(tinted))
517 .is_some_and(|have| (have - want).abs() <= LUMINANCE_ROUNDING)
518 });
519 if keeps {
520 return *amount;
521 }
522 }
523 0.0
524 }
525
526 /// The ramp rows the visible intersection needs, and the sample its first
527 /// row stands for. Anchored to `requested`, so clipping never re-scales the
528 /// gradient.
529 fn ramp_rows(visible: Rect, requested: Rect, direction: OmbreDirection) -> (u32, usize) {
530 let first = ramp_offset(visible.x, visible.y, requested, direction);
531 let last_x = u32::from(visible.x) + u32::from(visible.width).saturating_sub(1);
532 let last_y = u32::from(visible.y) + u32::from(visible.height).saturating_sub(1);
533 let last = ramp_offset_value(last_x, last_y, requested, direction);
534 (first, usize::try_from(last - first).unwrap_or(0) + 1)
535 }
536
537 /// How far along the requested area's ramp a coordinate is.
538 fn ramp_offset(x: u16, y: u16, area: Rect, direction: OmbreDirection) -> u32 {
539 ramp_offset_value(u32::from(x), u32::from(y), area, direction)
540 }
541
542 /// [`ramp_offset`] for coordinates that may exceed `u16` during the
543 /// arithmetic (the last cell of a clipped intersection).
544 fn ramp_offset_value(x: u32, y: u32, area: Rect, direction: OmbreDirection) -> u32 {
545 let dx = x.saturating_sub(u32::from(area.x));
546 let dy = y.saturating_sub(u32::from(area.y));
547 match direction {
548 OmbreDirection::Vertical => dy,
549 OmbreDirection::Diagonal => dx + dy,
550 }
551 }
552
553 /// The largest ramp sample the requested area spans; `0` when it cannot vary.
554 fn ramp_den(area: Rect, direction: OmbreDirection) -> u32 {
555 match direction {
556 OmbreDirection::Vertical => u32::from(area.height.saturating_sub(1)),
557 OmbreDirection::Diagonal => {
558 u32::from(area.width.saturating_sub(1)) + u32::from(area.height.saturating_sub(1))
559 }
560 }
561 }
562
563 /// Which structural ground a background is, exactly as the theme resolves
564 /// it. `Reset`, content tints, action fills and custom colors match nothing.
565 fn ground_index(bg: Color, theme: &Theme) -> Option<usize> {
566 GROUNDS
567 .iter()
568 .position(|role| theme.color(*role) == Some(bg))
569 }
570
571 /// `0xRRGGBB` for an RGB color; `None` for anything the terminal owns.
572 fn hex_of(color: Color) -> Option<u32> {
573 match color {
574 Color::Rgb(r, g, b) => Some(u32::from(r) << 16 | u32::from(g) << 8 | u32::from(b)),
575 _ => None,
576 }
577 }
578
578 lines RUST