Skip to main content

cellix_render/
grid.rs

1use compact_str::CompactString;
2use unicode_segmentation::UnicodeSegmentation;
3use unicode_width::UnicodeWidthStr;
4
5use crate::icon::{Icon, Piece};
6use crate::measure::Font;
7use crate::paint::{Bounds, Paint, UNIT, units};
8
9/// Heights of a button, in rows.
10/// Every button is one chip centred inside its row, so none stands past it and what's
11/// painted is what takes a click: about 30 px of a 37 px row, the air the design's 24 of 32
12/// gives its smaller text.
13const BUTTON_HEIGHT: f32 = 0.8;
14const LARGE_BUTTON_HEIGHT: f32 = BUTTON_HEIGHT;
15
16#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
17pub struct Rgb(pub u8, pub u8, pub u8);
18
19#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
20pub struct Style {
21    pub fg: Rgb,
22    pub bg: Rgb,
23    pub bold: bool,
24    pub italic: bool,
25    pub underline: bool,
26    /// The pixel tiers leave this cell's glyph out, because paint draws its text.
27    pub painted: bool,
28}
29
30/// `text` with nothing a terminal would act on: a control character, as a file, an agent's
31/// output or a transcript can hold, is shown by its picture (`␛` for escape), the way VS Code
32/// shows one, so it can't move the cursor, set the title or write the clipboard. A tab is a
33/// space.
34fn visible(text: &str) -> std::borrow::Cow<'_, str> {
35    let control = |c: char| c.is_control();
36    if !text.contains(control) {
37        return std::borrow::Cow::Borrowed(text);
38    }
39    let shown = text
40        .chars()
41        .map(|c| match c {
42            '\t' => ' ',
43            '\0'..='\u{1f}' => char::from_u32(0x2400 + c as u32).unwrap_or('\u{fffd}'),
44            '\u{7f}' => '\u{2421}',
45            c if c.is_control() => '\u{fffd}',
46            c => c,
47        })
48        .collect();
49    std::borrow::Cow::Owned(shown)
50}
51
52/// A screen cell. An empty symbol is the right half of a wide character.
53#[derive(Clone, Debug, PartialEq, Eq, Hash)]
54pub struct Cell {
55    pub symbol: CompactString,
56    pub style: Style,
57}
58
59/// Copies a run of cells within the grid's own cells. `Cell` isn't `Copy`, so this clones.
60trait CopyCells {
61    fn copy_within_cells(&mut self, from: std::ops::Range<usize>, to: usize);
62}
63
64impl CopyCells for Vec<Cell> {
65    fn copy_within_cells(&mut self, from: std::ops::Range<usize>, to: usize) {
66        for (n, at) in from.enumerate() {
67            let cell = self[at].clone();
68            self[to + n] = cell;
69        }
70    }
71}
72
73#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
74pub struct Rect {
75    pub x: u16,
76    pub y: u16,
77    pub w: u16,
78    pub h: u16,
79}
80
81impl Rect {
82    pub fn new(x: u16, y: u16, w: u16, h: u16) -> Self {
83        Self { x, y, w, h }
84    }
85
86    pub fn contains(&self, x: u16, y: u16) -> bool {
87        x >= self.x && x < self.x + self.w && y >= self.y && y < self.y + self.h
88    }
89
90    pub fn right(&self) -> u16 {
91        self.x + self.w
92    }
93
94    pub fn bottom(&self) -> u16 {
95        self.y + self.h
96    }
97}
98
99/// A span of changed cells on one row.
100#[derive(Clone, Copy, Debug, PartialEq, Eq)]
101pub struct Run {
102    pub x: u16,
103    pub y: u16,
104    pub len: u16,
105}
106
107#[derive(Clone, Debug, PartialEq, Eq)]
108pub struct Grid {
109    width: u16,
110    height: u16,
111    cells: Vec<Cell>,
112    pub cursor: Option<(u16, u16)>,
113    /// The caret's exact place on the pixel tiers, when text isn't on whole cells.
114    pub caret: Option<Bounds>,
115    /// Drawn over the cells on the pixel tiers, in order.
116    pub paint: Vec<Paint>,
117    /// Columns where a new band starts, in order. Each band of a row is its own tile, so text
118    /// that scrolls isn't tied to whatever the sidebar or minimap shows at that height.
119    pub bands: Vec<u16>,
120}
121
122impl Grid {
123    /// Moves rows `top..=bottom` up by `by` rows, or down if negative, across the whole width,
124    /// as a terminal's scroll region does. The rows left behind hold nothing any real cell
125    /// matches, so the next diff draws them.
126    pub fn scroll_rows(&mut self, top: u16, bottom: u16, by: i32) {
127        let width = self.width as usize;
128        let (top, bottom) = (
129            top as usize,
130            (bottom as usize).min(self.height as usize - 1),
131        );
132        if top > bottom || by == 0 {
133            return;
134        }
135        let rows = bottom + 1 - top;
136        let n = (by.unsigned_abs() as usize).min(rows);
137        let unknown = Cell {
138            symbol: CompactString::const_new("\u{fffe}"),
139            style: Style::default(),
140        };
141        let row = |y: usize| y * width..(y + 1) * width;
142        if by > 0 {
143            for y in top..bottom + 1 - n {
144                self.cells.copy_within_cells(row(y + n), row(y).start);
145            }
146            for y in bottom + 1 - n..=bottom {
147                self.cells[row(y)].fill(unknown.clone());
148            }
149        } else {
150            for y in (top + n..=bottom).rev() {
151                self.cells.copy_within_cells(row(y - n), row(y).start);
152            }
153            for y in top..top + n {
154                self.cells[row(y)].fill(unknown.clone());
155            }
156        }
157    }
158
159    pub fn new(width: u16, height: u16, style: Style) -> Self {
160        let blank = Cell {
161            symbol: " ".into(),
162            style,
163        };
164        Self {
165            width,
166            height,
167            cells: vec![blank; width as usize * height as usize],
168            cursor: None,
169            caret: None,
170            paint: Vec::new(),
171            bands: Vec::new(),
172        }
173    }
174
175    /// Text in the interface font on the pixel tiers, and ordinary cells on the cell tier.
176    pub fn label(&mut self, x: u16, y: u16, text: &str, style: Style, max_x: u16) -> u16 {
177        self.label_at(x as f32, x, y, text, style, max_x, 100)
178    }
179
180    /// A label starting between cells, at a size relative to the interface font.
181    #[allow(clippy::too_many_arguments)]
182    pub fn label_at(
183        &mut self,
184        x_px: f32,
185        x: u16,
186        y: u16,
187        text: &str,
188        style: Style,
189        max_x: u16,
190        size: u8,
191    ) -> u16 {
192        let end = self.put_str(
193            x,
194            y,
195            text,
196            Style {
197                painted: true,
198                ..style
199            },
200            max_x,
201        );
202        if y < self.height {
203            self.paint.push(Paint::Text {
204                x: units(x_px),
205                y: y as i32 * UNIT,
206                max_width: units(max_x.min(self.width) as f32 - x_px),
207                text: text.to_string(),
208                color: style.fg,
209                font: Font {
210                    bold: style.bold,
211                    size,
212                    ..Font::default()
213                },
214                align_right: false,
215                centred: false,
216                underline: false,
217            });
218        }
219        end
220    }
221
222    /// Paints a run of text with no cells behind it, at a place in cells and rows.
223    pub fn text_run(
224        &mut self,
225        (x, y): (f32, f32),
226        max_x: f32,
227        text: &str,
228        (color, underline): (Rgb, bool),
229        font: Font,
230    ) {
231        self.paint.push(Paint::Text {
232            x: units(x),
233            y: units(y),
234            max_width: units(max_x - x),
235            text: text.to_string(),
236            color,
237            font,
238            align_right: false,
239            centred: false,
240            underline,
241        });
242    }
243
244    /// Puts the caret at a place between cells, `height` rows tall and centred on `y`.
245    pub fn set_caret(&mut self, x: f32, y: u16, height: f32) {
246        self.cursor = Some((x as u16, y));
247        let top = y as f32 + (1.0 - height) / 2.0;
248        self.caret = Some(Bounds::cells(x, top, 0.0, height));
249    }
250
251    /// A label whose right edge sits at `right`, since proportional text is narrower than
252    /// its cells and would otherwise leave a gap at the end.
253    pub fn label_right(&mut self, right: u16, y: u16, text: &str, style: Style, size: u8) {
254        let cells = text.chars().count() as u16;
255        let x = right.saturating_sub(cells);
256        self.put_str(
257            x,
258            y,
259            text,
260            Style {
261                painted: true,
262                ..style
263            },
264            right,
265        );
266        self.paint.push(Paint::Text {
267            x: units(right as f32),
268            y: y as i32 * UNIT,
269            max_width: units(right as f32),
270            text: text.to_string(),
271            color: style.fg,
272            font: Font {
273                bold: style.bold,
274                size,
275                ..Font::default()
276            },
277            align_right: true,
278            centred: false,
279            underline: false,
280        });
281    }
282
283    /// A rounded box inside `rect`, with square corners cleaned up behind it.
284    pub fn field(&mut self, rect: Rect, behind: Rgb, fill: Rgb, border: Rgb) {
285        self.panel(Bounds::inset(rect, 0.0, 0.0), 0, Some(behind), None);
286        // Inset a little from its row, so fields stacked in rows next to each other keep
287        // their air.
288        self.panel(
289            Bounds::inset(rect, 0.15, 0.11),
290            22,
291            Some(fill),
292            Some(border),
293        );
294    }
295
296    /// A rounded button in a row of its own. The cell tier shows `cells`, which may be
297    /// wider than the label.
298    pub fn button(&mut self, x: u16, y: u16, cells: &str, label: &str, fill: Rgb, style: Style) {
299        self.button_of((BUTTON_HEIGHT, 0.0), (x, y), cells, label, fill, style);
300    }
301
302    /// A button that stands past its row, for where there's air around it.
303    pub fn large_button(
304        &mut self,
305        x: u16,
306        y: u16,
307        cells: &str,
308        label: &str,
309        fill: Rgb,
310        style: Style,
311    ) {
312        self.button_of(
313            (LARGE_BUTTON_HEIGHT, 0.0),
314            (x, y),
315            cells,
316            label,
317            fill,
318            style,
319        );
320    }
321
322    /// A large button centred between `y` and the row below it.
323    pub fn large_button_between(
324        &mut self,
325        x: u16,
326        y: u16,
327        cells: &str,
328        label: &str,
329        fill: Rgb,
330        style: Style,
331    ) {
332        self.button_of(
333            (LARGE_BUTTON_HEIGHT, 0.5),
334            (x, y),
335            cells,
336            label,
337            fill,
338            style,
339        );
340    }
341
342    fn button_of(
343        &mut self,
344        (height, drop): (f32, f32),
345        (x, y): (u16, u16),
346        cells: &str,
347        label: &str,
348        fill: Rgb,
349        style: Style,
350    ) {
351        let width = cells.chars().count() as u16;
352        let (left, top, right, bottom) = button_span((height, drop), (x, y), width);
353        self.put_str(
354            x,
355            y,
356            cells,
357            Style {
358                painted: true,
359                ..style
360            },
361            self.width,
362        );
363        let bounds = Bounds::cells(left, top, right - left, bottom - top);
364        self.panel(bounds, 22, Some(fill), None);
365        let middle = x as f32 + width as f32 / 2.0;
366        self.centred_text(middle, y as f32 + drop, label, style.fg, 90);
367    }
368
369    /// Moves what was painted last down by part of a row.
370    pub fn drop_last(&mut self, by: f32) {
371        match self.paint.last_mut() {
372            Some(Paint::Text { y, .. }) => *y += units(by),
373            Some(Paint::Icon { bounds, .. }) => bounds.y += units(by),
374            _ => {}
375        }
376    }
377
378    /// Paints text centred on `x`, at a place in rows.
379    pub fn centred_text(&mut self, x: f32, y: f32, text: &str, color: Rgb, size: u8) {
380        self.paint.push(Paint::Text {
381            x: units(x),
382            y: units(y),
383            max_width: units(self.width as f32),
384            text: text.to_string(),
385            color,
386            font: Font {
387                size,
388                ..Font::default()
389            },
390            align_right: false,
391            centred: true,
392            underline: false,
393        });
394    }
395
396    pub fn panel(&mut self, bounds: Bounds, radius: u8, fill: Option<Rgb>, border: Option<Rgb>) {
397        self.paint.push(Paint::Panel {
398            bounds,
399            radius,
400            fill,
401            border,
402            shadow: false,
403            dashed: false,
404        });
405    }
406
407    /// A panel with its border in dashes, for something offered rather than settled.
408    pub fn dashed_panel(&mut self, bounds: Bounds, radius: u8, fill: Option<Rgb>, border: Rgb) {
409        self.paint.push(Paint::Panel {
410            bounds,
411            radius,
412            fill,
413            border: Some(border),
414            shadow: false,
415            dashed: true,
416        });
417    }
418
419    /// A panel floating above the page, with a soft shadow.
420    pub fn popup(&mut self, bounds: Bounds, radius: u8, fill: Rgb, border: Rgb) {
421        self.paint.push(Paint::Panel {
422            bounds,
423            radius,
424            fill: Some(fill),
425            border: Some(border),
426            shadow: true,
427            dashed: false,
428        });
429    }
430
431    /// A see-through wash of `color` over `bounds`, `alpha` out of 255, with a border.
432    pub fn wash(
433        &mut self,
434        bounds: Bounds,
435        radius: u8,
436        (color, alpha): (Rgb, u8),
437        border: Option<Rgb>,
438    ) {
439        self.paint.push(Paint::Wash {
440            bounds,
441            radius,
442            color,
443            alpha,
444            border,
445        });
446    }
447
448    pub fn hairline(&mut self, bounds: Bounds, color: Rgb) {
449        self.paint.push(Paint::Hairline { bounds, color });
450    }
451
452    /// A small icon, one row tall, with its left edge at `x`. `fallback` is what the cell
453    /// tier shows there.
454    pub fn glyph(&mut self, x: f32, y: u16, icon: Icon, color: Rgb, fallback: &str, style: Style) {
455        let cell = x.floor() as u16;
456        if cell < self.width && y < self.height {
457            self.put_str(
458                cell,
459                y,
460                fallback,
461                Style {
462                    painted: true,
463                    ..style
464                },
465                self.width,
466            );
467        }
468        self.paint.push(Paint::Icon {
469            bounds: Bounds::cells(x, y as f32 + 0.14, 2.0, 0.72),
470            icon,
471            color,
472        });
473    }
474
475    /// Paint that touches row `y`, in drawing order.
476    pub fn corners(&mut self, bounds: Bounds, radius: u8, color: Rgb, which: u8) {
477        self.paint.push(Paint::Corners {
478            bounds,
479            radius,
480            color,
481            which,
482        });
483    }
484
485    pub fn paint_on_row(&self, y: u16) -> impl Iterator<Item = &Paint> {
486        let (top, bottom) = (y as i32 * UNIT, (y as i32 + 1) * UNIT);
487        self.paint.iter().filter(move |p| {
488            let (from, to) = p.span();
489            from < bottom && to > top
490        })
491    }
492
493    pub fn width(&self) -> u16 {
494        self.width
495    }
496
497    pub fn height(&self) -> u16 {
498        self.height
499    }
500
501    pub fn area(&self) -> Rect {
502        Rect::new(0, 0, self.width, self.height)
503    }
504
505    fn index(&self, x: u16, y: u16) -> usize {
506        y as usize * self.width as usize + x as usize
507    }
508
509    pub fn cell(&self, x: u16, y: u16) -> &Cell {
510        &self.cells[self.index(x, y)]
511    }
512
513    pub fn row(&self, y: u16) -> &[Cell] {
514        let start = self.index(0, y);
515        &self.cells[start..start + self.width as usize]
516    }
517
518    pub fn fill(&mut self, rect: Rect, style: Style) {
519        for y in rect.y..rect.bottom().min(self.height) {
520            for x in rect.x..rect.right().min(self.width) {
521                self.put_cell(x, y, " ", style);
522            }
523        }
524    }
525
526    fn put_cell(&mut self, x: u16, y: u16, symbol: &str, style: Style) {
527        // Overwriting half of a wide character blanks its other half.
528        let i = self.index(x, y);
529        if self.cells[i].symbol.is_empty() && x > 0 {
530            self.cells[i - 1].symbol = " ".into();
531        }
532        if x + 1 < self.width && self.cells[i + 1].symbol.is_empty() {
533            self.cells[i + 1].symbol = " ".into();
534        }
535        self.cells[i] = Cell {
536            symbol: symbol.into(),
537            style,
538        };
539    }
540
541    /// Writes text stopping before `max_x`, and returns the column after it. A wide
542    /// character that doesn't fit becomes a space.
543    pub fn put_str(&mut self, x: u16, y: u16, text: &str, style: Style, max_x: u16) -> u16 {
544        if y >= self.height {
545            return x;
546        }
547        let max_x = max_x.min(self.width);
548        let mut at = x;
549        let text = visible(text);
550        for g in text.graphemes(true) {
551            if at >= max_x {
552                break;
553            }
554            let width = g.width() as u16;
555            if width == 0 {
556                continue;
557            }
558            if at + width > max_x {
559                self.put_cell(at, y, " ", style);
560                return at + 1;
561            }
562            self.put_cell(at, y, g, style);
563            if width == 2 {
564                self.put_cell(at + 1, y, "", style);
565            }
566            at += width;
567        }
568        at
569    }
570
571    /// Places a multi-cell icon with its top-left corner at `x`, `y`.
572    pub fn put_icon(&mut self, x: u16, y: u16, icon: Icon, size: (u8, u8), style: Style) {
573        for row in 0..size.1 {
574            for column in 0..size.0 {
575                let (cx, cy) = (x + u16::from(column), y + u16::from(row));
576                if cx < self.width && cy < self.height {
577                    let piece = Piece {
578                        icon,
579                        width: size.0,
580                        height: size.1,
581                        column,
582                        row,
583                    };
584                    self.put_cell(cx, cy, piece.symbol().encode_utf8(&mut [0; 4]), style);
585                }
586            }
587        }
588    }
589
590    /// Overrides the style of existing cells, keeping their text.
591    pub fn set_style(&mut self, rect: Rect, f: impl Fn(Style) -> Style) {
592        for y in rect.y..rect.bottom().min(self.height) {
593            for x in rect.x..rect.right().min(self.width) {
594                let i = self.index(x, y);
595                self.cells[i].style = f(self.cells[i].style);
596            }
597        }
598    }
599
600    /// Spans that differ from `prev`. A size change makes the whole grid differ.
601    pub fn diff(&self, prev: &Grid) -> Vec<Run> {
602        let same_size = self.width == prev.width && self.height == prev.height;
603        let mut runs = Vec::new();
604        for y in 0..self.height {
605            if same_size && self.row(y) == prev.row(y) {
606                continue;
607            }
608            let mut x = 0;
609            while x < self.width {
610                if same_size && self.cell(x, y) == prev.cell(x, y) {
611                    x += 1;
612                    continue;
613                }
614                let start = x;
615                while x < self.width && !(same_size && self.cell(x, y) == prev.cell(x, y)) {
616                    x += 1;
617                }
618                // A run must never begin on the right half of a wide character.
619                let start = if self.cell(start, y).symbol.is_empty() && start > 0 {
620                    start - 1
621                } else {
622                    start
623                };
624                runs.push(Run {
625                    x: start,
626                    y,
627                    len: x - start,
628                });
629            }
630        }
631        runs
632    }
633
634    /// The text of a row, for tests and copy.
635    pub fn row_text(&self, y: u16) -> String {
636        self.row(y).iter().map(|c| c.symbol.as_str()).collect()
637    }
638
639    /// Everything on screen, one line per row with trailing spaces removed.
640    pub fn text(&self) -> String {
641        (0..self.height)
642            .map(|y| self.row_text(y).trim_end().to_string())
643            .collect::<Vec<_>>()
644            .join("\n")
645    }
646}
647
648/// Where a button is painted, as (left, top, right, bottom) in columns and rows.
649fn button_span((height, drop): (f32, f32), (x, y): (u16, u16), width: u16) -> (f32, f32, f32, f32) {
650    let top = y as f32 + drop + (1.0 - height) / 2.0;
651    (x as f32, top, (x + width) as f32, top + height)
652}
653
654/// Whether a click at `at` (columns and rows, with their fractions) lands on the large
655/// button `Grid::large_button` paints at `(x, y)`, `width` cells wide. It takes the whole
656/// of what's painted, which stands a little past its row above and below. A terminal
657/// without pixel reports gives the middle of a cell, so there it's the button's row.
658pub fn on_large_button((x, y): (u16, u16), width: u16, at: (f32, f32)) -> bool {
659    let (left, top, right, bottom) = button_span((LARGE_BUTTON_HEIGHT, 0.0), (x, y), width);
660    at.0 >= left && at.0 < right && at.1 >= top && at.1 < bottom
661}
662
663#[cfg(test)]
664mod tests {
665
666    #[test]
667    fn control_characters_never_reach_a_cell() {
668        let style = Style::default();
669        let mut grid = Grid::new(40, 2, style);
670        let text = "a\x1b]52;c;aGk=\x07b\r\n\x7f\u{9b}2Jc\td";
671        let end = grid.put_str(0, 0, text, style, 40);
672        let row: String = (0..end)
673            .map(|x| grid.cell(x, 0).symbol.to_string())
674            .collect();
675        assert_eq!(row, "a␛]52;c;aGk=␇b␍␊␡\u{fffd}2Jc d");
676        assert!(row.chars().all(|c| !c.is_control()), "{row:?}");
677    }
678
679    use super::*;
680
681    fn grid() -> Grid {
682        Grid::new(10, 3, Style::default())
683    }
684
685    #[test]
686    fn diff_emits_only_changed_cells() {
687        let before = grid();
688        let mut after = grid();
689        after.put_str(2, 1, "ab", Style::default(), 10);
690        after.put_str(7, 1, "c", Style::default(), 10);
691        assert_eq!(
692            after.diff(&before),
693            vec![Run { x: 2, y: 1, len: 2 }, Run { x: 7, y: 1, len: 1 }]
694        );
695        assert!(before.diff(&before.clone()).is_empty());
696    }
697
698    #[test]
699    fn resize_redraws_everything() {
700        let runs = grid().diff(&Grid::new(4, 4, Style::default()));
701        assert_eq!(runs.len(), 3);
702        assert!(runs.iter().all(|r| r.len == 10));
703    }
704
705    #[test]
706    fn wide_characters_take_two_cells() {
707        let mut g = grid();
708        let end = g.put_str(0, 0, "日本", Style::default(), 10);
709        assert_eq!(end, 4);
710        assert_eq!(g.cell(0, 0).symbol, "日");
711        assert_eq!(g.cell(1, 0).symbol, "");
712        assert_eq!(g.row_text(0).trim_end(), "日本");
713    }
714
715    #[test]
716    fn overwriting_half_a_wide_character_blanks_the_other_half() {
717        let mut g = grid();
718        g.put_str(0, 0, "日", Style::default(), 10);
719        g.put_str(1, 0, "x", Style::default(), 10);
720        assert_eq!(g.cell(0, 0).symbol, " ");
721        assert_eq!(g.cell(1, 0).symbol, "x");
722    }
723
724    #[test]
725    fn wide_character_at_the_edge_becomes_a_space() {
726        let mut g = grid();
727        g.put_str(9, 0, "日", Style::default(), 10);
728        assert_eq!(g.cell(9, 0).symbol, " ");
729    }
730
731    #[test]
732    fn combining_marks_stay_in_one_cell() {
733        let mut g = grid();
734        let end = g.put_str(0, 0, "e\u{301}x", Style::default(), 10);
735        assert_eq!(end, 2);
736        assert_eq!(g.cell(0, 0).symbol, "e\u{301}");
737    }
738
739    #[test]
740    fn diff_never_starts_on_a_continuation_cell() {
741        let mut before = grid();
742        before.put_str(0, 0, "日", Style::default(), 10);
743        let mut after = grid();
744        after.put_str(
745            0,
746            0,
747            "日",
748            Style {
749                bold: true,
750                ..Style::default()
751            },
752            10,
753        );
754        let mut only_right = before.clone();
755        only_right.cells[1].style.bold = true;
756        assert_eq!(only_right.diff(&before)[0].x, 0);
757        assert_eq!(after.diff(&before)[0].x, 0);
758    }
759}