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