Skip to main content

weirdnet_chart/backend/
ratatui.rs

1//! A [Ratatui](https://crates.io/crates/ratatui) backend (feature `ratatui`).
2//!
3//! Charts are laid out in braille dots, two across and four down per terminal cell, and
4//! drawn into a [`Buffer`]. It builds on `ratatui-core`, so the widget works with `ratatui`
5//! 0.30 and any other crate built on it.
6//!
7//! ```
8//! use ratatui_core::{buffer::Buffer, layout::Rect, widgets::Widget};
9//! use weirdnet_chart::{Chart, Point, Rgba, ratatui::ChartWidget};
10//!
11//! let mut chart = Chart::new();
12//! let price = chart.add_line(Chart::MAIN, "price", Rgba::hex(0x42a5f5)).unwrap();
13//! for t in 0..100 {
14//!     chart.push_point(price, Point::new(t * 1000, (t as f64 / 9.0).sin())).unwrap();
15//! }
16//! chart.fit_all();
17//! let area = Rect::new(0, 0, 60, 16);
18//! let mut buf = Buffer::empty(area);
19//! ChartWidget::new(&chart).render(area, &mut buf);
20//! ```
21//!
22//! Pan and zoom by terminal columns with [`pan_columns`] and [`zoom_columns`].
23
24use ratatui_core::buffer::Buffer;
25use ratatui_core::layout::Rect as CellRect;
26use ratatui_core::style::Color;
27use ratatui_core::widgets::Widget;
28
29use crate::chart::Chart;
30use crate::color::Rgba;
31use crate::scene::{Align, Metrics, Pos, Primitive, Rect, Scene, Size};
32
33/// Layout metrics in braille dots: a character is 2 dots wide and 4 high.
34pub const METRICS: Metrics = Metrics { char_width: 2.0, line_height: 4.0, padding: 1.0, min_stroke: 1.0 };
35
36/// Draws a [`Chart`] with braille dots.
37#[derive(Clone, Copy, Debug)]
38pub struct ChartWidget<'a> {
39    chart: &'a Chart,
40}
41
42impl<'a> ChartWidget<'a> {
43    /// A widget for `chart`.
44    pub fn new(chart: &'a Chart) -> ChartWidget<'a> {
45        ChartWidget { chart }
46    }
47}
48
49impl Widget for ChartWidget<'_> {
50    fn render(self, area: CellRect, buf: &mut Buffer) {
51        (&self).render(area, buf);
52    }
53}
54
55impl Widget for &ChartWidget<'_> {
56    fn render(self, area: CellRect, buf: &mut Buffer) {
57        let scene = scene_for(self.chart, area);
58        render_scene(&scene, area, buf);
59    }
60}
61
62/// Lays `chart` out for a terminal `area`, in dots.
63pub fn scene_for(chart: &Chart, area: CellRect) -> Scene {
64    chart.layout(Size::new(area.width as f32 * 2.0, area.height as f32 * 4.0), &METRICS)
65}
66
67/// Pans `chart` as if dragged `columns` cells to the right (negative pans towards newer data)
68/// when drawn in `area`.
69pub fn pan_columns(chart: &mut Chart, area: CellRect, columns: i32) {
70    let plot = scene_for(chart, area).plot;
71    chart.pan_pixels(columns as f64 * 2.0, plot.w as f64);
72}
73
74/// Zooms `chart` by `factor` (below 1 zooms in) around terminal column `column` of `area`.
75pub fn zoom_columns(chart: &mut Chart, area: CellRect, factor: f64, column: u16) {
76    let plot = scene_for(chart, area).plot;
77    let x = (column.saturating_sub(area.x) as f64 * 2.0 - plot.x as f64).clamp(0.0, plot.w as f64);
78    chart.zoom_at(factor, x, plot.w as f64);
79}
80
81const BRAILLE_BASE: u32 = 0x2800;
82// Dot bit for (column 0..2, row 0..4) within a cell.
83const DOT_BITS: [[u8; 4]; 2] = [[0x01, 0x02, 0x04, 0x40], [0x08, 0x10, 0x20, 0x80]];
84
85#[derive(Clone, Copy, Default)]
86struct DotCell {
87    bits: u8,
88    fg: Option<Rgba>,
89    bg: Option<Rgba>,
90    text: Option<(char, Rgba)>,
91}
92
93struct Raster {
94    w: i32,
95    h: i32,
96    cells: Vec<DotCell>,
97    backdrop: Rgba,
98}
99
100impl Raster {
101    fn cell(&mut self, cx: i32, cy: i32) -> Option<&mut DotCell> {
102        if cx < 0 || cy < 0 || cx >= self.w || cy >= self.h {
103            return None;
104        }
105        self.cells.get_mut((cy * self.w + cx) as usize)
106    }
107
108    fn dot(&mut self, x: i32, y: i32, color: Rgba, clip: Option<(i32, i32, i32, i32)>) {
109        if let Some((x0, y0, x1, y1)) = clip
110            && (x < x0 || x > x1 || y < y0 || y > y1)
111        {
112            return;
113        }
114        if x < 0 || y < 0 {
115            return;
116        }
117        let color = if color.a < 1.0 { color.over(self.backdrop) } else { color };
118        if let Some(c) = self.cell(x / 2, y / 4) {
119            c.bits |= DOT_BITS[(x % 2) as usize][(y % 4) as usize];
120            c.fg = Some(color);
121            c.text = None;
122        }
123    }
124
125    fn line(&mut self, a: Pos, b: Pos, color: Rgba, dashed: bool, clip: Option<(i32, i32, i32, i32)>) {
126        let (mut x0, mut y0) = (a.x.round() as i32, a.y.round() as i32);
127        let (x1, y1) = (b.x.round() as i32, b.y.round() as i32);
128        let (dx, dy) = ((x1 - x0).abs(), -(y1 - y0).abs());
129        let (sx, sy) = (if x0 < x1 { 1 } else { -1 }, if y0 < y1 { 1 } else { -1 });
130        let mut err = dx + dy;
131        let mut step = 0;
132        loop {
133            if !dashed || step % 3 == 0 {
134                self.dot(x0, y0, color, clip);
135            }
136            step += 1;
137            if (x0 == x1 && y0 == y1) || step > 100_000 {
138                break;
139            }
140            let e2 = 2 * err;
141            if e2 >= dy {
142                err += dy;
143                x0 += sx;
144            }
145            if e2 <= dx {
146                err += dx;
147                y0 += sy;
148            }
149        }
150    }
151
152    fn fill(&mut self, r: Rect, color: Rgba, clip: Option<(i32, i32, i32, i32)>) {
153        let x0 = r.x.round() as i32;
154        let x1 = ((r.right().round() as i32) - 1).max(x0);
155        let y0 = r.y.round() as i32;
156        let y1 = ((r.bottom().round() as i32) - 1).max(y0);
157        for y in y0..=y1.min(y0 + 4096) {
158            for x in x0..=x1.min(x0 + 4096) {
159                self.dot(x, y, color, clip);
160            }
161        }
162    }
163
164    fn background(&mut self, r: Rect, color: Rgba) {
165        let color = if color.a < 1.0 { color.over(self.backdrop) } else { color };
166        let cx0 = (r.x / 2.0).floor() as i32;
167        let cx1 = (r.right() / 2.0).ceil() as i32;
168        let cy0 = (r.y / 4.0).round() as i32;
169        let cy1 = ((r.bottom() / 4.0).round() as i32).max(cy0 + 1);
170        for cy in cy0..cy1 {
171            for cx in cx0..cx1 {
172                if let Some(c) = self.cell(cx, cy) {
173                    c.bg = Some(color);
174                }
175            }
176        }
177    }
178
179    fn text(&mut self, pos: Pos, text: &str, color: Rgba, h: Align, v: Align) {
180        let len = text.chars().count() as i32;
181        let col = match h {
182            Align::Start => (pos.x / 2.0).ceil() as i32,
183            Align::Center => (pos.x / 2.0).round() as i32 - len / 2,
184            Align::End => (pos.x / 2.0).floor() as i32 - len,
185        };
186        let row = match v {
187            Align::Start => (pos.y / 4.0).ceil() as i32,
188            Align::Center => (pos.y / 4.0).floor() as i32,
189            Align::End => (pos.y / 4.0).floor() as i32 - 1,
190        };
191        for (i, ch) in text.chars().enumerate() {
192            if let Some(c) = self.cell(col + i as i32, row) {
193                c.text = Some((ch, color));
194                c.bits = 0;
195            }
196        }
197    }
198}
199
200fn to_color(c: Rgba) -> Color {
201    let (r, g, b) = c.to_rgb8();
202    Color::Rgb(r, g, b)
203}
204
205/// Draws a scene laid out in dots (see [`scene_for`]) into `area` of `buf`.
206///
207/// Rectangles in unclipped layers (the background and last-value tags) become cell
208/// backgrounds; everything else is drawn with braille dots or text.
209pub fn render_scene(scene: &Scene, area: CellRect, buf: &mut Buffer) {
210    let area = area.intersection(buf.area);
211    if area.is_empty() {
212        return;
213    }
214    let backdrop = if scene.background.a >= 1.0 { scene.background } else { Rgba::hex(0x000000) };
215    let mut r =
216        Raster { w: area.width as i32, h: area.height as i32, cells: vec![DotCell::default(); area.width as usize * area.height as usize], backdrop };
217    for layer in &scene.layers {
218        let clip = layer.clip.map(|c| (c.x.round() as i32, c.y.round() as i32, c.right().round() as i32, c.bottom().round() as i32));
219        for p in &layer.primitives {
220            match p {
221                Primitive::Rect { rect, color } if layer.clip.is_none() => r.background(*rect, *color),
222                Primitive::Rect { rect, color } => r.fill(*rect, *color, clip),
223                Primitive::Line { from, to, color, dashed, .. } => r.line(*from, *to, *color, *dashed, clip),
224                Primitive::Polyline { points, color, .. } => {
225                    for w in points.windows(2) {
226                        r.line(w[0], w[1], *color, false, clip);
227                    }
228                }
229                Primitive::Area { points, baseline, color } => {
230                    for w in points.windows(2) {
231                        let (a, b) = (w[0], w[1]);
232                        let (xa, xb) = (a.x.round() as i32, b.x.round() as i32);
233                        for x in xa..xb.min(xa + 4096) {
234                            let t = if xb == xa { 0.0 } else { (x - xa) as f32 / (xb - xa) as f32 };
235                            let y = a.y + (b.y - a.y) * t;
236                            r.line(Pos::new(x as f32, y), Pos::new(x as f32, *baseline), *color, false, clip);
237                        }
238                    }
239                }
240                Primitive::Text { pos, text, color, h_align, v_align } => r.text(*pos, text, *color, *h_align, *v_align),
241            }
242        }
243    }
244    for cy in 0..r.h {
245        for cx in 0..r.w {
246            let c = r.cells[(cy * r.w + cx) as usize];
247            let Some(cell) = buf.cell_mut((area.x + cx as u16, area.y + cy as u16)) else { continue };
248            if let Some(bg) = c.bg {
249                cell.bg = to_color(bg);
250            }
251            if let Some((ch, fg)) = c.text {
252                cell.set_char(ch);
253                cell.fg = to_color(fg);
254            } else if c.bits != 0 {
255                cell.set_char(char::from_u32(BRAILLE_BASE + c.bits as u32).unwrap_or(' '));
256                if let Some(fg) = c.fg {
257                    cell.fg = to_color(fg);
258                }
259            }
260        }
261    }
262}
263
264#[cfg(test)]
265mod tests {
266    use super::*;
267    use crate::{Candle, Pane, Point, YRange, time::MINUTE};
268    use ratatui_core::backend::TestBackend;
269    use ratatui_core::terminal::Terminal;
270
271    fn lines(buf: &Buffer) -> Vec<String> {
272        (0..buf.area.height).map(|y| (0..buf.area.width).map(|x| buf[(x, y)].symbol().to_string()).collect()).collect()
273    }
274
275    #[test]
276    fn draws_candles_volume_and_axes_on_a_test_backend() {
277        let mut chart = Chart::new();
278        let c = chart.add_candles(Chart::MAIN, "XYZ").unwrap();
279        let vp = chart.add_pane(Pane { weight: 1.0, y_range: YRange::AutoFromZero, title: None });
280        chart.add_volume(vp, c).unwrap();
281        for i in 0..40 {
282            let o = 100.0 + i as f64;
283            chart.push_candle(c, Candle::new(i * MINUTE, o, o + 3.0, o - 2.0, if i % 2 == 0 { o + 2.0 } else { o - 1.0 }, 5.0 + i as f64)).unwrap();
284        }
285        chart.fit_all();
286        let mut term = Terminal::new(TestBackend::new(70, 20)).unwrap();
287        term.draw(|f| f.render_widget(ChartWidget::new(&chart), f.area())).unwrap();
288        let buf = term.backend().buffer();
289        let text = lines(buf).join("\n");
290        assert!(text.chars().any(|ch| ('\u{2801}'..='\u{28ff}').contains(&ch)), "{text}");
291        assert!(text.contains("00:"), "time labels:\n{text}");
292        assert!(text.contains("130") && text.contains("138"), "price labels and the last-value tag:\n{text}");
293        // Rising and falling candles use the theme colours.
294        let up = to_color(chart.theme().up);
295        let down = to_color(chart.theme().down);
296        let fgs: Vec<Color> = buf.content().iter().map(|c| c.fg).collect();
297        assert!(fgs.contains(&up) && fgs.contains(&down));
298        // The last-value tag has a background.
299        assert!(buf.content().iter().any(|c| c.bg == up || c.bg == down));
300    }
301
302    #[test]
303    fn line_chart_snapshot_is_stable() {
304        let mut chart = Chart::new();
305        let id = chart.add_line(Chart::MAIN, "p", Rgba::hex(0xffffff)).unwrap();
306        for t in 0..=60 {
307            chart.push_point(id, Point::new(t * 1000, t as f64)).unwrap();
308        }
309        chart.viewport_mut().set_right_margin(0.0);
310        chart.fit_all();
311        let area = CellRect::new(0, 0, 40, 10);
312        let mut a = Buffer::empty(area);
313        ChartWidget::new(&chart).render(area, &mut a);
314        let mut b = Buffer::empty(area);
315        (&ChartWidget::new(&chart)).render(area, &mut b);
316        assert_eq!(a, b);
317        let rows = lines(&a);
318        // A rising line: the top row's braille sits further right than the bottom row's.
319        let first_dot = |row: &str| row.chars().position(|ch| ('\u{2801}'..='\u{28ff}').contains(&ch));
320        let top = rows.iter().find_map(|r| first_dot(r)).unwrap();
321        let bottom = rows.iter().rev().find_map(|r| first_dot(r)).unwrap();
322        assert!(top >= bottom, "{rows:#?}");
323    }
324
325    #[test]
326    fn pan_and_zoom_by_columns() {
327        let mut chart = Chart::new();
328        let id = chart.add_line(Chart::MAIN, "p", Rgba::hex(0xffffff)).unwrap();
329        for t in 0..=100 {
330            chart.push_point(id, Point::new(t * 1000, 0.0)).unwrap();
331        }
332        chart.fit_all();
333        let area = CellRect::new(0, 0, 60, 10);
334        let span = chart.viewport().span();
335        pan_columns(&mut chart, area, 10);
336        assert!(!chart.viewport().is_following());
337        zoom_columns(&mut chart, area, 0.5, 20);
338        assert!((chart.viewport().span() - span / 2).abs() <= 1);
339        // Tiny areas draw nothing and don't panic.
340        let tiny = CellRect::new(0, 0, 3, 2);
341        let mut buf = Buffer::empty(tiny);
342        ChartWidget::new(&chart).render(tiny, &mut buf);
343    }
344}