Skip to main content

cellix_render/
raster.rs

1use std::collections::HashMap;
2use std::rc::Rc;
3
4use compact_str::CompactString;
5use cosmic_text::{
6    Attrs, Buffer, Color, Fallback, Family, FontSystem, Metrics, PlatformFallback, Shaping,
7    Style as FontStyle, SwashCache, Weight, fontdb,
8};
9use unicode_script::Script;
10use unicode_width::UnicodeWidthStr;
11
12use crate::grid::{Grid, Rgb};
13use crate::icon::{Icon, Piece, inked};
14use crate::measure::{Font, attrs, emoji_letter, runs};
15use crate::paint::{
16    BOTTOM_LEFT, BOTTOM_RIGHT, Bitmap, Bounds, Paint, Pixels, TOP_LEFT, TOP_RIGHT, UNIT,
17};
18
19/// A tightly packed RGB image, matching the Kitty protocol's `f=24`.
20#[derive(Clone, Debug, PartialEq, Eq)]
21pub struct Image {
22    pub width: usize,
23    pub height: usize,
24    pub rgb: Vec<u8>,
25}
26
27/// Turns one row of a grid into an image.
28pub trait Rasterizer {
29    fn row(&mut self, grid: &Grid, y: u16) -> Image;
30}
31
32#[derive(Clone, Hash, PartialEq, Eq)]
33struct GlyphKey {
34    symbol: CompactString,
35    bold: bool,
36    italic: bool,
37}
38
39/// Coverage of one glyph: pixel offsets from the cell's corner, with alpha.
40type Mask = Rc<Vec<(u16, u16, u8)>>;
41/// A colour glyph: pixel offsets, colours and alpha.
42type Painted = Rc<Vec<(u16, u16, Rgb, u8)>>;
43
44#[derive(Clone, Hash, PartialEq, Eq)]
45struct TextKey {
46    text: String,
47    font: Font,
48}
49
50/// A line of interface text, drawn once and blended wherever it's used.
51struct TextMask {
52    width: usize,
53    height: usize,
54    alpha: Vec<u8>,
55    /// The colour of each pixel that has one of its own, as an emoji's do, where the line
56    /// holds any. The rest take the text's.
57    own: Option<Vec<Option<Rgb>>>,
58    /// The first and last of its rows with ink in them, a capital's or a tall letter's top to
59    /// a tail's foot, or the baseline where it has none. None for a line with no ink at all.
60    ink: Option<(usize, usize)>,
61}
62
63/// How much of a pixel a letter covers before the pixel counts as its ink: a third. The faint
64/// edge of a curve doesn't move where words stand by a whole pixel.
65const INK: u8 = 85;
66
67/// What a button's words are stood by in its middle, whatever letters they have: a capital's
68/// height in their font, its top to the baseline, so tails hang under it as in any interface.
69/// Each by its own ink, a row of buttons had as many baselines and "Dismiss" stood 4 px under
70/// its button's top and 10 over its foot; by a capital's top to a tail's foot, every label
71/// without tails stood 2 to 3 px high (the release review of next, 2026-11-20).
72const SPAN: &str = "H";
73
74/// The first and last rows of a `width`-wide picture whose `alpha` reaches `INK` anywhere.
75fn ink_rows(alpha: &[u8], width: usize) -> Option<(usize, usize)> {
76    let mut rows = alpha
77        .chunks(width.max(1))
78        .enumerate()
79        .filter(|(_, row)| row.iter().any(|a| *a >= INK))
80        .map(|(y, _)| y);
81    let first = rows.next()?;
82    Some((first, rows.next_back().unwrap_or(first)))
83}
84
85/// Fonts that hold Chinese and Japanese. The usual choices can be on-demand downloads a
86/// machine doesn't have, and a missing one leaves the text blank.
87const CJK_FONTS: [&str; 9] = [
88    "PingFang SC",
89    "Hiragino Sans",
90    "Hiragino Sans GB",
91    "Songti SC",
92    "Heiti SC",
93    "Arial Unicode MS",
94    "Noto Sans CJK SC",
95    "Noto Sans CJK JP",
96    "WenQuanYi Micro Hei",
97];
98
99/// The platform's fallback, with a longer list for the scripts it runs out of.
100struct WiderFallback(PlatformFallback);
101
102impl Fallback for WiderFallback {
103    fn common_fallback(&self) -> &[&'static str] {
104        self.0.common_fallback()
105    }
106
107    fn forbidden_fallback(&self) -> &[&'static str] {
108        self.0.forbidden_fallback()
109    }
110
111    fn script_fallback(&self, script: Script, locale: &str) -> &[&'static str] {
112        match script {
113            Script::Han | Script::Hiragana | Script::Katakana => &CJK_FONTS,
114            other => self.0.script_fallback(other, locale),
115        }
116    }
117}
118
119fn system_fonts() -> fontdb::Database {
120    let mut db = fontdb::Database::new();
121    db.load_system_fonts();
122    db
123}
124
125/// The fonts text is drawn with: the ones in the binary, and behind them whatever the
126/// machine has, for the scripts those don't hold and for emoji in the machine's own style.
127fn drawing_fonts() -> FontSystem {
128    let mut fonts = FontSystem::new_with_locale_and_db_and_fallback(
129        "en-US".to_string(),
130        system_fonts(),
131        WiderFallback(PlatformFallback),
132    );
133    let db = fonts.db_mut();
134    db.load_font_data(INTER.to_vec());
135    db.load_font_data(INTER_ITALIC.to_vec());
136    db.load_font_data(MONO.to_vec());
137    db.load_font_data(MONO_ITALIC.to_vec());
138    db.load_font_data(EMOJI.to_vec());
139    db.set_monospace_family("JetBrains Mono");
140    db.set_sans_serif_family("Inter Variable");
141    if EMOJI_FONT.get().is_none() {
142        let found = find_emoji_font(&mut fonts);
143        EMOJI_FONT.get_or_init(|| found);
144    }
145    fonts
146}
147
148/// The font emoji are drawn in, as its family and where it's read from. Found once: finding
149/// it means looking at every font there is, which the rasterizer does as it starts.
150static EMOJI_FONT: std::sync::OnceLock<Option<(String, fontdb::Source)>> =
151    std::sync::OnceLock::new();
152
153/// The machine's own emoji fonts, in the order they're reached for, so emoji look here as
154/// they do in its other programs.
155const SYSTEM_EMOJI: [&str; 3] = ["Apple Color Emoji", "Noto Color Emoji", "Segoe UI Emoji"];
156/// What the emoji font in the binary calls itself: Twemoji, as Mozilla builds it.
157const BUILT_IN_EMOJI: &str = "Twemoji Mozilla";
158
159/// A line of emoji set in one family, when every one of them came from it and not from a
160/// font the search fell back to.
161fn set_in(fonts: &mut FontSystem, family: &str, emoji: &str) -> Option<Buffer> {
162    let mut buffer = Buffer::new(fonts, Metrics::new(32.0, 40.0));
163    buffer.set_size(None, Some(40.0));
164    let attrs = Attrs::new().family(Family::Name(family));
165    let rich = std::iter::once((emoji, attrs.clone()));
166    buffer.set_rich_text(rich, &attrs, Shaping::Advanced, None);
167    buffer.shape_until_scroll(fonts, false);
168    let from_it = |glyph: &cosmic_text::LayoutGlyph| {
169        let face = fonts.db().face(glyph.font_id);
170        glyph.glyph_id != 0
171            && face.is_some_and(|face| face.families.iter().any(|(name, _)| name == family))
172    };
173    let glyphs: Vec<&cosmic_text::LayoutGlyph> = buffer
174        .layout_runs()
175        .flat_map(|run| run.glyphs.iter())
176        .collect();
177    let whole = !glyphs.is_empty() && glyphs.into_iter().all(from_it);
178    whole.then_some(buffer)
179}
180
181/// Whether the emoji font in the binary holds an emoji, whole: one it only has the parts of
182/// would be drawn as those, side by side. This is what a machine with no emoji font of its
183/// own can show, so it's what's worth offering.
184pub fn built_in_emoji_holds(emoji: &str) -> bool {
185    thread_local! {
186        static FONTS: std::cell::RefCell<FontSystem> = std::cell::RefCell::new({
187            let mut db = fontdb::Database::new();
188            db.load_font_data(EMOJI.to_vec());
189            FontSystem::new_with_locale_and_db("en-US".to_string(), db)
190        });
191    }
192    FONTS.with(|fonts| {
193        let set = set_in(&mut fonts.borrow_mut(), BUILT_IN_EMOJI, emoji);
194        set.is_some_and(|buffer| {
195            let glyphs = buffer.layout_runs().flat_map(|run| run.glyphs.iter());
196            glyphs.filter(|glyph| glyph.w > 0.0).count() == 1
197        })
198    })
199}
200
201/// Whether a family's emoji come out in colour here. A font in a format the rasterizer
202/// can't read, as a newer Noto Color Emoji is, draws nothing or a plain shape.
203fn draws_colour(fonts: &mut FontSystem, family: &str) -> bool {
204    let Some(mut buffer) = set_in(fonts, family, "👍") else {
205        return false;
206    };
207    let mut coloured = false;
208    let mut swash = SwashCache::new();
209    let white = Color::rgb(255, 255, 255);
210    buffer.draw(fonts, &mut swash, white, |_, _, _, _, color| {
211        coloured |= color.a() > 0 && (color.r(), color.g(), color.b()) != (255, 255, 255);
212    });
213    coloured
214}
215
216/// The machine's own emoji font where it has one this can draw, and the one in the binary
217/// where it doesn't: a server reached over SSH rarely has any.
218fn find_emoji_font(fonts: &mut FontSystem) -> Option<(String, fontdb::Source)> {
219    // `CELLIX_EMOJI=built-in` keeps to the one in the binary, for the same emoji on every
220    // machine.
221    let built_in_only = std::env::var("CELLIX_EMOJI").is_ok_and(|choice| choice == "built-in");
222    let own = SYSTEM_EMOJI.iter().copied().filter(|_| !built_in_only);
223    for family in own.chain([BUILT_IN_EMOJI]) {
224        let source = fonts
225            .db()
226            .faces()
227            .find(|face| face.families.iter().any(|(name, _)| name == family))
228            .map(|face| face.source.clone());
229        if let Some(source) = source
230            && draws_colour(fonts, family)
231        {
232            return Some((family.to_string(), source));
233        }
234    }
235    None
236}
237
238/// The font emoji are drawn in. Whatever measures text sets its emoji in the same one, or a
239/// caret after an emoji stands in the wrong place.
240pub(crate) fn emoji_font() -> Option<&'static (String, fontdb::Source)> {
241    if EMOJI_FONT.get().is_none() {
242        drop(drawing_fonts());
243    }
244    EMOJI_FONT.get().and_then(Option::as_ref)
245}
246
247/// How dark a floating panel's shadow is at its edge, out of 255.
248const DARK_SHADOW: f32 = 110.0;
249const LIGHT_SHADOW: f32 = 38.0;
250/// Interface text is drawn at this size relative to the row height: 13 pt in a terminal set
251/// to 14 pt, whose row is 18.5 pt, which is the size VS Code sets its own words at.
252pub const INTERFACE_SIZE: f32 = 0.70;
253/// Cached text lines before the cache is dropped, so a long session can't grow it forever.
254const MAX_TEXT_MASKS: usize = 4096;
255
256pub(crate) const INTER: &[u8] = include_bytes!("../fonts/InterVariable.ttf");
257pub(crate) const INTER_ITALIC: &[u8] = include_bytes!("../fonts/InterVariable-Italic.ttf");
258pub(crate) const MONO: &[u8] = include_bytes!("../fonts/JetBrainsMonoVariable.ttf");
259pub(crate) const MONO_ITALIC: &[u8] = include_bytes!("../fonts/JetBrainsMonoVariable-Italic.ttf");
260/// Twemoji, for emoji on a machine with no emoji font of its own.
261pub(crate) const EMOJI: &[u8] = include_bytes!("../fonts/TwemojiMozilla.ttf");
262
263/// The pixel size painted text is drawn at, for a row height and font.
264pub(crate) fn text_pixels(row_height: usize, font: Font) -> f32 {
265    row_height as f32 * INTERFACE_SIZE * font.size as f32 / 100.0
266}
267
268/// Where something `h` paint units tall at `y` stands in rows `row` pixels tall whose words
269/// are set for a line of `line` pixels, as a top and a height in pixels. Anything shorter
270/// than a row keeps the height it has on that line, in the middle of where it stood: a
271/// mark, a badge, a rule. What all but fills its row on that line is a control with a row to
272/// itself, a button, a text box, the band behind a picked row, a tip. On a taller row
273/// those are one height, `CONTROL` of the row, about 20 pt where a row is 26: the air goes
274/// round them and inside them both. A chip, which holds words and is a little shorter than
275/// a control, is `CHIP` of a taller row, so its words stand in its middle with room under
276/// their tails: on the line it's too short for that, and its words are raised in it.
277pub fn stood(y: i32, h: i32, row: f32, line: f32) -> (f32, f32) {
278    let (top, tall) = (y as f32 * row / UNIT as f32, h as f32 * row / UNIT as f32);
279    if h < UNIT && line < row {
280        let kept = h as f32 * line / UNIT as f32;
281        let share = h as f32 / UNIT as f32;
282        let own = if share >= FILLS {
283            kept.max(row * CONTROL).min(tall)
284        } else if share >= HOLDS {
285            kept.max(row * CHIP).min(tall)
286        } else {
287            kept
288        };
289        (top + (tall - own) / 2.0, own)
290    } else {
291        (top, tall)
292    }
293}
294
295/// Where a button on a row's wash stands, as a top and a height in pixels: at the height it
296/// has on the terminal's line, in the middle of where it stood. `stood` grows a button to a
297/// control's height on a taller row, which is the height of the wash behind a pointed row,
298/// so a button on one was exactly as tall as the wash. Kept at the line's height, a button
299/// of 32 px on a wash of 39 has the wash 4 px over it and under it.
300pub fn inset(y: i32, h: i32, row: f32, line: f32) -> (f32, f32) {
301    let (top, tall) = (y as f32 * row / UNIT as f32, h as f32 * row / UNIT as f32);
302    let kept = (h as f32 * line / UNIT as f32).min(tall);
303    (top + (tall - kept) / 2.0, kept)
304}
305
306/// How much of the terminal's line something takes before it counts as a control with the
307/// row to itself, and how much of a taller row such a control is.
308const FILLS: f32 = 0.8;
309const CONTROL: f32 = 0.78;
310/// The same for a chip that holds words: the design's 20 px in a row of 28.
311const HOLDS: f32 = 0.7;
312const CHIP: f32 = 0.714;
313
314/// CPU rendering. Glyphs are rasterized once and blended into their cells, so text stays
315/// locked to the grid and a row costs little more than a copy.
316pub struct SoftwareRasterizer {
317    fonts: FontSystem,
318    /// The font emoji are drawn in, where the machine has one.
319    emoji: Option<String>,
320    swash: SwashCache,
321    metrics: Metrics,
322    cell: (usize, usize),
323    /// The row height that words, icons and controls take their size from. It's the row's
324    /// own, unless Cellix lays out rows taller than the terminal's line: then it's that line.
325    type_row: usize,
326    masks: HashMap<GlyphKey, Mask>,
327    /// Glyphs with colours of their own, such as emoji, as pixels with those colours.
328    painted: HashMap<GlyphKey, Painted>,
329    text: HashMap<TextKey, Rc<TextMask>>,
330}
331
332impl SoftwareRasterizer {
333    /// The fonts ship in the binary, because pixels are drawn on the remote host over SSH
334    /// and servers rarely have any. Returns None only when the cell size is unknown.
335    pub fn new(cell_width: usize, cell_height: usize) -> Option<Self> {
336        if cell_width == 0 || cell_height == 0 {
337            return None;
338        }
339        let mut fonts = drawing_fonts();
340        let metrics = fit_font(&mut fonts, cell_width, cell_height)?;
341        let emoji = emoji_font().map(|(family, _)| family.clone());
342        Some(Self {
343            fonts,
344            emoji,
345            swash: SwashCache::new(),
346            metrics,
347            cell: (cell_width, cell_height),
348            type_row: cell_height,
349            masks: HashMap::new(),
350            painted: HashMap::new(),
351            text: HashMap::new(),
352        })
353    }
354
355    /// Takes the size of words, icons and controls from a row of `rows` pixels instead of
356    /// this one's own height. Where Cellix lays out rows taller than the terminal's line,
357    /// what stands in a row stays the size it is and the row gives it air.
358    pub fn with_type_row(mut self, rows: usize) -> Self {
359        self.type_row = rows.clamp(1, self.cell.1);
360        self
361    }
362
363    /// Where something `h` tall at `y` stands, as a top and a height in pixels. Anything
364    /// shorter than a row is a control or a mark: it keeps the height it has on the
365    /// terminal's own line, in the middle of where it stood.
366    fn stand(&self, y: i32, h: i32) -> (f32, f32) {
367        stood(y, h, self.cell.1 as f32, self.type_row as f32)
368    }
369
370    fn mask(&mut self, key: &GlyphKey) -> Mask {
371        if let Some(mask) = self.masks.get(key) {
372            return mask.clone();
373        }
374        let (width, height) = (self.cell.0 * 2, self.cell.1);
375        let mut buffer = Buffer::new(&mut self.fonts, self.metrics);
376        buffer.set_size(Some(width as f32 * 2.0), Some(height as f32));
377        // Asked for a monospaced Han glyph, the search stops at a font that only has blanks.
378        // A wide glyph fills its two cells whatever font it's from.
379        // And an emoji is drawn in the emoji font: a text font may hold a plain form of it.
380        let emoji = self.emoji.clone().filter(|_| emoji_letter(&key.symbol));
381        let family = if let Some(emoji) = &emoji {
382            Family::Name(emoji)
383        } else if UnicodeWidthStr::width(key.symbol.as_str()) > 1 {
384            Family::SansSerif
385        } else {
386            Family::Monospace
387        };
388        let mut attrs = Attrs::new().family(family);
389        if key.bold {
390            attrs = attrs.weight(Weight::BOLD);
391        }
392        if key.italic {
393            attrs = attrs.style(FontStyle::Italic);
394        }
395        let rich = std::iter::once((key.symbol.as_str(), attrs.clone()));
396        buffer.set_rich_text(rich, &attrs, Shaping::Advanced, None);
397        buffer.shape_until_scroll(&mut self.fonts, false);
398        let mut pixels = Vec::new();
399        let mut coloured = Vec::new();
400        let white = Color::rgb(255, 255, 255);
401        buffer.draw(
402            &mut self.fonts,
403            &mut self.swash,
404            white,
405            |x, y, w, h, color| {
406                if color.a() == 0 {
407                    return;
408                }
409                for py in y..y + h as i32 {
410                    for px in x..x + w as i32 {
411                        if px >= 0 && py >= 0 && (px as usize) < width && (py as usize) < height {
412                            pixels.push((px as u16, py as u16, color.a()));
413                            let rgb = Rgb(color.r(), color.g(), color.b());
414                            coloured.push((px as u16, py as u16, rgb, color.a()));
415                        }
416                    }
417                }
418            },
419        );
420        // A terminal's box-drawing is made to meet the next line's. On a taller row it's
421        // drawn to the row's whole height, or the sides of a box would stop short of each other.
422        if self.type_row < height && boxes(&key.symbol) {
423            pixels = stretched(&pixels, self.type_row, height);
424            coloured.clear();
425        }
426        // Text comes out white, ready to take any colour. Anything else is the glyph's own.
427        if coloured
428            .iter()
429            .any(|(_, _, rgb, _)| *rgb != Rgb(255, 255, 255))
430        {
431            self.painted.insert(key.clone(), Rc::new(coloured));
432        }
433        let mask = Rc::new(pixels);
434        self.masks.insert(key.clone(), mask.clone());
435        mask
436    }
437
438    /// A line of painted text, tall enough for its size.
439    fn text_mask(&mut self, text: &str, font: Font) -> Rc<TextMask> {
440        let key = TextKey {
441            text: text.to_string(),
442            font,
443        };
444        if let Some(mask) = self.text.get(&key) {
445            return mask.clone();
446        }
447        if self.text.len() >= MAX_TEXT_MASKS {
448            self.text.clear();
449        }
450        let px = text_pixels(self.type_row, font);
451        let height = self.cell.1.max((px * 1.45).ceil() as usize);
452        let mut buffer = Buffer::new(&mut self.fonts, Metrics::new(px, height as f32));
453        buffer.set_size(None, Some(height as f32));
454        let emoji = self.emoji.clone();
455        let rich = runs(text, font, emoji.as_deref());
456        buffer.set_rich_text(rich, &attrs(font), Shaping::Advanced, None);
457        buffer.shape_until_scroll(&mut self.fonts, false);
458        let width = buffer
459            .layout_runs()
460            .next()
461            .map_or(0.0, |run| run.line_w)
462            .ceil() as usize
463            + 2;
464        let mut alpha = vec![0; width * height];
465        // Text comes out in the colour it's asked for, and an emoji in its own. Drawn in
466        // white, anything that isn't white is an emoji's.
467        let white = Rgb(255, 255, 255);
468        let mut drawn = vec![white; width * height];
469        let mut tinted = false;
470        buffer.draw(
471            &mut self.fonts,
472            &mut self.swash,
473            Color::rgb(255, 255, 255),
474            |x, y, w, h, color| {
475                let rgb = Rgb(color.r(), color.g(), color.b());
476                tinted |= color.a() > 0 && rgb != white;
477                for at in spots((width, height), (x, y), (w, h)) {
478                    if color.a() >= alpha[at] {
479                        drawn[at] = rgb;
480                    }
481                    alpha[at] = alpha[at].max(color.a());
482                }
483            },
484        );
485        // An emoji has white of its own too, which drawn in white can't be told from text.
486        // Drawn again in black, what turned black is text and what stayed is the emoji's.
487        let own = tinted.then(|| {
488            let black = Rgb(0, 0, 0);
489            let mut own = vec![None; width * height];
490            buffer.draw(
491                &mut self.fonts,
492                &mut self.swash,
493                Color::rgb(0, 0, 0),
494                |x, y, w, h, color| {
495                    let rgb = Rgb(color.r(), color.g(), color.b());
496                    for at in spots((width, height), (x, y), (w, h)) {
497                        if color.a() > 0 && (rgb != black || drawn[at] != white) {
498                            own[at] = Some(drawn[at]);
499                        }
500                    }
501                },
502            );
503            own
504        });
505        let ink = ink_rows(&alpha, width);
506        let mask = Rc::new(TextMask {
507            width,
508            height,
509            alpha,
510            own,
511            ink,
512        });
513        self.text.insert(key, mask.clone());
514        mask
515    }
516
517    fn draw_paint(&mut self, target: &mut Target, paint: &Paint) {
518        let (cw, ch) = (self.cell.0 as f32, self.cell.1 as f32);
519        // What sizes are taken from: the row's own height, or the terminal's line under a
520        // taller row.
521        let th = self.type_row as f32;
522        let scale = |v: i32, cell: f32| v as f32 * cell / UNIT as f32;
523        match paint {
524            Paint::Panel {
525                bounds,
526                radius,
527                fill,
528                border,
529                shadow,
530                dashed,
531                inset: on_a_wash,
532            } => {
533                let (y, h) = match (*on_a_wash, *shadow) {
534                    // A floating panel held to its bounds (`Grid::exact_popup`).
535                    (true, true) => (scale(bounds.y, ch), scale(bounds.h, ch)),
536                    (true, false) => inset(bounds.y, bounds.h, ch, th),
537                    _ => self.stand(bounds.y, bounds.h),
538                };
539                let mut shape = Shape {
540                    x: scale(bounds.x, cw),
541                    y,
542                    w: scale(bounds.w, cw),
543                    h,
544                    radius: *radius as f32 * th / 100.0,
545                };
546                // A panel with a line round it stands on whole pixels, so the line is one
547                // pixel of its own colour on every side. Between pixels it was two rows at
548                // half strength on one side and one at full on the other.
549                if border.is_some() {
550                    let right = (shape.x + shape.w).round();
551                    let bottom = (shape.y + shape.h).round();
552                    shape.x = shape.x.round();
553                    shape.y = shape.y.round();
554                    shape.w = right - shape.x;
555                    shape.h = bottom - shape.y;
556                }
557                target.panel(shape, (*fill, *border), *shadow, *dashed, th);
558            }
559            Paint::Wash {
560                bounds,
561                radius,
562                color,
563                alpha,
564                border,
565            } => {
566                let (y, h) = self.stand(bounds.y, bounds.h);
567                let shape = Shape {
568                    x: scale(bounds.x, cw),
569                    y,
570                    w: scale(bounds.w, cw),
571                    h,
572                    radius: *radius as f32 * th / 100.0,
573                };
574                target.wash(shape, (*color, *alpha), *border, th);
575            }
576            Paint::Hairline { bounds, color } => {
577                let thickness = (th / 24.0).ceil().max(1.0);
578                // Across its length on whole pixels: between two, a menu's rule a fraction of a
579                // row down was a pale band three pixels tall.
580                let (x, y) = (scale(bounds.x, cw), scale(bounds.y, ch));
581                let shape = Shape {
582                    x: if bounds.w == 0 { x.round() } else { x },
583                    y: if bounds.h == 0 { y.round() } else { y },
584                    w: scale(bounds.w, cw).max(thickness),
585                    h: scale(bounds.h, ch).max(thickness),
586                    radius: 0.0,
587                };
588                target.panel(shape, (Some(*color), None), false, false, th);
589            }
590            Paint::Text {
591                x,
592                y,
593                max_width,
594                text,
595                color,
596                font,
597                align_right,
598                centred,
599                underline,
600                span_centred,
601            } => {
602                let mask = self.text_mask(text, *font);
603                let mut left = scale(*x, cw).round() as i32;
604                if *align_right {
605                    left -= mask.width as i32;
606                } else if *centred {
607                    left -= mask.width as i32 / 2;
608                }
609                // Tall text stays centred on its row, and a button's words with their font's
610                // span in its middle (`SPAN`): the span's last row is a whole pixel, so it
611                // reaches to the row after it.
612                let lift = (mask.height as i32 - ch as i32) / 2;
613                let span = span_centred.then(|| self.text_mask(SPAN, *font).ink);
614                let top = match span.flatten() {
615                    Some((first, last)) => {
616                        let middle = scale(*y, ch) + ch / 2.0;
617                        (middle - (first + last + 1) as f32 / 2.0).round() as i32
618                    }
619                    None => scale(*y, ch).round() as i32 - lift,
620                };
621                let limit = scale(*max_width, cw).max(0.0) as usize;
622                target.blit(&mask, left, top, limit, *color);
623                if *underline {
624                    let thickness = (th / 24.0).ceil().max(1.0);
625                    let shape = Shape {
626                        x: left as f32,
627                        // Under the words, which stand in the middle of the row.
628                        y: scale(*y, ch) + (ch - th) / 2.0 + th * 0.78,
629                        w: mask.width.saturating_sub(2).min(limit) as f32,
630                        h: thickness,
631                        radius: 0.0,
632                    };
633                    target.panel(shape, (Some(*color), None), false, false, th);
634                }
635            }
636            Paint::Icon {
637                bounds,
638                icon,
639                color,
640            } => {
641                // An icon is the size it is on the terminal's own line, in the middle of
642                // where a taller row puts it.
643                let side = scale(bounds.h, th);
644                let left = scale(bounds.x, cw);
645                let top = scale(bounds.y, ch) + (scale(bounds.h, ch) - side) / 2.0;
646                target.icon(*icon, left, top, side, *color);
647            }
648            Paint::Spinner {
649                bounds,
650                color,
651                step,
652            } => {
653                let side = scale(bounds.h, th);
654                let left = scale(bounds.x, cw);
655                let top = scale(bounds.y, ch) + (scale(bounds.h, ch) - side) / 2.0;
656                target.spinner(*step, left, top, side, *color);
657            }
658            Paint::Corners {
659                bounds,
660                radius,
661                color,
662                which,
663            } => {
664                let shape = Shape {
665                    x: scale(bounds.x, cw),
666                    y: scale(bounds.y, ch),
667                    w: scale(bounds.w, cw),
668                    h: scale(bounds.h, ch),
669                    radius: *radius as f32 * th / 100.0,
670                };
671                target.corners(&shape, *color, *which);
672            }
673            Paint::Image {
674                bounds,
675                clip,
676                bitmap,
677                color,
678            } => {
679                let shape = Shape {
680                    x: scale(bounds.x, cw),
681                    y: scale(bounds.y, ch),
682                    w: scale(bounds.w, cw),
683                    h: scale(bounds.h, ch),
684                    radius: 0.0,
685                };
686                let across = (
687                    scale(clip.x, cw) as i32,
688                    scale(clip.x + clip.w, cw).ceil() as i32,
689                );
690                let down = (
691                    scale(clip.y, ch) as i32,
692                    scale(clip.y + clip.h, ch).ceil() as i32,
693                );
694                target.image(&shape, (across, down), bitmap, *color);
695            }
696            Paint::Strips { bounds, strips } => {
697                let (left, top) = (scale(bounds.x, cw), scale(bounds.y, ch));
698                let (width, height) = (scale(bounds.w, cw), scale(bounds.h, ch));
699                let thickness = (th / 24.0).ceil().max(1.0);
700                for strip in strips {
701                    let shape = Shape {
702                        x: left + strip.x as f32 * width / 256.0,
703                        y: top + strip.y as f32 * height / 256.0,
704                        w: (strip.w as f32 * width / 256.0).max(1.0),
705                        h: thickness,
706                        radius: 0.0,
707                    };
708                    target.panel(shape, (Some(strip.color), None), false, false, ch);
709                }
710            }
711        }
712    }
713}
714
715/// The places in a `size` image that a box at `at`, `by` across and down, covers.
716fn spots(
717    (width, height): (usize, usize),
718    (x, y): (i32, i32),
719    (w, h): (u32, u32),
720) -> impl Iterator<Item = usize> {
721    let across = x.max(0) as usize..((x + w as i32).max(0) as usize).min(width);
722    let down = y.max(0) as usize..((y + h as i32).max(0) as usize).min(height);
723    down.flat_map(move |py| across.clone().map(move |px| py * width + px))
724}
725
726/// Where the caret goes: its exact place, or the cell the cursor is in.
727fn caret_bounds(grid: &Grid) -> Option<Bounds> {
728    grid.caret.or_else(|| {
729        let (x, y) = grid.cursor?;
730        Some(Bounds::cells(x as f32, y as f32 + 0.08, 0.0, 0.84))
731    })
732}
733
734fn caret_color(grid: &Grid) -> Rgb {
735    let Some((x, y)) = grid.cursor else {
736        return Rgb(255, 255, 255);
737    };
738    grid.cell(x.min(grid.width().saturating_sub(1)), y).style.fg
739}
740
741struct Shape {
742    x: f32,
743    y: f32,
744    w: f32,
745    h: f32,
746    radius: f32,
747}
748
749/// Distance from a point to a rounded box's edge, negative inside.
750fn rounded_distance(shape: &Shape, x: f32, y: f32) -> f32 {
751    let (cx, cy) = (shape.x + shape.w / 2.0, shape.y + shape.h / 2.0);
752    let qx = (x - cx).abs() - shape.w / 2.0 + shape.radius;
753    let qy = (y - cy).abs() - shape.h / 2.0 + shape.radius;
754    let outside = (qx.max(0.0).powi(2) + qy.max(0.0).powi(2)).sqrt();
755    outside + qx.max(qy).min(0.0) - shape.radius
756}
757
758/// The part of the screen one row's tile covers, in screen pixels.
759struct Target<'a> {
760    rgb: &'a mut [u8],
761    width: usize,
762    height: usize,
763    top: i32,
764}
765
766impl Target<'_> {
767    fn corners(&mut self, s: &Shape, color: Rgb, which: u8) {
768        let r = s.radius;
769        let spots = [
770            (TOP_LEFT, s.x, s.y, s.x + r, s.y + r),
771            (TOP_RIGHT, s.x + s.w - r, s.y, s.x + s.w - r, s.y + r),
772            (
773                BOTTOM_RIGHT,
774                s.x + s.w - r,
775                s.y + s.h - r,
776                s.x + s.w - r,
777                s.y + s.h - r,
778            ),
779            (BOTTOM_LEFT, s.x, s.y + s.h - r, s.x + r, s.y + s.h - r),
780        ];
781        for (flag, left, top, cx, cy) in spots {
782            if which & flag == 0 {
783                continue;
784            }
785            for y in top.floor() as i32..(top + r).ceil() as i32 {
786                for x in left.floor() as i32..(left + r).ceil() as i32 {
787                    let d = ((x as f32 + 0.5 - cx).powi(2) + (y as f32 + 0.5 - cy).powi(2)).sqrt();
788                    let outside = (d - r + 0.5).clamp(0.0, 1.0);
789                    self.blend(x, y, color, (outside * 255.0) as u8);
790                }
791            }
792        }
793    }
794
795    fn blend(&mut self, x: i32, y: i32, color: Rgb, alpha: u8) {
796        let row = y - self.top;
797        if alpha == 0 || x < 0 || row < 0 || x as usize >= self.width || row as usize >= self.height
798        {
799            return;
800        }
801        let at = (row as usize * self.width + x as usize) * 3;
802        self.rgb[at] = blend(color.0, self.rgb[at], alpha);
803        self.rgb[at + 1] = blend(color.1, self.rgb[at + 1], alpha);
804        self.rgb[at + 2] = blend(color.2, self.rgb[at + 2], alpha);
805    }
806
807    fn panel(
808        &mut self,
809        s: Shape,
810        (fill, border): (Option<Rgb>, Option<Rgb>),
811        shadow: bool,
812        dashed: bool,
813        row: f32,
814    ) {
815        // Dashes a quarter of a row long, with gaps as long, measured along the edge so every
816        // row of a tall panel continues the same pattern.
817        let dash = (row / 4.0).max(2.0);
818        let on_dash = |x: f32, y: f32| {
819            let along_top = x > s.x + s.radius && x < s.x + s.w - s.radius;
820            let run = if along_top { x - s.x } else { y - s.y };
821            (run / dash).floor() as i64 % 2 == 0
822        };
823        // A shadow falls down and to the sides, never up onto what opened the panel.
824        let reach = if shadow { row * 0.35 } else { 1.0 };
825        let (x0, x1) = (
826            (s.x - reach).floor() as i32,
827            (s.x + s.w + reach).ceil() as i32,
828        );
829        let above = if shadow { 1.0 } else { reach };
830        let y0 = ((s.y - above).floor() as i32).max(self.top);
831        let y1 = ((s.y + s.h + reach).ceil() as i32).min(self.top + self.height as i32);
832        let stroke = (row / 30.0).max(1.0);
833        for y in y0..y1 {
834            for x in x0..x1 {
835                let d = rounded_distance(&s, x as f32 + 0.5, y as f32 + 0.5);
836                if shadow && d > 0.0 && y as f32 + 0.5 > s.y + s.radius {
837                    let fade = (1.0 - d / reach).clamp(0.0, 1.0);
838                    // A shadow heavy enough for dark surfaces is a grey halo on light ones.
839                    let light = fill.is_some_and(|f| f.0 > 180);
840                    let depth = if light { LIGHT_SHADOW } else { DARK_SHADOW };
841                    self.blend(x, y, Rgb(0, 0, 0), (fade * fade * depth) as u8);
842                }
843                let inside = ((0.5 - d) * 255.0).clamp(0.0, 255.0) as u8;
844                if let Some(color) = fill {
845                    self.blend(x, y, color, inside);
846                }
847                if let Some(color) = border
848                    && (!dashed || on_dash(x as f32 + 0.5, y as f32 + 0.5))
849                {
850                    let edge = ((0.5 - (d + stroke / 2.0).abs() + stroke / 2.0) * 255.0)
851                        .clamp(0.0, 255.0) as u8;
852                    self.blend(x, y, color, edge);
853                }
854            }
855        }
856    }
857
858    /// A see-through fill with round corners, and a border twice a panel's weight.
859    fn wash(&mut self, s: Shape, (color, alpha): (Rgb, u8), border: Option<Rgb>, row: f32) {
860        let (x0, x1) = (s.x.floor() as i32 - 1, (s.x + s.w).ceil() as i32 + 1);
861        let y0 = (s.y.floor() as i32 - 1).max(self.top);
862        let y1 = ((s.y + s.h).ceil() as i32 + 1).min(self.top + self.height as i32);
863        let stroke = (row / 15.0).max(2.0);
864        for y in y0..y1 {
865            for x in x0..x1 {
866                let d = rounded_distance(&s, x as f32 + 0.5, y as f32 + 0.5);
867                let inside = (0.5 - d).clamp(0.0, 1.0);
868                self.blend(x, y, color, (inside * alpha as f32) as u8);
869                if let Some(edge_color) = border {
870                    // The border runs just inside the edge.
871                    let along = (0.5 - (d + stroke / 2.0).abs() + stroke / 2.0).clamp(0.0, 1.0);
872                    self.blend(x, y, edge_color, (along * 255.0) as u8);
873                }
874            }
875        }
876    }
877
878    fn blit(&mut self, mask: &TextMask, left: i32, top: i32, limit: usize, color: Rgb) {
879        let from = (self.top - top).max(0) as usize;
880        let to = ((self.top + self.height as i32 - top).max(0) as usize).min(mask.height);
881        for y in from..to {
882            for x in 0..mask.width.min(limit) {
883                let at = y * mask.width + x;
884                let ink = mask.own.as_ref().and_then(|own| own[at]).unwrap_or(color);
885                self.blend(left + x as i32, top + y as i32, ink, mask.alpha[at]);
886            }
887        }
888    }
889
890    /// Scales a bitmap into `s`, sampling between its pixels so nothing shimmers.
891    fn image(&mut self, s: &Shape, clip: ((i32, i32), (i32, i32)), bitmap: &Bitmap, color: Rgb) {
892        let (width, height) = (bitmap.width as usize, bitmap.height as usize);
893        if width == 0 || height == 0 || s.w <= 0.0 || s.h <= 0.0 {
894            return;
895        }
896        let channels = match bitmap.kind {
897            Pixels::Coverage => 1,
898            Pixels::Rgba => 4,
899        };
900        let at = |x: usize, y: usize, c: usize| -> f32 {
901            let index = (y.min(height - 1) * width + x.min(width - 1)) * channels + c;
902            bitmap.pixels.get(index).copied().unwrap_or(0) as f32
903        };
904        let sample = |u: f32, v: f32, c: usize| -> f32 {
905            let (fx, fy) = (u.max(0.0), v.max(0.0));
906            let (x, y) = (fx as usize, fy as usize);
907            let (dx, dy) = (fx - x as f32, fy - y as f32);
908            let top = at(x, y, c) * (1.0 - dx) + at(x + 1, y, c) * dx;
909            let bottom = at(x, y + 1, c) * (1.0 - dx) + at(x + 1, y + 1, c) * dx;
910            top * (1.0 - dy) + bottom * dy
911        };
912        let ((left, right), (top, bottom)) = clip;
913        let y0 = (s.y.floor() as i32).max(self.top).max(top);
914        let y1 = ((s.y + s.h).ceil() as i32)
915            .min(self.top + self.height as i32)
916            .min(bottom);
917        let x0 = (s.x.floor() as i32).max(0).max(left);
918        let x1 = ((s.x + s.w).ceil() as i32)
919            .min(self.width as i32)
920            .min(right);
921        let (ax, ay) = (width as f32 / s.w, height as f32 / s.h);
922        // A frame made for exactly this size is a copy, which keeps a live page cheap.
923        if bitmap.kind == Pixels::Rgba && (ax - 1.0).abs() < 0.002 && (ay - 1.0).abs() < 0.002 {
924            let (left, top) = (s.x.round() as i32, s.y.round() as i32);
925            for y in y0..y1 {
926                for x in x0..x1 {
927                    let (u, v) = (x - left, y - top);
928                    if u < 0 || v < 0 || u as usize >= width || v as usize >= height {
929                        continue;
930                    }
931                    let at = (v as usize * width + u as usize) * 4;
932                    if let Some(p) = bitmap.pixels.get(at..at + 4) {
933                        self.blend(x, y, Rgb(p[0], p[1], p[2]), p[3]);
934                    }
935                }
936            }
937            return;
938        }
939        for y in y0..y1 {
940            for x in x0..x1 {
941                let u = (x as f32 + 0.5 - s.x) * ax - 0.5;
942                let v = (y as f32 + 0.5 - s.y) * ay - 0.5;
943                match bitmap.kind {
944                    Pixels::Coverage => self.blend(x, y, color, sample(u, v, 0) as u8),
945                    Pixels::Rgba => {
946                        let ink = Rgb(
947                            sample(u, v, 0) as u8,
948                            sample(u, v, 1) as u8,
949                            sample(u, v, 2) as u8,
950                        );
951                        self.blend(x, y, ink, sample(u, v, 3) as u8);
952                    }
953                }
954            }
955        }
956    }
957
958    /// A spinner in a square box: its ring at a quarter of the colour's strength and its arc
959    /// over that at full, or with no step a still dot.
960    fn spinner(&mut self, step: Option<u8>, left: f32, top: f32, side: f32, color: Rgb) {
961        const SAMPLES: usize = 5;
962        let y0 = (top.floor() as i32).max(self.top);
963        let y1 = ((top + side).ceil() as i32).min(self.top + self.height as i32);
964        for y in y0..y1 {
965            for x in left.floor() as i32..(left + side).ceil() as i32 {
966                let (mut ring, mut arc) = (0, 0);
967                for sy in 0..SAMPLES {
968                    for sx in 0..SAMPLES {
969                        let u = (x as f32 + (sx as f32 + 0.5) / SAMPLES as f32 - left) / side;
970                        let v = (y as f32 + (sy as f32 + 0.5) / SAMPLES as f32 - top) / side;
971                        if (0.0..1.0).contains(&u) && (0.0..1.0).contains(&v) {
972                            let (r, a) = crate::spinner::inked(step, u, v);
973                            ring += usize::from(r);
974                            arc += usize::from(a);
975                        }
976                    }
977                }
978                let all = SAMPLES * SAMPLES;
979                self.blend(x, y, color, (ring * 64 / all) as u8);
980                self.blend(x, y, color, (arc * 255 / all) as u8);
981            }
982        }
983    }
984
985    fn icon(&mut self, icon: Icon, left: f32, top: f32, side: f32, color: Rgb) {
986        // Five by five keeps thin curved strokes smooth, and tiles only draw this once.
987        const SAMPLES: usize = 5;
988        let y0 = (top.floor() as i32).max(self.top);
989        let y1 = ((top + side).ceil() as i32).min(self.top + self.height as i32);
990        for y in y0..y1 {
991            for x in left.floor() as i32..(left + side).ceil() as i32 {
992                let mut hits = 0;
993                for sy in 0..SAMPLES {
994                    for sx in 0..SAMPLES {
995                        let u = (x as f32 + (sx as f32 + 0.5) / SAMPLES as f32 - left) / side;
996                        let v = (y as f32 + (sy as f32 + 0.5) / SAMPLES as f32 - top) / side;
997                        if (0.0..1.0).contains(&u) && (0.0..1.0).contains(&v) && inked(icon, u, v) {
998                            hits += 1;
999                        }
1000                    }
1001                }
1002                self.blend(x, y, color, (hits * 255 / (SAMPLES * SAMPLES)) as u8);
1003            }
1004        }
1005    }
1006}
1007
1008/// Whether a cell holds box-drawing or a block element, which join across rows.
1009fn boxes(symbol: &str) -> bool {
1010    let mut chars = symbol.chars();
1011    matches!(
1012        (chars.next(), chars.next()),
1013        (Some('\u{2500}'..='\u{259f}'), None)
1014    )
1015}
1016
1017/// A glyph drawn in the middle `from` rows of `to`, pulled out to fill all of them.
1018fn stretched(pixels: &[(u16, u16, u8)], from: usize, to: usize) -> Vec<(u16, u16, u8)> {
1019    let first = (to - from) / 2;
1020    let mut out = Vec::with_capacity(pixels.len() * to / from.max(1) + 1);
1021    for &(x, y, alpha) in pixels {
1022        let line = (y as usize).checked_sub(first).filter(|line| *line < from);
1023        let Some(line) = line else { continue };
1024        for row in line * to / from..(line + 1) * to / from {
1025            out.push((x, row as u16, alpha));
1026        }
1027    }
1028    out
1029}
1030
1031/// Picks the largest font whose advance fits the cell and whose height fits the row.
1032fn fit_font(fonts: &mut FontSystem, cell_width: usize, cell_height: usize) -> Option<Metrics> {
1033    const PROBE: f32 = 100.0;
1034    let mut buffer = Buffer::new(fonts, Metrics::new(PROBE, PROBE * 1.2));
1035    buffer.set_size(Some(PROBE * 4.0), Some(PROBE * 2.0));
1036    let attrs = Attrs::new().family(Family::Monospace);
1037    buffer.set_rich_text(
1038        std::iter::once(("M", attrs.clone())),
1039        &attrs,
1040        Shaping::Advanced,
1041        None,
1042    );
1043    buffer.shape_until_scroll(fonts, false);
1044    let advance = buffer.layout_runs().next()?.line_w;
1045    if advance <= 0.0 {
1046        return None;
1047    }
1048    let by_width = cell_width as f32 * PROBE / advance;
1049    let by_height = cell_height as f32 * 0.8;
1050    Some(Metrics::new(by_width.min(by_height), cell_height as f32))
1051}
1052
1053/// Inks this cell's share of an icon, supersampled so curves stay smooth.
1054fn draw_icon(
1055    rgb: &mut [u8],
1056    stride: usize,
1057    left: usize,
1058    cell: (usize, usize),
1059    piece: Piece,
1060    fg: Rgb,
1061) {
1062    const SAMPLES: usize = 4;
1063    let (cw, ch) = cell;
1064    let (full_w, full_h) = (cw * piece.width as usize, ch * piece.height as usize);
1065    let side = full_w.min(full_h) as f32 * 0.94;
1066    let (off_x, off_y) = ((full_w as f32 - side) / 2.0, (full_h as f32 - side) / 2.0);
1067    for y in 0..ch {
1068        for x in 0..cw {
1069            let mut hits = 0;
1070            for sy in 0..SAMPLES {
1071                for sx in 0..SAMPLES {
1072                    let px = (piece.column as usize * cw + x) as f32
1073                        + (sx as f32 + 0.5) / SAMPLES as f32;
1074                    let py =
1075                        (piece.row as usize * ch + y) as f32 + (sy as f32 + 0.5) / SAMPLES as f32;
1076                    let (u, v) = ((px - off_x) / side, (py - off_y) / side);
1077                    if (0.0..1.0).contains(&u) && (0.0..1.0).contains(&v) && inked(piece.icon, u, v)
1078                    {
1079                        hits += 1;
1080                    }
1081                }
1082            }
1083            if hits > 0 {
1084                let alpha = (hits * 255 / (SAMPLES * SAMPLES)) as u8;
1085                let at = (y * stride + left + x) * 3;
1086                rgb[at] = blend(fg.0, rgb[at], alpha);
1087                rgb[at + 1] = blend(fg.1, rgb[at + 1], alpha);
1088                rgb[at + 2] = blend(fg.2, rgb[at + 2], alpha);
1089            }
1090        }
1091    }
1092}
1093
1094fn blend(fg: u8, bg: u8, alpha: u8) -> u8 {
1095    let a = alpha as u32;
1096    ((fg as u32 * a + bg as u32 * (255 - a)) / 255) as u8
1097}
1098
1099fn fill(rgb: &mut [u8], stride: usize, x: usize, y: usize, w: usize, h: usize, color: Rgb) {
1100    for row in y..y + h {
1101        for px in x..x + w {
1102            let i = (row * stride + px) * 3;
1103            if i + 2 < rgb.len() {
1104                rgb[i..i + 3].copy_from_slice(&[color.0, color.1, color.2]);
1105            }
1106        }
1107    }
1108}
1109
1110impl Rasterizer for SoftwareRasterizer {
1111    fn row(&mut self, grid: &Grid, y: u16) -> Image {
1112        let cells = grid.row(y);
1113        let (cw, ch) = self.cell;
1114        let width = cw * cells.len();
1115        let mut rgb = vec![0; width * ch * 3];
1116        // Backgrounds first: a wide glyph runs into the next cell, whose colour would cut it.
1117        for (i, cell) in cells.iter().enumerate() {
1118            fill(&mut rgb, width, i * cw, 0, cw, ch, cell.style.bg);
1119        }
1120        for (i, cell) in cells.iter().enumerate() {
1121            let fg = cell.style.fg;
1122            if cell.symbol.is_empty() || cell.symbol == " " || cell.style.painted {
1123                continue;
1124            }
1125            // Drawn rather than taken from a font, so stacked rows join with no gap.
1126            if cell.symbol == "▌" {
1127                fill(&mut rgb, width, i * cw, 0, cw.div_ceil(5), ch, fg);
1128                continue;
1129            }
1130            if let Some(piece) = Piece::decode(&cell.symbol) {
1131                draw_icon(&mut rgb, width, i * cw, (cw, ch), piece, fg);
1132                continue;
1133            }
1134            let key = GlyphKey {
1135                symbol: cell.symbol.clone(),
1136                bold: cell.style.bold,
1137                italic: cell.style.italic,
1138            };
1139            let mask = self.mask(&key);
1140            if let Some(painted) = self.painted.get(&key) {
1141                for &(x, y, color, alpha) in painted.iter() {
1142                    let at = (y as usize * width + i * cw + x as usize) * 3;
1143                    if at + 2 < rgb.len() && (i * cw + x as usize) < width {
1144                        rgb[at] = blend(color.0, rgb[at], alpha);
1145                        rgb[at + 1] = blend(color.1, rgb[at + 1], alpha);
1146                        rgb[at + 2] = blend(color.2, rgb[at + 2], alpha);
1147                    }
1148                }
1149                continue;
1150            }
1151            for &(x, y, alpha) in mask.iter() {
1152                let at = (y as usize * width + i * cw + x as usize) * 3;
1153                if at + 2 < rgb.len() && (i * cw + x as usize) < width {
1154                    rgb[at] = blend(fg.0, rgb[at], alpha);
1155                    rgb[at + 1] = blend(fg.1, rgb[at + 1], alpha);
1156                    rgb[at + 2] = blend(fg.2, rgb[at + 2], alpha);
1157                }
1158            }
1159        }
1160        for (i, cell) in cells.iter().enumerate() {
1161            // Painted text underlines itself, at its true width.
1162            if cell.style.underline && !cell.style.painted {
1163                fill(&mut rgb, width, i * cw, ch - 2, cw, 1, cell.style.fg);
1164            }
1165        }
1166        let paint: Vec<Paint> = grid.paint_on_row(y).cloned().collect();
1167        let mut target = Target {
1168            rgb: &mut rgb,
1169            width,
1170            height: ch,
1171            top: y as i32 * ch as i32,
1172        };
1173        for item in &paint {
1174            self.draw_paint(&mut target, item);
1175        }
1176        // A thin caret, as in a real editor, not a terminal's block.
1177        if let Some(bounds) = caret_bounds(grid) {
1178            let row = (y as i32 * UNIT, (y as i32 + 1) * UNIT);
1179            if bounds.y < row.1 && bounds.y + bounds.h > row.0 {
1180                // As tall as the words it stands among, whatever the row's height.
1181                let tall = bounds.h as f32 * ch as f32 / UNIT as f32;
1182                let own = if bounds.h <= UNIT {
1183                    bounds.h as f32 * self.type_row as f32 / UNIT as f32
1184                } else {
1185                    tall
1186                };
1187                let shape = Shape {
1188                    x: bounds.x as f32 * cw as f32 / UNIT as f32,
1189                    y: bounds.y as f32 * ch as f32 / UNIT as f32 + (tall - own) / 2.0,
1190                    w: (cw as f32 / 9.0).max(2.0),
1191                    h: own,
1192                    radius: 0.0,
1193                };
1194                let mut target = Target {
1195                    rgb: &mut rgb,
1196                    width,
1197                    height: ch,
1198                    top: y as i32 * ch as i32,
1199                };
1200                target.panel(
1201                    shape,
1202                    (Some(caret_color(grid)), None),
1203                    false,
1204                    false,
1205                    self.type_row as f32,
1206                );
1207            }
1208        }
1209        Image {
1210            width,
1211            height: ch,
1212            rgb,
1213        }
1214    }
1215}
1216
1217#[cfg(test)]
1218mod tests {
1219    use super::*;
1220    use crate::grid::{Grid, Rect, Style};
1221
1222    fn rasterizer() -> Option<SoftwareRasterizer> {
1223        SoftwareRasterizer::new(10, 20)
1224    }
1225
1226    fn style() -> Style {
1227        Style {
1228            fg: Rgb(250, 250, 250),
1229            bg: Rgb(10, 20, 30),
1230            ..Style::default()
1231        }
1232    }
1233
1234    fn lit(image: &Image, cell: usize, width: usize) -> usize {
1235        let mut count = 0;
1236        for y in 0..image.height {
1237            for x in cell * width..(cell + 1) * width {
1238                let i = (y * image.width + x) * 3;
1239                count += usize::from(image.rgb[i] > 128);
1240            }
1241        }
1242        count
1243    }
1244
1245    #[test]
1246    fn row_image_is_exactly_the_grid_size() {
1247        let Some(mut r) = rasterizer() else { return };
1248        let grid = Grid::new(8, 1, style());
1249        let image = r.row(&grid, 0);
1250        assert_eq!((image.width, image.height), (80, 20));
1251        assert_eq!(image.rgb.len(), 80 * 20 * 3);
1252    }
1253
1254    #[test]
1255    fn han_characters_are_drawn_in_the_cells() {
1256        let Some(mut r) = rasterizer() else { return };
1257        let fonts = system_fonts();
1258        let has_han = fonts.faces().any(|face| {
1259            let name = &face.families[0].0;
1260            CJK_FONTS.iter().any(|font| font == name)
1261        });
1262        if !has_han {
1263            return;
1264        }
1265        let mut grid = Grid::new(4, 1, style());
1266        grid.put_str(0, 0, "中", style(), 4);
1267        let image = r.row(&grid, 0);
1268        assert!(lit(&image, 0, 10) > 10);
1269    }
1270
1271    #[test]
1272    fn a_wide_glyph_keeps_its_right_half() {
1273        let Some(mut r) = rasterizer() else { return };
1274        let mut grid = Grid::new(4, 1, style());
1275        grid.put_str(1, 0, "MM", style(), 4);
1276        let image = r.row(&grid, 0);
1277        assert!(lit(&image, 1, 10) > 10);
1278        assert!(
1279            lit(&image, 2, 10) > 10,
1280            "the next cell's colour didn't cover it"
1281        );
1282    }
1283
1284    #[test]
1285    fn glyphs_land_in_their_own_cells() {
1286        let Some(mut r) = rasterizer() else { return };
1287        let mut grid = Grid::new(4, 1, style());
1288        grid.put_str(2, 0, "M", style(), 4);
1289        let image = r.row(&grid, 0);
1290        assert_eq!(lit(&image, 0, 10), 0);
1291        assert!(lit(&image, 2, 10) > 10, "M drew nothing");
1292        assert_eq!(lit(&image, 3, 10), 0, "M spilled into the next cell");
1293    }
1294
1295    #[test]
1296    fn the_caret_is_a_thin_line() {
1297        let Some(mut r) = rasterizer() else { return };
1298        let mut grid = Grid::new(3, 1, style());
1299        grid.cursor = Some((1, 0));
1300        let image = r.row(&grid, 0);
1301        let at = |x: usize| image.rgb[(10 * image.width + x) * 3];
1302        assert_eq!(at(10), 250);
1303        assert_eq!(at(15), 10);
1304        grid.caret = Some(Bounds::cells(1.5, 0.0, 0.0, 1.0));
1305        let image = r.row(&grid, 0);
1306        let at = |x: usize| image.rgb[(10 * image.width + x) * 3];
1307        assert_eq!(at(10), 10, "the exact caret replaces the cell one");
1308        assert_eq!(at(15), 250);
1309    }
1310
1311    #[test]
1312    fn labels_draw_without_their_cell_glyphs() {
1313        let Some(mut r) = rasterizer() else { return };
1314        let mut grid = Grid::new(20, 1, style());
1315        grid.label(1, 0, "Illi", style(), 20);
1316        assert!(grid.cell(1, 0).style.painted);
1317        let with_paint = r.row(&grid, 0);
1318        // Inter is proportional: this text is far narrower than four cells.
1319        let lit_right = (0..20)
1320            .flat_map(|y| (40..200).map(move |x| (x, y)))
1321            .any(|(x, y)| with_paint.rgb[(y * with_paint.width + x) * 3] > 128);
1322        assert!(!lit_right, "drew past the narrow label");
1323    }
1324
1325    /// Words are set at the size VS Code sets its own: 13 pt. A terminal set to 14 pt has a
1326    /// cell of 17 by 37 px at two pixels a point, and a capital of 13 pt Inter stands 19 px
1327    /// tall there, with as much of the row over it as under it. At three fifths of a row,
1328    /// as the words were, it stood 16.
1329    #[test]
1330    fn words_are_thirteen_points_in_a_terminal_set_to_fourteen() {
1331        use crate::measure::Measure as _;
1332        let Some(mut r) = SoftwareRasterizer::new(17, 37) else {
1333            return;
1334        };
1335        let mut grid = Grid::new(8, 1, style());
1336        grid.label(1, 0, "H", style(), 8);
1337        let image = r.row(&grid, 0);
1338        let inked: Vec<usize> = (0..image.height)
1339            .filter(|y| (0..image.width).any(|x| image.rgb[(y * image.width + x) * 3] > 128))
1340            .collect();
1341        let (top, bottom) = (inked[0], inked[inked.len() - 1]);
1342        let tall = bottom - top + 1;
1343        assert!((18..=20).contains(&tall), "a capital is {tall} px tall");
1344        let (over, under) = (top, image.height - 1 - bottom);
1345        assert!(
1346            over.abs_diff(under) <= 2,
1347            "{over} px over it, {under} under"
1348        );
1349        // And as wide as 13 pt is: the measure and the picture agree on it.
1350        let wide = crate::measure::FontMeasure::new(17, 37).width("H", Font::default()) * 17.0;
1351        assert!((17.0..21.0).contains(&wide), "an H is {wide} px wide");
1352    }
1353
1354    /// Where Cellix's rows are taller than the terminal's line, words stay the size they are
1355    /// on that line and stand in the middle of the taller row, which is air round them. So
1356    /// does a chip, being shorter than a row. And the side of a terminal's box is drawn the
1357    /// whole height of the row, so it meets the one in the next.
1358    #[test]
1359    fn a_taller_row_is_air_round_what_stands_in_it() {
1360        use crate::measure::Measure as _;
1361        let Some(r) = SoftwareRasterizer::new(17, 52) else {
1362            return;
1363        };
1364        let mut r = r.with_type_row(37);
1365        let mut grid = Grid::new(8, 1, style());
1366        grid.label(1, 0, "H", style(), 8);
1367        let image = r.row(&grid, 0);
1368        assert_eq!(image.height, 52);
1369        let inked: Vec<usize> = (0..image.height)
1370            .filter(|y| (0..image.width).any(|x| image.rgb[(y * image.width + x) * 3] > 128))
1371            .collect();
1372        let (top, bottom) = (inked[0], inked[inked.len() - 1]);
1373        let tall = bottom - top + 1;
1374        assert!(
1375            (18..=20).contains(&tall),
1376            "a capital is still {tall} px tall"
1377        );
1378        let (over, under) = (top, image.height - 1 - bottom);
1379        assert!(
1380            over.abs_diff(under) <= 2,
1381            "{over} px over it, {under} under"
1382        );
1383        let measure = crate::measure::FontMeasure::new(17, 52).with_type_row(37);
1384        let wide = measure.width("H", Font::default()) * 17.0;
1385        assert!((17.0..21.0).contains(&wide), "and as wide: {wide} px");
1386        // A badge five eighths of a row tall is five eighths of the line's 37 pixels. A chip
1387        // that holds words is taller than that, and grows: see
1388        // `a_control_is_one_height_on_a_taller_row`.
1389        let mut grid = Grid::new(8, 1, style());
1390        let chip = crate::paint::Bounds::cells(1.0, 0.1875, 4.0, 0.625);
1391        grid.panel(chip, 20, Some(Rgb(255, 0, 0)), None);
1392        let image = r.row(&grid, 0);
1393        let red: Vec<usize> = (0..image.height)
1394            .filter(|y| {
1395                let at = (y * image.width + 51) * 3;
1396                image.rgb[at] > 200 && image.rgb[at + 1] < 60
1397            })
1398            .collect();
1399        assert!(
1400            (22..=25).contains(&red.len()),
1401            "the badge is {} px tall",
1402            red.len()
1403        );
1404        let (over, under) = (red[0], 51 - red[red.len() - 1]);
1405        assert!(
1406            over.abs_diff(under) <= 2,
1407            "{over} px over it, {under} under"
1408        );
1409        // The side of a box, from a terminal in the side pane.
1410        let mut grid = Grid::new(4, 1, style());
1411        grid.put_str(1, 0, "│", style(), 4);
1412        let image = r.row(&grid, 0);
1413        let inked = (0..image.height)
1414            .filter(|y| (17..34).any(|x| image.rgb[(y * image.width + x) * 3] > 100))
1415            .count();
1416        assert!(inked >= 50, "the side is {inked} px of the row's 52");
1417    }
1418
1419    /// On a taller row a control was the 32 px it is on the terminal's line, in 50 px of
1420    /// row, with its words 3 px high in it. The design has one height for a button, a text
1421    /// box, the band behind a picked row and a tip: about 20 pt in a row of 26.
1422    #[test]
1423    fn a_control_is_one_height_on_a_taller_row() {
1424        let Some(r) = SoftwareRasterizer::new(17, 52) else {
1425            return;
1426        };
1427        let mut r = r.with_type_row(37);
1428        // A box that all but fills its row on the terminal's line is a control: on the
1429        // taller row it's 0.78 of it, whichever of them it is, and stands in the middle.
1430        for share in [0.89, 0.92, 0.98] {
1431            let mut grid = Grid::new(8, 1, style());
1432            let inset = (1.0 - share) / 2.0;
1433            let field = crate::paint::Bounds::cells(1.0, inset, 4.0, share);
1434            grid.panel(field, 20, Some(Rgb(255, 0, 0)), None);
1435            let image = r.row(&grid, 0);
1436            let red: Vec<usize> = (0..image.height)
1437                .filter(|y| {
1438                    let at = (y * image.width + 51) * 3;
1439                    image.rgb[at] > 200 && image.rgb[at + 1] < 60
1440                })
1441                .collect();
1442            assert!(
1443                (39..=42).contains(&red.len()),
1444                "a box of {share} is {} px tall",
1445                red.len()
1446            );
1447            let (over, under) = (red[0], 51 - red[red.len() - 1]);
1448            assert!(over.abs_diff(under) <= 2, "{over} over, {under} under");
1449        }
1450        // On the terminal's own line it's what it was.
1451        assert_eq!(stood(4, 57, 36.0, 36.0), (2.25, 57.0 * 36.0 / 64.0));
1452        // A chip that holds words, three quarters of the line, is 0.714 of the taller row,
1453        // which leaves room under a tail with its words in its middle.
1454        let (top, chip) = stood(8, 48, 52.0, 37.0);
1455        assert!((chip - 52.0 * 0.714).abs() < 0.01, "{chip}");
1456        assert!(
1457            (top + chip / 2.0 - 26.0).abs() < 0.01,
1458            "in the row's middle: {top}"
1459        );
1460        // A mark or a badge, shorter than that, keeps the height it has on the line.
1461        let (_, mark) = stood(12, 40, 52.0, 37.0);
1462        assert!((mark - 40.0 * 37.0 / 64.0).abs() < 0.01, "{mark}");
1463        // And a control never outgrows the room it was given.
1464        let (top, tall) = stood(0, 60, 40.0, 37.0);
1465        assert!(top >= 0.0 && tall <= 60.0 * 40.0 / 64.0, "{top} {tall}");
1466    }
1467
1468    /// A button on a pointed row's wash stands inside it where a row has room. Both were a
1469    /// control's height on a taller row, 39 px in one of 50, so the button's edges lay on the
1470    /// wash's. It keeps the 32 px it has on the terminal's line, in the middle of the wash.
1471    #[test]
1472    fn a_spinner_is_a_faint_ring_with_a_quarter_of_it_in_full_colour() {
1473        let Some(r) = SoftwareRasterizer::new(17, 50) else {
1474            return;
1475        };
1476        let mut r = r.with_type_row(37);
1477        let black = Style {
1478            bg: Rgb(0, 0, 0),
1479            ..style()
1480        };
1481        let side = 0.86 * 37.0;
1482        let (left, top) = (17.0, (50.0 - side) / 2.0);
1483        let ring = 3.0 / 24.0;
1484        // 0.86 of the line, 32 px across, in the middle of a row of 50: how blue it is at a
1485        // place in its box.
1486        let mut drawn = |turn: Option<u8>| {
1487            let mut grid = Grid::new(6, 1, black);
1488            grid.turn = turn;
1489            grid.spinner(1.0, 0, 0.86, Rgb(0, 0, 200), black);
1490            let image = r.row(&grid, 0);
1491            assert!(image.rgb.chunks(3).all(|p| p[0] == 0), "only its colour");
1492            move |u: f32, v: f32| {
1493                let (x, y) = ((left + u * side) as usize, (top + v * side) as usize);
1494                image.rgb[(y * image.width + x) * 3 + 2]
1495            }
1496        };
1497        // On the ring at its middle height: at the first step the arc is at the right, and the
1498        // left and the foot are only the faint ring, a quarter of the colour's strength.
1499        let at = drawn(Some(0));
1500        assert!(
1501            at(1.0 - ring, 0.5) > 150,
1502            "the arc: {}",
1503            at(1.0 - ring, 0.5)
1504        );
1505        assert!(
1506            (25..=70).contains(&at(ring, 0.5)),
1507            "faint: {}",
1508            at(ring, 0.5)
1509        );
1510        assert!((25..=70).contains(&at(0.5, 1.0 - ring)), "and at the foot");
1511        assert_eq!(at(0.5, 0.5), 0, "nothing in its middle");
1512        // Half a turn on, the arc is at the left.
1513        let at = drawn(Some(5));
1514        assert!(at(ring, 0.5) > 150);
1515        assert!(at(1.0 - ring, 0.5) < 70);
1516        // Still, it's a dot in its middle and no ring.
1517        let at = drawn(None);
1518        assert!(at(0.5, 0.5) > 150);
1519        assert_eq!(at(ring, 0.5), 0);
1520    }
1521
1522    #[test]
1523    fn a_button_on_a_rows_wash_stands_inside_it() {
1524        let Some(r) = SoftwareRasterizer::new(17, 50) else {
1525            return;
1526        };
1527        let mut r = r.with_type_row(36);
1528        let mut grid = Grid::new(12, 1, style());
1529        grid.roomy = true;
1530        grid.row_air = 139;
1531        // The wash behind the row, and the button at its end.
1532        let wash = crate::paint::Bounds::cells(0.4, 0.06, 11.2, 0.88);
1533        grid.panel(wash, 12, Some(Rgb(0, 0, 255)), None);
1534        grid.row_button((6, 0), "    ", "", Rgb(255, 0, 0), style());
1535        let image = r.row(&grid, 0);
1536        let rows = |x: usize, red: bool| -> Vec<usize> {
1537            (0..image.height)
1538                .filter(|y| {
1539                    let at = (y * image.width + x) * 3;
1540                    let (r, b) = (image.rgb[at], image.rgb[at + 2]);
1541                    if red {
1542                        r > 200 && b < 60
1543                    } else {
1544                        b > 200 && r < 60
1545                    }
1546                })
1547                .collect()
1548        };
1549        // Down the button's middle, eight cells along: wash, button, wash.
1550        let (button, round) = (rows(136, true), rows(136, false));
1551        // 31.7 px, the height it has on the terminal's line, thirty rows of it whole and a
1552        // blended one at each edge, so the wash has 4 px over it and under it. At 27 px, three
1553        // quarters of the line, its words' tails touched its foot.
1554        assert!(
1555            (30..=33).contains(&button.len()),
1556            "{} px of button",
1557            button.len()
1558        );
1559        // Inside the wash, gone down with its words onto the row's baseline
1560        // (`WORDS_BASELINE`), a pixel under the wash's middle.
1561        let over = round.iter().filter(|y| **y < button[0]).count();
1562        let under = round.len() - over;
1563        assert!(
1564            (4..=6).contains(&over) && (2..=4).contains(&under) && over >= under,
1565            "{over} px of wash over the button, {under} under"
1566        );
1567        // Its corners are tighter than a button's, with its height.
1568        let tight = grid.paint.iter().any(|p| {
1569            matches!(
1570                p,
1571                Paint::Panel {
1572                    inset: true,
1573                    radius: 17,
1574                    ..
1575                }
1576            )
1577        });
1578        assert!(tight, "17 per cent of the line, where a button's are 22");
1579        // Beside it the wash is a control, all of 39 px.
1580        assert!((38..=40).contains(&rows(40, false).len()));
1581        // Where a row is the terminal's line, it's a button like any other: as it stood.
1582        assert_eq!(inset(4, 56, 36.0, 36.0), stood(4, 56, 36.0, 36.0));
1583        grid.paint.clear();
1584        grid.roomy = false;
1585        grid.row_button((6, 0), "    ", "", Rgb(255, 0, 0), style());
1586        let plain = grid
1587            .paint
1588            .iter()
1589            .any(|p| matches!(p, Paint::Panel { inset: true, .. }));
1590        assert!(!plain, "not inset where a row has no room");
1591    }
1592
1593    /// A button at a row's end (`Grid::row_button`) is 32 px on a row of 50, and its words'
1594    /// ink, a capital's top to a "p"'s tail, stands in its middle with 4 px or more under the
1595    /// tail: at 27 px the tail of Keep's "p" ended on its foot.
1596    #[test]
1597    fn a_row_buttons_words_stand_in_its_middle_tails_and_all() {
1598        let Some(r) = SoftwareRasterizer::new(17, 50) else {
1599            return;
1600        };
1601        let mut r = r.with_type_row(36);
1602        let mut grid = Grid::new(16, 1, style());
1603        grid.roomy = true;
1604        grid.row_air = 139;
1605        grid.row_button((2, 0), "            ", "Keep", Rgb(255, 0, 0), style());
1606        let image = r.row(&grid, 0);
1607        let at = |x: usize, y: usize| {
1608            let i = (y * image.width + x) * 3;
1609            (image.rgb[i], image.rgb[i + 1])
1610        };
1611        // The button, down a column inside it and clear of its words.
1612        let button: Vec<usize> = (0..image.height).filter(|y| at(45, *y).0 > 200).collect();
1613        assert!(
1614            (30..=33).contains(&button.len()),
1615            "{} px of button",
1616            button.len()
1617        );
1618        // Clear of the row over it; under it, it's gone down onto the row's baseline.
1619        let (top, foot) = (button[0], *button.last().unwrap());
1620        assert!(top >= 8, "{top} px over it");
1621        // Its words, white on its red: the capital's top as far from its top as the baseline
1622        // from its foot, and the tail of its "p" clear of the foot.
1623        let [.., caps, tail, baseline] = chip_and_ink(&image, 45, (100, 170));
1624        let (over, under) = (caps - top, foot - baseline);
1625        assert!(
1626            over.abs_diff(under) <= 1 && foot - tail >= 2,
1627            "{over} px over its capitals, {under} under its baseline, {} under its tail",
1628            foot - tail
1629        );
1630    }
1631
1632    /// Where a row's picture has a red chip with white words on it between columns `from` and
1633    /// `to`: the chip's first and last whole rows, down column `side` clear of its words; its
1634    /// words' first and last inked rows; and their baseline, the row most of their inked
1635    /// columns end on.
1636    fn chip_and_ink(image: &Image, side: usize, (from, to): (usize, usize)) -> [usize; 5] {
1637        let at = |x: usize, y: usize| {
1638            let i = (y * image.width + x) * 3;
1639            (image.rgb[i], image.rgb[i + 1])
1640        };
1641        let chip: Vec<usize> = (0..image.height)
1642            .filter(|y| {
1643                let (r, g) = at(side, *y);
1644                r > 200 && g < 60
1645            })
1646            .collect();
1647        let inked = |x: usize, y: usize| {
1648            let (r, g) = at(x, y);
1649            r > 200 && g > 90
1650        };
1651        let ink: Vec<usize> = (0..image.height)
1652            .filter(|y| (from..to).any(|x| inked(x, *y)))
1653            .collect();
1654        let mut feet = HashMap::new();
1655        for x in from..to {
1656            if let Some(foot) = (0..image.height).rev().find(|y| inked(x, *y)) {
1657                *feet.entry(foot).or_insert(0) += 1;
1658            }
1659        }
1660        let baseline = feet.into_iter().max_by_key(|(_, n)| *n).unwrap().0;
1661        [
1662            chip[0],
1663            *chip.last().unwrap(),
1664            ink[0],
1665            *ink.last().unwrap(),
1666            baseline,
1667        ]
1668    }
1669
1670    /// A button's words stand by a capital's height in its middle, its top as far from the
1671    /// button's top as the baseline from its foot, whatever their letters, on a row with room
1672    /// and on the terminal's line alike: so every label of a size has one baseline, a row of
1673    /// buttons with it, and tails hang under it. In the font's line "Show Source" stood 5 px
1674    /// under its button's top and 10 over its foot; each by its own ink, "Dismiss" stood 4 px
1675    /// under its top and 10 over its foot beside "Keep"; by a capital's top to a tail's foot,
1676    /// every label without tails stood 2 to 3 px high (the release review of next). A button in
1677    /// a row of words, at its end or on its own, goes down onto the words' baseline with its
1678    /// words (`Grid::beside_words`): "Reject" rode 3 px over the hunk's heading beside it.
1679    #[test]
1680    fn a_buttons_words_stand_on_one_baseline_by_their_fonts_span() {
1681        let red = Rgb(255, 0, 0);
1682        for (row, line, roomy) in [(50, 36, true), (37, 37, false)] {
1683            let Some(r) = SoftwareRasterizer::new(17, row) else {
1684                return;
1685            };
1686            let mut r = r.with_type_row(line);
1687            for large in [false, true] {
1688                let mut baselines = Vec::new();
1689                for label in ["Show Source", "Accept Rewrite", "Next", "Keep", "Dismiss"] {
1690                    let mut grid = Grid::new(24, 1, style());
1691                    grid.roomy = roomy;
1692                    let cells = " ".repeat(20);
1693                    if large {
1694                        grid.large_button(1, 0, &cells, label, red, style());
1695                    } else {
1696                        grid.button(1, 0, &cells, label, red, style());
1697                    }
1698                    let image = r.row(&grid, 0);
1699                    let [top, foot, caps, tails, baseline] = chip_and_ink(&image, 21, (40, 330));
1700                    baselines.push((label, baseline - top, foot - baseline));
1701                    // A capital's top as far from the top as the baseline from the foot, and
1702                    // a tail, where there is one, clear of the foot.
1703                    let (over, under) = (caps - top, foot - baseline);
1704                    assert!(
1705                        over.abs_diff(under) <= 1 && foot - tails >= 2,
1706                        "{label} on a row of {row}: {over} px over its capitals, {under} under"
1707                    );
1708                }
1709                let first = baselines[0];
1710                assert!(
1711                    baselines.iter().all(|b| (b.1, b.2) == (first.1, first.2)),
1712                    "one baseline on a row of {row}: {baselines:?}"
1713                );
1714            }
1715        }
1716        // Beside words of 13 pt, on a row with room: at a row's end, and on its own.
1717        let Some(r) = SoftwareRasterizer::new(17, 50) else {
1718            return;
1719        };
1720        let mut r = r.with_type_row(36);
1721        for label in ["Keep", "Install", "Reject"] {
1722            for own in [false, true] {
1723                let mut grid = Grid::new(32, 1, style());
1724                grid.roomy = true;
1725                grid.row_air = 139;
1726                grid.label(1, 0, "Say what a caller", style(), 14);
1727                let cells = " ".repeat(10);
1728                if own {
1729                    let from = grid.painted_so_far();
1730                    grid.button(18, 0, &cells, label, red, style());
1731                    grid.beside_words(from);
1732                } else {
1733                    grid.row_button((18, 0), &cells, label, red, style());
1734                }
1735                let image = r.row(&grid, 0);
1736                let [.., words] = chip_and_ink(&image, 18 * 17 + 4, (17, 14 * 17));
1737                let [top, foot, .., baseline] =
1738                    chip_and_ink(&image, 18 * 17 + 4, (18 * 17 + 20, 27 * 17));
1739                assert!(
1740                    baseline.abs_diff(words) <= 1,
1741                    "{label}: its baseline at {baseline}, the words' at {words}"
1742                );
1743                // Its chip went down with its words, from the row's middle; at a row's end, at
1744                // the terminal's line's height, it keeps 8 px from the row's foot.
1745                let (over, under) = (top, image.height - 1 - foot);
1746                assert!(
1747                    over >= under && (own || under >= 8),
1748                    "{label}: {over} px over it, {under} under"
1749                );
1750            }
1751        }
1752    }
1753
1754    /// An emoji in a line of painted text keeps its own colours, where the machine has a
1755    /// font that holds them: the letters beside it take the text's.
1756    #[test]
1757    fn an_emoji_in_painted_text_keeps_its_own_colours() {
1758        let Some(mut r) = rasterizer() else { return };
1759        let mask = r.text_mask("ok 🚀", Font::default());
1760        // Without a colour emoji font it's a blank, in the text's colour like the rest.
1761        let Some(own) = &mask.own else { return };
1762        let coloured = own.iter().flatten().filter(|rgb| rgb.0 != rgb.2).count();
1763        assert!(coloured > 10, "a rocket has red and blue in it: {coloured}");
1764        let plain = r.text_mask("ok", Font::default());
1765        assert!(plain.own.is_none(), "letters have no colour of their own");
1766        // Drawn in dark text on light, the letters are dark and the emoji is still itself.
1767        let mut grid = Grid::new(12, 1, style());
1768        let dark = Style {
1769            fg: Rgb(10, 10, 10),
1770            bg: Rgb(240, 240, 240),
1771            ..Style::default()
1772        };
1773        grid.fill(Rect::new(0, 0, 12, 1), dark);
1774        grid.label(0, 0, "ok 🚀", dark, 12);
1775        let image = r.row(&grid, 0);
1776        let pixels: Vec<Rgb> = image.rgb.chunks(3).map(|p| Rgb(p[0], p[1], p[2])).collect();
1777        let tinted = |p: &&Rgb| p.0.abs_diff(p.2) > 60;
1778        assert!(pixels.iter().filter(tinted).count() > 10);
1779    }
1780
1781    #[test]
1782    fn panels_have_rounded_corners() {
1783        let Some(mut r) = rasterizer() else { return };
1784        let mut grid = Grid::new(10, 1, style());
1785        grid.panel(
1786            crate::paint::Bounds::cells(1.0, 0.0, 8.0, 1.0),
1787            40,
1788            Some(Rgb(255, 0, 0)),
1789            None,
1790        );
1791        let image = r.row(&grid, 0);
1792        let red = |x: usize, y: usize| image.rgb[(y * image.width + x) * 3];
1793        assert_eq!(red(50, 10), 255, "the middle is filled");
1794        assert_eq!(red(10, 0), 10, "the corner is cut");
1795    }
1796
1797    /// A hairline a fraction of a row down stands on whole pixels, in its full colour: between
1798    /// two it was a pale band a pixel taller, as a menu's rules were where they shared out a
1799    /// half row.
1800    #[test]
1801    fn a_hairline_stands_on_whole_pixels() {
1802        let Some(mut r) = rasterizer() else { return };
1803        let mut grid = Grid::new(10, 1, style());
1804        // A third of a row down a row of 20 pixels: 6.67 pixels.
1805        let line = crate::paint::Bounds::cells(1.0, 1.0 / 3.0, 8.0, 0.0);
1806        grid.hairline(line, Rgb(255, 0, 0));
1807        let image = r.row(&grid, 0);
1808        let red = |y: usize| image.rgb[(y * image.width + 50) * 3];
1809        let touched: Vec<u8> = (0..image.height).map(red).filter(|r| *r > 10).collect();
1810        assert!(!touched.is_empty(), "the line is drawn");
1811        assert!(
1812            touched.iter().all(|r| *r == 255),
1813            "every row it touches in full: {touched:?}"
1814        );
1815    }
1816
1817    #[test]
1818    fn a_wash_lets_what_is_under_it_show() {
1819        let Some(mut r) = rasterizer() else { return };
1820        let mut grid = Grid::new(20, 2, style());
1821        let bounds = crate::paint::Bounds::cells(1.0, 0.0, 18.0, 2.0);
1822        grid.wash(bounds, 10, (Rgb(255, 0, 0), 64), Some(Rgb(0, 0, 255)));
1823        let image = r.row(&grid, 0);
1824        let at = |x: usize, y: usize| {
1825            let i = (y * image.width + x) * 3;
1826            (image.rgb[i], image.rgb[i + 1], image.rgb[i + 2])
1827        };
1828        let middle = at(image.width / 2, image.height - 1);
1829        assert!(middle.0 > 0 && middle.0 < 200, "a little red: {middle:?}");
1830        let edge = at(image.width / 2, 0);
1831        assert!(edge.2 > 200, "the border: {edge:?}");
1832    }
1833
1834    #[test]
1835    fn a_dashed_border_has_gaps() {
1836        let Some(mut r) = rasterizer() else { return };
1837        let mut grid = Grid::new(20, 1, style());
1838        grid.dashed_panel(
1839            crate::paint::Bounds::cells(1.0, 0.0, 18.0, 1.0),
1840            10,
1841            None,
1842            Rgb(255, 0, 0),
1843        );
1844        let image = r.row(&grid, 0);
1845        // Along the top edge, past the corner: some pixels inked, some left.
1846        let y = 0;
1847        let reds: Vec<u8> = (30..170)
1848            .map(|x| image.rgb[(y * image.width + x) * 3])
1849            .collect();
1850        assert!(reds.iter().any(|r| *r > 200), "dashes are drawn");
1851        assert!(reds.iter().any(|r| *r < 60), "with gaps between them");
1852    }
1853
1854    /// The emoji font in the binary draws in colour with none of the machine's fonts, which
1855    /// is what a server reached over SSH has, and holds the eight emoji that stand under a
1856    /// comment being written.
1857    #[test]
1858    fn the_emoji_font_in_the_binary_draws_in_colour_by_itself() {
1859        let mut db = fontdb::Database::new();
1860        for data in [INTER, INTER_ITALIC, MONO, MONO_ITALIC, EMOJI] {
1861            db.load_font_data(data.to_vec());
1862        }
1863        db.set_monospace_family("JetBrains Mono");
1864        db.set_sans_serif_family("Inter Variable");
1865        let mut fonts = FontSystem::new_with_locale_and_db("en-US".to_string(), db);
1866        assert!(draws_colour(&mut fonts, BUILT_IN_EMOJI));
1867        let found = find_emoji_font(&mut fonts).map(|(family, _)| family);
1868        assert_eq!(found.as_deref(), Some(BUILT_IN_EMOJI));
1869        for emoji in ["👍", "💯", "❤\u{fe0f}", "🎉", "😄", "👀", "🚀", "✅"] {
1870            assert!(
1871                set_in(&mut fonts, BUILT_IN_EMOJI, emoji).is_some(),
1872                "{emoji}"
1873            );
1874        }
1875        // A family the machine doesn't have draws nothing in colour.
1876        assert!(!draws_colour(&mut fonts, "No Such Emoji"));
1877        // It holds a flag and a family whole, and not an emoji newer than it is.
1878        for emoji in ["🇹🇷", "👩\u{200d}💻", "❤\u{fe0f}", "1\u{fe0f}\u{20e3}"] {
1879            assert!(built_in_emoji_holds(emoji), "{emoji}");
1880        }
1881        assert!(
1882            !built_in_emoji_holds("🫨"),
1883            "a face from a year after the font"
1884        );
1885        assert!(!built_in_emoji_holds("ok"));
1886        // And through the rasterizer itself: a line of words with two in it.
1887        let metrics = fit_font(&mut fonts, 10, 20).unwrap();
1888        let mut r = SoftwareRasterizer {
1889            fonts,
1890            emoji: Some(BUILT_IN_EMOJI.to_string()),
1891            swash: SwashCache::new(),
1892            metrics,
1893            cell: (10, 20),
1894            type_row: 20,
1895            masks: HashMap::new(),
1896            painted: HashMap::new(),
1897            text: HashMap::new(),
1898        };
1899        let mask = r.text_mask("ok 🚀 ❤\u{fe0f}", Font::default());
1900        let own = mask
1901            .own
1902            .as_ref()
1903            .expect("the emoji have colours of their own");
1904        let red = own
1905            .iter()
1906            .flatten()
1907            .filter(|rgb| rgb.0 > 150 && rgb.2 < 120);
1908        assert!(red.count() > 10, "a heart and a rocket's flame are red");
1909    }
1910
1911    #[test]
1912    fn fonts_ship_in_the_binary() {
1913        let mut r = SoftwareRasterizer::new(10, 20).unwrap();
1914        assert!(
1915            r.fonts
1916                .db()
1917                .faces()
1918                .any(|f| f.families.iter().any(|(n, _)| n.contains("Inter")))
1919        );
1920        assert!(
1921            r.text_mask("x", Font::default())
1922                .alpha
1923                .iter()
1924                .any(|a| *a > 0)
1925        );
1926    }
1927
1928    #[test]
1929    fn unknown_cell_size_refuses_pixels() {
1930        assert!(SoftwareRasterizer::new(0, 20).is_none());
1931    }
1932}