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