Skip to main content

tui_chart/
canvas.rs

1//! Sub-cell resolution drawing surface used by the line/area/scatter chart.
2
3use ratatui::{buffer::Buffer, layout::Rect, style::Color};
4
5/// Glyph family used to draw plotted points.
6#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
7#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
8pub enum Marker {
9    /// Braille patterns: 2×4 dots per cell (highest resolution).
10    #[default]
11    Braille,
12    /// Half blocks `▀▄█`: 1×2 per cell.
13    HalfBlock,
14    /// Full block `█`: 1×1 per cell.
15    Block,
16    /// Bullet `•`: 1×1 per cell.
17    Dot,
18    /// Sextants (Unicode "Symbols for Legacy Computing", U+1FB00..U+1FB3B):
19    /// 2×3 dots per cell.
20    ///
21    /// Font caveat: many terminal fonts lack these glyphs (they render as
22    /// tofu or blanks), so this marker is opt-in. Braille is the default.
23    Sextant,
24}
25
26/// Which colour wins when several dots with different colours share a cell.
27#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
28#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
29pub enum OverlapPolicy {
30    /// The most recently set dot decides the cell colour (default).
31    #[default]
32    LastWins,
33    /// The first dot set in a cell keeps its colour.
34    FirstWins,
35}
36
37impl Marker {
38    /// All markers in cycle order.
39    pub const ALL: [Marker; 5] = [
40        Marker::Braille,
41        Marker::HalfBlock,
42        Marker::Block,
43        Marker::Dot,
44        Marker::Sextant,
45    ];
46
47    /// Next marker in [`Marker::ALL`] (wraps); handy for demo key bindings.
48    pub fn next(self) -> Marker {
49        let i = Self::ALL.iter().position(|m| *m == self).unwrap_or(0);
50        Self::ALL[(i + 1) % Self::ALL.len()]
51    }
52
53    /// Dots (x, y) per terminal cell.
54    pub fn resolution(self) -> (u16, u16) {
55        match self {
56            Marker::Braille => (2, 4),
57            Marker::HalfBlock => (1, 2),
58            Marker::Block | Marker::Dot => (1, 1),
59            Marker::Sextant => (2, 3),
60        }
61    }
62
63    fn glyph(self, mask: u8) -> char {
64        match self {
65            Marker::Braille => char::from_u32(0x2800 + mask as u32).unwrap_or(' '),
66            Marker::HalfBlock => [' ', '▀', '▄', '█'][(mask & 3) as usize],
67            Marker::Block => '█',
68            Marker::Dot => '•',
69            Marker::Sextant => match mask & 63 {
70                0 => ' ',
71                21 => '▌',
72                42 => '▐',
73                63 => '█',
74                m => {
75                    let m = m as u32;
76                    let skipped = (m > 21) as u32 + (m > 42) as u32;
77                    char::from_u32(0x1FB00 + m - 1 - skipped).unwrap_or(' ')
78                }
79            },
80        }
81    }
82
83    fn bit(self, dx: u16, dy: u16) -> u8 {
84        match self {
85            Marker::Braille => {
86                const BITS: [[u8; 4]; 2] = [[0x01, 0x02, 0x04, 0x40], [0x08, 0x10, 0x20, 0x80]];
87                BITS[dx as usize][dy as usize]
88            }
89            Marker::HalfBlock => 1 << dy,
90            Marker::Block | Marker::Dot => 1,
91            Marker::Sextant => 1 << (dy * 2 + dx),
92        }
93    }
94}
95
96/// A pixel canvas where each terminal cell holds several dots.
97#[derive(Debug, Clone)]
98pub struct Canvas {
99    w: u16,
100    h: u16,
101    marker: Marker,
102    overlap: OverlapPolicy,
103    mask: Vec<u8>,
104    color: Vec<Color>,
105}
106
107impl Canvas {
108    /// Create a canvas covering `w × h` terminal cells.
109    pub fn new(w: u16, h: u16, marker: Marker) -> Self {
110        let n = w as usize * h as usize;
111        Self {
112            w,
113            h,
114            marker,
115            overlap: OverlapPolicy::default(),
116            mask: vec![0; n],
117            color: vec![Color::Reset; n],
118        }
119    }
120
121    /// Set the per-cell colour policy for overlapping dots.
122    pub fn set_overlap(&mut self, policy: OverlapPolicy) {
123        self.overlap = policy;
124    }
125
126    setter!(
127        /// Builder form of [`Canvas::set_overlap`].
128        with_overlap => overlap: OverlapPolicy
129    );
130
131    /// Marker of this canvas.
132    pub fn marker(&self) -> Marker {
133        self.marker
134    }
135
136    /// Width in dots.
137    pub fn px_w(&self) -> i32 {
138        self.w as i32 * self.marker.resolution().0 as i32
139    }
140
141    /// Height in dots.
142    pub fn px_h(&self) -> i32 {
143        self.h as i32 * self.marker.resolution().1 as i32
144    }
145
146    /// Set one dot. Out-of-range coordinates are ignored.
147    pub fn set(&mut self, px: i32, py: i32, color: Color) {
148        if px < 0 || py < 0 || px >= self.px_w() || py >= self.px_h() {
149            return;
150        }
151        let (rx, ry) = self.marker.resolution();
152        let (cx, cy) = (px as u16 / rx, py as u16 / ry);
153        let (dx, dy) = (px as u16 % rx, py as u16 % ry);
154        let i = cy as usize * self.w as usize + cx as usize;
155        let was_empty = self.mask[i] == 0;
156        self.mask[i] |= self.marker.bit(dx, dy);
157        if was_empty || self.overlap == OverlapPolicy::LastWins {
158            self.color[i] = color;
159        }
160    }
161
162    /// Whether a dot is set.
163    pub fn is_set(&self, px: i32, py: i32) -> bool {
164        if px < 0 || py < 0 || px >= self.px_w() || py >= self.px_h() {
165            return false;
166        }
167        let (rx, ry) = self.marker.resolution();
168        let i = (py as u16 / ry) as usize * self.w as usize + (px as u16 / rx) as usize;
169        self.mask[i] & self.marker.bit(px as u16 % rx, py as u16 % ry) != 0
170    }
171
172    /// A slightly bigger point (2×2 dots on braille) for scatter plots.
173    pub fn blob(&mut self, px: i32, py: i32, color: Color) {
174        self.set(px, py, color);
175        if matches!(self.marker, Marker::Braille | Marker::Sextant) {
176            self.set(px + 1, py, color);
177            self.set(px, py + 1, color);
178            self.set(px + 1, py + 1, color);
179        }
180    }
181
182    /// Bresenham line between two dots. Segments leaving the canvas are
183    /// clipped first, so cost is bounded by the canvas size, not by the
184    /// (possibly huge) coordinates.
185    pub fn line(&mut self, x0: i32, y0: i32, x1: i32, y1: i32, color: Color) {
186        let (w, h) = (self.px_w(), self.px_h());
187        if w == 0 || h == 0 {
188            return;
189        }
190        let inside = |x: i32, y: i32| x >= 0 && y >= 0 && x < w && y < h;
191        let (mut x0, mut y0, mut x1, mut y1) = (x0 as i64, y0 as i64, x1 as i64, y1 as i64);
192        if !(inside(x0 as i32, y0 as i32) && inside(x1 as i32, y1 as i32)) {
193            match clip_segment(x0, y0, x1, y1, w as i64 - 1, h as i64 - 1) {
194                Some((a, b, c, d)) => (x0, y0, x1, y1) = (a, b, c, d),
195                None => return,
196            }
197        }
198        // Fast paths: horizontal / vertical runs.
199        if y0 == y1 {
200            for x in x0.min(x1)..=x0.max(x1) {
201                self.set(x as i32, y0 as i32, color);
202            }
203            return;
204        }
205        if x0 == x1 {
206            for y in y0.min(y1)..=y0.max(y1) {
207                self.set(x0 as i32, y as i32, color);
208            }
209            return;
210        }
211        let dx = (x1 - x0).abs();
212        let dy = -(y1 - y0).abs();
213        let sx = if x0 < x1 { 1 } else { -1 };
214        let sy = if y0 < y1 { 1 } else { -1 };
215        let mut err = dx + dy;
216        loop {
217            self.set(x0 as i32, y0 as i32, color);
218            if x0 == x1 && y0 == y1 {
219                break;
220            }
221            let e2 = 2 * err;
222            if e2 >= dy {
223                err += dy;
224                x0 += sx;
225            }
226            if e2 <= dx {
227                err += dx;
228                y0 += sy;
229            }
230        }
231    }
232
233    /// Paint non-empty cells into `buf` at `origin` (top-left of the plot area).
234    pub fn render(&self, buf: &mut Buffer, origin: Rect) {
235        for cy in 0..self.h.min(origin.height) {
236            for cx in 0..self.w.min(origin.width) {
237                let i = cy as usize * self.w as usize + cx as usize;
238                if self.mask[i] == 0 {
239                    continue;
240                }
241                if let Some(cell) = buf.cell_mut((origin.x + cx, origin.y + cy)) {
242                    cell.set_char(self.marker.glyph(self.mask[i]));
243                    cell.set_fg(self.color[i]);
244                }
245            }
246        }
247    }
248}
249
250/// Liang-Barsky clip of a segment to `[0, xmax] x [0, ymax]`; endpoints are
251/// rounded back to dots.
252fn clip_segment(
253    x0: i64,
254    y0: i64,
255    x1: i64,
256    y1: i64,
257    xmax: i64,
258    ymax: i64,
259) -> Option<(i64, i64, i64, i64)> {
260    let (dx, dy) = ((x1 - x0) as f64, (y1 - y0) as f64);
261    let (mut t0, mut t1) = (0f64, 1f64);
262    for (p, q) in [
263        (-dx, x0 as f64),
264        (dx, (xmax - x0) as f64),
265        (-dy, y0 as f64),
266        (dy, (ymax - y0) as f64),
267    ] {
268        if p == 0.0 {
269            if q < 0.0 {
270                return None;
271            }
272        } else {
273            let r = q / p;
274            if p < 0.0 {
275                t0 = t0.max(r);
276            } else {
277                t1 = t1.min(r);
278            }
279            if t0 > t1 {
280                return None;
281            }
282        }
283    }
284    let pt = |t: f64| {
285        (
286            (x0 as f64 + t * dx).round().clamp(0.0, xmax as f64) as i64,
287            (y0 as f64 + t * dy).round().clamp(0.0, ymax as f64) as i64,
288        )
289    };
290    let (a, b) = pt(t0);
291    let (c, d) = pt(t1);
292    Some((a, b, c, d))
293}
294
295#[cfg(test)]
296mod tests {
297    use super::*;
298
299    #[test]
300    fn resolution_per_marker() {
301        assert_eq!(Marker::Braille.resolution(), (2, 4));
302        assert_eq!(Marker::HalfBlock.resolution(), (1, 2));
303        assert_eq!(Marker::Block.resolution(), (1, 1));
304        assert_eq!(Marker::Dot.resolution(), (1, 1));
305        assert_eq!(Marker::Sextant.resolution(), (2, 3));
306    }
307
308    #[test]
309    fn marker_cycle_wraps() {
310        let mut m = Marker::Braille;
311        for _ in 0..Marker::ALL.len() {
312            m = m.next();
313        }
314        assert_eq!(m, Marker::Braille);
315    }
316
317    #[test]
318    fn sextant_glyphs() {
319        let g = |m: u8| Marker::Sextant.glyph(m);
320        assert_eq!(g(0), ' ');
321        assert_eq!(g(1), '\u{1FB00}');
322        assert_eq!(g(20), '\u{1FB13}');
323        assert_eq!(g(21), '▌');
324        assert_eq!(g(22), '\u{1FB14}');
325        assert_eq!(g(42), '▐');
326        assert_eq!(g(43), '\u{1FB28}');
327        assert_eq!(g(62), '\u{1FB3B}');
328        assert_eq!(g(63), '█');
329        let mut c = Canvas::new(1, 1, Marker::Sextant);
330        assert_eq!((c.px_w(), c.px_h()), (2, 3));
331        for y in 0..3 {
332            c.set(0, y, Color::Red);
333        }
334        let mut buf = Buffer::empty(Rect::new(0, 0, 1, 1));
335        c.render(&mut buf, Rect::new(0, 0, 1, 1));
336        assert_eq!(buf[(0, 0)].symbol(), "▌");
337    }
338
339    #[test]
340    fn overlap_policy() {
341        let mut c = Canvas::new(1, 1, Marker::Braille);
342        c.set(0, 0, Color::Red);
343        c.set(1, 0, Color::Blue);
344        let mut buf = Buffer::empty(Rect::new(0, 0, 1, 1));
345        c.render(&mut buf, Rect::new(0, 0, 1, 1));
346        assert_eq!(buf[(0, 0)].fg, Color::Blue);
347        let mut c = Canvas::new(1, 1, Marker::Braille);
348        c.set_overlap(OverlapPolicy::FirstWins);
349        c.set(0, 0, Color::Red);
350        c.set(1, 0, Color::Blue);
351        c.render(&mut buf, Rect::new(0, 0, 1, 1));
352        assert_eq!(buf[(0, 0)].fg, Color::Red);
353    }
354
355    #[test]
356    fn set_and_query() {
357        let mut c = Canvas::new(4, 2, Marker::Braille);
358        assert_eq!((c.px_w(), c.px_h()), (8, 8));
359        c.set(3, 5, Color::Red);
360        assert!(c.is_set(3, 5));
361        assert!(!c.is_set(2, 5));
362        c.set(-1, 0, Color::Red);
363        c.set(8, 0, Color::Red);
364        assert!(!c.is_set(8, 0));
365    }
366
367    #[test]
368    fn braille_glyph() {
369        let mut c = Canvas::new(1, 1, Marker::Braille);
370        c.set(0, 0, Color::Red);
371        let mut buf = Buffer::empty(Rect::new(0, 0, 1, 1));
372        c.render(&mut buf, Rect::new(0, 0, 1, 1));
373        assert_eq!(buf[(0, 0)].symbol(), "\u{2801}");
374        c.set(1, 3, Color::Red);
375        c.render(&mut buf, Rect::new(0, 0, 1, 1));
376        assert_eq!(buf[(0, 0)].symbol(), "\u{2881}");
377    }
378
379    #[test]
380    fn half_block_glyph() {
381        let mut c = Canvas::new(1, 1, Marker::HalfBlock);
382        let mut buf = Buffer::empty(Rect::new(0, 0, 1, 1));
383        c.set(0, 0, Color::Red);
384        c.render(&mut buf, Rect::new(0, 0, 1, 1));
385        assert_eq!(buf[(0, 0)].symbol(), "▀");
386        c.set(0, 1, Color::Red);
387        c.render(&mut buf, Rect::new(0, 0, 1, 1));
388        assert_eq!(buf[(0, 0)].symbol(), "█");
389    }
390
391    #[test]
392    fn huge_offscreen_line_is_fast_and_clipped() {
393        let mut c = Canvas::new(10, 5, Marker::Braille);
394        c.line(-2_000_000_000, 10, 2_000_000_000, 10, Color::Red);
395        assert!(c.is_set(0, 10) && c.is_set(19, 10));
396        c.line(
397            -2_000_000_000,
398            -2_000_000_000,
399            2_000_000_000,
400            2_000_000_000,
401            Color::Red,
402        );
403        assert!(c.is_set(0, 0) && c.is_set(19, 19));
404        let mut d = Canvas::new(10, 5, Marker::Braille);
405        d.line(-100, -100, -50, 200, Color::Red); // fully outside
406        assert!((0..20).all(|y| (0..20).all(|x| !d.is_set(x, y))));
407    }
408
409    #[test]
410    fn line_connects_endpoints() {
411        let mut c = Canvas::new(10, 5, Marker::Braille);
412        c.line(0, 0, 19, 19, Color::Green);
413        assert!(c.is_set(0, 0));
414        assert!(c.is_set(19, 19));
415        assert!(c.is_set(10, 10));
416    }
417
418    #[test]
419    fn line_with_huge_coords_terminates() {
420        let mut c = Canvas::new(4, 4, Marker::Block);
421        c.line(-10_000, -10_000, 10_000, 10_000, Color::Green);
422        assert!(c.is_set(2, 2));
423    }
424
425    #[test]
426    fn blob_is_bigger_on_braille() {
427        let mut c = Canvas::new(2, 2, Marker::Braille);
428        c.blob(1, 1, Color::Red);
429        assert!(c.is_set(2, 2));
430        let mut d = Canvas::new(2, 2, Marker::Block);
431        d.blob(1, 1, Color::Red);
432        assert!(!d.is_set(0, 0));
433    }
434}