| 1 | //! Color depth, quantization and contrast. |
| 2 | //! |
| 3 | //! Extracted from the Codewhale engine's `crates/palette` (`adapt.rs` and |
| 4 | //! `contrast.rs` at `Hmbown/CodeWhale` `58b1dd3dd`; depth detection last |
| 5 | //! changed in `c6416b203`, "Honor NO_COLOR with colorless terminal output"). |
| 6 | //! The engine's legacy-constant remapping is not carried over: components |
| 7 | //! here name roles, and [`crate::theme::Theme`] resolves a role for the |
| 8 | //! terminal's depth when it paints. |
| 9 | |
| 10 | use ratatui::{ |
| 11 | buffer::Buffer, |
| 12 | layout::Rect, |
| 13 | style::{Color, Modifier, Style}, |
| 14 | }; |
| 15 | |
| 16 | use crate::theme::{Role, Theme}; |
| 17 | |
| 18 | /// How many colors the terminal can show. |
| 19 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] |
| 20 | pub enum ColorDepth { |
| 21 | /// `NO_COLOR` is set: the terminal owns foreground and background. Bold, |
| 22 | /// dim, underline and every glyph still render. |
| 23 | Monochrome, |
| 24 | /// 16 named colors, remapped by the user's terminal profile. |
| 25 | Ansi16, |
| 26 | /// The fixed xterm 256-color cube and gray ramp. |
| 27 | Ansi256, |
| 28 | /// 24-bit color. |
| 29 | TrueColor, |
| 30 | } |
| 31 | |
| 32 | impl ColorDepth { |
| 33 | /// Detect the active terminal's depth from the environment. |
| 34 | #[must_use] |
| 35 | pub fn detect() -> Self { |
| 36 | Self::detect_with(|key| std::env::var_os(key)) |
| 37 | } |
| 38 | |
| 39 | /// Decide depth from an injected environment reader, so every branch is |
| 40 | /// testable without touching the process environment. |
| 41 | /// |
| 42 | /// Order: `NO_COLOR` (present and non-empty, per no-color.org) wins, then |
| 43 | /// `COLORTERM`, Windows Terminal, known truecolor `TERM_PROGRAM`s, and |
| 44 | /// finally `TERM`. An unknown `TERM` gets 256 colors, not 24-bit: older |
| 45 | /// remote terminals render truecolor backgrounds as bright blocks. |
| 46 | #[must_use] |
| 47 | pub fn detect_with(get: impl Fn(&str) -> Option<std::ffi::OsString>) -> Self { |
| 48 | if let Some(no_color) = get("NO_COLOR") |
| 49 | && !no_color.is_empty() |
| 50 | { |
| 51 | return Self::Monochrome; |
| 52 | } |
| 53 | if let Some(ct) = get("COLORTERM") { |
| 54 | let ct = ct.to_string_lossy().to_ascii_lowercase(); |
| 55 | if ct.contains("truecolor") || ct.contains("24bit") { |
| 56 | return Self::TrueColor; |
| 57 | } |
| 58 | } |
| 59 | if get("WT_SESSION").is_some() { |
| 60 | return Self::TrueColor; |
| 61 | } |
| 62 | if let Some(term_program) = get("TERM_PROGRAM") { |
| 63 | let term_program = term_program.to_string_lossy().to_ascii_lowercase(); |
| 64 | if ["iterm", "wezterm", "vscode", "warp"] |
| 65 | .iter() |
| 66 | .any(|name| term_program.contains(name)) |
| 67 | { |
| 68 | return Self::TrueColor; |
| 69 | } |
| 70 | } |
| 71 | let term = get("TERM") |
| 72 | .map(|t| t.to_string_lossy().to_ascii_lowercase()) |
| 73 | .unwrap_or_default(); |
| 74 | if term.contains("truecolor") || term.contains("24bit") { |
| 75 | Self::TrueColor |
| 76 | } else if term.contains("256") { |
| 77 | Self::Ansi256 |
| 78 | } else if term.is_empty() || term == "dumb" { |
| 79 | Self::Ansi16 |
| 80 | } else { |
| 81 | Self::Ansi256 |
| 82 | } |
| 83 | } |
| 84 | } |
| 85 | |
| 86 | /// A 24-bit color from a `0xRRGGBB` token value. |
| 87 | #[must_use] |
| 88 | pub const fn rgb(hex: u32) -> Color { |
| 89 | Color::Rgb((hex >> 16) as u8, (hex >> 8) as u8, hex as u8) |
| 90 | } |
| 91 | |
| 92 | /// `ink` lifted out of `water` by `amount`, when both are RGB. `None` means |
| 93 | /// the pair has no meaningful blend and the caller keeps its role colour. |
| 94 | #[must_use] |
| 95 | pub fn glow_over(ink: Color, water: Color, amount: f32) -> Option<Color> { |
| 96 | matches!((ink, water), (Color::Rgb(..), Color::Rgb(..))).then(|| blend(ink, water, amount)) |
| 97 | } |
| 98 | |
| 99 | /// Mix two RGB colors at `alpha` (0.0 = `bg`, 1.0 = `fg`). A non-RGB input |
| 100 | /// returns `fg`: a named color has no meaningful blend. |
| 101 | #[must_use] |
| 102 | pub fn blend(fg: Color, bg: Color, alpha: f32) -> Color { |
| 103 | let alpha = alpha.clamp(0.0, 1.0); |
| 104 | match (fg, bg) { |
| 105 | (Color::Rgb(fr, fg_, fb), Color::Rgb(br, bg_, bb)) => { |
| 106 | let mix = |a: u8, b: u8| -> u8 { |
| 107 | let a = f32::from(a); |
| 108 | let b = f32::from(b); |
| 109 | (b + (a - b) * alpha).round().clamp(0.0, 255.0) as u8 |
| 110 | }; |
| 111 | Color::Rgb(mix(fr, br), mix(fg_, bg_), mix(fb, bb)) |
| 112 | } |
| 113 | _ => fg, |
| 114 | } |
| 115 | } |
| 116 | |
| 117 | /// Map an RGB triple to the nearest xterm 256-color index. Uses only the |
| 118 | /// stable 6x6x6 cube and gray ramp (16..=255), never the user-remapped 0..=15. |
| 119 | #[must_use] |
| 120 | pub fn rgb_to_ansi256(r: u8, g: u8, b: u8) -> u8 { |
| 121 | const CUBE_LEVELS: [u8; 6] = [0, 95, 135, 175, 215, 255]; |
| 122 | |
| 123 | fn nearest_cube_level(channel: u8) -> usize { |
| 124 | CUBE_LEVELS |
| 125 | .iter() |
| 126 | .enumerate() |
| 127 | .min_by_key(|(_, level)| channel.abs_diff(**level)) |
| 128 | .map_or(0, |(idx, _)| idx) |
| 129 | } |
| 130 | |
| 131 | fn dist_sq(a: (u8, u8, u8), b: (u8, u8, u8)) -> u32 { |
| 132 | let dr = i32::from(a.0) - i32::from(b.0); |
| 133 | let dg = i32::from(a.1) - i32::from(b.1); |
| 134 | let db = i32::from(a.2) - i32::from(b.2); |
| 135 | (dr * dr + dg * dg + db * db) as u32 |
| 136 | } |
| 137 | |
| 138 | let ri = nearest_cube_level(r); |
| 139 | let gi = nearest_cube_level(g); |
| 140 | let bi = nearest_cube_level(b); |
| 141 | let cube_rgb = (CUBE_LEVELS[ri], CUBE_LEVELS[gi], CUBE_LEVELS[bi]); |
| 142 | let cube_index = 16 + (36 * ri) as u8 + (6 * gi) as u8 + bi as u8; |
| 143 | |
| 144 | let avg = ((u16::from(r) + u16::from(g) + u16::from(b)) / 3) as u8; |
| 145 | let gray_i = if avg <= 8 { |
| 146 | 0 |
| 147 | } else if avg >= 238 { |
| 148 | 23 |
| 149 | } else { |
| 150 | ((u16::from(avg) - 8 + 5) / 10).min(23) as u8 |
| 151 | }; |
| 152 | let gray = 8 + 10 * gray_i; |
| 153 | let gray_index = 232 + gray_i; |
| 154 | |
| 155 | if dist_sq((r, g, b), (gray, gray, gray)) < dist_sq((r, g, b), cube_rgb) { |
| 156 | gray_index |
| 157 | } else { |
| 158 | cube_index |
| 159 | } |
| 160 | } |
| 161 | |
| 162 | /// The RGB an xterm 256-color index renders as. Only 16..=255 are fixed by |
| 163 | /// the specification; 0..=15 belong to the user's profile. |
| 164 | #[must_use] |
| 165 | pub fn indexed_rgb(index: u8) -> Option<(u8, u8, u8)> { |
| 166 | const CUBE_LEVELS: [u8; 6] = [0, 95, 135, 175, 215, 255]; |
| 167 | match index { |
| 168 | 0..=15 => None, |
| 169 | 16..=231 => { |
| 170 | let i = index - 16; |
| 171 | Some(( |
| 172 | CUBE_LEVELS[usize::from(i / 36)], |
| 173 | CUBE_LEVELS[usize::from((i / 6) % 6)], |
| 174 | CUBE_LEVELS[usize::from(i % 6)], |
| 175 | )) |
| 176 | } |
| 177 | 232..=255 => { |
| 178 | let v = 8 + 10 * (index - 232); |
| 179 | Some((v, v, v)) |
| 180 | } |
| 181 | } |
| 182 | } |
| 183 | |
| 184 | #[must_use] |
| 185 | pub(crate) const fn is_truecolor(color: Color) -> bool { |
| 186 | matches!(color, Color::Rgb(..)) |
| 187 | } |
| 188 | |
| 189 | /// The RGB a color is *known* to render as, or `None` when the terminal owns |
| 190 | /// the decision (`Reset`, named colors, indices 0..=15). |
| 191 | #[must_use] |
| 192 | pub fn resolvable_rgb(color: Color) -> Option<(u8, u8, u8)> { |
| 193 | match color { |
| 194 | Color::Rgb(r, g, b) => Some((r, g, b)), |
| 195 | Color::Indexed(index) => indexed_rgb(index), |
| 196 | _ => None, |
| 197 | } |
| 198 | } |
| 199 | |
| 200 | /// WCAG 2.x relative luminance in `0.0..=1.0`, or `None` for a color whose |
| 201 | /// RGB the terminal decides. |
| 202 | #[must_use] |
| 203 | pub fn relative_luminance(color: Color) -> Option<f32> { |
| 204 | let (r, g, b) = resolvable_rgb(color)?; |
| 205 | fn channel(value: u8) -> f32 { |
| 206 | let c = f32::from(value) / 255.0; |
| 207 | if c <= 0.039_28 { |
| 208 | c / 12.92 |
| 209 | } else { |
| 210 | ((c + 0.055) / 1.055).powf(2.4) |
| 211 | } |
| 212 | } |
| 213 | Some(0.2126 * channel(r) + 0.7152 * channel(g) + 0.0722 * channel(b)) |
| 214 | } |
| 215 | |
| 216 | /// WCAG contrast ratio in `1.0..=21.0`, or `None` if either side is |
| 217 | /// terminal-defined. |
| 218 | #[must_use] |
| 219 | pub fn contrast_ratio(fg: Color, bg: Color) -> Option<f32> { |
| 220 | let a = relative_luminance(fg)?; |
| 221 | let b = relative_luminance(bg)?; |
| 222 | let (hi, lo) = if a >= b { (a, b) } else { (b, a) }; |
| 223 | Some((hi + 0.05) / (lo + 0.05)) |
| 224 | } |
| 225 | |
| 226 | pub(crate) fn prepared_ink( |
| 227 | pigment: [u8; 3], |
| 228 | alpha: f32, |
| 229 | background: Color, |
| 230 | theme: &Theme, |
| 231 | ) -> Style { |
| 232 | if !theme.paints_grounds() { |
| 233 | return theme.fg(Role::Accent); |
| 234 | } |
| 235 | let ground = resolvable_rgb(background) |
| 236 | .map(|(r, g, b)| Color::Rgb(r, g, b)) |
| 237 | .unwrap_or_else(|| theme.token(Role::Background)); |
| 238 | let base = blend( |
| 239 | Color::Rgb(pigment[0], pigment[1], pigment[2]), |
| 240 | ground, |
| 241 | alpha, |
| 242 | ); |
| 243 | let quantize = |color| match (theme.depth(), color) { |
| 244 | (ColorDepth::Ansi256, Color::Rgb(r, g, b)) => Color::Indexed(rgb_to_ansi256(r, g, b)), |
| 245 | (_, color) => color, |
| 246 | }; |
| 247 | let mut result = quantize(base); |
| 248 | for step in 1..=8 { |
| 249 | if contrast_ratio(result, ground).is_none_or(|ratio| ratio >= 3.0) { |
| 250 | break; |
| 251 | } |
| 252 | result = quantize(blend(theme.token(Role::Accent), base, step as f32 / 8.0)); |
| 253 | } |
| 254 | Style::default().fg(result) |
| 255 | } |
| 256 | |
| 257 | /// `hex` moved `amount` of the way toward `toward`, then rescaled so its |
| 258 | /// WCAG relative luminance stays `hex`'s. Contrast depends only on |
| 259 | /// luminance, so every contrast pair audited for `hex` holds for the result |
| 260 | /// (within rounding, which the audits check). Colors are `0xRRGGBB`. |
| 261 | #[must_use] |
| 262 | pub fn tint_keeping_luminance(hex: u32, toward: u32, amount: f64) -> u32 { |
| 263 | fn split(v: u32) -> [f64; 3] { |
| 264 | [(v >> 16) & 0xff, (v >> 8) & 0xff, v & 0xff].map(|c| f64::from(c) / 255.0) |
| 265 | } |
| 266 | fn lin(c: f64) -> f64 { |
| 267 | if c <= 0.039_28 { |
| 268 | c / 12.92 |
| 269 | } else { |
| 270 | ((c + 0.055) / 1.055).powf(2.4) |
| 271 | } |
| 272 | } |
| 273 | fn unlin(v: f64) -> u32 { |
| 274 | let v = v.clamp(0.0, 1.0); |
| 275 | let s = if v <= 0.003_130_8 { |
| 276 | v * 12.92 |
| 277 | } else { |
| 278 | 1.055 * v.powf(1.0 / 2.4) - 0.055 |
| 279 | }; |
| 280 | (s * 255.0).round().clamp(0.0, 255.0) as u32 |
| 281 | } |
| 282 | let lum = |c: [f64; 3]| 0.2126 * c[0] + 0.7152 * c[1] + 0.0722 * c[2]; |
| 283 | let amount = amount.clamp(0.0, 1.0); |
| 284 | let from = split(hex); |
| 285 | let to = split(toward); |
| 286 | let mixed: [f64; 3] = std::array::from_fn(|i| { |
| 287 | let a = (from[i] * 255.0).round(); |
| 288 | let b = (to[i] * 255.0).round(); |
| 289 | lin((a + (b - a) * amount).round() / 255.0) |
| 290 | }); |
| 291 | let want = lum(from.map(lin)); |
| 292 | let have = lum(mixed); |
| 293 | let k = if have > 0.0 { want / have } else { 1.0 }; |
| 294 | let [r, g, b] = mixed.map(|c| unlin(c * k)); |
| 295 | (r << 16) | (g << 8) | b |
| 296 | } |
| 297 | |
| 298 | fn srgb_to_linear(value: u8) -> f32 { |
| 299 | let c = f32::from(value) / 255.0; |
| 300 | if c <= 0.040_45 { |
| 301 | c / 12.92 |
| 302 | } else { |
| 303 | ((c + 0.055) / 1.055).powf(2.4) |
| 304 | } |
| 305 | } |
| 306 | |
| 307 | fn linear_to_srgb(value: f32) -> u8 { |
| 308 | let v = value.clamp(0.0, 1.0); |
| 309 | let s = if v <= 0.003_130_8 { |
| 310 | v * 12.92 |
| 311 | } else { |
| 312 | 1.055 * v.powf(1.0 / 2.4) - 0.055 |
| 313 | }; |
| 314 | (s * 255.0).round().clamp(0.0, 255.0) as u8 |
| 315 | } |
| 316 | |
| 317 | fn rgb_to_oklab(r: u8, g: u8, b: u8) -> (f32, f32, f32) { |
| 318 | let r = srgb_to_linear(r); |
| 319 | let g = srgb_to_linear(g); |
| 320 | let b = srgb_to_linear(b); |
| 321 | let l = (0.412_221_47 * r + 0.536_332_55 * g + 0.051_445_993 * b).cbrt(); |
| 322 | let m = (0.211_903_5 * r + 0.680_699_5 * g + 0.107_396_96 * b).cbrt(); |
| 323 | let s = (0.088_302_46 * r + 0.281_718_85 * g + 0.629_978_7 * b).cbrt(); |
| 324 | ( |
| 325 | 0.210_454_26 * l + 0.793_617_8 * m - 0.004_072_047 * s, |
| 326 | 1.977_998_5 * l - 2.428_592_2 * m + 0.450_593_7 * s, |
| 327 | 0.025_904_037 * l + 0.782_771_77 * m - 0.808_675_77 * s, |
| 328 | ) |
| 329 | } |
| 330 | |
| 331 | fn oklab_to_rgb(l_in: f32, a_in: f32, b_in: f32) -> (u8, u8, u8) { |
| 332 | let l_ = l_in + 0.396_337_78 * a_in + 0.215_803_76 * b_in; |
| 333 | let m_ = l_in - 0.105_561_346 * a_in - 0.063_854_17 * b_in; |
| 334 | let s_ = l_in - 0.089_484_18 * a_in - 1.291_485_5 * b_in; |
| 335 | let l = l_ * l_ * l_; |
| 336 | let m = m_ * m_ * m_; |
| 337 | let s = s_ * s_ * s_; |
| 338 | let r = 4.076_741_7 * l - 3.307_711_6 * m + 0.230_969_94 * s; |
| 339 | let g = -1.268_438 * l + 2.609_757_4 * m - 0.341_319_38 * s; |
| 340 | let b = -0.004_196_086_3 * l - 0.703_418_6 * m + 1.707_614_7 * s; |
| 341 | (linear_to_srgb(r), linear_to_srgb(g), linear_to_srgb(b)) |
| 342 | } |
| 343 | |
| 344 | /// Perceptually uniform OKLab interpolation between `from` (`t = 0.0`) and |
| 345 | /// `to` (`t = 1.0`). |
| 346 | /// |
| 347 | /// Endpoints return the exact input color without rounding drift. When either |
| 348 | /// side is non-RGB, falls back to the nearer input. |
| 349 | #[must_use] |
| 350 | pub fn mix_oklab(from: Color, to: Color, t: f32) -> Color { |
| 351 | let t = if t.is_nan() { 0.0 } else { t.clamp(0.0, 1.0) }; |
| 352 | if t <= 0.0 { |
| 353 | return from; |
| 354 | } |
| 355 | if t >= 1.0 { |
| 356 | return to; |
| 357 | } |
| 358 | match (from, to) { |
| 359 | (Color::Rgb(r0, g0, b0), Color::Rgb(r1, g1, b1)) => { |
| 360 | let (l0, a0, b0_) = rgb_to_oklab(r0, g0, b0); |
| 361 | let (l1, a1, b1_) = rgb_to_oklab(r1, g1, b1); |
| 362 | let (r, g, b) = oklab_to_rgb( |
| 363 | l0 + (l1 - l0) * t, |
| 364 | a0 + (a1 - a0) * t, |
| 365 | b0_ + (b1_ - b0_) * t, |
| 366 | ); |
| 367 | Color::Rgb(r, g, b) |
| 368 | } |
| 369 | _ if t >= 0.5 => to, |
| 370 | _ => from, |
| 371 | } |
| 372 | } |
| 373 | |
| 374 | /// Sample a multi-stop perceptual OKLab color ramp at `t` in `0.0..=1.0`. |
| 375 | /// |
| 376 | /// Returns [`Color::Reset`] for an empty slice and `stops[0]` for a single |
| 377 | /// stop. |
| 378 | #[must_use] |
| 379 | pub fn oklab_ramp(stops: &[Color], t: f32) -> Color { |
| 380 | match stops { |
| 381 | [] => Color::Reset, |
| 382 | [only] => *only, |
| 383 | _ => { |
| 384 | let t = if t.is_nan() { 0.0 } else { t.clamp(0.0, 1.0) }; |
| 385 | if t <= 0.0 { |
| 386 | return stops[0]; |
| 387 | } |
| 388 | if t >= 1.0 { |
| 389 | return stops[stops.len() - 1]; |
| 390 | } |
| 391 | let scaled = t * (stops.len() - 1) as f32; |
| 392 | let idx = (scaled.floor() as usize).min(stops.len() - 2); |
| 393 | let local = scaled - idx as f32; |
| 394 | mix_oklab(stops[idx], stops[idx + 1], local) |
| 395 | } |
| 396 | } |
| 397 | } |
| 398 | |
| 399 | /// Optical specular highlight lift in OKLab. |
| 400 | /// |
| 401 | /// Moves `base` toward `light` while giving perceptual lightness a crisp |
| 402 | /// specular boost so edges and active frontiers stay luminous instead of |
| 403 | /// washing out. Non-RGB inputs return `base`. |
| 404 | #[must_use] |
| 405 | pub fn specular_lift(base: Color, light: Color, amount: f32) -> Color { |
| 406 | let amount = if amount.is_nan() { |
| 407 | 0.0 |
| 408 | } else { |
| 409 | amount.clamp(0.0, 1.0) |
| 410 | }; |
| 411 | if amount <= 0.0 { |
| 412 | return base; |
| 413 | } |
| 414 | match (base, light) { |
| 415 | (Color::Rgb(r0, g0, b0), Color::Rgb(r1, g1, b1)) => { |
| 416 | let (l0, a0, b0_) = rgb_to_oklab(r0, g0, b0); |
| 417 | let (l1, a1, b1_) = rgb_to_oklab(r1, g1, b1); |
| 418 | let target_l = l1.max((l0 + 0.14).min(0.98)); |
| 419 | let l = (l0 + (target_l - l0) * amount).clamp(0.0, 1.0); |
| 420 | let chroma_t = (amount * 0.85).clamp(0.0, 1.0); |
| 421 | let a = a0 + (a1 - a0) * chroma_t; |
| 422 | let b = b0_ + (b1_ - b0_) * chroma_t; |
| 423 | let (r, g, b) = oklab_to_rgb(l, a, b); |
| 424 | Color::Rgb(r, g, b) |
| 425 | } |
| 426 | _ => base, |
| 427 | } |
| 428 | } |
| 429 | |
| 430 | /// Optical depth shadow in OKLab. |
| 431 | /// |
| 432 | /// Reduces perceptual lightness by `amount` (`0.0..=1.0`) while preserving |
| 433 | /// hue angle and gently compressing chroma near deep shadow so cast shadows |
| 434 | /// remain jewel-toned rather than muddy gray. Non-RGB inputs return `base`. |
| 435 | #[must_use] |
| 436 | pub fn depth_shade(base: Color, amount: f32) -> Color { |
| 437 | let amount = if amount.is_nan() { |
| 438 | 0.0 |
| 439 | } else { |
| 440 | amount.clamp(0.0, 1.0) |
| 441 | }; |
| 442 | if amount <= 0.0 { |
| 443 | return base; |
| 444 | } |
| 445 | match base { |
| 446 | Color::Rgb(r0, g0, b0) => { |
| 447 | let (l0, a0, b0_) = rgb_to_oklab(r0, g0, b0); |
| 448 | let l = (l0 * (1.0 - amount * 0.62)).clamp(0.0, 1.0); |
| 449 | let chroma_keep = 1.0 - amount * 0.25; |
| 450 | let (r, g, b) = oklab_to_rgb(l, a0 * chroma_keep, b0_ * chroma_keep); |
| 451 | Color::Rgb(r, g, b) |
| 452 | } |
| 453 | _ => base, |
| 454 | } |
| 455 | } |
| 456 | |
| 457 | /// Darken a truecolor underlying cell ground for translucent drop-shadow |
| 458 | /// compositing; returns `None` when `under` is not RGB so terminal-owned |
| 459 | /// grounds remain untouched. |
| 460 | #[must_use] |
| 461 | pub fn shadow_blend(under: Color, strength: f32) -> Option<Color> { |
| 462 | is_truecolor(under).then(|| depth_shade(under, strength)) |
| 463 | } |
| 464 | |
| 465 | /// Contrast-guarded OKLab blend from `from` toward `to` against `ground`. |
| 466 | /// |
| 467 | /// Keeps the WCAG contrast ratio against `ground` at or above |
| 468 | /// `min(original_contrast, floor)` by easing `amount` down if needed. |
| 469 | #[must_use] |
| 470 | pub fn contrast_safe_oklab_mix( |
| 471 | from: Color, |
| 472 | to: Color, |
| 473 | ground: Color, |
| 474 | amount: f32, |
| 475 | floor: f32, |
| 476 | ) -> Color { |
| 477 | let amount = if amount.is_nan() { |
| 478 | 0.0 |
| 479 | } else { |
| 480 | amount.clamp(0.0, 1.0) |
| 481 | }; |
| 482 | if amount <= 0.0 || !is_truecolor(from) || !is_truecolor(to) { |
| 483 | return from; |
| 484 | } |
| 485 | let Some(before) = contrast_ratio(from, ground) else { |
| 486 | return from; |
| 487 | }; |
| 488 | let required = before.min(floor); |
| 489 | let mut step_amount = amount; |
| 490 | for _ in 0..10 { |
| 491 | let candidate = mix_oklab(from, to, step_amount); |
| 492 | if contrast_ratio(candidate, ground).is_some_and(|after| after + 1e-4 >= required) { |
| 493 | return candidate; |
| 494 | } |
| 495 | step_amount *= 0.6; |
| 496 | } |
| 497 | from |
| 498 | } |
| 499 | |
| 500 | /// `hex` moved `amount` of the way toward `toward` in perceptual OKLab, then |
| 501 | /// rescaled so its WCAG relative luminance stays `hex`'s. |
| 502 | #[must_use] |
| 503 | pub fn tint_keeping_luminance_oklab(hex: u32, toward: u32, amount: f64) -> u32 { |
| 504 | let amount = amount.clamp(0.0, 1.0); |
| 505 | let Color::Rgb(mr, mg, mb) = mix_oklab(rgb(hex), rgb(toward), amount as f32) else { |
| 506 | return hex; |
| 507 | }; |
| 508 | let mixed_hex = (u32::from(mr) << 16) | (u32::from(mg) << 8) | u32::from(mb); |
| 509 | tint_keeping_luminance(hex, mixed_hex, 1.0) |
| 510 | } |
| 511 | |
| 512 | /// Compute a contrast-guarded OKLab tonal chip `(chip_bg, chip_fg)` for |
| 513 | /// micro-beveled truecolor pills, returning `None` for non-RGB inputs. |
| 514 | #[must_use] |
| 515 | pub fn bevel_chip_colors( |
| 516 | accent: Color, |
| 517 | surface: Color, |
| 518 | fg_fallback: Color, |
| 519 | light_appearance: bool, |
| 520 | ) -> Option<(Color, Color)> { |
| 521 | if !is_truecolor(accent) || !is_truecolor(surface) { |
| 522 | return None; |
| 523 | } |
| 524 | let bg_mix = if light_appearance { 0.14 } else { 0.22 }; |
| 525 | let chip_bg = mix_oklab(surface, accent, bg_mix); |
| 526 | let mut chip_fg = if light_appearance { |
| 527 | depth_shade(accent, 0.22) |
| 528 | } else { |
| 529 | specular_lift(accent, fg_fallback, 0.28) |
| 530 | }; |
| 531 | if contrast_ratio(chip_fg, chip_bg).is_none_or(|ratio| ratio < 4.5) { |
| 532 | chip_fg = contrast_safe_oklab_mix(fg_fallback, accent, chip_bg, 0.35, 4.5); |
| 533 | } |
| 534 | if contrast_ratio(chip_fg, chip_bg).is_none_or(|ratio| ratio < 4.5) { |
| 535 | chip_fg = fg_fallback; |
| 536 | } |
| 537 | Some((chip_bg, chip_fg)) |
| 538 | } |
| 539 | |
| 540 | fn is_box_border_symbol(symbol: &str) -> bool { |
| 541 | matches!( |
| 542 | symbol, |
| 543 | "╭" | "╮" | "╰" | "╯" | "─" | "│" | "┌" | "┐" | "└" | "┘" | "+" | "-" | "|" |
| 544 | ) |
| 545 | } |
| 546 | |
| 547 | /// Apply an overhead specular rim gradient to an already-painted box border. |
| 548 | /// |
| 549 | /// Modulates only box-drawing border cells along the perimeter of `area`, |
| 550 | /// leaving titles, metadata spans and interior content untouched. Cleanly |
| 551 | /// no-ops when `border` or `highlight` is not truecolor RGB. |
| 552 | pub fn paint_sculpted_border_colors( |
| 553 | area: Rect, |
| 554 | buf: &mut Buffer, |
| 555 | border: Color, |
| 556 | highlight: Color, |
| 557 | bg: Color, |
| 558 | _ascii: bool, |
| 559 | ) { |
| 560 | let clipped = area.intersection(buf.area); |
| 561 | if clipped.width < 3 || clipped.height < 3 || !is_truecolor(border) || !is_truecolor(highlight) |
| 562 | { |
| 563 | return; |
| 564 | } |
| 565 | let light_ground = relative_luminance(bg).is_some_and(|lum| lum >= 0.5); |
| 566 | let max_x = area.width.saturating_sub(1).max(1); |
| 567 | let max_y = area.height.saturating_sub(1).max(1); |
| 568 | |
| 569 | let top_y = area.y; |
| 570 | if top_y >= clipped.top() && top_y < clipped.bottom() { |
| 571 | for x in clipped.left()..clipped.right() { |
| 572 | let cell = &mut buf[(x, top_y)]; |
| 573 | if cell.modifier.contains(Modifier::REVERSED) || !is_box_border_symbol(cell.symbol()) { |
| 574 | continue; |
| 575 | } |
| 576 | let u = f32::from(x.saturating_sub(area.x)) / f32::from(max_x); |
| 577 | let dist = ((u - 0.38).abs() / 0.62).clamp(0.0, 1.0); |
| 578 | let wave = 0.5 * (1.0 + (std::f32::consts::PI * dist).cos()); |
| 579 | let lift = 0.22 + 0.44 * wave * wave; |
| 580 | let rim = if light_ground { |
| 581 | mix_oklab(border, highlight, lift * 0.72) |
| 582 | } else { |
| 583 | specular_lift(border, highlight, lift) |
| 584 | }; |
| 585 | cell.set_fg(rim); |
| 586 | } |
| 587 | } |
| 588 | |
| 589 | for y in clipped.top().max(area.y.saturating_add(1)) |
| 590 | ..clipped.bottom().min(area.bottom().saturating_sub(1)) |
| 591 | { |
| 592 | let v = f32::from(y.saturating_sub(area.y)) / f32::from(max_y); |
| 593 | let side_color = if v < 0.48 { |
| 594 | let t = 1.0 - v / 0.48; |
| 595 | let lift = t * t * 0.28; |
| 596 | if light_ground { |
| 597 | mix_oklab(border, highlight, lift * 0.65) |
| 598 | } else { |
| 599 | specular_lift(border, highlight, lift) |
| 600 | } |
| 601 | } else if v > 0.72 { |
| 602 | let shade = ((v - 0.72) / 0.28) * 0.14; |
| 603 | if light_ground { |
| 604 | depth_shade(border, shade * 0.65) |
| 605 | } else { |
| 606 | depth_shade(border, shade) |
| 607 | } |
| 608 | } else { |
| 609 | border |
| 610 | }; |
| 611 | for x in [area.x, area.right().saturating_sub(1)] { |
| 612 | if x >= clipped.left() && x < clipped.right() { |
| 613 | let cell = &mut buf[(x, y)]; |
| 614 | if !cell.modifier.contains(Modifier::REVERSED) |
| 615 | && is_box_border_symbol(cell.symbol()) |
| 616 | { |
| 617 | cell.set_fg(side_color); |
| 618 | } |
| 619 | } |
| 620 | } |
| 621 | } |
| 622 | |
| 623 | let bottom_y = area.bottom().saturating_sub(1); |
| 624 | if bottom_y > top_y && bottom_y >= clipped.top() && bottom_y < clipped.bottom() { |
| 625 | let bottom_color = depth_shade(border, if light_ground { 0.08 } else { 0.16 }); |
| 626 | for x in clipped.left()..clipped.right() { |
| 627 | let cell = &mut buf[(x, bottom_y)]; |
| 628 | if !cell.modifier.contains(Modifier::REVERSED) && is_box_border_symbol(cell.symbol()) { |
| 629 | cell.set_fg(bottom_color); |
| 630 | } |
| 631 | } |
| 632 | } |
| 633 | } |
| 634 | |
| 635 | /// Cast a soft, translucent, buffer-blended drop shadow around `popup_area` |
| 636 | /// within `bounds`. |
| 637 | /// |
| 638 | /// Reads each underlying cell's actual RGB background from `buf` and shades it |
| 639 | /// in OKLab, using half-block glyphs (`▄`/`▀`) on blank cells for half-cell |
| 640 | /// vertical offset and feathering into a two-column outer penumbra. Cleanly |
| 641 | /// no-ops on non-truecolor profiles, narrow bounds, reversed cells, or |
| 642 | /// terminal-owned (`Reset` / named) backgrounds. |
| 643 | pub fn paint_translucent_shadow( |
| 644 | popup_area: Rect, |
| 645 | bounds: Rect, |
| 646 | buf: &mut Buffer, |
| 647 | depth: ColorDepth, |
| 648 | ascii: bool, |
| 649 | ) { |
| 650 | if depth != ColorDepth::TrueColor { |
| 651 | return; |
| 652 | } |
| 653 | let bounds = bounds.intersection(buf.area); |
| 654 | if bounds.width < 20 || bounds.height < 8 || popup_area.width < 4 || popup_area.height < 3 { |
| 655 | return; |
| 656 | } |
| 657 | |
| 658 | let darken_cell = |buf: &mut Buffer, x: u16, y: u16, bg_strength: f32, fg_strength: f32| { |
| 659 | if !bounds.contains((x, y).into()) { |
| 660 | return; |
| 661 | } |
| 662 | let cell = &mut buf[(x, y)]; |
| 663 | if cell.modifier.contains(Modifier::REVERSED) { |
| 664 | return; |
| 665 | } |
| 666 | let Some(shaded_bg) = shadow_blend(cell.bg, bg_strength) else { |
| 667 | return; |
| 668 | }; |
| 669 | cell.set_bg(shaded_bg); |
| 670 | if is_truecolor(cell.fg) { |
| 671 | cell.set_fg(depth_shade(cell.fg, fg_strength)); |
| 672 | } |
| 673 | }; |
| 674 | |
| 675 | let half_block_shadow = |buf: &mut Buffer, x: u16, y: u16, glyph: &str, strength: f32| { |
| 676 | if !bounds.contains((x, y).into()) { |
| 677 | return; |
| 678 | } |
| 679 | let cell = &mut buf[(x, y)]; |
| 680 | if cell.modifier.contains(Modifier::REVERSED) { |
| 681 | return; |
| 682 | } |
| 683 | let Some(shaded) = shadow_blend(cell.bg, strength) else { |
| 684 | return; |
| 685 | }; |
| 686 | let is_blank = cell.symbol() == " " || cell.symbol().is_empty(); |
| 687 | if !ascii && is_blank { |
| 688 | cell.set_symbol(glyph).set_fg(shaded); |
| 689 | } else { |
| 690 | cell.set_bg(shaded); |
| 691 | if is_truecolor(cell.fg) { |
| 692 | cell.set_fg(depth_shade(cell.fg, strength * 0.85)); |
| 693 | } |
| 694 | } |
| 695 | }; |
| 696 | |
| 697 | let right_x = popup_area.right(); |
| 698 | if right_x < bounds.right() { |
| 699 | half_block_shadow(buf, right_x, popup_area.y, "▄", 0.44); |
| 700 | for y in popup_area.y.saturating_add(1)..popup_area.bottom() { |
| 701 | darken_cell(buf, right_x, y, 0.48, 0.40); |
| 702 | } |
| 703 | } |
| 704 | |
| 705 | let penumbra_x = right_x.saturating_add(1); |
| 706 | if penumbra_x < bounds.right() { |
| 707 | half_block_shadow(buf, penumbra_x, popup_area.y, "▄", 0.18); |
| 708 | for y in popup_area.y.saturating_add(1)..popup_area.bottom() { |
| 709 | darken_cell(buf, penumbra_x, y, 0.20, 0.18); |
| 710 | } |
| 711 | } |
| 712 | |
| 713 | let bottom_y = popup_area.bottom(); |
| 714 | if bottom_y < bounds.bottom() { |
| 715 | for x in popup_area.x.saturating_add(1)..popup_area.right() { |
| 716 | half_block_shadow(buf, x, bottom_y, "▀", 0.48); |
| 717 | } |
| 718 | if right_x < bounds.right() { |
| 719 | half_block_shadow(buf, right_x, bottom_y, "▀", 0.36); |
| 720 | } |
| 721 | if penumbra_x < bounds.right() { |
| 722 | half_block_shadow(buf, penumbra_x, bottom_y, "▀", 0.16); |
| 723 | } |
| 724 | } |
| 725 | } |
| 726 | |
| 727 | #[cfg(test)] |
| 728 | mod tests { |
| 729 | use super::*; |
| 730 | use std::collections::HashMap; |
| 731 | use std::ffi::OsString; |
| 732 | |
| 733 | fn env(pairs: &[(&str, &str)]) -> impl Fn(&str) -> Option<OsString> { |
| 734 | let map: HashMap<String, OsString> = pairs |
| 735 | .iter() |
| 736 | .map(|(k, v)| ((*k).to_string(), OsString::from(*v))) |
| 737 | .collect(); |
| 738 | move |key| map.get(key).cloned() |
| 739 | } |
| 740 | |
| 741 | #[test] |
| 742 | fn no_color_wins_over_every_other_signal() { |
| 743 | let get = env(&[("NO_COLOR", "1"), ("COLORTERM", "truecolor")]); |
| 744 | assert_eq!(ColorDepth::detect_with(get), ColorDepth::Monochrome); |
| 745 | // An empty NO_COLOR is not a request (no-color.org). |
| 746 | let get = env(&[("NO_COLOR", ""), ("COLORTERM", "truecolor")]); |
| 747 | assert_eq!(ColorDepth::detect_with(get), ColorDepth::TrueColor); |
| 748 | } |
| 749 | |
| 750 | #[test] |
| 751 | fn term_fallbacks_are_conservative() { |
| 752 | assert_eq!( |
| 753 | ColorDepth::detect_with(env(&[("TERM", "xterm-256color")])), |
| 754 | ColorDepth::Ansi256 |
| 755 | ); |
| 756 | assert_eq!(ColorDepth::detect_with(env(&[])), ColorDepth::Ansi16); |
| 757 | assert_eq!( |
| 758 | ColorDepth::detect_with(env(&[("TERM", "dumb")])), |
| 759 | ColorDepth::Ansi16 |
| 760 | ); |
| 761 | assert_eq!( |
| 762 | ColorDepth::detect_with(env(&[("TERM", "screen")])), |
| 763 | ColorDepth::Ansi256 |
| 764 | ); |
| 765 | assert_eq!( |
| 766 | ColorDepth::detect_with(env(&[("TERM_PROGRAM", "WezTerm")])), |
| 767 | ColorDepth::TrueColor |
| 768 | ); |
| 769 | } |
| 770 | |
| 771 | #[test] |
| 772 | fn ansi256_round_trips_through_the_fixed_cube() { |
| 773 | for index in 16..=255u8 { |
| 774 | let (r, g, b) = indexed_rgb(index).unwrap(); |
| 775 | let back = rgb_to_ansi256(r, g, b); |
| 776 | assert_eq!(indexed_rgb(back), Some((r, g, b)), "index {index}"); |
| 777 | } |
| 778 | assert_eq!(indexed_rgb(7), None); |
| 779 | } |
| 780 | |
| 781 | #[test] |
| 782 | fn contrast_matches_wcag_extremes() { |
| 783 | let ratio = contrast_ratio(rgb(0xffffff), rgb(0x000000)).unwrap(); |
| 784 | assert!((ratio - 21.0).abs() < 0.01); |
| 785 | assert_eq!(contrast_ratio(Color::Reset, rgb(0)), None); |
| 786 | } |
| 787 | } |
| 788 |