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                // Without an explicit background there is nothing to blend with
69                // (the terminal colour is unknown), so leave the cell alone.
70                if cell.bg == Color::Reset {
71                    continue;
72                }
73                let base = cell.bg;
74                let a = strength.clamp(0.0, 1.0) * (1.0 - dist / (f64::from(radius) + 1.0)) * 0.5;
75                cell.bg = mix(base, fg, a);
76            }
77        }
78    }
79}
80
81/// Darken every other row (`strength` `0..=1`), like a CRT scanline mask.
82pub fn scanlines(buf: &mut Buffer, area: Rect, strength: f64) {
83    let area = area.intersection(buf.area);
84    if strength <= 0.0 {
85        return;
86    }
87    for y in area.top()..area.bottom() {
88        if (y - area.top()) & 1 == 0 {
89            continue;
90        }
91        for x in area.left()..area.right() {
92            let c = &mut buf[(x, y)];
93            if c.fg != Color::Reset {
94                c.fg = darken(c.fg, strength);
95            }
96            if c.bg != Color::Reset {
97                c.bg = darken(c.bg, strength);
98            }
99        }
100    }
101}
102
103/// Wraps a widget and applies post effects after it renders.
104#[derive(Debug, Clone)]
105pub struct Fx<W> {
106    inner: W,
107    glow: Option<(u16, f64)>,
108    scan: Option<f64>,
109}
110
111impl<W> Fx<W> {
112    /// Wrap `inner` with no effects yet.
113    pub fn new(inner: W) -> Self {
114        Self {
115            inner,
116            glow: None,
117            scan: None,
118        }
119    }
120
121    /// Add a [`glow`] of `radius` cells and `strength` `0..=1`.
122    pub fn glow(mut self, radius: u16, strength: f64) -> Self {
123        self.glow = Some((radius, strength));
124        self
125    }
126
127    /// Add [`scanlines`] of `strength` `0..=1`.
128    pub fn scanlines(mut self, strength: f64) -> Self {
129        self.scan = Some(strength);
130        self
131    }
132}
133
134impl<W: Widget> Widget for Fx<W> {
135    fn render(self, area: Rect, buf: &mut Buffer) {
136        self.inner.render(area, buf);
137        if let Some((r, s)) = self.glow {
138            glow(buf, area, r, s);
139        }
140        if let Some(s) = self.scan {
141            scanlines(buf, area, s);
142        }
143    }
144}
145
146/// A frame with cut (chamfered) corners and a title.
147pub fn chamfer_block(title: &'static str) -> Block<'static> {
148    Block::new()
149        .borders(Borders::ALL)
150        .border_set(border::Set {
151            top_left: "╱",
152            top_right: "╲",
153            bottom_left: "╲",
154            bottom_right: "╱",
155            ..border::PLAIN
156        })
157        .title(title)
158}
159
160/// A frame with heavy corner brackets and light sides, like a HUD readout.
161pub fn bracket_block(title: &'static str) -> Block<'static> {
162    Block::new()
163        .borders(Borders::ALL)
164        .border_set(border::Set {
165            top_left: "┏",
166            top_right: "┓",
167            bottom_left: "┗",
168            bottom_right: "┛",
169            horizontal_top: "─",
170            horizontal_bottom: "─",
171            vertical_left: "│",
172            vertical_right: "│",
173        })
174        .title(title)
175}
176
177#[cfg(test)]
178mod tests {
179    use super::*;
180
181    fn buf_with_dot() -> (Buffer, Rect) {
182        let a = Rect::new(0, 0, 9, 5);
183        let mut b = Buffer::empty(a);
184        b.set_style(a, ratatui::style::Style::default().bg(Color::Rgb(0, 0, 0)));
185        b[(4, 2)].set_char('█').set_fg(Color::Rgb(255, 0, 255));
186        (b, a)
187    }
188
189    #[test]
190    fn glow_tints_neighbours_but_not_far_cells_or_glyphs() {
191        let (mut b, a) = buf_with_dot();
192        b[(5, 2)].set_char('x');
193        glow(&mut b, a, 2, 1.0);
194        assert!(matches!(b[(3, 2)].bg, Color::Rgb(r, 0, _) if r > 0));
195        assert_eq!(b[(5, 2)].bg, Color::Rgb(0, 0, 0));
196        assert_eq!(b[(0, 0)].bg, Color::Rgb(0, 0, 0));
197        assert!(matches!(b[(4, 1)].bg, Color::Rgb(..)));
198    }
199
200    #[test]
201    fn glow_leaves_unset_backgrounds_alone() {
202        let a = Rect::new(0, 0, 5, 3);
203        let mut b = Buffer::empty(a);
204        b[(2, 1)].set_char('█').set_fg(Color::Rgb(255, 0, 255));
205        glow(&mut b, a, 2, 1.0);
206        assert_eq!(b[(1, 1)].bg, Color::Reset);
207    }
208
209    #[test]
210    fn glow_noops_and_edges() {
211        let (mut b, a) = buf_with_dot();
212        let before = b.clone();
213        glow(&mut b, a, 0, 1.0);
214        glow(&mut b, a, 2, 0.0);
215        assert_eq!(b, before);
216        let mut e = Buffer::empty(Rect::new(0, 0, 2, 2));
217        e[(0, 0)].set_char('#').set_fg(Color::Red);
218        glow(&mut e, Rect::new(0, 0, 50, 50), 3, 1.0);
219    }
220
221    #[test]
222    fn scanlines_darken_odd_rows_only() {
223        let a = Rect::new(0, 0, 2, 3);
224        let mut b = Buffer::empty(a);
225        for y in 0..3 {
226            b[(0, y)].set_char('#').set_fg(Color::Rgb(200, 200, 200));
227        }
228        scanlines(&mut b, a, 0.5);
229        assert_eq!(b[(0, 0)].fg, Color::Rgb(200, 200, 200));
230        assert_eq!(b[(0, 1)].fg, Color::Rgb(100, 100, 100));
231        assert_eq!(b[(0, 2)].fg, Color::Rgb(200, 200, 200));
232    }
233
234    #[test]
235    fn fx_applies_after_widget_and_frames_render() {
236        let a = Rect::new(0, 0, 12, 5);
237        let mut b = Buffer::empty(a);
238        let w = crate::Spectrum::new([0.2, 0.9, 0.5]).block(chamfer_block(" fx "));
239        Fx::new(w).glow(1, 0.5).scanlines(0.3).render(a, &mut b);
240        assert_eq!(b[(0, 0)].symbol(), "╱");
241        let mut c = Buffer::empty(a);
242        bracket_block("t").render(a, &mut c);
243        assert_eq!(c[(0, 0)].symbol(), "┏");
244    }
245}