Skip to main content

tui_chart/
effects.rs

1//! Cyberpunk-style post effects for any widget: [`glow`], [`scanlines`], the
2//! [`Fx`] wrapper and cut-corner frames ([`chamfer_block`], [`bracket_block`]).
3//!
4//! Effects run on the rendered [`Buffer`], so they work with every chart.
5//! They need a color terminal (truecolor looks best).
6//!
7//! ```
8//! use ratatui::{buffer::Buffer, layout::Rect, widgets::Widget};
9//! use tui_chart::{chamfer_block, Fx, Sparkline};
10//!
11//! let area = Rect::new(0, 0, 30, 6);
12//! let mut buf = Buffer::empty(area);
13//! let chart = Sparkline::new([1.0, 4.0, 2.0, 8.0]).block(chamfer_block(" cpu "));
14//! Fx::new(chart).glow(1, 0.35).scanlines(0.25).render(area, &mut buf);
15//! ```
16
17use crate::util::{darken, mix};
18use ratatui::{
19    buffer::Buffer,
20    layout::Rect,
21    style::Color,
22    symbols::border,
23    widgets::{Block, Borders, Widget},
24};
25
26fn blank(sym: &str) -> bool {
27    sym.chars().all(|c| c == ' ' || c == '\u{2800}')
28}
29
30/// Spread each lit cell's color into the background of nearby empty cells.
31///
32/// `radius` is in cells (cells are about twice as tall as wide, so horizontal
33/// reach is shorter); `strength` is `0..=1`. Glyph cells are left untouched.
34pub fn glow(buf: &mut Buffer, area: Rect, radius: u16, strength: f64) {
35    let area = area.intersection(buf.area);
36    if radius == 0 || strength <= 0.0 || area.is_empty() {
37        return;
38    }
39    let mut lit = Vec::new();
40    for y in area.top()..area.bottom() {
41        for x in area.left()..area.right() {
42            let c = &buf[(x, y)];
43            if !blank(c.symbol()) && c.fg != Color::Reset {
44                lit.push((x, y, c.fg));
45            }
46        }
47    }
48    let r = i32::from(radius);
49    for (x, y, fg) in lit {
50        for dy in -r..=r {
51            for dx in -2 * r..=2 * r {
52                let dist = (f64::from(dx) * 0.5).hypot(f64::from(dy));
53                if dist == 0.0 || dist > f64::from(radius) {
54                    continue;
55                }
56                let (nx, ny) = (i32::from(x) + dx, i32::from(y) + dy);
57                if nx < i32::from(area.left())
58                    || ny < i32::from(area.top())
59                    || nx >= i32::from(area.right())
60                    || ny >= i32::from(area.bottom())
61                {
62                    continue;
63                }
64                let cell = &mut buf[(nx as u16, ny as u16)];
65                if !blank(cell.symbol()) {
66                    continue;
67                }
68                let base = if cell.bg == Color::Reset {
69                    Color::Black
70                } else {
71                    cell.bg
72                };
73                let a = strength.clamp(0.0, 1.0) * (1.0 - dist / (f64::from(radius) + 1.0)) * 0.5;
74                cell.bg = mix(base, fg, a);
75            }
76        }
77    }
78}
79
80/// Darken every other row (`strength` `0..=1`), like a CRT scanline mask.
81pub fn scanlines(buf: &mut Buffer, area: Rect, strength: f64) {
82    let area = area.intersection(buf.area);
83    if strength <= 0.0 {
84        return;
85    }
86    for y in area.top()..area.bottom() {
87        if (y - area.top()) & 1 == 0 {
88            continue;
89        }
90        for x in area.left()..area.right() {
91            let c = &mut buf[(x, y)];
92            if c.fg != Color::Reset {
93                c.fg = darken(c.fg, strength);
94            }
95            if c.bg != Color::Reset {
96                c.bg = darken(c.bg, strength);
97            }
98        }
99    }
100}
101
102/// Wraps a widget and applies post effects after it renders.
103#[derive(Debug, Clone)]
104pub struct Fx<W> {
105    inner: W,
106    glow: Option<(u16, f64)>,
107    scan: Option<f64>,
108}
109
110impl<W> Fx<W> {
111    /// Wrap `inner` with no effects yet.
112    pub fn new(inner: W) -> Self {
113        Self {
114            inner,
115            glow: None,
116            scan: None,
117        }
118    }
119
120    /// Add a [`glow`] of `radius` cells and `strength` `0..=1`.
121    pub fn glow(mut self, radius: u16, strength: f64) -> Self {
122        self.glow = Some((radius, strength));
123        self
124    }
125
126    /// Add [`scanlines`] of `strength` `0..=1`.
127    pub fn scanlines(mut self, strength: f64) -> Self {
128        self.scan = Some(strength);
129        self
130    }
131}
132
133impl<W: Widget> Widget for Fx<W> {
134    fn render(self, area: Rect, buf: &mut Buffer) {
135        self.inner.render(area, buf);
136        if let Some((r, s)) = self.glow {
137            glow(buf, area, r, s);
138        }
139        if let Some(s) = self.scan {
140            scanlines(buf, area, s);
141        }
142    }
143}
144
145/// A frame with cut (chamfered) corners and a title.
146pub fn chamfer_block(title: &'static str) -> Block<'static> {
147    Block::new()
148        .borders(Borders::ALL)
149        .border_set(border::Set {
150            top_left: "╱",
151            top_right: "╲",
152            bottom_left: "╲",
153            bottom_right: "╱",
154            ..border::PLAIN
155        })
156        .title(title)
157}
158
159/// A frame with heavy corner brackets and light sides, like a HUD readout.
160pub fn bracket_block(title: &'static str) -> Block<'static> {
161    Block::new()
162        .borders(Borders::ALL)
163        .border_set(border::Set {
164            top_left: "┏",
165            top_right: "┓",
166            bottom_left: "┗",
167            bottom_right: "┛",
168            horizontal_top: "─",
169            horizontal_bottom: "─",
170            vertical_left: "│",
171            vertical_right: "│",
172        })
173        .title(title)
174}
175
176#[cfg(test)]
177mod tests {
178    use super::*;
179
180    fn buf_with_dot() -> (Buffer, Rect) {
181        let a = Rect::new(0, 0, 9, 5);
182        let mut b = Buffer::empty(a);
183        b[(4, 2)].set_char('█').set_fg(Color::Rgb(255, 0, 255));
184        (b, a)
185    }
186
187    #[test]
188    fn glow_tints_neighbours_but_not_far_cells_or_glyphs() {
189        let (mut b, a) = buf_with_dot();
190        b[(5, 2)].set_char('x');
191        glow(&mut b, a, 2, 1.0);
192        assert!(matches!(b[(3, 2)].bg, Color::Rgb(r, 0, _) if r > 0));
193        assert_eq!(b[(5, 2)].bg, Color::Reset);
194        assert_eq!(b[(0, 0)].bg, Color::Reset);
195        assert!(matches!(b[(4, 1)].bg, Color::Rgb(..)));
196    }
197
198    #[test]
199    fn glow_noops_and_edges() {
200        let (mut b, a) = buf_with_dot();
201        let before = b.clone();
202        glow(&mut b, a, 0, 1.0);
203        glow(&mut b, a, 2, 0.0);
204        assert_eq!(b, before);
205        let mut e = Buffer::empty(Rect::new(0, 0, 2, 2));
206        e[(0, 0)].set_char('#').set_fg(Color::Red);
207        glow(&mut e, Rect::new(0, 0, 50, 50), 3, 1.0);
208    }
209
210    #[test]
211    fn scanlines_darken_odd_rows_only() {
212        let a = Rect::new(0, 0, 2, 3);
213        let mut b = Buffer::empty(a);
214        for y in 0..3 {
215            b[(0, y)].set_char('#').set_fg(Color::Rgb(200, 200, 200));
216        }
217        scanlines(&mut b, a, 0.5);
218        assert_eq!(b[(0, 0)].fg, Color::Rgb(200, 200, 200));
219        assert_eq!(b[(0, 1)].fg, Color::Rgb(100, 100, 100));
220        assert_eq!(b[(0, 2)].fg, Color::Rgb(200, 200, 200));
221    }
222
223    #[test]
224    fn fx_applies_after_widget_and_frames_render() {
225        let a = Rect::new(0, 0, 12, 5);
226        let mut b = Buffer::empty(a);
227        let w = crate::Spectrum::new([0.2, 0.9, 0.5]).block(chamfer_block(" fx "));
228        Fx::new(w).glow(1, 0.5).scanlines(0.3).render(a, &mut b);
229        assert_eq!(b[(0, 0)].symbol(), "╱");
230        let mut c = Buffer::empty(a);
231        bracket_block("t").render(a, &mut c);
232        assert_eq!(c[(0, 0)].symbol(), "┏");
233    }
234}