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::Monogram { bounds, .. }
564                | Paint::Spinner { bounds, .. }
565                | Paint::Corners { bounds, .. }
566                | Paint::Strips { bounds, .. } => bounds.x += by,
567                Paint::Image { bounds, clip, .. } => {
568                    bounds.x += by;
569                    clip.x += by;
570                }
571            }
572        }
573    }
574
575    /// A label starting between cells, at a size relative to the interface font.
576    #[allow(clippy::too_many_arguments)]
577    pub fn label_at(
578        &mut self,
579        x_px: f32,
580        x: u16,
581        y: u16,
582        text: &str,
583        style: Style,
584        max_x: u16,
585        size: u8,
586    ) -> u16 {
587        let end = self.put_str(
588            x,
589            y,
590            text,
591            Style {
592                painted: true,
593                ..style
594            },
595            max_x,
596        );
597        if y < self.height {
598            self.paint.push(Paint::Text {
599                x: units(x_px),
600                y: y as i32 * UNIT,
601                max_width: units(max_x.min(self.width) as f32 - x_px),
602                text: text.to_string(),
603                color: style.fg,
604                font: Font {
605                    bold: style.bold,
606                    size,
607                    ..Font::default()
608                },
609                align_right: false,
610                centred: false,
611                underline: false,
612                span_centred: false,
613            });
614        }
615        end
616    }
617
618    /// Paints a run of text with no cells behind it, at a place in cells and rows.
619    pub fn text_run(
620        &mut self,
621        (x, y): (f32, f32),
622        max_x: f32,
623        text: &str,
624        (color, underline): (Rgb, bool),
625        font: Font,
626    ) {
627        self.paint.push(Paint::Text {
628            x: units(x),
629            y: units(y),
630            max_width: units(max_x - x),
631            text: text.to_string(),
632            color,
633            font,
634            align_right: false,
635            centred: false,
636            underline,
637            span_centred: false,
638        });
639    }
640
641    /// Puts the caret at a place between cells, `height` rows tall and centred on `y`.
642    pub fn set_caret(&mut self, x: f32, y: u16, height: f32) {
643        self.cursor = Some((x as u16, y));
644        let top = y as f32 + (1.0 - height) / 2.0;
645        self.caret = Some(Bounds::cells(x, top, 0.0, height));
646    }
647
648    /// A label whose right edge sits at `right`, since proportional text is narrower than
649    /// its cells and would otherwise leave a gap at the end.
650    pub fn label_right(&mut self, right: u16, y: u16, text: &str, style: Style, size: u8) {
651        self.label_right_at(right as f32, right, y, text, style, size);
652    }
653
654    /// The same, its painted words ending at `right`, between cells, and its letters in the
655    /// cells ending at `cell`.
656    pub fn label_right_at(
657        &mut self,
658        right: f32,
659        cell: u16,
660        y: u16,
661        text: &str,
662        style: Style,
663        size: u8,
664    ) {
665        let cells = text.chars().count() as u16;
666        let x = cell.saturating_sub(cells);
667        self.put_str(
668            x,
669            y,
670            text,
671            Style {
672                painted: true,
673                ..style
674            },
675            cell,
676        );
677        self.paint.push(Paint::Text {
678            x: units(right),
679            y: y as i32 * UNIT,
680            max_width: units(right),
681            text: text.to_string(),
682            color: style.fg,
683            font: Font {
684                bold: style.bold,
685                size,
686                ..Font::default()
687            },
688            align_right: true,
689            centred: false,
690            underline: false,
691            span_centred: false,
692        });
693    }
694
695    /// A rounded box inside `rect`, with square corners cleaned up behind it.
696    pub fn field(&mut self, rect: Rect, behind: Rgb, fill: Rgb, border: Rgb) {
697        self.panel(Bounds::inset(rect, 0.0, 0.0), 0, Some(behind), None);
698        // Inset a little from its row, so fields stacked in rows next to each other keep
699        // their air.
700        self.panel(
701            Bounds::inset(rect, 0.15, FIELD_AIR),
702            22,
703            Some(fill),
704            Some(border),
705        );
706    }
707
708    /// A rounded button in a row of its own. The cell tier shows `cells`, which may be
709    /// wider than the label.
710    pub fn button(&mut self, x: u16, y: u16, cells: &str, label: &str, fill: Rgb, style: Style) {
711        self.button_of((BUTTON_HEIGHT, 0.0), (x, y), cells, label, fill, style);
712    }
713
714    /// A button at the end of a row of words, which may be washed under the pointer. Where a
715    /// row has room, it's the height it has on the terminal's line, 32 px in a row of 50 and
716    /// inside a pointed row's wash: as tall as the wash, the two read as one shape with a step
717    /// in it, and taller, as a button too big for its row. Its words' span, a capital's top to
718    /// a tail's foot, stands in its middle as every button's does (at 27 px a "p"'s tail ended
719    /// on its foot), and it goes down with its words onto the row's baseline (`beside_words`).
720    /// On the terminal's line a button and the wash have the row between them and nothing to
721    /// spare, and it's a button like any other.
722    pub fn row_button(
723        &mut self,
724        (x, y): (u16, u16),
725        cells: &str,
726        label: &str,
727        fill: Rgb,
728        style: Style,
729    ) {
730        let from = self.paint.len();
731        self.button(x, y, cells, label, fill, style);
732        if !self.roomy {
733            return;
734        }
735        // Its corners a little tighter with its height: a button's 8 px beside the wash's 4
736        // read as two kinds of shape once there was wash to see round it.
737        for paint in &mut self.paint[from..] {
738            if let Paint::Panel { inset, radius, .. } = paint {
739                *inset = true;
740                *radius = ROW_BUTTON_RADIUS;
741            }
742        }
743        self.beside_words(from);
744    }
745
746    /// The chip of a button at a row's end, from `left` to `right` between cells, behind words
747    /// its caller sets where they stand with the row at rest: as tall as `row_button`'s and in
748    /// the middle of the row, so in the middle of a pointed row's wash, where a row has room.
749    /// Gone down onto the words' baseline, as a `row_button` goes, it stood 10 px under the
750    /// wash's top and 8 over its foot.
751    pub fn row_chip(&mut self, (left, right): (f32, f32), y: u16, fill: Rgb) {
752        let (_, top, _, bottom) = button_span((BUTTON_HEIGHT, 0.0), (0, y), 1);
753        let (radius, inset) = if self.roomy {
754            (ROW_BUTTON_RADIUS, true)
755        } else {
756            (22, false)
757        };
758        self.paint.push(Paint::Panel {
759            bounds: Bounds::cells(left, top, right - left, bottom - top),
760            radius,
761            fill: Some(fill),
762            border: None,
763            shadow: false,
764            dashed: false,
765            inset,
766        });
767    }
768
769    /// Moves a button painted since `from` down onto the baseline of the words beside it in
770    /// its row, chip and words together (`WORDS_BASELINE`), where a row has room. On the
771    /// terminal's line a button has the row to itself and nothing to spare.
772    pub fn beside_words(&mut self, from: usize) {
773        if self.roomy {
774            let line = 100.0 / f32::from(self.row_air.max(1));
775            self.lift_since(from, -WORDS_BASELINE * line);
776        }
777    }
778
779    /// A fill of `color` exactly where `bounds` is. A panel shorter than a row is stood as a
780    /// control is on a taller row (`raster::stood`), grown or shrunk about its middle, which
781    /// a surface reaching part way into a row mustn't be: peek's card reaching into the
782    /// pane's last row stood 4 px clear of its own cells.
783    pub fn exact_fill(&mut self, bounds: Bounds, color: Rgb) {
784        let bitmap = crate::paint::Bitmap {
785            id: EXACT_FILL,
786            width: 1,
787            height: 1,
788            kind: crate::paint::Pixels::Coverage,
789            pixels: std::sync::Arc::new(vec![255]),
790        };
791        self.paint.push(Paint::Image {
792            bounds,
793            clip: bounds,
794            bitmap,
795            color,
796        });
797    }
798
799    /// `exact_fill`, put in under what's been painted from `index` on.
800    pub fn exact_fill_under(&mut self, index: usize, bounds: Bounds, color: Rgb) {
801        self.exact_fill(bounds, color);
802        if let Some(fill) = self.paint.pop() {
803            self.insert_paint(index, fill);
804        }
805    }
806
807    /// A button's chip by itself, as wide as asked and not a whole number of cells, for one
808    /// whose words and marks are placed by what draws it.
809    pub fn chip(&mut self, x: f32, y: u16, wide: f32, fill: Rgb) {
810        let top = y as f32 + (1.0 - BUTTON_HEIGHT) / 2.0;
811        let bounds = Bounds::cells(x, top, wide, BUTTON_HEIGHT);
812        self.panel(bounds, 22, Some(fill), None);
813    }
814
815    /// A button that stands past its row, for where there's air around it.
816    pub fn large_button(
817        &mut self,
818        x: u16,
819        y: u16,
820        cells: &str,
821        label: &str,
822        fill: Rgb,
823        style: Style,
824    ) {
825        self.button_of(
826            (LARGE_BUTTON_HEIGHT, 0.0),
827            (x, y),
828            cells,
829            label,
830            fill,
831            style,
832        );
833    }
834
835    /// A large button centred between `y` and the row below it.
836    pub fn large_button_between(
837        &mut self,
838        x: u16,
839        y: u16,
840        cells: &str,
841        label: &str,
842        fill: Rgb,
843        style: Style,
844    ) {
845        self.button_of(
846            (LARGE_BUTTON_HEIGHT, 0.5),
847            (x, y),
848            cells,
849            label,
850            fill,
851            style,
852        );
853    }
854
855    fn button_of(
856        &mut self,
857        (height, drop): (f32, f32),
858        (x, y): (u16, u16),
859        cells: &str,
860        label: &str,
861        fill: Rgb,
862        style: Style,
863    ) {
864        let width = cells.chars().count() as u16;
865        let (left, top, right, bottom) = button_span((height, drop), (x, y), width);
866        self.put_str(
867            x,
868            y,
869            cells,
870            Style {
871                painted: true,
872                ..style
873            },
874            self.width,
875        );
876        let bounds = Bounds::cells(left, top, right - left, bottom - top);
877        self.panel(bounds, 22, Some(fill), None);
878        let middle = x as f32 + width as f32 / 2.0;
879        self.button_label(middle, y as f32 + drop, label, style.fg, 90);
880    }
881
882    /// A button's words by themselves, centred on `middle` in row `y` and standing in it as a
883    /// button's do, for a control that paints its own chip.
884    pub fn button_words(&mut self, middle: f32, y: u16, label: &str, color: Rgb) {
885        self.button_label(middle, y as f32, label, color, 90);
886    }
887
888    /// Words centred on `x` that stand in the middle of the row starting at `y` as a button's
889    /// do: their font's span, a capital's top to a tail's foot, in its middle, whatever their
890    /// letters, so a row of buttons has one baseline. The font's line in the row's middle put
891    /// "Show Source" 5 px under its button's top and 10 over its foot, and the tails of "Accept
892    /// Rewrite" 6 px over its foot with its capitals 9 under its top.
893    pub fn button_label(&mut self, x: f32, y: f32, text: &str, color: Rgb, size: u8) {
894        self.centred_text(x, y, text, color, size);
895        self.centre_span_since(self.paint.len() - 1);
896    }
897
898    /// Has the words painted since `from` stand as a button's words do (`button_label`), for a
899    /// button that places its own words.
900    pub fn centre_span_since(&mut self, from: usize) {
901        for paint in self.paint.iter_mut().skip(from) {
902            if let Paint::Text { span_centred, .. } = paint {
903                *span_centred = true;
904            }
905        }
906    }
907
908    /// Moves what was painted last down by part of a row.
909    pub fn drop_last(&mut self, by: f32) {
910        match self.paint.last_mut() {
911            Some(Paint::Text { y, .. }) => *y += units(by),
912            Some(Paint::Icon { bounds, .. }) => bounds.y += units(by),
913            _ => {}
914        }
915    }
916
917    /// Paints text centred on `x`, at a place in rows.
918    pub fn centred_text(&mut self, x: f32, y: f32, text: &str, color: Rgb, size: u8) {
919        self.paint.push(Paint::Text {
920            x: units(x),
921            y: units(y),
922            max_width: units(self.width as f32),
923            text: text.to_string(),
924            color,
925            font: Font {
926                size,
927                ..Font::default()
928            },
929            align_right: false,
930            centred: true,
931            underline: false,
932            span_centred: false,
933        });
934    }
935
936    pub fn panel(&mut self, bounds: Bounds, radius: u8, fill: Option<Rgb>, border: Option<Rgb>) {
937        self.paint.push(Paint::Panel {
938            bounds,
939            radius,
940            fill,
941            border,
942            shadow: false,
943            dashed: false,
944            inset: false,
945        });
946    }
947
948    /// A panel with its border in dashes, for something offered rather than settled.
949    pub fn dashed_panel(&mut self, bounds: Bounds, radius: u8, fill: Option<Rgb>, border: Rgb) {
950        self.paint.push(Paint::Panel {
951            bounds,
952            radius,
953            fill,
954            border: Some(border),
955            shadow: false,
956            dashed: true,
957            inset: false,
958        });
959    }
960
961    /// A panel floating above the page, with a soft shadow.
962    pub fn popup(&mut self, bounds: Bounds, radius: u8, fill: Rgb, border: Rgb) {
963        self.paint.push(Paint::Panel {
964            bounds,
965            radius,
966            fill: Some(fill),
967            border: Some(border),
968            shadow: true,
969            dashed: false,
970            inset: false,
971        });
972    }
973
974    /// A panel floating above the page drawn exactly over `bounds`, however much shorter than
975    /// its row: `popup`'s is stood as a control is on a taller row (`raster::stood`), grown or
976    /// shrunk about its middle, and a tip's box sized for its words' ink mustn't be.
977    pub fn exact_popup(&mut self, bounds: Bounds, radius: u8, fill: Rgb, border: Rgb) {
978        self.paint.push(Paint::Panel {
979            bounds,
980            radius,
981            fill: Some(fill),
982            border: Some(border),
983            shadow: true,
984            dashed: false,
985            inset: true,
986        });
987    }
988
989    /// A see-through wash of `color` over `bounds`, `alpha` out of 255, with a border.
990    pub fn wash(
991        &mut self,
992        bounds: Bounds,
993        radius: u8,
994        (color, alpha): (Rgb, u8),
995        border: Option<Rgb>,
996    ) {
997        self.paint.push(Paint::Wash {
998            bounds,
999            radius,
1000            color,
1001            alpha,
1002            border,
1003        });
1004    }
1005
1006    pub fn hairline(&mut self, bounds: Bounds, color: Rgb) {
1007        self.paint.push(Paint::Hairline { bounds, color });
1008    }
1009
1010    /// A small icon in the row, 16 pt in a terminal set to 14 pt, as VS Code's are beside a
1011    /// name. It stands about `x`: its middle is where it was when it was a sixth smaller, so
1012    /// what's placed after it needn't move. `fallback` is what the cell tier shows there.
1013    pub fn glyph(&mut self, x: f32, y: u16, icon: Icon, color: Rgb, fallback: &str, style: Style) {
1014        self.glyph_in((x, x.floor() as u16), y, (icon, color), fallback, style);
1015    }
1016
1017    /// The same, `fallback` on the cell tier in column `cell`, as `spinner_in`'s letter.
1018    pub fn glyph_in(
1019        &mut self,
1020        (x, cell): (f32, u16),
1021        y: u16,
1022        (icon, color): (Icon, Rgb),
1023        fallback: &str,
1024        style: Style,
1025    ) {
1026        if cell < self.width && y < self.height {
1027            self.put_str(
1028                cell,
1029                y,
1030                fallback,
1031                Style {
1032                    painted: true,
1033                    ..style
1034                },
1035                self.width,
1036            );
1037        }
1038        self.paint.push(Paint::Icon {
1039            bounds: Bounds::cells(x - GLYPH_LEAD, y as f32 + (1.0 - GLYPH) / 2.0, 2.0, GLYPH),
1040            icon,
1041            color,
1042        });
1043    }
1044
1045    /// The same icon at `SMALL_GLYPH`, for inside a text box or a chip, its left edge at `x`.
1046    #[allow(clippy::too_many_arguments)]
1047    pub fn small_glyph(
1048        &mut self,
1049        x: f32,
1050        y: u16,
1051        icon: Icon,
1052        color: Rgb,
1053        fallback: &str,
1054        style: Style,
1055    ) {
1056        self.glyph(x, y, icon, color, fallback, style);
1057        if let Some(Paint::Icon { bounds, .. }) = self.paint.last_mut() {
1058            let top = y as f32 + (1.0 - SMALL_GLYPH) / 2.0;
1059            *bounds = Bounds::cells(x, top, 2.0, SMALL_GLYPH);
1060        }
1061    }
1062
1063    /// Paint that touches row `y`, in drawing order.
1064    pub fn corners(&mut self, bounds: Bounds, radius: u8, color: Rgb, which: u8) {
1065        self.paint.push(Paint::Corners {
1066            bounds,
1067            radius,
1068            color,
1069            which,
1070        });
1071    }
1072
1073    pub fn paint_on_row(&self, y: u16) -> impl Iterator<Item = &Paint> {
1074        let (top, bottom) = (y as i32 * UNIT, (y as i32 + 1) * UNIT);
1075        let kept_off = move |index: usize| {
1076            self.kept.iter().any(|((from, to), (first, end))| {
1077                (*from..*to).contains(&index) && !(*first..*end).contains(&y)
1078            })
1079        };
1080        self.paint
1081            .iter()
1082            .enumerate()
1083            .filter(move |(index, p)| {
1084                let (from, to) = p.span();
1085                from < bottom && to > top && !kept_off(*index)
1086            })
1087            .map(|(_, paint)| paint)
1088    }
1089
1090    /// The bands of row `y`, as (first column, column past the last), each a tile of its own:
1091    /// `bands`, or `row_bands` on its own row. The last row is the status bar, which nothing
1092    /// scrolls in, and is one.
1093    pub fn spans(&self, y: u16) -> Vec<(u16, u16)> {
1094        let width = self.width;
1095        let own = self.row_bands.as_ref().filter(|(row, _)| *row == y);
1096        let bands = match own {
1097            Some((_, bands)) => bands,
1098            None if y + 1 == self.height => return vec![(0, width)],
1099            None => &self.bands,
1100        };
1101        let inside = bands.iter().copied().filter(|x| *x > 0 && *x < width);
1102        let edges: Vec<u16> = [0].into_iter().chain(inside).chain([width]).collect();
1103        edges.windows(2).map(|edge| (edge[0], edge[1])).collect()
1104    }
1105
1106    pub fn width(&self) -> u16 {
1107        self.width
1108    }
1109
1110    pub fn height(&self) -> u16 {
1111        self.height
1112    }
1113
1114    pub fn area(&self) -> Rect {
1115        Rect::new(0, 0, self.width, self.height)
1116    }
1117
1118    fn index(&self, x: u16, y: u16) -> usize {
1119        y as usize * self.width as usize + x as usize
1120    }
1121
1122    pub fn cell(&self, x: u16, y: u16) -> &Cell {
1123        &self.cells[self.index(x, y)]
1124    }
1125
1126    pub fn row(&self, y: u16) -> &[Cell] {
1127        let start = self.index(0, y);
1128        &self.cells[start..start + self.width as usize]
1129    }
1130
1131    pub fn fill(&mut self, rect: Rect, style: Style) {
1132        for y in rect.y..rect.bottom().min(self.height) {
1133            for x in rect.x..rect.right().min(self.width) {
1134                self.put_cell(x, y, " ", style);
1135            }
1136        }
1137    }
1138
1139    fn put_cell(&mut self, x: u16, y: u16, symbol: &str, style: Style) {
1140        // Overwriting half of a wide character blanks its other half.
1141        let i = self.index(x, y);
1142        if self.cells[i].symbol.is_empty() && x > 0 {
1143            self.cells[i - 1].symbol = " ".into();
1144        }
1145        if x + 1 < self.width && self.cells[i + 1].symbol.is_empty() {
1146            self.cells[i + 1].symbol = " ".into();
1147        }
1148        self.cells[i] = Cell {
1149            symbol: symbol.into(),
1150            style,
1151        };
1152    }
1153
1154    /// Writes text stopping before `max_x`, and returns the column after it. A wide
1155    /// character that doesn't fit becomes a space.
1156    pub fn put_str(&mut self, x: u16, y: u16, text: &str, style: Style, max_x: u16) -> u16 {
1157        if y >= self.height {
1158            return x;
1159        }
1160        let max_x = max_x.min(self.width);
1161        let mut at = x;
1162        let text = visible(text);
1163        for g in text.graphemes(true) {
1164            if at >= max_x {
1165                break;
1166            }
1167            let width = g.width() as u16;
1168            if width == 0 {
1169                continue;
1170            }
1171            if at + width > max_x {
1172                self.put_cell(at, y, " ", style);
1173                return at + 1;
1174            }
1175            self.put_cell(at, y, g, style);
1176            if width == 2 {
1177                self.put_cell(at + 1, y, "", style);
1178            }
1179            at += width;
1180        }
1181        at
1182    }
1183
1184    /// Places a multi-cell icon with its top-left corner at `x`, `y`.
1185    pub fn put_icon(&mut self, x: u16, y: u16, icon: Icon, size: (u8, u8), style: Style) {
1186        for row in 0..size.1 {
1187            for column in 0..size.0 {
1188                let (cx, cy) = (x + u16::from(column), y + u16::from(row));
1189                if cx < self.width && cy < self.height {
1190                    let piece = Piece {
1191                        icon,
1192                        width: size.0,
1193                        height: size.1,
1194                        column,
1195                        row,
1196                    };
1197                    self.put_cell(cx, cy, piece.symbol().encode_utf8(&mut [0; 4]), style);
1198                }
1199            }
1200        }
1201    }
1202
1203    /// Overrides the style of existing cells, keeping their text.
1204    pub fn set_style(&mut self, rect: Rect, f: impl Fn(Style) -> Style) {
1205        for y in rect.y..rect.bottom().min(self.height) {
1206            for x in rect.x..rect.right().min(self.width) {
1207                let i = self.index(x, y);
1208                self.cells[i].style = f(self.cells[i].style);
1209            }
1210        }
1211    }
1212
1213    /// Spans that differ from `prev`. A size change makes the whole grid differ.
1214    pub fn diff(&self, prev: &Grid) -> Vec<Run> {
1215        let same_size = self.width == prev.width && self.height == prev.height;
1216        let mut runs = Vec::new();
1217        for y in 0..self.height {
1218            if same_size && self.row(y) == prev.row(y) {
1219                continue;
1220            }
1221            let mut x = 0;
1222            while x < self.width {
1223                if same_size && self.cell(x, y) == prev.cell(x, y) {
1224                    x += 1;
1225                    continue;
1226                }
1227                let start = x;
1228                while x < self.width && !(same_size && self.cell(x, y) == prev.cell(x, y)) {
1229                    x += 1;
1230                }
1231                // A run must never begin on the right half of a wide character.
1232                let start = if self.cell(start, y).symbol.is_empty() && start > 0 {
1233                    start - 1
1234                } else {
1235                    start
1236                };
1237                runs.push(Run {
1238                    x: start,
1239                    y,
1240                    len: x - start,
1241                });
1242            }
1243        }
1244        runs
1245    }
1246
1247    /// The text of a row, for tests and copy.
1248    pub fn row_text(&self, y: u16) -> String {
1249        self.row(y).iter().map(|c| c.symbol.as_str()).collect()
1250    }
1251
1252    /// Everything on screen, one line per row with trailing spaces removed.
1253    pub fn text(&self) -> String {
1254        (0..self.height)
1255            .map(|y| self.row_text(y).trim_end().to_string())
1256            .collect::<Vec<_>>()
1257            .join("\n")
1258    }
1259}
1260
1261/// Where a button is painted, as (left, top, right, bottom) in columns and rows.
1262fn button_span((height, drop): (f32, f32), (x, y): (u16, u16), width: u16) -> (f32, f32, f32, f32) {
1263    let top = y as f32 + drop + (1.0 - height) / 2.0;
1264    (x as f32, top, (x + width) as f32, top + height)
1265}
1266
1267/// How far a button's row reaches under its foot, in pixels, on rows `row` px tall with words
1268/// sized for a line `line` px tall: what a menu dropping from the button already has clear.
1269pub fn air_under_button(row: f32, line: f32) -> f32 {
1270    row - button_in_row(row, line).1
1271}
1272
1273/// Where a button inside a row's wash (`Grid::row_button`) stands in its row where a row has
1274/// room, its top and its foot in pixels from the row's top, on rows `row` px tall with words
1275/// sized for a line `line` px tall. It's under the row's middle by `WORDS_BASELINE`, as paint
1276/// moves, in whole units.
1277pub fn row_button_in_row(row: f32, line: f32) -> (f32, f32) {
1278    let (_, top, _, bottom) = button_span((BUTTON_HEIGHT, 0.0), (0, 0), 1);
1279    let drop = units(WORDS_BASELINE * line / row) as f32 * row / UNIT as f32;
1280    let (top, tall) = crate::raster::inset(units(top), units(bottom - top), row, line);
1281    (top + drop, top + drop + tall)
1282}
1283
1284/// Where a button's chip stands in its row, its top and its foot in pixels from the row's
1285/// top, on rows `row` px tall with words sized for a line `line` px tall.
1286pub fn button_in_row(row: f32, line: f32) -> (f32, f32) {
1287    let (_, top, _, bottom) = button_span((BUTTON_HEIGHT, 0.0), (0, 0), 1);
1288    let bounds = Bounds::cells(0.0, top, 1.0, bottom - top);
1289    let (y, h) = crate::raster::stood(bounds.y, bounds.h, row, line);
1290    (y, y + h)
1291}
1292
1293/// Whether a click at `at` (columns and rows, with their fractions) lands on the large
1294/// button `Grid::large_button` paints at `(x, y)`, `width` cells wide. It takes the whole
1295/// of what's painted, which stands a little past its row above and below. A terminal
1296/// without pixel reports gives the middle of a cell, so there it's the button's row.
1297pub fn on_large_button((x, y): (u16, u16), width: u16, at: (f32, f32)) -> bool {
1298    let (left, top, right, bottom) = button_span((LARGE_BUTTON_HEIGHT, 0.0), (x, y), width);
1299    at.0 >= left && at.0 < right && at.1 >= top && at.1 < bottom
1300}
1301
1302#[cfg(test)]
1303mod tests {
1304    /// Paint kept to a band of rows shows on those rows only, and paint put in under it
1305    /// later doesn't move which paint that is.
1306    #[test]
1307    fn paint_kept_to_its_rows_is_on_no_other() {
1308        let style = Style::default();
1309        let mut grid = Grid::new(10, 6, style);
1310        let panel = |grid: &mut Grid, y: f32, h: f32| {
1311            grid.panel(Bounds::cells(0.0, y, 10.0, h), 0, Some(Rgb(1, 2, 3)), None);
1312        };
1313        panel(&mut grid, 0.0, 1.0);
1314        let from = grid.painted_so_far();
1315        // A card from the second row to past the fifth, in a list that ends before it.
1316        panel(&mut grid, 1.0, 4.5);
1317        grid.keep_to_rows(from, 2, 4);
1318        panel(&mut grid, 5.0, 1.0);
1319        let on = |grid: &Grid, y: u16| grid.paint_on_row(y).count();
1320        let rows: Vec<usize> = (0..6).map(|y| on(&grid, y)).collect();
1321        assert_eq!(rows, [1, 0, 1, 1, 0, 1]);
1322        // A mark put in before the card: the card is still the one that's kept.
1323        grid.insert_paint(
1324            0,
1325            Paint::Hairline {
1326                bounds: Bounds::cells(0.0, 1.0, 10.0, 0.0),
1327                color: Rgb(9, 9, 9),
1328            },
1329        );
1330        let rows: Vec<usize> = (0..6).map(|y| on(&grid, y)).collect();
1331        assert_eq!(rows, [1, 1, 1, 1, 0, 1]);
1332    }
1333
1334    #[test]
1335    fn control_characters_never_reach_a_cell() {
1336        let style = Style::default();
1337        let mut grid = Grid::new(40, 2, style);
1338        let text = "a\x1b]52;c;aGk=\x07b\r\n\x7f\u{9b}2Jc\td";
1339        let end = grid.put_str(0, 0, text, style, 40);
1340        let row: String = (0..end)
1341            .map(|x| grid.cell(x, 0).symbol.to_string())
1342            .collect();
1343        assert_eq!(row, "a␛]52;c;aGk=␇b␍␊␡\u{fffd}2Jc d");
1344        assert!(row.chars().all(|c| !c.is_control()), "{row:?}");
1345    }
1346
1347    use super::*;
1348
1349    fn grid() -> Grid {
1350        Grid::new(10, 3, Style::default())
1351    }
1352
1353    #[test]
1354    fn diff_emits_only_changed_cells() {
1355        let before = grid();
1356        let mut after = grid();
1357        after.put_str(2, 1, "ab", Style::default(), 10);
1358        after.put_str(7, 1, "c", Style::default(), 10);
1359        assert_eq!(
1360            after.diff(&before),
1361            vec![Run { x: 2, y: 1, len: 2 }, Run { x: 7, y: 1, len: 1 }]
1362        );
1363        assert!(before.diff(&before.clone()).is_empty());
1364    }
1365
1366    #[test]
1367    fn resize_redraws_everything() {
1368        let runs = grid().diff(&Grid::new(4, 4, Style::default()));
1369        assert_eq!(runs.len(), 3);
1370        assert!(runs.iter().all(|r| r.len == 10));
1371    }
1372
1373    #[test]
1374    fn wide_characters_take_two_cells() {
1375        let mut g = grid();
1376        let end = g.put_str(0, 0, "日本", Style::default(), 10);
1377        assert_eq!(end, 4);
1378        assert_eq!(g.cell(0, 0).symbol, "日");
1379        assert_eq!(g.cell(1, 0).symbol, "");
1380        assert_eq!(g.row_text(0).trim_end(), "日本");
1381    }
1382
1383    #[test]
1384    fn overwriting_half_a_wide_character_blanks_the_other_half() {
1385        let mut g = grid();
1386        g.put_str(0, 0, "日", Style::default(), 10);
1387        g.put_str(1, 0, "x", Style::default(), 10);
1388        assert_eq!(g.cell(0, 0).symbol, " ");
1389        assert_eq!(g.cell(1, 0).symbol, "x");
1390    }
1391
1392    #[test]
1393    fn wide_character_at_the_edge_becomes_a_space() {
1394        let mut g = grid();
1395        g.put_str(9, 0, "日", Style::default(), 10);
1396        assert_eq!(g.cell(9, 0).symbol, " ");
1397    }
1398
1399    #[test]
1400    fn combining_marks_stay_in_one_cell() {
1401        let mut g = grid();
1402        let end = g.put_str(0, 0, "e\u{301}x", Style::default(), 10);
1403        assert_eq!(end, 2);
1404        assert_eq!(g.cell(0, 0).symbol, "e\u{301}");
1405    }
1406
1407    #[test]
1408    fn diff_never_starts_on_a_continuation_cell() {
1409        let mut before = grid();
1410        before.put_str(0, 0, "日", Style::default(), 10);
1411        let mut after = grid();
1412        after.put_str(
1413            0,
1414            0,
1415            "日",
1416            Style {
1417                bold: true,
1418                ..Style::default()
1419            },
1420            10,
1421        );
1422        let mut only_right = before.clone();
1423        only_right.cells[1].style.bold = true;
1424        assert_eq!(only_right.diff(&before)[0].x, 0);
1425        assert_eq!(after.diff(&before)[0].x, 0);
1426    }
1427
1428    /// A step taken on the grid as drawn is the grid drawn at that step: the frame the loop
1429    /// shows when nothing but a spinner changed is the one a whole draw would have made.
1430    #[test]
1431    fn a_step_on_the_drawn_grid_is_the_grid_drawn_at_that_step() {
1432        let draw = |step: u8| {
1433            let mut grid = Grid::new(30, 4, Style::default());
1434            grid.turn = Some(step);
1435            grid.put_str(0, 1, "working", Style::default(), 30);
1436            grid.spinner(9.0, 1, 0.65, Rgb(1, 2, 3), Style::default());
1437            grid.dot(12.0, 1, 0.65, Rgb(4, 5, 6), Style::default());
1438            grid.spinner(3.0, 3, 0.65, Rgb(1, 2, 3), Style::default());
1439            grid
1440        };
1441        let mut stepped = draw(0);
1442        for step in [1, 7, 0, 9] {
1443            stepped.turn_to(step);
1444            assert_eq!(stepped, draw(step), "step {step}");
1445        }
1446        assert_eq!(
1447            stepped.cell(12, 1).symbol,
1448            crate::spinner::STILL,
1449            "a dot stays"
1450        );
1451        // Over a spinner's cell, what's drawn after it is left as it is.
1452        let mut covered = draw(0);
1453        covered.put_str(8, 1, "menu", Style::default(), 30);
1454        covered.turn_to(4);
1455        assert_eq!(covered.row_text(1).trim_end(), "working menu●");
1456        // Motion off, nothing turns.
1457        let mut still = Grid::new(30, 4, Style::default());
1458        still.turn = None;
1459        still.spinner(9.0, 1, 0.65, Rgb(1, 2, 3), Style::default());
1460        let before = still.clone();
1461        still.turn_to(3);
1462        assert_eq!(still, before);
1463    }
1464}