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/// `.glow(..)` / `.scanlines(..)` on any widget, so effects read like any other builder call:
104///
105/// ```
106/// use tui_chart::{FxExt, Spectrum};
107///
108/// let chart = Spectrum::new([0.2, 0.9, 0.5]).glow(1, 0.25).scanlines(0.15);
109/// # let _ = chart;
110/// ```
111pub trait FxExt: Widget + Sized {
112    /// Wrap in an [`Fx`] with a [`glow`] of `radius` cells and `strength`.
113    fn glow(self, radius: u16, strength: f64) -> Fx<Self> {
114        Fx::new(self).glow(radius, strength)
115    }
116
117    /// Wrap in an [`Fx`] with [`scanlines`] of `strength`.
118    fn scanlines(self, strength: f64) -> Fx<Self> {
119        Fx::new(self).scanlines(strength)
120    }
121}
122
123impl<W: Widget> FxExt for W {}
124
125/// Wraps a widget and applies post effects after it renders.
126#[derive(Debug, Clone)]
127pub struct Fx<W> {
128    inner: W,
129    glow: Option<(u16, f64)>,
130    scan: Option<f64>,
131}
132
133impl<W> Fx<W> {
134    /// Wrap `inner` with no effects yet.
135    pub fn new(inner: W) -> Self {
136        Self {
137            inner,
138            glow: None,
139            scan: None,
140        }
141    }
142
143    /// Add a [`glow`] of `radius` cells and `strength` `0..=1`.
144    pub fn glow(mut self, radius: u16, strength: f64) -> Self {
145        self.glow = Some((radius, strength));
146        self
147    }
148
149    /// Add [`scanlines`] of `strength` `0..=1`.
150    pub fn scanlines(mut self, strength: f64) -> Self {
151        self.scan = Some(strength);
152        self
153    }
154}
155
156impl<W: Widget> Widget for Fx<W> {
157    fn render(self, area: Rect, buf: &mut Buffer) {
158        self.inner.render(area, buf);
159        if let Some((r, s)) = self.glow {
160            glow(buf, area, r, s);
161        }
162        if let Some(s) = self.scan {
163            scanlines(buf, area, s);
164        }
165    }
166}
167
168/// A frame with cut (chamfered) corners and a title.
169pub fn chamfer_block(title: &'static str) -> Block<'static> {
170    Block::new()
171        .borders(Borders::ALL)
172        .border_set(border::Set {
173            top_left: "╱",
174            top_right: "╲",
175            bottom_left: "╲",
176            bottom_right: "╱",
177            ..border::PLAIN
178        })
179        .title(title)
180}
181
182/// A frame with heavy corner brackets and light sides, like a HUD readout.
183pub fn bracket_block(title: &'static str) -> Block<'static> {
184    Block::new()
185        .borders(Borders::ALL)
186        .border_set(border::Set {
187            top_left: "┏",
188            top_right: "┓",
189            bottom_left: "┗",
190            bottom_right: "┛",
191            horizontal_top: "─",
192            horizontal_bottom: "─",
193            vertical_left: "│",
194            vertical_right: "│",
195        })
196        .title(title)
197}
198
199#[cfg(test)]
200mod tests {
201    use super::*;
202
203    fn buf_with_dot() -> (Buffer, Rect) {
204        let a = Rect::new(0, 0, 9, 5);
205        let mut b = Buffer::empty(a);
206        b.set_style(a, ratatui::style::Style::default().bg(Color::Rgb(0, 0, 0)));
207        b[(4, 2)].set_char('█').set_fg(Color::Rgb(255, 0, 255));
208        (b, a)
209    }
210
211    #[test]
212    fn glow_tints_neighbours_but_not_far_cells_or_glyphs() {
213        let (mut b, a) = buf_with_dot();
214        b[(5, 2)].set_char('x');
215        glow(&mut b, a, 2, 1.0);
216        assert!(matches!(b[(3, 2)].bg, Color::Rgb(r, 0, _) if r > 0));
217        assert_eq!(b[(5, 2)].bg, Color::Rgb(0, 0, 0));
218        assert_eq!(b[(0, 0)].bg, Color::Rgb(0, 0, 0));
219        assert!(matches!(b[(4, 1)].bg, Color::Rgb(..)));
220    }
221
222    #[test]
223    fn glow_leaves_unset_backgrounds_alone() {
224        let a = Rect::new(0, 0, 5, 3);
225        let mut b = Buffer::empty(a);
226        b[(2, 1)].set_char('█').set_fg(Color::Rgb(255, 0, 255));
227        glow(&mut b, a, 2, 1.0);
228        assert_eq!(b[(1, 1)].bg, Color::Reset);
229    }
230
231    #[test]
232    fn glow_noops_and_edges() {
233        let (mut b, a) = buf_with_dot();
234        let before = b.clone();
235        glow(&mut b, a, 0, 1.0);
236        glow(&mut b, a, 2, 0.0);
237        assert_eq!(b, before);
238        let mut e = Buffer::empty(Rect::new(0, 0, 2, 2));
239        e[(0, 0)].set_char('#').set_fg(Color::Red);
240        glow(&mut e, Rect::new(0, 0, 50, 50), 3, 1.0);
241    }
242
243    #[test]
244    fn scanlines_darken_odd_rows_only() {
245        let a = Rect::new(0, 0, 2, 3);
246        let mut b = Buffer::empty(a);
247        for y in 0..3 {
248            b[(0, y)].set_char('#').set_fg(Color::Rgb(200, 200, 200));
249        }
250        scanlines(&mut b, a, 0.5);
251        assert_eq!(b[(0, 0)].fg, Color::Rgb(200, 200, 200));
252        assert_eq!(b[(0, 1)].fg, Color::Rgb(100, 100, 100));
253        assert_eq!(b[(0, 2)].fg, Color::Rgb(200, 200, 200));
254    }
255
256    #[test]
257    fn fx_applies_after_widget_and_frames_render() {
258        let a = Rect::new(0, 0, 12, 5);
259        let mut b = Buffer::empty(a);
260        let w = crate::Spectrum::new([0.2, 0.9, 0.5]).block(chamfer_block(" fx "));
261        Fx::new(w).glow(1, 0.5).scanlines(0.3).render(a, &mut b);
262        assert_eq!(b[(0, 0)].symbol(), "╱");
263        let mut c = Buffer::empty(a);
264        bracket_block("t").render(a, &mut c);
265        assert_eq!(c[(0, 0)].symbol(), "┏");
266    }
267}