| 1 | //! Codewhale's terminal-native underwater column, as a finishing pass. |
| 2 | //! |
| 3 | //! Adapted from `Hmbown/CodeWhale`'s `crates/tui/src/tui/ocean.rs` at |
| 4 | //! `a79ce5c4d5ed1a5f7032185710c27343a900351c`: the authored three stops, |
| 5 | //! quadratic depth curve, context rise, 90-second phase breath, steady |
| 6 | //! attention/failure tint and 800-millisecond completion breath. The host |
| 7 | //! supplies time and phase; this module owns no clock, event loop or theme. |
| 8 | //! |
| 9 | //! Paint ordinary components first, then apply the column to their ordinary |
| 10 | //! `Background` and `Sidebar` cells. Raised surfaces, selections, diff/code |
| 11 | //! grounds, custom fills, symbols, inks and modifiers remain theirs. The |
| 12 | //! authored dark field remains exact on Ocean; other measured truecolor |
| 13 | //! themes draw depth and ambient light from their own grounds and accent. |
| 14 | //! Terminal-owned grounds, unknown appearances and lower depths stay unchanged. |
| 15 | //! Native chrome can join the same column with [`OceanColumn::apply_matching`] |
| 16 | //! over its own region and explicit base ground. Native cached-row painting, |
| 17 | //! semantic-surface projection and sparse caustics are adapted from the same |
| 18 | //! MIT-licensed Engine at `e7de150f3621740c982e7e6c90d69ac48ccc80d5`; |
| 19 | //! capability facts, palette adaptation, cache and redraw lifecycle stay host-owned. |
| 20 | |
| 21 | use std::time::Duration; |
| 22 | |
| 23 | use ratatui::{ |
| 24 | buffer::{Buffer, Cell}, |
| 25 | layout::{Alignment, Rect}, |
| 26 | style::{Color, Modifier}, |
| 27 | text::Line, |
| 28 | }; |
| 29 | |
| 30 | use unicode_segmentation::UnicodeSegmentation; |
| 31 | |
| 32 | use crate::{ |
| 33 | Ground, MotionMode, Paint, Role, Theme, |
| 34 | color::{ColorDepth, blend, contrast_ratio, mix_oklab, relative_luminance, rgb, specular_lift}, |
| 35 | detect::Appearance, |
| 36 | }; |
| 37 | |
| 38 | /// A caller-reported phase, matching the native terminal's `ShellPhase`. |
| 39 | /// It is visual input, never a state machine or evidence of work completing. |
| 40 | #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] |
| 41 | pub enum OceanPhase { |
| 42 | #[default] |
| 43 | Idle, |
| 44 | Typing, |
| 45 | Working, |
| 46 | Verifying, |
| 47 | Waiting, |
| 48 | Approval, |
| 49 | Done, |
| 50 | Failed, |
| 51 | } |
| 52 | |
| 53 | impl OceanPhase { |
| 54 | const fn needs_attention(self) -> bool { |
| 55 | matches!(self, Self::Waiting | Self::Approval | Self::Failed) |
| 56 | } |
| 57 | } |
| 58 | |
| 59 | /// A depth ramp in the active theme's own colors. Semantic tints come from [`Theme`]. |
| 60 | /// [`Self::for_theme`] resolves the guarded default; [`Self::new`] supplies |
| 61 | /// exact caller colors for pure math. Neither replaces a theme table. |
| 62 | #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] |
| 63 | pub struct OceanRamp { |
| 64 | surface: Color, |
| 65 | middle: Color, |
| 66 | deep: Color, |
| 67 | ambient: Color, |
| 68 | attention: Color, |
| 69 | failure: Color, |
| 70 | quiet: [Option<Color>; 2], |
| 71 | } |
| 72 | |
| 73 | impl OceanRamp { |
| 74 | /// The native sunlit stop, `#102a45`. |
| 75 | pub const SURFACE: Color = rgb(0x102a45); |
| 76 | /// The native middle control point, `#0a1e33`. |
| 77 | pub const MIDDLE: Color = rgb(0x0a1e33); |
| 78 | /// The native deep stop, `#061320`. |
| 79 | pub const DEEP: Color = rgb(0x061320); |
| 80 | /// The native ambient light, `#264866`. |
| 81 | pub const AMBIENT: Color = rgb(0x264866); |
| 82 | /// The authored completion pulse ends after 800 milliseconds. |
| 83 | pub const COMPLETION_BREATH: Duration = Duration::from_millis(800); |
| 84 | |
| 85 | /// An explicit caller-owned ramp. Pure sampling may use these exact |
| 86 | /// colors; guarded column painting still requires the normal theme and |
| 87 | /// capability gates and preserves its contrast policy. |
| 88 | #[must_use] |
| 89 | pub const fn new( |
| 90 | surface: Color, |
| 91 | middle: Color, |
| 92 | deep: Color, |
| 93 | ambient: Color, |
| 94 | attention: Color, |
| 95 | failure: Color, |
| 96 | ) -> Self { |
| 97 | Self { |
| 98 | surface, |
| 99 | middle, |
| 100 | deep, |
| 101 | ambient, |
| 102 | attention, |
| 103 | failure, |
| 104 | quiet: [None; 2], |
| 105 | } |
| 106 | } |
| 107 | |
| 108 | fn holding_quiet_inks(mut self, theme: &Theme) -> Self { |
| 109 | self.quiet = [theme.color(Role::Hint), theme.color(Role::Dim)]; |
| 110 | self |
| 111 | } |
| 112 | |
| 113 | fn warm(self, base: Color, toward: Color, amount: f32) -> Color { |
| 114 | let floors = [(self.quiet[0], 4.5), (self.quiet[1], 3.0)].map(|(ink, floor)| { |
| 115 | let ink = ink?; |
| 116 | Some((ink, contrast_ratio(ink, base)?.min(floor))) |
| 117 | }); |
| 118 | let mut amount = amount; |
| 119 | loop { |
| 120 | let tinted = mix_toward(base, toward, amount); |
| 121 | let holds = floors.iter().flatten().all(|(ink, floor)| { |
| 122 | contrast_ratio(*ink, tinted).is_some_and(|ratio| ratio + 1e-5 >= *floor) |
| 123 | }); |
| 124 | if holds || amount <= 0.0 { |
| 125 | return tinted; |
| 126 | } |
| 127 | amount = (amount - 0.005).max(0.0); |
| 128 | } |
| 129 | } |
| 130 | |
| 131 | /// Resolve a measured truecolor field from the theme's painted RGB grounds. |
| 132 | /// Native Ocean keeps its authored stops; terminal-owned bases stay unpainted. |
| 133 | #[must_use] |
| 134 | pub fn for_theme(theme: &Theme) -> Option<Self> { |
| 135 | if theme.depth() != ColorDepth::TrueColor |
| 136 | || !theme.caps().paints_tokens() |
| 137 | || !theme.paints_base_ground() |
| 138 | { |
| 139 | return None; |
| 140 | } |
| 141 | let background = theme.color(Role::Background)?; |
| 142 | if !matches!(background, Color::Rgb(..)) { |
| 143 | return None; |
| 144 | } |
| 145 | let attention = theme.color(Role::Attention)?; |
| 146 | let failure = theme.color(Role::Danger)?; |
| 147 | if theme.caps().appearance == Appearance::Dark |
| 148 | && theme.ground_kind() == Ground::Ocean |
| 149 | && theme |
| 150 | .native_palette() |
| 151 | .is_none_or(|palette| palette == crate::TuiPalette::Underwater) |
| 152 | { |
| 153 | return Some( |
| 154 | Self::new( |
| 155 | Self::SURFACE, |
| 156 | Self::MIDDLE, |
| 157 | Self::DEEP, |
| 158 | Self::AMBIENT, |
| 159 | attention, |
| 160 | failure, |
| 161 | ) |
| 162 | .holding_quiet_inks(theme), |
| 163 | ); |
| 164 | } |
| 165 | let mut brightest = background; |
| 166 | let mut darkest = background; |
| 167 | let mut high = relative_luminance(background)?; |
| 168 | let mut low = high; |
| 169 | for role in [Role::Surface, Role::Hover, Role::Sidebar] { |
| 170 | let color = theme.color(role)?; |
| 171 | if !matches!(color, Color::Rgb(..)) { |
| 172 | return None; |
| 173 | } |
| 174 | let luminance = relative_luminance(color)?; |
| 175 | if luminance > high { |
| 176 | brightest = color; |
| 177 | high = luminance; |
| 178 | } |
| 179 | if luminance < low { |
| 180 | darkest = color; |
| 181 | low = luminance; |
| 182 | } |
| 183 | } |
| 184 | let light = theme.caps().appearance == Appearance::Light; |
| 185 | let surface = mix_toward(background, brightest, if light { 0.45 } else { 0.35 }); |
| 186 | Some( |
| 187 | Self::new( |
| 188 | surface, |
| 189 | background, |
| 190 | mix_toward(background, darkest, if light { 0.45 } else { 0.65 }), |
| 191 | mix_toward(surface, theme.color(Role::Accent)?, 0.20), |
| 192 | attention, |
| 193 | failure, |
| 194 | ) |
| 195 | .holding_quiet_inks(theme), |
| 196 | ) |
| 197 | } |
| 198 | |
| 199 | /// The native quadratic surface → middle → deep curve. Explicit context |
| 200 | /// fullness (0–100) raises the abyss; omit it at the component level when |
| 201 | /// the host has no measured context value. Rows outside the column clamp. |
| 202 | #[must_use] |
| 203 | pub fn color_at_context(self, row: u16, height: u16, context_percent: u8) -> Color { |
| 204 | let rise = f32::from(context_percent.min(100)) / 100.0; |
| 205 | if height <= 1 { |
| 206 | return mix_toward(self.surface, self.deep, rise); |
| 207 | } |
| 208 | let position = (f32::from(row.min(height - 1)) / f32::from(height - 1) + rise).min(1.0); |
| 209 | let toward_middle = mix_toward(self.surface, self.middle, position); |
| 210 | let toward_deep = mix_toward(self.middle, self.deep, position); |
| 211 | mix_toward(toward_middle, toward_deep, position) |
| 212 | } |
| 213 | |
| 214 | /// The native phase treatment at caller time. Waiting/approval are warm |
| 215 | /// and failure is steady; neither depends on elapsed time. |
| 216 | #[must_use] |
| 217 | pub fn color_at_phase_context( |
| 218 | self, |
| 219 | row: u16, |
| 220 | height: u16, |
| 221 | elapsed: Duration, |
| 222 | phase: OceanPhase, |
| 223 | context_percent: u8, |
| 224 | ) -> Color { |
| 225 | if phase.needs_attention() { |
| 226 | return self.color_at_attention_context(row, height, phase, context_percent); |
| 227 | } |
| 228 | let base = self.color_at_context(row, height, context_percent); |
| 229 | let depth = depth_at(row, height, context_percent); |
| 230 | let cycle = (elapsed.as_millis() % 90_000) as f32 / 90_000.0; |
| 231 | let breath = (cycle * std::f32::consts::TAU).sin() * 0.5 + 0.5; |
| 232 | let (bias, phase_depth) = match phase { |
| 233 | OceanPhase::Idle => (0.035, 1.0 - depth), |
| 234 | OceanPhase::Typing => (0.025, 1.0 - depth), |
| 235 | OceanPhase::Working => (0.045, 0.35 + depth * 0.65), |
| 236 | OceanPhase::Verifying => (0.055, 0.65 + (1.0 - depth) * 0.35), |
| 237 | OceanPhase::Done => (0.018, 1.0 - depth), |
| 238 | OceanPhase::Waiting | OceanPhase::Approval | OceanPhase::Failed => unreachable!(), |
| 239 | }; |
| 240 | mix_toward(base, self.ambient, breath * bias * phase_depth) |
| 241 | } |
| 242 | |
| 243 | /// The native steady attention/failure tint, also used in reduced motion. |
| 244 | #[must_use] |
| 245 | pub fn color_at_attention_context( |
| 246 | self, |
| 247 | row: u16, |
| 248 | height: u16, |
| 249 | phase: OceanPhase, |
| 250 | context_percent: u8, |
| 251 | ) -> Color { |
| 252 | let base = self.color_at_context(row, height, context_percent); |
| 253 | match phase { |
| 254 | OceanPhase::Waiting | OceanPhase::Approval => self.warm( |
| 255 | base, |
| 256 | self.attention, |
| 257 | 0.10 * (0.6 + 0.4 * (1.0 - depth_at(row, height, context_percent))), |
| 258 | ), |
| 259 | OceanPhase::Failed => self.warm(base, self.failure, 0.09), |
| 260 | _ => base, |
| 261 | } |
| 262 | } |
| 263 | |
| 264 | /// Perceptual OKLab quadratic surface → middle → deep curve. |
| 265 | /// |
| 266 | /// Keeps jewel-toned ocean blues smooth across every row without sRGB |
| 267 | /// midtone desaturation while preserving exact `surface` and `deep` |
| 268 | /// endpoints. |
| 269 | #[must_use] |
| 270 | pub fn color_at_context_oklab(self, row: u16, height: u16, context_percent: u8) -> Color { |
| 271 | let rise = f32::from(context_percent.min(100)) / 100.0; |
| 272 | if height <= 1 { |
| 273 | return mix_toward_oklab(self.surface, self.deep, rise); |
| 274 | } |
| 275 | let position = (f32::from(row.min(height - 1)) / f32::from(height - 1) + rise).min(1.0); |
| 276 | let toward_middle = mix_toward_oklab(self.surface, self.middle, position); |
| 277 | let toward_deep = mix_toward_oklab(self.middle, self.deep, position); |
| 278 | mix_toward_oklab(toward_middle, toward_deep, position) |
| 279 | } |
| 280 | |
| 281 | /// Perceptual OKLab phase treatment at caller time. Waiting/approval stay |
| 282 | /// warm and failure stays steady, preserving contrast floors. |
| 283 | #[must_use] |
| 284 | pub fn color_at_phase_context_oklab( |
| 285 | self, |
| 286 | row: u16, |
| 287 | height: u16, |
| 288 | elapsed: Duration, |
| 289 | phase: OceanPhase, |
| 290 | context_percent: u8, |
| 291 | ) -> Color { |
| 292 | if phase.needs_attention() { |
| 293 | return self.color_at_attention_context(row, height, phase, context_percent); |
| 294 | } |
| 295 | let base = self.color_at_context_oklab(row, height, context_percent); |
| 296 | let depth = depth_at(row, height, context_percent); |
| 297 | let cycle = (elapsed.as_millis() % 90_000) as f32 / 90_000.0; |
| 298 | let breath = (cycle * std::f32::consts::TAU).sin() * 0.5 + 0.5; |
| 299 | let (bias, phase_depth) = match phase { |
| 300 | OceanPhase::Idle => (0.035, 1.0 - depth), |
| 301 | OceanPhase::Typing => (0.025, 1.0 - depth), |
| 302 | OceanPhase::Working => (0.045, 0.35 + depth * 0.65), |
| 303 | OceanPhase::Verifying => (0.055, 0.65 + (1.0 - depth) * 0.35), |
| 304 | OceanPhase::Done => (0.018, 1.0 - depth), |
| 305 | OceanPhase::Waiting | OceanPhase::Approval | OceanPhase::Failed => unreachable!(), |
| 306 | }; |
| 307 | mix_toward_oklab(base, self.ambient, breath * bias * phase_depth) |
| 308 | } |
| 309 | |
| 310 | /// Dark completion brightness: 88% → 112% at 320 ms → 100% at 800 ms. |
| 311 | /// Light grounds receive a gentle accent reflection over the same interval. |
| 312 | /// The component uses it only for a reported `Done` phase in |
| 313 | /// [`MotionMode::Full`]; a stale completion clock cannot mask failure. |
| 314 | #[must_use] |
| 315 | pub fn color_at_completion_context( |
| 316 | self, |
| 317 | row: u16, |
| 318 | height: u16, |
| 319 | elapsed: Duration, |
| 320 | context_percent: u8, |
| 321 | ) -> Color { |
| 322 | let base = self.color_at_context(row, height, context_percent); |
| 323 | let t = elapsed.as_millis().min(800) as f32 / 800.0; |
| 324 | if relative_luminance(base).is_some_and(|luminance| luminance >= 0.5) { |
| 325 | let pulse = if t <= 0.4 { t / 0.4 } else { (1.0 - t) / 0.6 }; |
| 326 | return mix_toward( |
| 327 | base, |
| 328 | self.ambient, |
| 329 | 0.12 * pulse * pulse * (3.0 - 2.0 * pulse), |
| 330 | ); |
| 331 | } |
| 332 | let brightness = if t <= 0.4 { |
| 333 | 0.88 + (1.12 - 0.88) * (t / 0.4) |
| 334 | } else { |
| 335 | 1.12 + (1.0 - 1.12) * ((t - 0.4) / 0.6) |
| 336 | }; |
| 337 | let Color::Rgb(r, g, b) = base else { |
| 338 | return base; |
| 339 | }; |
| 340 | let scale = |c| (f32::from(c) * brightness).round().clamp(0.0, 255.0) as u8; |
| 341 | Color::Rgb(scale(r), scale(g), scale(b)) |
| 342 | } |
| 343 | } |
| 344 | |
| 345 | // Explicit native ramps may carry a terminal-owned or indexed tint. There |
| 346 | // is no RGB interpolation evidence in that case; retain the source color. |
| 347 | fn mix_toward(from: Color, to: Color, amount: f32) -> Color { |
| 348 | if matches!((from, to), (Color::Rgb(..), Color::Rgb(..))) { |
| 349 | blend(to, from, amount) |
| 350 | } else { |
| 351 | from |
| 352 | } |
| 353 | } |
| 354 | |
| 355 | fn mix_toward_oklab(from: Color, to: Color, amount: f32) -> Color { |
| 356 | if matches!((from, to), (Color::Rgb(..), Color::Rgb(..))) { |
| 357 | mix_oklab(from, to, amount) |
| 358 | } else { |
| 359 | from |
| 360 | } |
| 361 | } |
| 362 | |
| 363 | fn depth_at(row: u16, height: u16, context_percent: u8) -> f32 { |
| 364 | if height <= 1 { |
| 365 | 0.0 |
| 366 | } else { |
| 367 | (f32::from(row.min(height - 1)) / f32::from(height - 1) |
| 368 | + f32::from(context_percent.min(100)) / 100.0) |
| 369 | .min(1.0) |
| 370 | } |
| 371 | } |
| 372 | |
| 373 | /// One shared native water column over caller-owned components. |
| 374 | /// |
| 375 | /// The host supplies elapsed time and decides when a visible field deserves |
| 376 | /// another redraw. [`MotionMode::Reduced`] and [`MotionMode::Still`] ignore |
| 377 | /// both clocks and keep steady attention/failure tint. ASCII changes no text |
| 378 | /// here: this finishing pass paints backgrounds only. |
| 379 | #[derive(Clone, Copy, Debug, PartialEq, Eq)] |
| 380 | pub struct OceanColumn { |
| 381 | ramp: Option<OceanRamp>, |
| 382 | elapsed: Duration, |
| 383 | motion: MotionMode, |
| 384 | phase: OceanPhase, |
| 385 | completion_elapsed: Option<Duration>, |
| 386 | viewport: Option<Rect>, |
| 387 | context_percent: u8, |
| 388 | presence: u16, |
| 389 | contrast_inks: Option<OceanContrastInks>, |
| 390 | oklab_depth: bool, |
| 391 | } |
| 392 | |
| 393 | impl OceanColumn { |
| 394 | #[must_use] |
| 395 | pub const fn new(elapsed: Duration, motion: MotionMode) -> Self { |
| 396 | Self { |
| 397 | ramp: None, |
| 398 | elapsed, |
| 399 | motion, |
| 400 | phase: OceanPhase::Idle, |
| 401 | completion_elapsed: None, |
| 402 | viewport: None, |
| 403 | context_percent: 0, |
| 404 | presence: 1000, |
| 405 | contrast_inks: None, |
| 406 | oklab_depth: false, |
| 407 | } |
| 408 | } |
| 409 | |
| 410 | /// Interpolate the vertical depth curve and ambient breath in perceptual |
| 411 | /// OKLab while keeping exact stop endpoints and contrast guards. |
| 412 | #[must_use] |
| 413 | pub const fn oklab_depth(mut self, enabled: bool) -> Self { |
| 414 | self.oklab_depth = enabled; |
| 415 | self |
| 416 | } |
| 417 | |
| 418 | /// Supply the host's actual ramp without granting paint capability. |
| 419 | /// `color_at_y`, `apply` and `apply_matching` keep their existing theme, |
| 420 | /// terminal, semantic-surface and contrast guards. |
| 421 | #[must_use] |
| 422 | pub const fn ramp(mut self, ramp: OceanRamp) -> Self { |
| 423 | self.ramp = Some(ramp); |
| 424 | self |
| 425 | } |
| 426 | |
| 427 | #[must_use] |
| 428 | pub const fn phase(mut self, phase: OceanPhase) -> Self { |
| 429 | self.phase = phase; |
| 430 | self |
| 431 | } |
| 432 | |
| 433 | /// Caller-measured context fullness, clamped to 100. The default leaves |
| 434 | /// the authored column at its normal depth and asserts no usage fact. |
| 435 | #[must_use] |
| 436 | pub const fn context_percent(mut self, context_percent: u8) -> Self { |
| 437 | self.context_percent = if context_percent > 100 { |
| 438 | 100 |
| 439 | } else { |
| 440 | context_percent |
| 441 | }; |
| 442 | self |
| 443 | } |
| 444 | |
| 445 | /// Caller time since an actual successful completion. Honored only in |
| 446 | /// `Done` with Full motion, and only before the native 800 ms boundary. |
| 447 | #[must_use] |
| 448 | pub const fn completion_elapsed(mut self, elapsed: Duration) -> Self { |
| 449 | self.completion_elapsed = Some(elapsed); |
| 450 | self |
| 451 | } |
| 452 | |
| 453 | /// Share this viewport across separate bands so the gradient continues |
| 454 | /// through them. Without it, the paint area is the complete column. |
| 455 | #[must_use] |
| 456 | pub const fn viewport(mut self, viewport: Rect) -> Self { |
| 457 | self.viewport = Some(viewport); |
| 458 | self |
| 459 | } |
| 460 | |
| 461 | /// Host-sampled ambient presence, 0–1000 as in the native renderer. |
| 462 | /// This eases only phase breathing; attention/failure remain steady and |
| 463 | /// the successful completion pulse keeps its own gated clock. |
| 464 | #[must_use] |
| 465 | pub const fn presence(mut self, presence: u16) -> Self { |
| 466 | self.presence = if presence > 1000 { 1000 } else { presence }; |
| 467 | self |
| 468 | } |
| 469 | |
| 470 | /// Pure sampling at an absolute row. `viewport` supplies the default |
| 471 | /// column bounds unless the builder already specifies shared bounds. |
| 472 | /// Returns `None` where a measured RGB field is unavailable. |
| 473 | #[must_use] |
| 474 | pub fn color_at_y(&self, y: u16, viewport: Rect, theme: &Theme) -> Option<Color> { |
| 475 | let ramp = OceanRamp::for_theme(theme)?; |
| 476 | Some(self.color_at_y_with_ramp(y, viewport, ramp)) |
| 477 | } |
| 478 | |
| 479 | /// Pure sampling under a caller-owned rendering policy. |
| 480 | /// Like the ramp's math helpers, this paints nothing and has no terminal |
| 481 | /// capability gate; guarded sampling and painting keep their own gates. |
| 482 | /// A builder-supplied `ramp` overrides this fallback ramp; `viewport` |
| 483 | /// likewise retains the shared absolute column. Motion, completion, |
| 484 | /// phase, context and presence follow the same kernel as guarded paint. |
| 485 | /// Hosts must keep their existing paint/terminal guards around the result. |
| 486 | #[must_use] |
| 487 | pub fn color_at_y_with_ramp(&self, y: u16, viewport: Rect, ramp: OceanRamp) -> Color { |
| 488 | let viewport = self.viewport.unwrap_or(viewport); |
| 489 | let ramp = self.ramp.unwrap_or(ramp); |
| 490 | let height = viewport.height.max(1); |
| 491 | let row = y.saturating_sub(viewport.y).min(height - 1); |
| 492 | if self.motion.animates() |
| 493 | && self.phase == OceanPhase::Done |
| 494 | && let Some(elapsed) = self |
| 495 | .completion_elapsed |
| 496 | .filter(|t| *t < OceanRamp::COMPLETION_BREATH) |
| 497 | { |
| 498 | return ramp.color_at_completion_context(row, height, elapsed, self.context_percent); |
| 499 | } |
| 500 | if self.phase.needs_attention() { |
| 501 | return ramp.color_at_attention_context(row, height, self.phase, self.context_percent); |
| 502 | } |
| 503 | let base = if self.oklab_depth { |
| 504 | ramp.color_at_context_oklab(row, height, self.context_percent) |
| 505 | } else { |
| 506 | ramp.color_at_context(row, height, self.context_percent) |
| 507 | }; |
| 508 | if !self.motion.animates() || self.presence == 0 { |
| 509 | return base; |
| 510 | } |
| 511 | let phase = if self.oklab_depth { |
| 512 | ramp.color_at_phase_context_oklab( |
| 513 | row, |
| 514 | height, |
| 515 | self.elapsed, |
| 516 | self.phase, |
| 517 | self.context_percent, |
| 518 | ) |
| 519 | } else { |
| 520 | ramp.color_at_phase_context(row, height, self.elapsed, self.phase, self.context_percent) |
| 521 | }; |
| 522 | if self.oklab_depth { |
| 523 | mix_toward_oklab(base, phase, f32::from(self.presence) / 1000.0) |
| 524 | } else { |
| 525 | mix_toward(base, phase, f32::from(self.presence) / 1000.0) |
| 526 | } |
| 527 | } |
| 528 | |
| 529 | /// Finish ordinary `Background` and `Sidebar` cells, clipped to the |
| 530 | /// buffer. Colors shared with semantic fills remain exact; explicit |
| 531 | /// chrome regions can opt in through `apply_matching`. Visible inks must retain their |
| 532 | /// contrast floor; unknown terminal inks and reversed cells are spared. |
| 533 | pub fn apply(&self, area: Rect, buf: &mut Buffer, theme: &Theme) { |
| 534 | let semantic = [ |
| 535 | Role::Surface, |
| 536 | Role::Hover, |
| 537 | Role::Selected, |
| 538 | Role::DiffAddedTint, |
| 539 | Role::DiffRemovedTint, |
| 540 | Role::Accent, |
| 541 | Role::Live, |
| 542 | Role::Attention, |
| 543 | Role::Danger, |
| 544 | ] |
| 545 | .map(|role| theme.bg(role).bg); |
| 546 | let grounds = [Role::Background, Role::Sidebar].map(|role| { |
| 547 | theme |
| 548 | .bg(role) |
| 549 | .bg |
| 550 | .filter(|color| !semantic.contains(&Some(*color))) |
| 551 | }); |
| 552 | self.apply_grounds(area, buf, theme, &grounds); |
| 553 | } |
| 554 | |
| 555 | /// Continue the column through cells with the caller's explicit base |
| 556 | /// `ground`, restricted to `area`. Use [`Self::viewport`] to share one |
| 557 | /// absolute water column across conversation, composer and footer bands. |
| 558 | /// |
| 559 | /// Other grounds, symbols, inks and modifiers remain untouched. The |
| 560 | /// existing theme, clipping and contrast policy still applies, including |
| 561 | /// protection for unknown inks and reversed cells. The caller chooses a |
| 562 | /// region containing ordinary chrome: a semantic surface using this same |
| 563 | /// base color must be kept outside that region. |
| 564 | pub fn apply_matching(&self, area: Rect, buf: &mut Buffer, theme: &Theme, ground: Color) { |
| 565 | self.apply_grounds(area, buf, theme, &[Some(ground)]); |
| 566 | } |
| 567 | |
| 568 | /// Native finishing inputs: cached samples and semantic rectangles are |
| 569 | /// caller facts, while capability, clipping, reverse and contrast guards |
| 570 | /// are the same guard kernel used by `apply` and `apply_matching`. |
| 571 | /// `project_ink` returns the host backend's actual proposed visible ink; |
| 572 | /// it never mutates the source cell, symbols or modifiers. |
| 573 | pub fn apply_native( |
| 574 | &self, |
| 575 | area: Rect, |
| 576 | buf: &mut Buffer, |
| 577 | theme: &Theme, |
| 578 | facts: &OceanPaintFacts<'_>, |
| 579 | project_ink: impl Fn(&Cell, Color) -> Color, |
| 580 | ) { |
| 581 | self.apply_grounds_with(area, buf, theme, &[Some(facts.ground)], facts, project_ink); |
| 582 | } |
| 583 | |
| 584 | /// Map the three decorative/supporting floors to exact live host colors. |
| 585 | /// Other inks keep the text floor, including unrecognized custom colors. |
| 586 | #[must_use] |
| 587 | pub const fn contrast_inks(mut self, inks: OceanContrastInks) -> Self { |
| 588 | self.contrast_inks = Some(inks); |
| 589 | self |
| 590 | } |
| 591 | |
| 592 | fn apply_grounds( |
| 593 | &self, |
| 594 | area: Rect, |
| 595 | buf: &mut Buffer, |
| 596 | theme: &Theme, |
| 597 | grounds: &[Option<Color>], |
| 598 | ) { |
| 599 | self.apply_grounds_with( |
| 600 | area, |
| 601 | buf, |
| 602 | theme, |
| 603 | grounds, |
| 604 | &OceanPaintFacts::new(Color::Reset), |
| 605 | |cell, _| cell.fg, |
| 606 | ); |
| 607 | } |
| 608 | |
| 609 | fn apply_grounds_with( |
| 610 | &self, |
| 611 | area: Rect, |
| 612 | buf: &mut Buffer, |
| 613 | theme: &Theme, |
| 614 | grounds: &[Option<Color>], |
| 615 | facts: &OceanPaintFacts<'_>, |
| 616 | project_ink: impl Fn(&Cell, Color) -> Color, |
| 617 | ) { |
| 618 | let Some(ramp) = OceanRamp::for_theme(theme) else { |
| 619 | return; |
| 620 | }; |
| 621 | let viewport = self.viewport.unwrap_or(area); |
| 622 | let area = area.intersection(buf.area); |
| 623 | for y in area.top()..area.bottom() { |
| 624 | let water = facts |
| 625 | .samples |
| 626 | .get(usize::from(y.saturating_sub(facts.sample_top))) |
| 627 | .filter(|_| y >= facts.sample_top) |
| 628 | .copied() |
| 629 | .unwrap_or_else(|| self.color_at_y_with_ramp(y, viewport, ramp)); |
| 630 | let mut previous_ink = None; |
| 631 | for x in area.left()..area.right() { |
| 632 | if facts |
| 633 | .protected |
| 634 | .iter() |
| 635 | .any(|rect| rect.contains((x, y).into())) |
| 636 | { |
| 637 | continue; |
| 638 | } |
| 639 | let cell = &mut buf[(x, y)]; |
| 640 | if grounds.contains(&Some(cell.bg)) && !cell.modifier.contains(Modifier::REVERSED) { |
| 641 | let safe = cell.symbol() == " " || { |
| 642 | let ink = project_ink(cell, water); |
| 643 | if let Some((previous, safe)) = previous_ink |
| 644 | && previous == ink |
| 645 | { |
| 646 | safe |
| 647 | } else { |
| 648 | let safe = ink_is_safe(ink, water, theme, self.contrast_inks); |
| 649 | previous_ink = Some((ink, safe)); |
| 650 | safe |
| 651 | } |
| 652 | }; |
| 653 | if safe { |
| 654 | cell.set_bg(water); |
| 655 | } |
| 656 | } |
| 657 | } |
| 658 | } |
| 659 | } |
| 660 | |
| 661 | /// Sparse caustics can finish only already painted ordinary water. |
| 662 | /// They share the same capability/motion guard and never cross a semantic |
| 663 | /// rectangle, a different ground, visible ink or a reversed cell. |
| 664 | pub fn apply_caustics( |
| 665 | &self, |
| 666 | area: Rect, |
| 667 | buf: &mut Buffer, |
| 668 | theme: &Theme, |
| 669 | facts: &OceanCausticFacts<'_>, |
| 670 | ) { |
| 671 | if !self.motion.animates() || area.width < 40 || area.height < 10 { |
| 672 | return; |
| 673 | } |
| 674 | let Some(ramp) = OceanRamp::for_theme(theme) else { |
| 675 | return; |
| 676 | }; |
| 677 | let ramp = self.ramp.unwrap_or(ramp); |
| 678 | let viewport = self.viewport.unwrap_or(area); |
| 679 | let clipped = area.intersection(buf.area); |
| 680 | let band = facts.band_rows.min(area.height); |
| 681 | for y in clipped.y..clipped.bottom().min(area.y.saturating_add(band)) { |
| 682 | let local_y = y.saturating_sub(area.y); |
| 683 | let water = facts |
| 684 | .paint |
| 685 | .samples |
| 686 | .get(usize::from(y.saturating_sub(facts.paint.sample_top))) |
| 687 | .filter(|_| y >= facts.paint.sample_top) |
| 688 | .copied() |
| 689 | .unwrap_or_else(|| self.color_at_y_with_ramp(y, viewport, ramp)); |
| 690 | let depth = 1.0 - f32::from(local_y) / f32::from(band.max(1)); |
| 691 | for x in clipped.x..clipped.right() { |
| 692 | let local_x = x.saturating_sub(area.x); |
| 693 | if local_x % 3 != 0 |
| 694 | || facts |
| 695 | .paint |
| 696 | .protected |
| 697 | .iter() |
| 698 | .any(|r| r.contains((x, y).into())) |
| 699 | { |
| 700 | continue; |
| 701 | } |
| 702 | let cell = &mut buf[(x, y)]; |
| 703 | if cell.bg != water |
| 704 | || cell.modifier.contains(Modifier::REVERSED) |
| 705 | || !(cell.symbol() == " " || cell.symbol().is_empty()) |
| 706 | { |
| 707 | continue; |
| 708 | } |
| 709 | let brightness = |
| 710 | ocean_caustic_brightness(facts.elapsed, local_x, local_y, depth * depth); |
| 711 | if let Color::Rgb(r, g, b) = water { |
| 712 | if relative_luminance(water).is_some_and(|luminance| luminance >= 0.5) { |
| 713 | cell.set_bg(mix_toward(water, ramp.ambient, (brightness - 1.0) * 1.5)); |
| 714 | continue; |
| 715 | } |
| 716 | let scale = |
| 717 | |value| (f32::from(value) * brightness).round().clamp(0.0, 255.0) as u8; |
| 718 | cell.set_bg(Color::Rgb(scale(r), scale(g), scale(b))); |
| 719 | } |
| 720 | } |
| 721 | } |
| 722 | } |
| 723 | |
| 724 | /// Volumetric diagonal sun-shafts and shimmering underwater caustics in |
| 725 | /// perceptual OKLab over already-painted ordinary water. |
| 726 | /// |
| 727 | /// Respects [`MotionMode`] (no-op in `Reduced`/`Still`), minimum viewport |
| 728 | /// size (`40x10`), truecolor theme guards, protected semantic rectangles, |
| 729 | /// reversed cells, and unoccupied water cells so text contrast floors are |
| 730 | /// never degraded. |
| 731 | pub fn apply_volumetric_caustics( |
| 732 | &self, |
| 733 | area: Rect, |
| 734 | buf: &mut Buffer, |
| 735 | theme: &Theme, |
| 736 | facts: &OceanCausticFacts<'_>, |
| 737 | ) { |
| 738 | if !self.motion.animates() || area.width < 40 || area.height < 10 { |
| 739 | return; |
| 740 | } |
| 741 | let Some(ramp) = OceanRamp::for_theme(theme) else { |
| 742 | return; |
| 743 | }; |
| 744 | let ramp = self.ramp.unwrap_or(ramp); |
| 745 | let viewport = self.viewport.unwrap_or(area); |
| 746 | let clipped = area.intersection(buf.area); |
| 747 | let band = facts.band_rows.min(area.height); |
| 748 | if band == 0 { |
| 749 | return; |
| 750 | } |
| 751 | let presence_scale = f32::from(self.presence) / 1000.0; |
| 752 | if presence_scale <= 0.0 { |
| 753 | return; |
| 754 | } |
| 755 | for y in clipped.y..clipped.bottom().min(area.y.saturating_add(band)) { |
| 756 | let local_y = y.saturating_sub(area.y); |
| 757 | let water = facts |
| 758 | .paint |
| 759 | .samples |
| 760 | .get(usize::from(y.saturating_sub(facts.paint.sample_top))) |
| 761 | .filter(|_| y >= facts.paint.sample_top) |
| 762 | .copied() |
| 763 | .unwrap_or_else(|| self.color_at_y_with_ramp(y, viewport, ramp)); |
| 764 | let is_light = relative_luminance(water).is_some_and(|lum| lum >= 0.5); |
| 765 | for x in clipped.x..clipped.right() { |
| 766 | if facts |
| 767 | .paint |
| 768 | .protected |
| 769 | .iter() |
| 770 | .any(|r| r.contains((x, y).into())) |
| 771 | { |
| 772 | continue; |
| 773 | } |
| 774 | let cell = &mut buf[(x, y)]; |
| 775 | if cell.bg != water |
| 776 | || cell.modifier.contains(Modifier::REVERSED) |
| 777 | || !(cell.symbol() == " " || cell.symbol().is_empty()) |
| 778 | { |
| 779 | continue; |
| 780 | } |
| 781 | let local_x = x.saturating_sub(area.x); |
| 782 | let shimmer = |
| 783 | ocean_volumetric_caustic(facts.elapsed, local_x, local_y, area.width, band) |
| 784 | * presence_scale; |
| 785 | if shimmer <= 0.0 { |
| 786 | continue; |
| 787 | } |
| 788 | let lifted = if is_light { |
| 789 | mix_oklab(water, ramp.ambient, shimmer * 0.14) |
| 790 | } else { |
| 791 | specular_lift(water, ramp.ambient, shimmer * 0.28) |
| 792 | }; |
| 793 | cell.set_bg(lifted); |
| 794 | } |
| 795 | } |
| 796 | } |
| 797 | } |
| 798 | |
| 799 | impl Paint for OceanColumn { |
| 800 | fn paint(&self, area: Rect, buf: &mut Buffer, theme: &Theme) { |
| 801 | self.apply(area, buf, theme); |
| 802 | } |
| 803 | } |
| 804 | |
| 805 | fn ink_is_safe(ink: Color, water: Color, theme: &Theme, live: Option<OceanContrastInks>) -> bool { |
| 806 | if let Some(live) = live { |
| 807 | let floor = if live.border == Some(ink) { |
| 808 | 1.0 |
| 809 | } else if live.border_strong == Some(ink) || live.dim == Some(ink) { |
| 810 | 3.0 |
| 811 | } else { |
| 812 | 4.5 |
| 813 | }; |
| 814 | return contrast_ratio(ink, water).is_some_and(|ratio| ratio >= floor); |
| 815 | } |
| 816 | let floor = if [Role::Border, Role::BorderStrong, Role::Dim] |
| 817 | .into_iter() |
| 818 | .any(|role| theme.color(role) == Some(ink)) |
| 819 | { |
| 820 | // Border is purely decorative and deliberately has no text floor. |
| 821 | if theme.color(Role::Border) == Some(ink) { |
| 822 | 1.0 |
| 823 | } else { |
| 824 | 3.0 |
| 825 | } |
| 826 | } else { |
| 827 | 4.5 |
| 828 | }; |
| 829 | contrast_ratio(ink, water).is_some_and(|ratio| ratio >= floor) |
| 830 | } |
| 831 | |
| 832 | /// Actual live host colors for the existing decorative/supporting floors. |
| 833 | #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] |
| 834 | pub struct OceanContrastInks { |
| 835 | pub border: Option<Color>, |
| 836 | pub border_strong: Option<Color>, |
| 837 | pub dim: Option<Color>, |
| 838 | } |
| 839 | |
| 840 | /// Bounded frame-derived presentation facts; no cache or surface store. |
| 841 | #[derive(Clone, Copy, Debug)] |
| 842 | pub struct OceanPaintFacts<'a> { |
| 843 | pub ground: Color, |
| 844 | pub sample_top: u16, |
| 845 | pub samples: &'a [Color], |
| 846 | pub protected: &'a [Rect], |
| 847 | } |
| 848 | impl OceanPaintFacts<'_> { |
| 849 | #[must_use] |
| 850 | pub const fn new(ground: Color) -> Self { |
| 851 | Self { |
| 852 | ground, |
| 853 | sample_top: 0, |
| 854 | samples: &[], |
| 855 | protected: &[], |
| 856 | } |
| 857 | } |
| 858 | } |
| 859 | |
| 860 | /// The host reports elapsed time and its unoccupied surface-band height. |
| 861 | #[derive(Clone, Copy, Debug)] |
| 862 | pub struct OceanCausticFacts<'a> { |
| 863 | pub paint: OceanPaintFacts<'a>, |
| 864 | pub elapsed: Duration, |
| 865 | pub band_rows: u16, |
| 866 | } |
| 867 | |
| 868 | /// The native continuous 960ms travelling crest; owns no clock or loop. |
| 869 | #[must_use] |
| 870 | pub fn ocean_caustic_brightness( |
| 871 | elapsed: Duration, |
| 872 | local_x: u16, |
| 873 | local_y: u16, |
| 874 | depth_fade: f32, |
| 875 | ) -> f32 { |
| 876 | let time = (elapsed.as_millis() % 960) as f64 / 960.0; |
| 877 | let slot = (u32::from(local_x / 3) + u32::from(local_y)) % 4; |
| 878 | let phase = (time + f64::from(slot) / 4.0) * std::f64::consts::TAU; |
| 879 | let crest = ((phase.cos() + 1.0) * 0.5).powi(8); |
| 880 | 1.0 + 0.08 * (crest as f32) * depth_fade.clamp(0.0, 1.0) |
| 881 | } |
| 882 | |
| 883 | /// Dual-harmonic slanted underwater sun-shaft and caustic intensity in |
| 884 | /// `0.0..=1.0`, quantized to 12 calm perceptual steps. Pure function of caller |
| 885 | /// time and local coordinates. |
| 886 | #[must_use] |
| 887 | pub fn ocean_volumetric_caustic( |
| 888 | elapsed: Duration, |
| 889 | local_x: u16, |
| 890 | local_y: u16, |
| 891 | width: u16, |
| 892 | band_rows: u16, |
| 893 | ) -> f32 { |
| 894 | if band_rows == 0 || width == 0 || local_y >= band_rows { |
| 895 | return 0.0; |
| 896 | } |
| 897 | let depth = f32::from(local_y) / f32::from(band_rows); |
| 898 | let depth_fade = (1.0 - depth).clamp(0.0, 1.0).powf(2.1); |
| 899 | let t_a = (elapsed.as_millis() % 14_000) as f64 / 14_000.0; |
| 900 | let t_b = (elapsed.as_millis() % 9_400) as f64 / 9_400.0; |
| 901 | let x = f64::from(local_x); |
| 902 | let y = f64::from(local_y); |
| 903 | let theta_a = x * 0.16 - y * 0.42 - t_a * std::f64::consts::TAU; |
| 904 | let theta_b = x * 0.29 + y * 0.23 + t_b * std::f64::consts::TAU; |
| 905 | let shaft = ((theta_a.cos() + 1.0) * 0.5).powi(3) as f32; |
| 906 | let ripple = ((theta_b.cos() + 1.0) * 0.5).powi(2) as f32; |
| 907 | let edge_u = f32::from(local_x) / f32::from(width.saturating_sub(1).max(1)); |
| 908 | let horizontal_envelope = 0.75 + 0.25 * (std::f32::consts::PI * edge_u).sin(); |
| 909 | let raw = |
| 910 | ((0.62 * shaft + 0.38 * shaft * ripple) * depth_fade * horizontal_envelope).clamp(0.0, 1.0); |
| 911 | let quantized = (raw * 12.0).round() / 12.0; |
| 912 | if quantized < 0.08 { 0.0 } else { quantized } |
| 913 | } |
| 914 | |
| 915 | /// Explicit styled grounds are semantic even when a custom theme aliases |
| 916 | /// their RGB to an ordinary pane. Project guarded prewrapped source once; |
| 917 | /// callers pass these frame-only rectangles to native finishing. |
| 918 | #[must_use] |
| 919 | pub fn ocean_semantic_surfaces( |
| 920 | rows: &[Line<'static>], |
| 921 | area: Rect, |
| 922 | measure_grapheme: impl Fn(&str) -> usize, |
| 923 | ) -> Vec<Rect> { |
| 924 | let measure = |value: &str| { |
| 925 | crate::text::display_safe(value) |
| 926 | .graphemes(true) |
| 927 | .fold(0usize, |width, g| width.saturating_add(measure_grapheme(g))) |
| 928 | }; |
| 929 | let mut regions = Vec::new(); |
| 930 | for (index, line) in rows.iter().take(usize::from(area.height)).enumerate() { |
| 931 | let y = area |
| 932 | .y |
| 933 | .saturating_add(u16::try_from(index).unwrap_or(u16::MAX)); |
| 934 | if line.style.bg.is_some() { |
| 935 | if area.width > 0 { |
| 936 | regions.push(Rect::new(area.x, y, area.width, 1)); |
| 937 | } |
| 938 | continue; |
| 939 | } |
| 940 | let width = line.spans.iter().fold(0usize, |width, span| { |
| 941 | width.saturating_add(measure(&span.content)) |
| 942 | }); |
| 943 | let padding = usize::from(area.width).saturating_sub(width); |
| 944 | let mut column = match line.alignment.unwrap_or(Alignment::Left) { |
| 945 | Alignment::Left => 0, |
| 946 | Alignment::Center => padding / 2, |
| 947 | Alignment::Right => padding, |
| 948 | }; |
| 949 | for span in &line.spans { |
| 950 | let end = column.saturating_add(measure(&span.content)); |
| 951 | let clipped_end = end.min(usize::from(area.width)); |
| 952 | if span.style.bg.is_some() && column < clipped_end { |
| 953 | regions.push(Rect::new( |
| 954 | area.x.saturating_add(column as u16), |
| 955 | y, |
| 956 | (clipped_end - column) as u16, |
| 957 | 1, |
| 958 | )); |
| 959 | } |
| 960 | column = end; |
| 961 | } |
| 962 | } |
| 963 | regions |
| 964 | } |
| 965 |