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