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