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