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