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/// The one picture `Grid::exact_fill` scales: a single pixel, all ink.
20const EXACT_FILL: u64 = u64::MAX - 1;
21/// How far a button's words, a capital's height in their middle (`Paint::Text`'s
22/// `span_centred`), stand over the baseline of words of 13 pt in the middle of the same row, in
23/// the terminal's lines: their 90 per cent puts it a pixel higher, 0.9 px of a line of 36. A
24/// button in a row of words goes down this far with its words (`Grid::beside_words`), so they
25/// stand on the row's baseline: "Reject" rode 3 px over the hunk's heading beside it.
26pub const WORDS_BASELINE: f32 = 0.026;
27/// Rows tall an icon beside a name is: 16 pt where a row is 18.5 pt, VS Code's size.
28pub const GLYPH: f32 = 0.86;
29/// Rows tall an icon inside a text box or a chip is, where one of `GLYPH` would stand against
30/// the box's edges: 13 pt.
31pub const SMALL_GLYPH: f32 = 0.70;
32/// How far a text box stands inside its row, above and below: the box is seven eighths of
33/// its row, which holds words of 13 pt raised in it with their tails off its lower edge, and
34/// leaves 4 px between two boxes in rows one under the other.
35pub const FIELD_AIR: f32 = 0.0625;
36/// Columns such an icon starts before where it's asked for, which keeps its middle where an
37/// icon of 0.72 of a row had it, so it grew evenly to both sides.
38pub const GLYPH_LEAD: f32 = 0.15;
39
40#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
41pub struct Rgb(pub u8, pub u8, pub u8);
42
43#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
44pub struct Style {
45    pub fg: Rgb,
46    pub bg: Rgb,
47    pub bold: bool,
48    pub italic: bool,
49    pub underline: bool,
50    /// The pixel tiers leave this cell's glyph out, because paint draws its text.
51    pub painted: bool,
52}
53
54/// `text` with nothing a terminal would act on: a control character, as a file, an agent's
55/// output or a transcript can hold, is shown by its picture (`␛` for escape), the way VS Code
56/// shows one, so it can't move the cursor, set the title or write the clipboard. A tab is a
57/// space.
58fn visible(text: &str) -> std::borrow::Cow<'_, str> {
59    let control = |c: char| c.is_control();
60    if !text.contains(control) {
61        return std::borrow::Cow::Borrowed(text);
62    }
63    let shown = text
64        .chars()
65        .map(|c| match c {
66            '\t' => ' ',
67            '\0'..='\u{1f}' => char::from_u32(0x2400 + c as u32).unwrap_or('\u{fffd}'),
68            '\u{7f}' => '\u{2421}',
69            c if c.is_control() => '\u{fffd}',
70            c => c,
71        })
72        .collect();
73    std::borrow::Cow::Owned(shown)
74}
75
76/// A screen cell. An empty symbol is the right half of a wide character.
77#[derive(Clone, Debug, PartialEq, Eq, Hash)]
78pub struct Cell {
79    pub symbol: CompactString,
80    pub style: Style,
81}
82
83/// The shape a terminal's own cursor takes on the cell tier: a bar between letters for the
84/// caret in a file or a box, as an editor's, and for a program in a terminal pane what it
85/// asked for (DECSCUSR), a block unless it asked.
86#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
87pub enum CursorShape {
88    #[default]
89    Bar,
90    Block,
91    Underline,
92}
93
94/// A terminal pane's cursor as its session drew it: its cell inverted (`on`), and that cell's
95/// own look (`off`), which is what shows in the half of a blink the cursor is away, and on the
96/// cell tier, where the terminal's own cursor stands there instead. `blinks` is whether its
97/// program left it blinking: DECSCUSR 2, 4 or 6, or `CSI ? 12 l`, asks for a steady one.
98#[derive(Clone, Debug, PartialEq, Eq)]
99pub struct TermCursor {
100    pub at: (u16, u16),
101    pub on: Cell,
102    pub off: Cell,
103    pub shape: CursorShape,
104    pub blinks: bool,
105}
106
107/// What a blink takes away while it's in its hidden half, to put back: the caret and the
108/// cursor's cell, and the cells that show another look, each with the look they had.
109#[derive(Clone, Debug, Default, PartialEq, Eq)]
110struct Blinked {
111    caret: Option<Bounds>,
112    cursor: Option<(u16, u16)>,
113    cells: Vec<(u16, u16, Cell)>,
114}
115
116/// Copies a run of cells within the grid's own cells. `Cell` isn't `Copy`, so this clones.
117trait CopyCells {
118    fn copy_within_cells(&mut self, from: std::ops::Range<usize>, to: usize);
119}
120
121impl CopyCells for Vec<Cell> {
122    fn copy_within_cells(&mut self, from: std::ops::Range<usize>, to: usize) {
123        for (n, at) in from.enumerate() {
124            let cell = self[at].clone();
125            self[to + n] = cell;
126        }
127    }
128}
129
130#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
131pub struct Rect {
132    pub x: u16,
133    pub y: u16,
134    pub w: u16,
135    pub h: u16,
136}
137
138impl Rect {
139    pub fn new(x: u16, y: u16, w: u16, h: u16) -> Self {
140        Self { x, y, w, h }
141    }
142
143    pub fn contains(&self, x: u16, y: u16) -> bool {
144        x >= self.x && x < self.x + self.w && y >= self.y && y < self.y + self.h
145    }
146
147    pub fn right(&self) -> u16 {
148        self.x + self.w
149    }
150
151    pub fn bottom(&self) -> u16 {
152        self.y + self.h
153    }
154}
155
156/// A span of changed cells on one row.
157#[derive(Clone, Copy, Debug, PartialEq, Eq)]
158pub struct Run {
159    pub x: u16,
160    pub y: u16,
161    pub len: u16,
162}
163
164#[derive(Clone, Debug, PartialEq, Eq)]
165pub struct Grid {
166    width: u16,
167    height: u16,
168    cells: Vec<Cell>,
169    pub cursor: Option<(u16, u16)>,
170    /// The caret's exact place on the pixel tiers, when text isn't on whole cells.
171    pub caret: Option<Bounds>,
172    /// Drawn over the cells on the pixel tiers, in order.
173    pub paint: Vec<Paint>,
174    /// Columns where a new band starts, in order. Each band of a row is its own tile, so text
175    /// that scrolls isn't tied to whatever the sidebar or minimap shows at that height.
176    pub bands: Vec<u16>,
177    /// The colour past the grid's right edge, where a terminal lets a row's picture run on
178    /// over the window's padding. Unset, it's the colour of the row's last cell.
179    pub edge: Option<Rgb>,
180    /// Whether a row here is tall enough for a control to stand in it with its words in its
181    /// middle: rows of Cellix's own, well taller than the terminal's line. What draws into
182    /// the grid says so. Where it is, a button on a row's wash stands inside the wash.
183    pub roomy: bool,
184    /// How tall one of these rows is in hundredths of the terminal's line, which words are
185    /// sized for: 100 unless Cellix lays out rows taller than that line. What draws into the
186    /// grid says so.
187    pub row_air: u16,
188    /// How many rows at the grid's foot are bars under the sheets: one, unless what draws
189    /// says there are two, as where the workspaces have a row of their own under the status
190    /// bar. A backend that fills the window under its last row stands them evenly in what's
191    /// there.
192    pub foot: u16,
193    /// A row cut into bands of its own, in place of `bands`, as (the row, where each band
194    /// after the first starts): the status bar, where a spinner is a tile by itself, so its
195    /// steps don't send the rest of the bar again, nor the bar's other changes the spinner.
196    pub row_bands: Option<(u16, Vec<u16>)>,
197    /// The step of its turn every spinner drawn here stands at, from the clock in
198    /// `spinner`, or none where motion is off: a spinner is then a still dot.
199    pub turn: Option<u8>,
200    /// Whether anything drawn here is turning, so whatever shows the grid draws it again at
201    /// the next step. Nothing turning, nothing asks for a frame.
202    pub spinning: bool,
203    /// The cells turning spinners stand in, so a step can be taken on the grid as drawn.
204    turning: Vec<(u16, u16)>,
205    /// Runs of `paint` kept to a band of rows: as (from, to) in `paint` and (top, bottom) in
206    /// rows. A list scrolled in a pane paints its cards whole, and the part of one that's
207    /// past the pane's edge mustn't land on the bar beside it.
208    kept: Vec<((usize, usize), (u16, u16))>,
209    /// The shape of the terminal's own cursor where the cell tier shows it at `cursor`.
210    pub cursor_shape: CursorShape,
211    /// Whether the caret or cursor shown here blinks: on the cell tier the terminal is asked
212    /// to blink its own cursor (DECSCUSR), and on the pixel tiers whatever shows the grid
213    /// takes it through its two halves (`blink_to`). What draws says so.
214    pub cursor_blinks: bool,
215    /// The terminal panes' cursors drawn, for what draws to place as its tier shows them.
216    pub term_cursors: Vec<TermCursor>,
217    /// Cells with another look while a blink is in its hidden half, as (column, row, that
218    /// look, the look drawn): a terminal pane's cursor, which is its cell inverted.
219    blinking: Vec<(u16, u16, Cell, Cell)>,
220    /// What the blink took away, while it's in its hidden half.
221    blinked: Option<Blinked>,
222}
223
224impl Grid {
225    /// Moves rows `top..=bottom` up by `by` rows, or down if negative, across the whole width,
226    /// as a terminal's scroll region does. The rows left behind hold nothing any real cell
227    /// matches, so the next diff draws them.
228    pub fn scroll_rows(&mut self, top: u16, bottom: u16, by: i32) {
229        let width = self.width as usize;
230        let (top, bottom) = (
231            top as usize,
232            (bottom as usize).min(self.height as usize - 1),
233        );
234        if top > bottom || by == 0 {
235            return;
236        }
237        let rows = bottom + 1 - top;
238        let n = (by.unsigned_abs() as usize).min(rows);
239        let unknown = Cell {
240            symbol: CompactString::const_new("\u{fffe}"),
241            style: Style::default(),
242        };
243        let row = |y: usize| y * width..(y + 1) * width;
244        if by > 0 {
245            for y in top..bottom + 1 - n {
246                self.cells.copy_within_cells(row(y + n), row(y).start);
247            }
248            for y in bottom + 1 - n..=bottom {
249                self.cells[row(y)].fill(unknown.clone());
250            }
251        } else {
252            for y in (top + n..=bottom).rev() {
253                self.cells.copy_within_cells(row(y - n), row(y).start);
254            }
255            for y in top..top + n {
256                self.cells[row(y)].fill(unknown.clone());
257            }
258        }
259    }
260
261    pub fn new(width: u16, height: u16, style: Style) -> Self {
262        let blank = Cell {
263            symbol: " ".into(),
264            style,
265        };
266        Self {
267            width,
268            height,
269            cells: vec![blank; width as usize * height as usize],
270            cursor: None,
271            caret: None,
272            paint: Vec::new(),
273            bands: Vec::new(),
274            edge: None,
275            roomy: false,
276            row_air: 100,
277            foot: 1,
278            row_bands: None,
279            turn: Some(0),
280            spinning: false,
281            turning: Vec::new(),
282            kept: Vec::new(),
283            cursor_shape: CursorShape::Bar,
284            cursor_blinks: false,
285            term_cursors: Vec::new(),
286            blinking: Vec::new(),
287            blinked: None,
288        }
289    }
290
291    /// Has a cell show `off` in the half of a blink the caret is away, while it still shows
292    /// what it does now: a terminal pane's cursor, its cell inverted, on the pixel tiers.
293    pub fn blink_cell(&mut self, x: u16, y: u16, off: Cell) {
294        if x < self.width && y < self.height {
295            let on = self.cell(x, y).clone();
296            self.blinking.push((x, y, off, on));
297        }
298    }
299
300    /// Whether anything shown here comes and goes with the blink: a caret, a cursor's cell,
301    /// or a cell with another look for it.
302    pub fn blinks(&self) -> bool {
303        self.cursor_blinks
304            && (self.caret.is_some()
305                || self.cursor.is_some()
306                || self.blinked.is_some()
307                || !self.blinking.is_empty())
308    }
309
310    /// Whether the blink is in the half that shows the caret.
311    pub fn caret_shown(&self) -> bool {
312        self.blinked.is_none()
313    }
314
315    /// Takes the caret to one half of its blink, as drawing it again in that half would:
316    /// away, there's no caret and no cursor's cell, and a terminal's cursor shows its cell's
317    /// own look; shown, they're back. A cell something drawn later stands in keeps that. A
318    /// tile is a hash of its row, so once both halves of a row are in the terminal, a blink
319    /// sends nothing but its placement. Nothing that doesn't blink changes.
320    pub fn blink_to(&mut self, shown: bool) {
321        if shown == self.caret_shown() || (!shown && !self.blinks()) {
322            return;
323        }
324        if shown {
325            let blinked = self.blinked.take().unwrap_or_default();
326            self.caret = blinked.caret;
327            self.cursor = blinked.cursor;
328            for (x, y, on) in blinked.cells {
329                let at = self.index(x, y);
330                self.cells[at] = on;
331            }
332            return;
333        }
334        let mut cells = Vec::new();
335        for (x, y, off, on) in &self.blinking {
336            let at = self.index(*x, *y);
337            if self.cells[at] == *on {
338                self.cells[at] = off.clone();
339                cells.push((*x, *y, on.clone()));
340            }
341        }
342        self.blinked = Some(Blinked {
343            caret: self.caret.take(),
344            cursor: self.cursor.take(),
345            cells,
346        });
347    }
348
349    /// Something under way, in the colour of what it means: a faint ring with a quarter of it
350    /// turning where there are pictures, a turning braille letter on cells, and with motion
351    /// off a still dot. Its box is `size` rows of the terminal's line square, as an icon's
352    /// is, starting at `x` and standing in the middle of row `y`; on cells it's the one
353    /// letter at `x`.
354    pub fn spinner(&mut self, x: f32, y: u16, size: f32, color: Rgb, style: Style) {
355        self.spinner_in((x, x.floor() as u16), y, size, color, style);
356    }
357
358    /// The same, its letter on the cell tier in column `cell` rather than the one its paint
359    /// starts in: where painted words are narrower than their letters, the cells keep what
360    /// they can of the words before it.
361    pub fn spinner_in(
362        &mut self,
363        (x, cell): (f32, u16),
364        y: u16,
365        size: f32,
366        color: Rgb,
367        style: Style,
368    ) {
369        let step = self.turn;
370        self.spinning |= step.is_some();
371        let letter = step.map_or(crate::spinner::STILL, |s| {
372            crate::spinner::FRAMES[s as usize % crate::spinner::FRAMES.len()]
373        });
374        self.mark((x, cell), y, size, color, style, (step, letter));
375    }
376
377    /// Takes every spinner on the grid to `step` of its turn, as drawing it again at that step
378    /// would: when nothing else has changed, a step is this and not the whole interface laid
379    /// out again. Still ones stay still.
380    pub fn turn_to(&mut self, step: u8) {
381        if self.turn.is_none() {
382            return;
383        }
384        self.turn = Some(step);
385        for paint in &mut self.paint {
386            if let Paint::Spinner { step: Some(at), .. } = paint {
387                *at = step;
388            }
389        }
390        let letter = crate::spinner::FRAMES[step as usize % crate::spinner::FRAMES.len()];
391        for &(x, y) in &self.turning {
392            let at = y as usize * self.width as usize + x as usize;
393            // Unless something drawn after it stands there now.
394            let cell = self.cells.get_mut(at).filter(|_| x < self.width);
395            if let Some(cell) = cell.filter(|c| crate::spinner::FRAMES.contains(&c.symbol.as_str()))
396            {
397                cell.symbol = letter.into();
398            }
399        }
400    }
401
402    /// A still dot in the colour of what it means, sized and placed as a spinner is: a
403    /// state that wants seeing, as an agent that needs you or one that's done.
404    pub fn dot(&mut self, x: f32, y: u16, size: f32, color: Rgb, style: Style) {
405        self.dot_in((x, x.floor() as u16), y, size, color, style);
406    }
407
408    /// The same, its letter on the cell tier in column `cell`, as `spinner_in`'s.
409    pub fn dot_in(&mut self, (x, cell): (f32, u16), y: u16, size: f32, color: Rgb, style: Style) {
410        let still = (None, crate::spinner::STILL);
411        self.mark((x, cell), y, size, color, style, still);
412    }
413
414    fn mark(
415        &mut self,
416        (x, cell): (f32, u16),
417        y: u16,
418        size: f32,
419        color: Rgb,
420        style: Style,
421        (step, letter): (Option<u8>, &str),
422    ) {
423        if step.is_some() {
424            self.turning.push((cell, y));
425        }
426        if cell < self.width && y < self.height {
427            let shown = Style {
428                fg: color,
429                painted: true,
430                ..style
431            };
432            self.put_str(cell, y, letter, shown, cell + 1);
433        }
434        self.paint.push(Paint::Spinner {
435            bounds: Bounds::cells(x, y as f32 + (1.0 - size) / 2.0, 2.0, size),
436            color,
437            step,
438        });
439    }
440
441    /// Text in the interface font on the pixel tiers, and ordinary cells on the cell tier.
442    pub fn label(&mut self, x: u16, y: u16, text: &str, style: Style, max_x: u16) -> u16 {
443        self.label_at(x as f32, x, y, text, style, max_x, 100)
444    }
445
446    /// Takes away what was painted that starts inside `area`, for a surface of cells laid over
447    /// it: paint can't go under text, so cells can't cover it, and it would show through.
448    pub fn clear_paint_in(&mut self, area: Rect) {
449        let (left, right) = (i32::from(area.x) * UNIT, i32::from(area.right()) * UNIT);
450        let (top, bottom) = (i32::from(area.y) * UNIT, i32::from(area.bottom()) * UNIT);
451        self.paint.retain(|paint| {
452            let (from, _) = paint.reach();
453            let start = paint.top();
454            !(start >= top && start < bottom && from >= left && from < right)
455        });
456    }
457
458    /// Paints again, clipped to `area`, the pictures painted before `before` that reach into
459    /// it, for a surface that hides its edge rows' cells whole, so no words show half covered,
460    /// though its panel covers only part of their pixels: painted over that ground, a picture
461    /// shows whole up to the surface's line, and the panel painted next hides what it covers.
462    /// The Ask card's last row hid 29 px of an equation under the card's foot (the release
463    /// review of 0.12.0, q4-ask-follow-up). Fills (`exact_fill`) aren't pictures and stay hidden
464    /// with the words, and a picture kept to some rows (`keep_to_rows`) stays on them.
465    pub fn pictures_again_in(&mut self, before: usize, area: Rect) {
466        let clip_to = |clip: Bounds, (left, top, right, bottom): (i32, i32, i32, i32)| {
467            let (x, y) = (clip.x.max(left), clip.y.max(top));
468            let (end_x, end_y) = ((clip.x + clip.w).min(right), (clip.y + clip.h).min(bottom));
469            Bounds {
470                x,
471                y,
472                w: end_x - x,
473                h: end_y - y,
474            }
475        };
476        let (left, right) = (i32::from(area.x) * UNIT, i32::from(area.right()) * UNIT);
477        let (top, bottom) = (i32::from(area.y) * UNIT, i32::from(area.bottom()) * UNIT);
478        let mut again = Vec::new();
479        for (index, paint) in self.paint.iter().enumerate().take(before) {
480            let Paint::Image {
481                bounds,
482                clip,
483                bitmap,
484                color,
485            } = paint
486            else {
487                continue;
488            };
489            if bitmap.id == EXACT_FILL {
490                continue;
491            }
492            let mut clip = clip_to(*clip, (left, top, right, bottom));
493            for ((from, to), (first, end)) in &self.kept {
494                if (*from..*to).contains(&index) {
495                    let rows = (i32::from(*first) * UNIT, i32::from(*end) * UNIT);
496                    clip = clip_to(clip, (left, rows.0, right, rows.1));
497                }
498            }
499            let shown = clip_to(
500                clip,
501                (bounds.x, bounds.y, bounds.x + bounds.w, bounds.y + bounds.h),
502            );
503            if shown.w > 0 && shown.h > 0 {
504                again.push(Paint::Image {
505                    bounds: *bounds,
506                    clip,
507                    bitmap: bitmap.clone(),
508                    color: *color,
509                });
510            }
511        }
512        self.paint.extend(again);
513    }
514
515    /// How much has been painted so far, to `lift_since` later.
516    pub fn painted_so_far(&self) -> usize {
517        self.paint.len()
518    }
519
520    /// Keeps what was painted since `from` to the rows from `top` up to `bottom`: on any other
521    /// row none of it is drawn, however far it reaches.
522    pub fn keep_to_rows(&mut self, from: usize, top: u16, bottom: u16) {
523        if from < self.paint.len() {
524            self.kept.push(((from, self.paint.len()), (top, bottom)));
525        }
526    }
527
528    /// Puts paint in under what's already painted from `index` on, as a mark under words is.
529    pub fn insert_paint(&mut self, index: usize, paint: Paint) {
530        let index = index.min(self.paint.len());
531        self.paint.insert(index, paint);
532        // What was kept to its rows still is, and what's put inside a kept run is kept too.
533        for ((from, to), _) in &mut self.kept {
534            if index < *from {
535                *from += 1;
536            }
537            if index < *to {
538                *to += 1;
539            }
540        }
541    }
542
543    /// Moves what was painted since `from` up by `rows`, which only the pixel tiers can show:
544    /// the cells under it stay in their rows, and so does where a click lands.
545    pub fn lift_since(&mut self, from: usize, rows: f32) {
546        let by = units(rows);
547        for paint in self.paint.iter_mut().skip(from) {
548            paint.lift(by);
549        }
550    }
551
552    /// Moves what was painted since `from` right by `columns`, which only the pixel tiers can
553    /// show: the cells under it stay in their columns, and so does where a click lands.
554    pub fn nudge_since(&mut self, from: usize, columns: f32) {
555        let by = units(columns);
556        for paint in self.paint.iter_mut().skip(from) {
557            match paint {
558                Paint::Text { x, .. } => *x += by,
559                Paint::Panel { bounds, .. }
560                | Paint::Wash { bounds, .. }
561                | Paint::Hairline { bounds, .. }
562                | Paint::Icon { bounds, .. }
563                | Paint::Spinner { bounds, .. }
564                | Paint::Corners { bounds, .. }
565                | Paint::Strips { bounds, .. } => bounds.x += by,
566                Paint::Image { bounds, clip, .. } => {
567                    bounds.x += by;
568                    clip.x += by;
569                }
570            }
571        }
572    }
573
574    /// A label starting between cells, at a size relative to the interface font.
575    #[allow(clippy::too_many_arguments)]
576    pub fn label_at(
577        &mut self,
578        x_px: f32,
579        x: u16,
580        y: u16,
581        text: &str,
582        style: Style,
583        max_x: u16,
584        size: u8,
585    ) -> u16 {
586        let end = self.put_str(
587            x,
588            y,
589            text,
590            Style {
591                painted: true,
592                ..style
593            },
594            max_x,
595        );
596        if y < self.height {
597            self.paint.push(Paint::Text {
598                x: units(x_px),
599                y: y as i32 * UNIT,
600                max_width: units(max_x.min(self.width) as f32 - x_px),
601                text: text.to_string(),
602                color: style.fg,
603                font: Font {
604                    bold: style.bold,
605                    size,
606                    ..Font::default()
607                },
608                align_right: false,
609                centred: false,
610                underline: false,
611                span_centred: false,
612            });
613        }
614        end
615    }
616
617    /// Paints a run of text with no cells behind it, at a place in cells and rows.
618    pub fn text_run(
619        &mut self,
620        (x, y): (f32, f32),
621        max_x: f32,
622        text: &str,
623        (color, underline): (Rgb, bool),
624        font: Font,
625    ) {
626        self.paint.push(Paint::Text {
627            x: units(x),
628            y: units(y),
629            max_width: units(max_x - x),
630            text: text.to_string(),
631            color,
632            font,
633            align_right: false,
634            centred: false,
635            underline,
636            span_centred: false,
637        });
638    }
639
640    /// Puts the caret at a place between cells, `height` rows tall and centred on `y`.
641    pub fn set_caret(&mut self, x: f32, y: u16, height: f32) {
642        self.cursor = Some((x as u16, y));
643        let top = y as f32 + (1.0 - height) / 2.0;
644        self.caret = Some(Bounds::cells(x, top, 0.0, height));
645    }
646
647    /// A label whose right edge sits at `right`, since proportional text is narrower than
648    /// its cells and would otherwise leave a gap at the end.
649    pub fn label_right(&mut self, right: u16, y: u16, text: &str, style: Style, size: u8) {
650        self.label_right_at(right as f32, right, y, text, style, size);
651    }
652
653    /// The same, its painted words ending at `right`, between cells, and its letters in the
654    /// cells ending at `cell`.
655    pub fn label_right_at(
656        &mut self,
657        right: f32,
658        cell: u16,
659        y: u16,
660        text: &str,
661        style: Style,
662        size: u8,
663    ) {
664        let cells = text.chars().count() as u16;
665        let x = cell.saturating_sub(cells);
666        self.put_str(
667            x,
668            y,
669            text,
670            Style {
671                painted: true,
672                ..style
673            },
674            cell,
675        );
676        self.paint.push(Paint::Text {
677            x: units(right),
678            y: y as i32 * UNIT,
679            max_width: units(right),
680            text: text.to_string(),
681            color: style.fg,
682            font: Font {
683                bold: style.bold,
684                size,
685                ..Font::default()
686            },
687            align_right: true,
688            centred: false,
689            underline: false,
690            span_centred: false,
691        });
692    }
693
694    /// A rounded box inside `rect`, with square corners cleaned up behind it.
695    pub fn field(&mut self, rect: Rect, behind: Rgb, fill: Rgb, border: Rgb) {
696        self.panel(Bounds::inset(rect, 0.0, 0.0), 0, Some(behind), None);
697        // Inset a little from its row, so fields stacked in rows next to each other keep
698        // their air.
699        self.panel(
700            Bounds::inset(rect, 0.15, FIELD_AIR),
701            22,
702            Some(fill),
703            Some(border),
704        );
705    }
706
707    /// A rounded button in a row of its own. The cell tier shows `cells`, which may be
708    /// wider than the label.
709    pub fn button(&mut self, x: u16, y: u16, cells: &str, label: &str, fill: Rgb, style: Style) {
710        self.button_of((BUTTON_HEIGHT, 0.0), (x, y), cells, label, fill, style);
711    }
712
713    /// A button at the end of a row of words, which may be washed under the pointer. Where a
714    /// row has room, it's the height it has on the terminal's line, 32 px in a row of 50 and
715    /// inside a pointed row's wash: as tall as the wash, the two read as one shape with a step
716    /// in it, and taller, as a button too big for its row. Its words' span, a capital's top to
717    /// a tail's foot, stands in its middle as every button's does (at 27 px a "p"'s tail ended
718    /// on its foot), and it goes down with its words onto the row's baseline (`beside_words`).
719    /// On the terminal's line a button and the wash have the row between them and nothing to
720    /// spare, and it's a button like any other.
721    pub fn row_button(
722        &mut self,
723        (x, y): (u16, u16),
724        cells: &str,
725        label: &str,
726        fill: Rgb,
727        style: Style,
728    ) {
729        let from = self.paint.len();
730        self.button(x, y, cells, label, fill, style);
731        if !self.roomy {
732            return;
733        }
734        // Its corners a little tighter with its height: a button's 8 px beside the wash's 4
735        // read as two kinds of shape once there was wash to see round it.
736        for paint in &mut self.paint[from..] {
737            if let Paint::Panel { inset, radius, .. } = paint {
738                *inset = true;
739                *radius = ROW_BUTTON_RADIUS;
740            }
741        }
742        self.beside_words(from);
743    }
744
745    /// The chip of a button at a row's end, from `left` to `right` between cells, behind words
746    /// its caller sets where they stand with the row at rest: as tall as `row_button`'s and in
747    /// the middle of the row, so in the middle of a pointed row's wash, where a row has room.
748    /// Gone down onto the words' baseline, as a `row_button` goes, it stood 10 px under the
749    /// wash's top and 8 over its foot.
750    pub fn row_chip(&mut self, (left, right): (f32, f32), y: u16, fill: Rgb) {
751        let (_, top, _, bottom) = button_span((BUTTON_HEIGHT, 0.0), (0, y), 1);
752        let (radius, inset) = if self.roomy {
753            (ROW_BUTTON_RADIUS, true)
754        } else {
755            (22, false)
756        };
757        self.paint.push(Paint::Panel {
758            bounds: Bounds::cells(left, top, right - left, bottom - top),
759            radius,
760            fill: Some(fill),
761            border: None,
762            shadow: false,
763            dashed: false,
764            inset,
765        });
766    }
767
768    /// Moves a button painted since `from` down onto the baseline of the words beside it in
769    /// its row, chip and words together (`WORDS_BASELINE`), where a row has room. On the
770    /// terminal's line a button has the row to itself and nothing to spare.
771    pub fn beside_words(&mut self, from: usize) {
772        if self.roomy {
773            let line = 100.0 / f32::from(self.row_air.max(1));
774            self.lift_since(from, -WORDS_BASELINE * line);
775        }
776    }
777
778    /// A fill of `color` exactly where `bounds` is. A panel shorter than a row is stood as a
779    /// control is on a taller row (`raster::stood`), grown or shrunk about its middle, which
780    /// a surface reaching part way into a row mustn't be: peek's card reaching into the
781    /// pane's last row stood 4 px clear of its own cells.
782    pub fn exact_fill(&mut self, bounds: Bounds, color: Rgb) {
783        let bitmap = crate::paint::Bitmap {
784            id: EXACT_FILL,
785            width: 1,
786            height: 1,
787            kind: crate::paint::Pixels::Coverage,
788            pixels: std::sync::Arc::new(vec![255]),
789        };
790        self.paint.push(Paint::Image {
791            bounds,
792            clip: bounds,
793            bitmap,
794            color,
795        });
796    }
797
798    /// `exact_fill`, put in under what's been painted from `index` on.
799    pub fn exact_fill_under(&mut self, index: usize, bounds: Bounds, color: Rgb) {
800        self.exact_fill(bounds, color);
801        if let Some(fill) = self.paint.pop() {
802            self.insert_paint(index, fill);
803        }
804    }
805
806    /// A button's chip by itself, as wide as asked and not a whole number of cells, for one
807    /// whose words and marks are placed by what draws it.
808    pub fn chip(&mut self, x: f32, y: u16, wide: f32, fill: Rgb) {
809        let top = y as f32 + (1.0 - BUTTON_HEIGHT) / 2.0;
810        let bounds = Bounds::cells(x, top, wide, BUTTON_HEIGHT);
811        self.panel(bounds, 22, Some(fill), None);
812    }
813
814    /// A button that stands past its row, for where there's air around it.
815    pub fn large_button(
816        &mut self,
817        x: u16,
818        y: u16,
819        cells: &str,
820        label: &str,
821        fill: Rgb,
822        style: Style,
823    ) {
824        self.button_of(
825            (LARGE_BUTTON_HEIGHT, 0.0),
826            (x, y),
827            cells,
828            label,
829            fill,
830            style,
831        );
832    }
833
834    /// A large button centred between `y` and the row below it.
835    pub fn large_button_between(
836        &mut self,
837        x: u16,
838        y: u16,
839        cells: &str,
840        label: &str,
841        fill: Rgb,
842        style: Style,
843    ) {
844        self.button_of(
845            (LARGE_BUTTON_HEIGHT, 0.5),
846            (x, y),
847            cells,
848            label,
849            fill,
850            style,
851        );
852    }
853
854    fn button_of(
855        &mut self,
856        (height, drop): (f32, f32),
857        (x, y): (u16, u16),
858        cells: &str,
859        label: &str,
860        fill: Rgb,
861        style: Style,
862    ) {
863        let width = cells.chars().count() as u16;
864        let (left, top, right, bottom) = button_span((height, drop), (x, y), width);
865        self.put_str(
866            x,
867            y,
868            cells,
869            Style {
870                painted: true,
871                ..style
872            },
873            self.width,
874        );
875        let bounds = Bounds::cells(left, top, right - left, bottom - top);
876        self.panel(bounds, 22, Some(fill), None);
877        let middle = x as f32 + width as f32 / 2.0;
878        self.button_label(middle, y as f32 + drop, label, style.fg, 90);
879    }
880
881    /// A button's words by themselves, centred on `middle` in row `y` and standing in it as a
882    /// button's do, for a control that paints its own chip.
883    pub fn button_words(&mut self, middle: f32, y: u16, label: &str, color: Rgb) {
884        self.button_label(middle, y as f32, label, color, 90);
885    }
886
887    /// Words centred on `x` that stand in the middle of the row starting at `y` as a button's
888    /// do: their font's span, a capital's top to a tail's foot, in its middle, whatever their
889    /// letters, so a row of buttons has one baseline. The font's line in the row's middle put
890    /// "Show Source" 5 px under its button's top and 10 over its foot, and the tails of "Accept
891    /// Rewrite" 6 px over its foot with its capitals 9 under its top.
892    pub fn button_label(&mut self, x: f32, y: f32, text: &str, color: Rgb, size: u8) {
893        self.centred_text(x, y, text, color, size);
894        self.centre_span_since(self.paint.len() - 1);
895    }
896
897    /// Has the words painted since `from` stand as a button's words do (`button_label`), for a
898    /// button that places its own words.
899    pub fn centre_span_since(&mut self, from: usize) {
900        for paint in self.paint.iter_mut().skip(from) {
901            if let Paint::Text { span_centred, .. } = paint {
902                *span_centred = true;
903            }
904        }
905    }
906
907    /// Moves what was painted last down by part of a row.
908    pub fn drop_last(&mut self, by: f32) {
909        match self.paint.last_mut() {
910            Some(Paint::Text { y, .. }) => *y += units(by),
911            Some(Paint::Icon { bounds, .. }) => bounds.y += units(by),
912            _ => {}
913        }
914    }
915
916    /// Paints text centred on `x`, at a place in rows.
917    pub fn centred_text(&mut self, x: f32, y: f32, text: &str, color: Rgb, size: u8) {
918        self.paint.push(Paint::Text {
919            x: units(x),
920            y: units(y),
921            max_width: units(self.width as f32),
922            text: text.to_string(),
923            color,
924            font: Font {
925                size,
926                ..Font::default()
927            },
928            align_right: false,
929            centred: true,
930            underline: false,
931            span_centred: false,
932        });
933    }
934
935    pub fn panel(&mut self, bounds: Bounds, radius: u8, fill: Option<Rgb>, border: Option<Rgb>) {
936        self.paint.push(Paint::Panel {
937            bounds,
938            radius,
939            fill,
940            border,
941            shadow: false,
942            dashed: false,
943            inset: false,
944        });
945    }
946
947    /// A panel with its border in dashes, for something offered rather than settled.
948    pub fn dashed_panel(&mut self, bounds: Bounds, radius: u8, fill: Option<Rgb>, border: Rgb) {
949        self.paint.push(Paint::Panel {
950            bounds,
951            radius,
952            fill,
953            border: Some(border),
954            shadow: false,
955            dashed: true,
956            inset: false,
957        });
958    }
959
960    /// A panel floating above the page, with a soft shadow.
961    pub fn popup(&mut self, bounds: Bounds, radius: u8, fill: Rgb, border: Rgb) {
962        self.paint.push(Paint::Panel {
963            bounds,
964            radius,
965            fill: Some(fill),
966            border: Some(border),
967            shadow: true,
968            dashed: false,
969            inset: false,
970        });
971    }
972
973    /// A panel floating above the page drawn exactly over `bounds`, however much shorter than
974    /// its row: `popup`'s is stood as a control is on a taller row (`raster::stood`), grown or
975    /// shrunk about its middle, and a tip's box sized for its words' ink mustn't be.
976    pub fn exact_popup(&mut self, bounds: Bounds, radius: u8, fill: Rgb, border: Rgb) {
977        self.paint.push(Paint::Panel {
978            bounds,
979            radius,
980            fill: Some(fill),
981            border: Some(border),
982            shadow: true,
983            dashed: false,
984            inset: true,
985        });
986    }
987
988    /// A see-through wash of `color` over `bounds`, `alpha` out of 255, with a border.
989    pub fn wash(
990        &mut self,
991        bounds: Bounds,
992        radius: u8,
993        (color, alpha): (Rgb, u8),
994        border: Option<Rgb>,
995    ) {
996        self.paint.push(Paint::Wash {
997            bounds,
998            radius,
999            color,
1000            alpha,
1001            border,
1002        });
1003    }
1004
1005    pub fn hairline(&mut self, bounds: Bounds, color: Rgb) {
1006        self.paint.push(Paint::Hairline { bounds, color });
1007    }
1008
1009    /// A small icon in the row, 16 pt in a terminal set to 14 pt, as VS Code's are beside a
1010    /// name. It stands about `x`: its middle is where it was when it was a sixth smaller, so
1011    /// what's placed after it needn't move. `fallback` is what the cell tier shows there.
1012    pub fn glyph(&mut self, x: f32, y: u16, icon: Icon, color: Rgb, fallback: &str, style: Style) {
1013        self.glyph_in((x, x.floor() as u16), y, (icon, color), fallback, style);
1014    }
1015
1016    /// The same, `fallback` on the cell tier in column `cell`, as `spinner_in`'s letter.
1017    pub fn glyph_in(
1018        &mut self,
1019        (x, cell): (f32, u16),
1020        y: u16,
1021        (icon, color): (Icon, Rgb),
1022        fallback: &str,
1023        style: Style,
1024    ) {
1025        if cell < self.width && y < self.height {
1026            self.put_str(
1027                cell,
1028                y,
1029                fallback,
1030                Style {
1031                    painted: true,
1032                    ..style
1033                },
1034                self.width,
1035            );
1036        }
1037        self.paint.push(Paint::Icon {
1038            bounds: Bounds::cells(x - GLYPH_LEAD, y as f32 + (1.0 - GLYPH) / 2.0, 2.0, GLYPH),
1039            icon,
1040            color,
1041        });
1042    }
1043
1044    /// The same icon at `SMALL_GLYPH`, for inside a text box or a chip, its left edge at `x`.
1045    #[allow(clippy::too_many_arguments)]
1046    pub fn small_glyph(
1047        &mut self,
1048        x: f32,
1049        y: u16,
1050        icon: Icon,
1051        color: Rgb,
1052        fallback: &str,
1053        style: Style,
1054    ) {
1055        self.glyph(x, y, icon, color, fallback, style);
1056        if let Some(Paint::Icon { bounds, .. }) = self.paint.last_mut() {
1057            let top = y as f32 + (1.0 - SMALL_GLYPH) / 2.0;
1058            *bounds = Bounds::cells(x, top, 2.0, SMALL_GLYPH);
1059        }
1060    }
1061
1062    /// Paint that touches row `y`, in drawing order.
1063    pub fn corners(&mut self, bounds: Bounds, radius: u8, color: Rgb, which: u8) {
1064        self.paint.push(Paint::Corners {
1065            bounds,
1066            radius,
1067            color,
1068            which,
1069        });
1070    }
1071
1072    pub fn paint_on_row(&self, y: u16) -> impl Iterator<Item = &Paint> {
1073        let (top, bottom) = (y as i32 * UNIT, (y as i32 + 1) * UNIT);
1074        let kept_off = move |index: usize| {
1075            self.kept.iter().any(|((from, to), (first, end))| {
1076                (*from..*to).contains(&index) && !(*first..*end).contains(&y)
1077            })
1078        };
1079        self.paint
1080            .iter()
1081            .enumerate()
1082            .filter(move |(index, p)| {
1083                let (from, to) = p.span();
1084                from < bottom && to > top && !kept_off(*index)
1085            })
1086            .map(|(_, paint)| paint)
1087    }
1088
1089    /// The bands of row `y`, as (first column, column past the last), each a tile of its own:
1090    /// `bands`, or `row_bands` on its own row. The last row is the status bar, which nothing
1091    /// scrolls in, and is one.
1092    pub fn spans(&self, y: u16) -> Vec<(u16, u16)> {
1093        let width = self.width;
1094        let own = self.row_bands.as_ref().filter(|(row, _)| *row == y);
1095        let bands = match own {
1096            Some((_, bands)) => bands,
1097            None if y + 1 == self.height => return vec![(0, width)],
1098            None => &self.bands,
1099        };
1100        let inside = bands.iter().copied().filter(|x| *x > 0 && *x < width);
1101        let edges: Vec<u16> = [0].into_iter().chain(inside).chain([width]).collect();
1102        edges.windows(2).map(|edge| (edge[0], edge[1])).collect()
1103    }
1104
1105    pub fn width(&self) -> u16 {
1106        self.width
1107    }
1108
1109    pub fn height(&self) -> u16 {
1110        self.height
1111    }
1112
1113    pub fn area(&self) -> Rect {
1114        Rect::new(0, 0, self.width, self.height)
1115    }
1116
1117    fn index(&self, x: u16, y: u16) -> usize {
1118        y as usize * self.width as usize + x as usize
1119    }
1120
1121    pub fn cell(&self, x: u16, y: u16) -> &Cell {
1122        &self.cells[self.index(x, y)]
1123    }
1124
1125    pub fn row(&self, y: u16) -> &[Cell] {
1126        let start = self.index(0, y);
1127        &self.cells[start..start + self.width as usize]
1128    }
1129
1130    pub fn fill(&mut self, rect: Rect, style: Style) {
1131        for y in rect.y..rect.bottom().min(self.height) {
1132            for x in rect.x..rect.right().min(self.width) {
1133                self.put_cell(x, y, " ", style);
1134            }
1135        }
1136    }
1137
1138    fn put_cell(&mut self, x: u16, y: u16, symbol: &str, style: Style) {
1139        // Overwriting half of a wide character blanks its other half.
1140        let i = self.index(x, y);
1141        if self.cells[i].symbol.is_empty() && x > 0 {
1142            self.cells[i - 1].symbol = " ".into();
1143        }
1144        if x + 1 < self.width && self.cells[i + 1].symbol.is_empty() {
1145            self.cells[i + 1].symbol = " ".into();
1146        }
1147        self.cells[i] = Cell {
1148            symbol: symbol.into(),
1149            style,
1150        };
1151    }
1152
1153    /// Writes text stopping before `max_x`, and returns the column after it. A wide
1154    /// character that doesn't fit becomes a space.
1155    pub fn put_str(&mut self, x: u16, y: u16, text: &str, style: Style, max_x: u16) -> u16 {
1156        if y >= self.height {
1157            return x;
1158        }
1159        let max_x = max_x.min(self.width);
1160        let mut at = x;
1161        let text = visible(text);
1162        for g in text.graphemes(true) {
1163            if at >= max_x {
1164                break;
1165            }
1166            let width = g.width() as u16;
1167            if width == 0 {
1168                continue;
1169            }
1170            if at + width > max_x {
1171                self.put_cell(at, y, " ", style);
1172                return at + 1;
1173            }
1174            self.put_cell(at, y, g, style);
1175            if width == 2 {
1176                self.put_cell(at + 1, y, "", style);
1177            }
1178            at += width;
1179        }
1180        at
1181    }
1182
1183    /// Places a multi-cell icon with its top-left corner at `x`, `y`.
1184    pub fn put_icon(&mut self, x: u16, y: u16, icon: Icon, size: (u8, u8), style: Style) {
1185        for row in 0..size.1 {
1186            for column in 0..size.0 {
1187                let (cx, cy) = (x + u16::from(column), y + u16::from(row));
1188                if cx < self.width && cy < self.height {
1189                    let piece = Piece {
1190                        icon,
1191                        width: size.0,
1192                        height: size.1,
1193                        column,
1194                        row,
1195                    };
1196                    self.put_cell(cx, cy, piece.symbol().encode_utf8(&mut [0; 4]), style);
1197                }
1198            }
1199        }
1200    }
1201
1202    /// Overrides the style of existing cells, keeping their text.
1203    pub fn set_style(&mut self, rect: Rect, f: impl Fn(Style) -> Style) {
1204        for y in rect.y..rect.bottom().min(self.height) {
1205            for x in rect.x..rect.right().min(self.width) {
1206                let i = self.index(x, y);
1207                self.cells[i].style = f(self.cells[i].style);
1208            }
1209        }
1210    }
1211
1212    /// Spans that differ from `prev`. A size change makes the whole grid differ.
1213    pub fn diff(&self, prev: &Grid) -> Vec<Run> {
1214        let same_size = self.width == prev.width && self.height == prev.height;
1215        let mut runs = Vec::new();
1216        for y in 0..self.height {
1217            if same_size && self.row(y) == prev.row(y) {
1218                continue;
1219            }
1220            let mut x = 0;
1221            while x < self.width {
1222                if same_size && self.cell(x, y) == prev.cell(x, y) {
1223                    x += 1;
1224                    continue;
1225                }
1226                let start = x;
1227                while x < self.width && !(same_size && self.cell(x, y) == prev.cell(x, y)) {
1228                    x += 1;
1229                }
1230                // A run must never begin on the right half of a wide character.
1231                let start = if self.cell(start, y).symbol.is_empty() && start > 0 {
1232                    start - 1
1233                } else {
1234                    start
1235                };
1236                runs.push(Run {
1237                    x: start,
1238                    y,
1239                    len: x - start,
1240                });
1241            }
1242        }
1243        runs
1244    }
1245
1246    /// The text of a row, for tests and copy.
1247    pub fn row_text(&self, y: u16) -> String {
1248        self.row(y).iter().map(|c| c.symbol.as_str()).collect()
1249    }
1250
1251    /// Everything on screen, one line per row with trailing spaces removed.
1252    pub fn text(&self) -> String {
1253        (0..self.height)
1254            .map(|y| self.row_text(y).trim_end().to_string())
1255            .collect::<Vec<_>>()
1256            .join("\n")
1257    }
1258}
1259
1260/// Where a button is painted, as (left, top, right, bottom) in columns and rows.
1261fn button_span((height, drop): (f32, f32), (x, y): (u16, u16), width: u16) -> (f32, f32, f32, f32) {
1262    let top = y as f32 + drop + (1.0 - height) / 2.0;
1263    (x as f32, top, (x + width) as f32, top + height)
1264}
1265
1266/// How far a button's row reaches under its foot, in pixels, on rows `row` px tall with words
1267/// sized for a line `line` px tall: what a menu dropping from the button already has clear.
1268pub fn air_under_button(row: f32, line: f32) -> f32 {
1269    row - button_in_row(row, line).1
1270}
1271
1272/// Where a button inside a row's wash (`Grid::row_button`) stands in its row where a row has
1273/// room, its top and its foot in pixels from the row's top, on rows `row` px tall with words
1274/// sized for a line `line` px tall. It's under the row's middle by `WORDS_BASELINE`, as paint
1275/// moves, in whole units.
1276pub fn row_button_in_row(row: f32, line: f32) -> (f32, f32) {
1277    let (_, top, _, bottom) = button_span((BUTTON_HEIGHT, 0.0), (0, 0), 1);
1278    let drop = units(WORDS_BASELINE * line / row) as f32 * row / UNIT as f32;
1279    let (top, tall) = crate::raster::inset(units(top), units(bottom - top), row, line);
1280    (top + drop, top + drop + tall)
1281}
1282
1283/// Where a button's chip stands in its row, its top and its foot in pixels from the row's
1284/// top, on rows `row` px tall with words sized for a line `line` px tall.
1285pub fn button_in_row(row: f32, line: f32) -> (f32, f32) {
1286    let (_, top, _, bottom) = button_span((BUTTON_HEIGHT, 0.0), (0, 0), 1);
1287    let bounds = Bounds::cells(0.0, top, 1.0, bottom - top);
1288    let (y, h) = crate::raster::stood(bounds.y, bounds.h, row, line);
1289    (y, y + h)
1290}
1291
1292/// Whether a click at `at` (columns and rows, with their fractions) lands on the large
1293/// button `Grid::large_button` paints at `(x, y)`, `width` cells wide. It takes the whole
1294/// of what's painted, which stands a little past its row above and below. A terminal
1295/// without pixel reports gives the middle of a cell, so there it's the button's row.
1296pub fn on_large_button((x, y): (u16, u16), width: u16, at: (f32, f32)) -> bool {
1297    let (left, top, right, bottom) = button_span((LARGE_BUTTON_HEIGHT, 0.0), (x, y), width);
1298    at.0 >= left && at.0 < right && at.1 >= top && at.1 < bottom
1299}
1300
1301#[cfg(test)]
1302mod tests {
1303    /// Paint kept to a band of rows shows on those rows only, and paint put in under it
1304    /// later doesn't move which paint that is.
1305    #[test]
1306    fn paint_kept_to_its_rows_is_on_no_other() {
1307        let style = Style::default();
1308        let mut grid = Grid::new(10, 6, style);
1309        let panel = |grid: &mut Grid, y: f32, h: f32| {
1310            grid.panel(Bounds::cells(0.0, y, 10.0, h), 0, Some(Rgb(1, 2, 3)), None);
1311        };
1312        panel(&mut grid, 0.0, 1.0);
1313        let from = grid.painted_so_far();
1314        // A card from the second row to past the fifth, in a list that ends before it.
1315        panel(&mut grid, 1.0, 4.5);
1316        grid.keep_to_rows(from, 2, 4);
1317        panel(&mut grid, 5.0, 1.0);
1318        let on = |grid: &Grid, y: u16| grid.paint_on_row(y).count();
1319        let rows: Vec<usize> = (0..6).map(|y| on(&grid, y)).collect();
1320        assert_eq!(rows, [1, 0, 1, 1, 0, 1]);
1321        // A mark put in before the card: the card is still the one that's kept.
1322        grid.insert_paint(
1323            0,
1324            Paint::Hairline {
1325                bounds: Bounds::cells(0.0, 1.0, 10.0, 0.0),
1326                color: Rgb(9, 9, 9),
1327            },
1328        );
1329        let rows: Vec<usize> = (0..6).map(|y| on(&grid, y)).collect();
1330        assert_eq!(rows, [1, 1, 1, 1, 0, 1]);
1331    }
1332
1333    #[test]
1334    fn control_characters_never_reach_a_cell() {
1335        let style = Style::default();
1336        let mut grid = Grid::new(40, 2, style);
1337        let text = "a\x1b]52;c;aGk=\x07b\r\n\x7f\u{9b}2Jc\td";
1338        let end = grid.put_str(0, 0, text, style, 40);
1339        let row: String = (0..end)
1340            .map(|x| grid.cell(x, 0).symbol.to_string())
1341            .collect();
1342        assert_eq!(row, "a␛]52;c;aGk=␇b␍␊␡\u{fffd}2Jc d");
1343        assert!(row.chars().all(|c| !c.is_control()), "{row:?}");
1344    }
1345
1346    use super::*;
1347
1348    fn grid() -> Grid {
1349        Grid::new(10, 3, Style::default())
1350    }
1351
1352    #[test]
1353    fn diff_emits_only_changed_cells() {
1354        let before = grid();
1355        let mut after = grid();
1356        after.put_str(2, 1, "ab", Style::default(), 10);
1357        after.put_str(7, 1, "c", Style::default(), 10);
1358        assert_eq!(
1359            after.diff(&before),
1360            vec![Run { x: 2, y: 1, len: 2 }, Run { x: 7, y: 1, len: 1 }]
1361        );
1362        assert!(before.diff(&before.clone()).is_empty());
1363    }
1364
1365    #[test]
1366    fn resize_redraws_everything() {
1367        let runs = grid().diff(&Grid::new(4, 4, Style::default()));
1368        assert_eq!(runs.len(), 3);
1369        assert!(runs.iter().all(|r| r.len == 10));
1370    }
1371
1372    #[test]
1373    fn wide_characters_take_two_cells() {
1374        let mut g = grid();
1375        let end = g.put_str(0, 0, "日本", Style::default(), 10);
1376        assert_eq!(end, 4);
1377        assert_eq!(g.cell(0, 0).symbol, "日");
1378        assert_eq!(g.cell(1, 0).symbol, "");
1379        assert_eq!(g.row_text(0).trim_end(), "日本");
1380    }
1381
1382    #[test]
1383    fn overwriting_half_a_wide_character_blanks_the_other_half() {
1384        let mut g = grid();
1385        g.put_str(0, 0, "日", Style::default(), 10);
1386        g.put_str(1, 0, "x", Style::default(), 10);
1387        assert_eq!(g.cell(0, 0).symbol, " ");
1388        assert_eq!(g.cell(1, 0).symbol, "x");
1389    }
1390
1391    #[test]
1392    fn wide_character_at_the_edge_becomes_a_space() {
1393        let mut g = grid();
1394        g.put_str(9, 0, "日", Style::default(), 10);
1395        assert_eq!(g.cell(9, 0).symbol, " ");
1396    }
1397
1398    #[test]
1399    fn combining_marks_stay_in_one_cell() {
1400        let mut g = grid();
1401        let end = g.put_str(0, 0, "e\u{301}x", Style::default(), 10);
1402        assert_eq!(end, 2);
1403        assert_eq!(g.cell(0, 0).symbol, "e\u{301}");
1404    }
1405
1406    #[test]
1407    fn diff_never_starts_on_a_continuation_cell() {
1408        let mut before = grid();
1409        before.put_str(0, 0, "日", Style::default(), 10);
1410        let mut after = grid();
1411        after.put_str(
1412            0,
1413            0,
1414            "日",
1415            Style {
1416                bold: true,
1417                ..Style::default()
1418            },
1419            10,
1420        );
1421        let mut only_right = before.clone();
1422        only_right.cells[1].style.bold = true;
1423        assert_eq!(only_right.diff(&before)[0].x, 0);
1424        assert_eq!(after.diff(&before)[0].x, 0);
1425    }
1426
1427    /// A step taken on the grid as drawn is the grid drawn at that step: the frame the loop
1428    /// shows when nothing but a spinner changed is the one a whole draw would have made.
1429    #[test]
1430    fn a_step_on_the_drawn_grid_is_the_grid_drawn_at_that_step() {
1431        let draw = |step: u8| {
1432            let mut grid = Grid::new(30, 4, Style::default());
1433            grid.turn = Some(step);
1434            grid.put_str(0, 1, "working", Style::default(), 30);
1435            grid.spinner(9.0, 1, 0.65, Rgb(1, 2, 3), Style::default());
1436            grid.dot(12.0, 1, 0.65, Rgb(4, 5, 6), Style::default());
1437            grid.spinner(3.0, 3, 0.65, Rgb(1, 2, 3), Style::default());
1438            grid
1439        };
1440        let mut stepped = draw(0);
1441        for step in [1, 7, 0, 9] {
1442            stepped.turn_to(step);
1443            assert_eq!(stepped, draw(step), "step {step}");
1444        }
1445        assert_eq!(
1446            stepped.cell(12, 1).symbol,
1447            crate::spinner::STILL,
1448            "a dot stays"
1449        );
1450        // Over a spinner's cell, what's drawn after it is left as it is.
1451        let mut covered = draw(0);
1452        covered.put_str(8, 1, "menu", Style::default(), 30);
1453        covered.turn_to(4);
1454        assert_eq!(covered.row_text(1).trim_end(), "working menu●");
1455        // Motion off, nothing turns.
1456        let mut still = Grid::new(30, 4, Style::default());
1457        still.turn = None;
1458        still.spinner(9.0, 1, 0.65, Rgb(1, 2, 3), Style::default());
1459        let before = still.clone();
1460        still.turn_to(3);
1461        assert_eq!(still, before);
1462    }
1463}