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