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/// CPU rendering. Glyphs are rasterized once and blended into their cells, so text stays
244/// locked to the grid and a row costs little more than a copy.
245pub struct SoftwareRasterizer {
246    fonts: FontSystem,
247    /// The font emoji are drawn in, where the machine has one.
248    emoji: Option<String>,
249    swash: SwashCache,
250    metrics: Metrics,
251    cell: (usize, usize),
252    masks: HashMap<GlyphKey, Mask>,
253    /// Glyphs with colours of their own, such as emoji, as pixels with those colours.
254    painted: HashMap<GlyphKey, Painted>,
255    text: HashMap<TextKey, Rc<TextMask>>,
256}
257
258impl SoftwareRasterizer {
259    /// The fonts ship in the binary, because pixels are drawn on the remote host over SSH
260    /// and servers rarely have any. Returns None only when the cell size is unknown.
261    pub fn new(cell_width: usize, cell_height: usize) -> Option<Self> {
262        if cell_width == 0 || cell_height == 0 {
263            return None;
264        }
265        let mut fonts = drawing_fonts();
266        let metrics = fit_font(&mut fonts, cell_width, cell_height)?;
267        let emoji = emoji_font().map(|(family, _)| family.clone());
268        Some(Self {
269            fonts,
270            emoji,
271            swash: SwashCache::new(),
272            metrics,
273            cell: (cell_width, cell_height),
274            masks: HashMap::new(),
275            painted: HashMap::new(),
276            text: HashMap::new(),
277        })
278    }
279
280    fn mask(&mut self, key: &GlyphKey) -> Mask {
281        if let Some(mask) = self.masks.get(key) {
282            return mask.clone();
283        }
284        let (width, height) = (self.cell.0 * 2, self.cell.1);
285        let mut buffer = Buffer::new(&mut self.fonts, self.metrics);
286        buffer.set_size(Some(width as f32 * 2.0), Some(height as f32));
287        // Asked for a monospaced Han glyph, the search stops at a font that only has blanks.
288        // A wide glyph fills its two cells whatever font it's from.
289        // And an emoji is drawn in the emoji font: a text font may hold a plain form of it.
290        let emoji = self.emoji.clone().filter(|_| emoji_letter(&key.symbol));
291        let family = if let Some(emoji) = &emoji {
292            Family::Name(emoji)
293        } else if UnicodeWidthStr::width(key.symbol.as_str()) > 1 {
294            Family::SansSerif
295        } else {
296            Family::Monospace
297        };
298        let mut attrs = Attrs::new().family(family);
299        if key.bold {
300            attrs = attrs.weight(Weight::BOLD);
301        }
302        if key.italic {
303            attrs = attrs.style(FontStyle::Italic);
304        }
305        let rich = std::iter::once((key.symbol.as_str(), attrs.clone()));
306        buffer.set_rich_text(rich, &attrs, Shaping::Advanced, None);
307        buffer.shape_until_scroll(&mut self.fonts, false);
308        let mut pixels = Vec::new();
309        let mut coloured = Vec::new();
310        let white = Color::rgb(255, 255, 255);
311        buffer.draw(
312            &mut self.fonts,
313            &mut self.swash,
314            white,
315            |x, y, w, h, color| {
316                if color.a() == 0 {
317                    return;
318                }
319                for py in y..y + h as i32 {
320                    for px in x..x + w as i32 {
321                        if px >= 0 && py >= 0 && (px as usize) < width && (py as usize) < height {
322                            pixels.push((px as u16, py as u16, color.a()));
323                            let rgb = Rgb(color.r(), color.g(), color.b());
324                            coloured.push((px as u16, py as u16, rgb, color.a()));
325                        }
326                    }
327                }
328            },
329        );
330        // Text comes out white, ready to take any colour. Anything else is the glyph's own.
331        if coloured
332            .iter()
333            .any(|(_, _, rgb, _)| *rgb != Rgb(255, 255, 255))
334        {
335            self.painted.insert(key.clone(), Rc::new(coloured));
336        }
337        let mask = Rc::new(pixels);
338        self.masks.insert(key.clone(), mask.clone());
339        mask
340    }
341
342    /// A line of painted text, tall enough for its size.
343    fn text_mask(&mut self, text: &str, font: Font) -> Rc<TextMask> {
344        let key = TextKey {
345            text: text.to_string(),
346            font,
347        };
348        if let Some(mask) = self.text.get(&key) {
349            return mask.clone();
350        }
351        if self.text.len() >= MAX_TEXT_MASKS {
352            self.text.clear();
353        }
354        let px = text_pixels(self.cell.1, font);
355        let height = self.cell.1.max((px * 1.45).ceil() as usize);
356        let mut buffer = Buffer::new(&mut self.fonts, Metrics::new(px, height as f32));
357        buffer.set_size(None, Some(height as f32));
358        let emoji = self.emoji.clone();
359        let rich = runs(text, font, emoji.as_deref());
360        buffer.set_rich_text(rich, &attrs(font), Shaping::Advanced, None);
361        buffer.shape_until_scroll(&mut self.fonts, false);
362        let width = buffer
363            .layout_runs()
364            .next()
365            .map_or(0.0, |run| run.line_w)
366            .ceil() as usize
367            + 2;
368        let mut alpha = vec![0; width * height];
369        // Text comes out in the colour it's asked for, and an emoji in its own. Drawn in
370        // white, anything that isn't white is an emoji's.
371        let white = Rgb(255, 255, 255);
372        let mut drawn = vec![white; width * height];
373        let mut tinted = false;
374        buffer.draw(
375            &mut self.fonts,
376            &mut self.swash,
377            Color::rgb(255, 255, 255),
378            |x, y, w, h, color| {
379                let rgb = Rgb(color.r(), color.g(), color.b());
380                tinted |= color.a() > 0 && rgb != white;
381                for at in spots((width, height), (x, y), (w, h)) {
382                    if color.a() >= alpha[at] {
383                        drawn[at] = rgb;
384                    }
385                    alpha[at] = alpha[at].max(color.a());
386                }
387            },
388        );
389        // An emoji has white of its own too, which drawn in white can't be told from text.
390        // Drawn again in black, what turned black is text and what stayed is the emoji's.
391        let own = tinted.then(|| {
392            let black = Rgb(0, 0, 0);
393            let mut own = vec![None; width * height];
394            buffer.draw(
395                &mut self.fonts,
396                &mut self.swash,
397                Color::rgb(0, 0, 0),
398                |x, y, w, h, color| {
399                    let rgb = Rgb(color.r(), color.g(), color.b());
400                    for at in spots((width, height), (x, y), (w, h)) {
401                        if color.a() > 0 && (rgb != black || drawn[at] != white) {
402                            own[at] = Some(drawn[at]);
403                        }
404                    }
405                },
406            );
407            own
408        });
409        let mask = Rc::new(TextMask {
410            width,
411            height,
412            alpha,
413            own,
414        });
415        self.text.insert(key, mask.clone());
416        mask
417    }
418
419    fn draw_paint(&mut self, target: &mut Target, paint: &Paint) {
420        let (cw, ch) = (self.cell.0 as f32, self.cell.1 as f32);
421        let scale = |v: i32, cell: f32| v as f32 * cell / UNIT as f32;
422        match paint {
423            Paint::Panel {
424                bounds,
425                radius,
426                fill,
427                border,
428                shadow,
429                dashed,
430            } => {
431                let mut shape = Shape {
432                    x: scale(bounds.x, cw),
433                    y: scale(bounds.y, ch),
434                    w: scale(bounds.w, cw),
435                    h: scale(bounds.h, ch),
436                    radius: *radius as f32 * ch / 100.0,
437                };
438                // A panel with a line round it stands on whole pixels, so the line is one
439                // pixel of its own colour on every side. Between pixels it was two rows at
440                // half strength on one side and one at full on the other.
441                if border.is_some() {
442                    let right = (shape.x + shape.w).round();
443                    let bottom = (shape.y + shape.h).round();
444                    shape.x = shape.x.round();
445                    shape.y = shape.y.round();
446                    shape.w = right - shape.x;
447                    shape.h = bottom - shape.y;
448                }
449                target.panel(shape, (*fill, *border), *shadow, *dashed, ch);
450            }
451            Paint::Wash {
452                bounds,
453                radius,
454                color,
455                alpha,
456                border,
457            } => {
458                let shape = Shape {
459                    x: scale(bounds.x, cw),
460                    y: scale(bounds.y, ch),
461                    w: scale(bounds.w, cw),
462                    h: scale(bounds.h, ch),
463                    radius: *radius as f32 * ch / 100.0,
464                };
465                target.wash(shape, (*color, *alpha), *border, ch);
466            }
467            Paint::Hairline { bounds, color } => {
468                let thickness = (ch / 24.0).ceil().max(1.0);
469                let shape = Shape {
470                    x: scale(bounds.x, cw),
471                    y: scale(bounds.y, ch),
472                    w: scale(bounds.w, cw).max(thickness),
473                    h: scale(bounds.h, ch).max(thickness),
474                    radius: 0.0,
475                };
476                target.panel(shape, (Some(*color), None), false, false, ch);
477            }
478            Paint::Text {
479                x,
480                y,
481                max_width,
482                text,
483                color,
484                font,
485                align_right,
486                centred,
487                underline,
488            } => {
489                let mask = self.text_mask(text, *font);
490                let mut left = scale(*x, cw).round() as i32;
491                if *align_right {
492                    left -= mask.width as i32;
493                } else if *centred {
494                    left -= mask.width as i32 / 2;
495                }
496                // Tall text stays centred on its row.
497                let lift = (mask.height as i32 - ch as i32) / 2;
498                let top = scale(*y, ch).round() as i32 - lift;
499                let limit = scale(*max_width, cw).max(0.0) as usize;
500                target.blit(&mask, left, top, limit, *color);
501                if *underline {
502                    let thickness = (ch / 24.0).ceil().max(1.0);
503                    let shape = Shape {
504                        x: left as f32,
505                        y: scale(*y, ch) + ch * 0.78,
506                        w: mask.width.saturating_sub(2).min(limit) as f32,
507                        h: thickness,
508                        radius: 0.0,
509                    };
510                    target.panel(shape, (Some(*color), None), false, false, ch);
511                }
512            }
513            Paint::Icon {
514                bounds,
515                icon,
516                color,
517            } => {
518                let side = scale(bounds.h, ch);
519                let left = scale(bounds.x, cw);
520                let top = scale(bounds.y, ch);
521                target.icon(*icon, left, top, side, *color);
522            }
523            Paint::Corners {
524                bounds,
525                radius,
526                color,
527                which,
528            } => {
529                let shape = Shape {
530                    x: scale(bounds.x, cw),
531                    y: scale(bounds.y, ch),
532                    w: scale(bounds.w, cw),
533                    h: scale(bounds.h, ch),
534                    radius: *radius as f32 * ch / 100.0,
535                };
536                target.corners(&shape, *color, *which);
537            }
538            Paint::Image {
539                bounds,
540                clip,
541                bitmap,
542                color,
543            } => {
544                let shape = Shape {
545                    x: scale(bounds.x, cw),
546                    y: scale(bounds.y, ch),
547                    w: scale(bounds.w, cw),
548                    h: scale(bounds.h, ch),
549                    radius: 0.0,
550                };
551                let across = (
552                    scale(clip.x, cw) as i32,
553                    scale(clip.x + clip.w, cw).ceil() as i32,
554                );
555                let down = (
556                    scale(clip.y, ch) as i32,
557                    scale(clip.y + clip.h, ch).ceil() as i32,
558                );
559                target.image(&shape, (across, down), bitmap, *color);
560            }
561            Paint::Strips { bounds, strips } => {
562                let (left, top) = (scale(bounds.x, cw), scale(bounds.y, ch));
563                let (width, height) = (scale(bounds.w, cw), scale(bounds.h, ch));
564                let thickness = (ch / 24.0).ceil().max(1.0);
565                for strip in strips {
566                    let shape = Shape {
567                        x: left + strip.x as f32 * width / 256.0,
568                        y: top + strip.y as f32 * height / 256.0,
569                        w: (strip.w as f32 * width / 256.0).max(1.0),
570                        h: thickness,
571                        radius: 0.0,
572                    };
573                    target.panel(shape, (Some(strip.color), None), false, false, ch);
574                }
575            }
576        }
577    }
578}
579
580/// The places in a `size` image that a box at `at`, `by` across and down, covers.
581fn spots(
582    (width, height): (usize, usize),
583    (x, y): (i32, i32),
584    (w, h): (u32, u32),
585) -> impl Iterator<Item = usize> {
586    let across = x.max(0) as usize..((x + w as i32).max(0) as usize).min(width);
587    let down = y.max(0) as usize..((y + h as i32).max(0) as usize).min(height);
588    down.flat_map(move |py| across.clone().map(move |px| py * width + px))
589}
590
591/// Where the caret goes: its exact place, or the cell the cursor is in.
592fn caret_bounds(grid: &Grid) -> Option<Bounds> {
593    grid.caret.or_else(|| {
594        let (x, y) = grid.cursor?;
595        Some(Bounds::cells(x as f32, y as f32 + 0.08, 0.0, 0.84))
596    })
597}
598
599fn caret_color(grid: &Grid) -> Rgb {
600    let Some((x, y)) = grid.cursor else {
601        return Rgb(255, 255, 255);
602    };
603    grid.cell(x.min(grid.width().saturating_sub(1)), y).style.fg
604}
605
606struct Shape {
607    x: f32,
608    y: f32,
609    w: f32,
610    h: f32,
611    radius: f32,
612}
613
614/// Distance from a point to a rounded box's edge, negative inside.
615fn rounded_distance(shape: &Shape, x: f32, y: f32) -> f32 {
616    let (cx, cy) = (shape.x + shape.w / 2.0, shape.y + shape.h / 2.0);
617    let qx = (x - cx).abs() - shape.w / 2.0 + shape.radius;
618    let qy = (y - cy).abs() - shape.h / 2.0 + shape.radius;
619    let outside = (qx.max(0.0).powi(2) + qy.max(0.0).powi(2)).sqrt();
620    outside + qx.max(qy).min(0.0) - shape.radius
621}
622
623/// The part of the screen one row's tile covers, in screen pixels.
624struct Target<'a> {
625    rgb: &'a mut [u8],
626    width: usize,
627    height: usize,
628    top: i32,
629}
630
631impl Target<'_> {
632    fn corners(&mut self, s: &Shape, color: Rgb, which: u8) {
633        let r = s.radius;
634        let spots = [
635            (TOP_LEFT, s.x, s.y, s.x + r, s.y + r),
636            (TOP_RIGHT, s.x + s.w - r, s.y, s.x + s.w - r, s.y + r),
637            (
638                BOTTOM_RIGHT,
639                s.x + s.w - r,
640                s.y + s.h - r,
641                s.x + s.w - r,
642                s.y + s.h - r,
643            ),
644            (BOTTOM_LEFT, s.x, s.y + s.h - r, s.x + r, s.y + s.h - r),
645        ];
646        for (flag, left, top, cx, cy) in spots {
647            if which & flag == 0 {
648                continue;
649            }
650            for y in top.floor() as i32..(top + r).ceil() as i32 {
651                for x in left.floor() as i32..(left + r).ceil() as i32 {
652                    let d = ((x as f32 + 0.5 - cx).powi(2) + (y as f32 + 0.5 - cy).powi(2)).sqrt();
653                    let outside = (d - r + 0.5).clamp(0.0, 1.0);
654                    self.blend(x, y, color, (outside * 255.0) as u8);
655                }
656            }
657        }
658    }
659
660    fn blend(&mut self, x: i32, y: i32, color: Rgb, alpha: u8) {
661        let row = y - self.top;
662        if alpha == 0 || x < 0 || row < 0 || x as usize >= self.width || row as usize >= self.height
663        {
664            return;
665        }
666        let at = (row as usize * self.width + x as usize) * 3;
667        self.rgb[at] = blend(color.0, self.rgb[at], alpha);
668        self.rgb[at + 1] = blend(color.1, self.rgb[at + 1], alpha);
669        self.rgb[at + 2] = blend(color.2, self.rgb[at + 2], alpha);
670    }
671
672    fn panel(
673        &mut self,
674        s: Shape,
675        (fill, border): (Option<Rgb>, Option<Rgb>),
676        shadow: bool,
677        dashed: bool,
678        row: f32,
679    ) {
680        // Dashes a quarter of a row long, with gaps as long, measured along the edge so every
681        // row of a tall panel continues the same pattern.
682        let dash = (row / 4.0).max(2.0);
683        let on_dash = |x: f32, y: f32| {
684            let along_top = x > s.x + s.radius && x < s.x + s.w - s.radius;
685            let run = if along_top { x - s.x } else { y - s.y };
686            (run / dash).floor() as i64 % 2 == 0
687        };
688        // A shadow falls down and to the sides, never up onto what opened the panel.
689        let reach = if shadow { row * 0.35 } else { 1.0 };
690        let (x0, x1) = (
691            (s.x - reach).floor() as i32,
692            (s.x + s.w + reach).ceil() as i32,
693        );
694        let above = if shadow { 1.0 } else { reach };
695        let y0 = ((s.y - above).floor() as i32).max(self.top);
696        let y1 = ((s.y + s.h + reach).ceil() as i32).min(self.top + self.height as i32);
697        let stroke = (row / 30.0).max(1.0);
698        for y in y0..y1 {
699            for x in x0..x1 {
700                let d = rounded_distance(&s, x as f32 + 0.5, y as f32 + 0.5);
701                if shadow && d > 0.0 && y as f32 + 0.5 > s.y + s.radius {
702                    let fade = (1.0 - d / reach).clamp(0.0, 1.0);
703                    // A shadow heavy enough for dark surfaces is a grey halo on light ones.
704                    let light = fill.is_some_and(|f| f.0 > 180);
705                    let depth = if light { LIGHT_SHADOW } else { DARK_SHADOW };
706                    self.blend(x, y, Rgb(0, 0, 0), (fade * fade * depth) as u8);
707                }
708                let inside = ((0.5 - d) * 255.0).clamp(0.0, 255.0) as u8;
709                if let Some(color) = fill {
710                    self.blend(x, y, color, inside);
711                }
712                if let Some(color) = border
713                    && (!dashed || on_dash(x as f32 + 0.5, y as f32 + 0.5))
714                {
715                    let edge = ((0.5 - (d + stroke / 2.0).abs() + stroke / 2.0) * 255.0)
716                        .clamp(0.0, 255.0) as u8;
717                    self.blend(x, y, color, edge);
718                }
719            }
720        }
721    }
722
723    /// A see-through fill with round corners, and a border twice a panel's weight.
724    fn wash(&mut self, s: Shape, (color, alpha): (Rgb, u8), border: Option<Rgb>, row: f32) {
725        let (x0, x1) = (s.x.floor() as i32 - 1, (s.x + s.w).ceil() as i32 + 1);
726        let y0 = (s.y.floor() as i32 - 1).max(self.top);
727        let y1 = ((s.y + s.h).ceil() as i32 + 1).min(self.top + self.height as i32);
728        let stroke = (row / 15.0).max(2.0);
729        for y in y0..y1 {
730            for x in x0..x1 {
731                let d = rounded_distance(&s, x as f32 + 0.5, y as f32 + 0.5);
732                let inside = (0.5 - d).clamp(0.0, 1.0);
733                self.blend(x, y, color, (inside * alpha as f32) as u8);
734                if let Some(edge_color) = border {
735                    // The border runs just inside the edge.
736                    let along = (0.5 - (d + stroke / 2.0).abs() + stroke / 2.0).clamp(0.0, 1.0);
737                    self.blend(x, y, edge_color, (along * 255.0) as u8);
738                }
739            }
740        }
741    }
742
743    fn blit(&mut self, mask: &TextMask, left: i32, top: i32, limit: usize, color: Rgb) {
744        let from = (self.top - top).max(0) as usize;
745        let to = ((self.top + self.height as i32 - top).max(0) as usize).min(mask.height);
746        for y in from..to {
747            for x in 0..mask.width.min(limit) {
748                let at = y * mask.width + x;
749                let ink = mask.own.as_ref().and_then(|own| own[at]).unwrap_or(color);
750                self.blend(left + x as i32, top + y as i32, ink, mask.alpha[at]);
751            }
752        }
753    }
754
755    /// Scales a bitmap into `s`, sampling between its pixels so nothing shimmers.
756    fn image(&mut self, s: &Shape, clip: ((i32, i32), (i32, i32)), bitmap: &Bitmap, color: Rgb) {
757        let (width, height) = (bitmap.width as usize, bitmap.height as usize);
758        if width == 0 || height == 0 || s.w <= 0.0 || s.h <= 0.0 {
759            return;
760        }
761        let channels = match bitmap.kind {
762            Pixels::Coverage => 1,
763            Pixels::Rgba => 4,
764        };
765        let at = |x: usize, y: usize, c: usize| -> f32 {
766            let index = (y.min(height - 1) * width + x.min(width - 1)) * channels + c;
767            bitmap.pixels.get(index).copied().unwrap_or(0) as f32
768        };
769        let sample = |u: f32, v: f32, c: usize| -> f32 {
770            let (fx, fy) = (u.max(0.0), v.max(0.0));
771            let (x, y) = (fx as usize, fy as usize);
772            let (dx, dy) = (fx - x as f32, fy - y as f32);
773            let top = at(x, y, c) * (1.0 - dx) + at(x + 1, y, c) * dx;
774            let bottom = at(x, y + 1, c) * (1.0 - dx) + at(x + 1, y + 1, c) * dx;
775            top * (1.0 - dy) + bottom * dy
776        };
777        let ((left, right), (top, bottom)) = clip;
778        let y0 = (s.y.floor() as i32).max(self.top).max(top);
779        let y1 = ((s.y + s.h).ceil() as i32)
780            .min(self.top + self.height as i32)
781            .min(bottom);
782        let x0 = (s.x.floor() as i32).max(0).max(left);
783        let x1 = ((s.x + s.w).ceil() as i32)
784            .min(self.width as i32)
785            .min(right);
786        let (ax, ay) = (width as f32 / s.w, height as f32 / s.h);
787        // A frame made for exactly this size is a copy, which keeps a live page cheap.
788        if bitmap.kind == Pixels::Rgba && (ax - 1.0).abs() < 0.002 && (ay - 1.0).abs() < 0.002 {
789            let (left, top) = (s.x.round() as i32, s.y.round() as i32);
790            for y in y0..y1 {
791                for x in x0..x1 {
792                    let (u, v) = (x - left, y - top);
793                    if u < 0 || v < 0 || u as usize >= width || v as usize >= height {
794                        continue;
795                    }
796                    let at = (v as usize * width + u as usize) * 4;
797                    if let Some(p) = bitmap.pixels.get(at..at + 4) {
798                        self.blend(x, y, Rgb(p[0], p[1], p[2]), p[3]);
799                    }
800                }
801            }
802            return;
803        }
804        for y in y0..y1 {
805            for x in x0..x1 {
806                let u = (x as f32 + 0.5 - s.x) * ax - 0.5;
807                let v = (y as f32 + 0.5 - s.y) * ay - 0.5;
808                match bitmap.kind {
809                    Pixels::Coverage => self.blend(x, y, color, sample(u, v, 0) as u8),
810                    Pixels::Rgba => {
811                        let ink = Rgb(
812                            sample(u, v, 0) as u8,
813                            sample(u, v, 1) as u8,
814                            sample(u, v, 2) as u8,
815                        );
816                        self.blend(x, y, ink, sample(u, v, 3) as u8);
817                    }
818                }
819            }
820        }
821    }
822
823    fn icon(&mut self, icon: Icon, left: f32, top: f32, side: f32, color: Rgb) {
824        // Five by five keeps thin curved strokes smooth, and tiles only draw this once.
825        const SAMPLES: usize = 5;
826        let y0 = (top.floor() as i32).max(self.top);
827        let y1 = ((top + side).ceil() as i32).min(self.top + self.height as i32);
828        for y in y0..y1 {
829            for x in left.floor() as i32..(left + side).ceil() as i32 {
830                let mut hits = 0;
831                for sy in 0..SAMPLES {
832                    for sx in 0..SAMPLES {
833                        let u = (x as f32 + (sx as f32 + 0.5) / SAMPLES as f32 - left) / side;
834                        let v = (y as f32 + (sy as f32 + 0.5) / SAMPLES as f32 - top) / side;
835                        if (0.0..1.0).contains(&u) && (0.0..1.0).contains(&v) && inked(icon, u, v) {
836                            hits += 1;
837                        }
838                    }
839                }
840                self.blend(x, y, color, (hits * 255 / (SAMPLES * SAMPLES)) as u8);
841            }
842        }
843    }
844}
845
846/// Picks the largest font whose advance fits the cell and whose height fits the row.
847fn fit_font(fonts: &mut FontSystem, cell_width: usize, cell_height: usize) -> Option<Metrics> {
848    const PROBE: f32 = 100.0;
849    let mut buffer = Buffer::new(fonts, Metrics::new(PROBE, PROBE * 1.2));
850    buffer.set_size(Some(PROBE * 4.0), Some(PROBE * 2.0));
851    let attrs = Attrs::new().family(Family::Monospace);
852    buffer.set_rich_text(
853        std::iter::once(("M", attrs.clone())),
854        &attrs,
855        Shaping::Advanced,
856        None,
857    );
858    buffer.shape_until_scroll(fonts, false);
859    let advance = buffer.layout_runs().next()?.line_w;
860    if advance <= 0.0 {
861        return None;
862    }
863    let by_width = cell_width as f32 * PROBE / advance;
864    let by_height = cell_height as f32 * 0.8;
865    Some(Metrics::new(by_width.min(by_height), cell_height as f32))
866}
867
868/// Inks this cell's share of an icon, supersampled so curves stay smooth.
869fn draw_icon(
870    rgb: &mut [u8],
871    stride: usize,
872    left: usize,
873    cell: (usize, usize),
874    piece: Piece,
875    fg: Rgb,
876) {
877    const SAMPLES: usize = 4;
878    let (cw, ch) = cell;
879    let (full_w, full_h) = (cw * piece.width as usize, ch * piece.height as usize);
880    let side = full_w.min(full_h) as f32 * 0.94;
881    let (off_x, off_y) = ((full_w as f32 - side) / 2.0, (full_h as f32 - side) / 2.0);
882    for y in 0..ch {
883        for x in 0..cw {
884            let mut hits = 0;
885            for sy in 0..SAMPLES {
886                for sx in 0..SAMPLES {
887                    let px = (piece.column as usize * cw + x) as f32
888                        + (sx as f32 + 0.5) / SAMPLES as f32;
889                    let py =
890                        (piece.row as usize * ch + y) as f32 + (sy as f32 + 0.5) / SAMPLES as f32;
891                    let (u, v) = ((px - off_x) / side, (py - off_y) / side);
892                    if (0.0..1.0).contains(&u) && (0.0..1.0).contains(&v) && inked(piece.icon, u, v)
893                    {
894                        hits += 1;
895                    }
896                }
897            }
898            if hits > 0 {
899                let alpha = (hits * 255 / (SAMPLES * SAMPLES)) as u8;
900                let at = (y * stride + left + x) * 3;
901                rgb[at] = blend(fg.0, rgb[at], alpha);
902                rgb[at + 1] = blend(fg.1, rgb[at + 1], alpha);
903                rgb[at + 2] = blend(fg.2, rgb[at + 2], alpha);
904            }
905        }
906    }
907}
908
909fn blend(fg: u8, bg: u8, alpha: u8) -> u8 {
910    let a = alpha as u32;
911    ((fg as u32 * a + bg as u32 * (255 - a)) / 255) as u8
912}
913
914fn fill(rgb: &mut [u8], stride: usize, x: usize, y: usize, w: usize, h: usize, color: Rgb) {
915    for row in y..y + h {
916        for px in x..x + w {
917            let i = (row * stride + px) * 3;
918            if i + 2 < rgb.len() {
919                rgb[i..i + 3].copy_from_slice(&[color.0, color.1, color.2]);
920            }
921        }
922    }
923}
924
925impl Rasterizer for SoftwareRasterizer {
926    fn row(&mut self, grid: &Grid, y: u16) -> Image {
927        let cells = grid.row(y);
928        let (cw, ch) = self.cell;
929        let width = cw * cells.len();
930        let mut rgb = vec![0; width * ch * 3];
931        // Backgrounds first: a wide glyph runs into the next cell, whose colour would cut it.
932        for (i, cell) in cells.iter().enumerate() {
933            fill(&mut rgb, width, i * cw, 0, cw, ch, cell.style.bg);
934        }
935        for (i, cell) in cells.iter().enumerate() {
936            let fg = cell.style.fg;
937            if cell.symbol.is_empty() || cell.symbol == " " || cell.style.painted {
938                continue;
939            }
940            // Drawn rather than taken from a font, so stacked rows join with no gap.
941            if cell.symbol == "β–Œ" {
942                fill(&mut rgb, width, i * cw, 0, cw.div_ceil(5), ch, fg);
943                continue;
944            }
945            if let Some(piece) = Piece::decode(&cell.symbol) {
946                draw_icon(&mut rgb, width, i * cw, (cw, ch), piece, fg);
947                continue;
948            }
949            let key = GlyphKey {
950                symbol: cell.symbol.clone(),
951                bold: cell.style.bold,
952                italic: cell.style.italic,
953            };
954            let mask = self.mask(&key);
955            if let Some(painted) = self.painted.get(&key) {
956                for &(x, y, color, alpha) in painted.iter() {
957                    let at = (y as usize * width + i * cw + x as usize) * 3;
958                    if at + 2 < rgb.len() && (i * cw + x as usize) < width {
959                        rgb[at] = blend(color.0, rgb[at], alpha);
960                        rgb[at + 1] = blend(color.1, rgb[at + 1], alpha);
961                        rgb[at + 2] = blend(color.2, rgb[at + 2], alpha);
962                    }
963                }
964                continue;
965            }
966            for &(x, y, alpha) in mask.iter() {
967                let at = (y as usize * width + i * cw + x as usize) * 3;
968                if at + 2 < rgb.len() && (i * cw + x as usize) < width {
969                    rgb[at] = blend(fg.0, rgb[at], alpha);
970                    rgb[at + 1] = blend(fg.1, rgb[at + 1], alpha);
971                    rgb[at + 2] = blend(fg.2, rgb[at + 2], alpha);
972                }
973            }
974        }
975        for (i, cell) in cells.iter().enumerate() {
976            // Painted text underlines itself, at its true width.
977            if cell.style.underline && !cell.style.painted {
978                fill(&mut rgb, width, i * cw, ch - 2, cw, 1, cell.style.fg);
979            }
980        }
981        let paint: Vec<Paint> = grid.paint_on_row(y).cloned().collect();
982        let mut target = Target {
983            rgb: &mut rgb,
984            width,
985            height: ch,
986            top: y as i32 * ch as i32,
987        };
988        for item in &paint {
989            self.draw_paint(&mut target, item);
990        }
991        // A thin caret, as in a real editor, not a terminal's block.
992        if let Some(bounds) = caret_bounds(grid) {
993            let row = (y as i32 * UNIT, (y as i32 + 1) * UNIT);
994            if bounds.y < row.1 && bounds.y + bounds.h > row.0 {
995                let shape = Shape {
996                    x: bounds.x as f32 * cw as f32 / UNIT as f32,
997                    y: bounds.y as f32 * ch as f32 / UNIT as f32,
998                    w: (cw as f32 / 9.0).max(2.0),
999                    h: bounds.h as f32 * ch as f32 / UNIT as f32,
1000                    radius: 0.0,
1001                };
1002                let mut target = Target {
1003                    rgb: &mut rgb,
1004                    width,
1005                    height: ch,
1006                    top: y as i32 * ch as i32,
1007                };
1008                target.panel(
1009                    shape,
1010                    (Some(caret_color(grid)), None),
1011                    false,
1012                    false,
1013                    ch as f32,
1014                );
1015            }
1016        }
1017        Image {
1018            width,
1019            height: ch,
1020            rgb,
1021        }
1022    }
1023}
1024
1025#[cfg(test)]
1026mod tests {
1027    use super::*;
1028    use crate::grid::{Grid, Rect, Style};
1029
1030    fn rasterizer() -> Option<SoftwareRasterizer> {
1031        SoftwareRasterizer::new(10, 20)
1032    }
1033
1034    fn style() -> Style {
1035        Style {
1036            fg: Rgb(250, 250, 250),
1037            bg: Rgb(10, 20, 30),
1038            ..Style::default()
1039        }
1040    }
1041
1042    fn lit(image: &Image, cell: usize, width: usize) -> usize {
1043        let mut count = 0;
1044        for y in 0..image.height {
1045            for x in cell * width..(cell + 1) * width {
1046                let i = (y * image.width + x) * 3;
1047                count += usize::from(image.rgb[i] > 128);
1048            }
1049        }
1050        count
1051    }
1052
1053    #[test]
1054    fn row_image_is_exactly_the_grid_size() {
1055        let Some(mut r) = rasterizer() else { return };
1056        let grid = Grid::new(8, 1, style());
1057        let image = r.row(&grid, 0);
1058        assert_eq!((image.width, image.height), (80, 20));
1059        assert_eq!(image.rgb.len(), 80 * 20 * 3);
1060    }
1061
1062    #[test]
1063    fn han_characters_are_drawn_in_the_cells() {
1064        let Some(mut r) = rasterizer() else { return };
1065        let fonts = system_fonts();
1066        let has_han = fonts.faces().any(|face| {
1067            let name = &face.families[0].0;
1068            CJK_FONTS.iter().any(|font| font == name)
1069        });
1070        if !has_han {
1071            return;
1072        }
1073        let mut grid = Grid::new(4, 1, style());
1074        grid.put_str(0, 0, "δΈ­", style(), 4);
1075        let image = r.row(&grid, 0);
1076        assert!(lit(&image, 0, 10) > 10);
1077    }
1078
1079    #[test]
1080    fn a_wide_glyph_keeps_its_right_half() {
1081        let Some(mut r) = rasterizer() else { return };
1082        let mut grid = Grid::new(4, 1, style());
1083        grid.put_str(1, 0, "MM", style(), 4);
1084        let image = r.row(&grid, 0);
1085        assert!(lit(&image, 1, 10) > 10);
1086        assert!(
1087            lit(&image, 2, 10) > 10,
1088            "the next cell's colour didn't cover it"
1089        );
1090    }
1091
1092    #[test]
1093    fn glyphs_land_in_their_own_cells() {
1094        let Some(mut r) = rasterizer() else { return };
1095        let mut grid = Grid::new(4, 1, style());
1096        grid.put_str(2, 0, "M", style(), 4);
1097        let image = r.row(&grid, 0);
1098        assert_eq!(lit(&image, 0, 10), 0);
1099        assert!(lit(&image, 2, 10) > 10, "M drew nothing");
1100        assert_eq!(lit(&image, 3, 10), 0, "M spilled into the next cell");
1101    }
1102
1103    #[test]
1104    fn the_caret_is_a_thin_line() {
1105        let Some(mut r) = rasterizer() else { return };
1106        let mut grid = Grid::new(3, 1, style());
1107        grid.cursor = Some((1, 0));
1108        let image = r.row(&grid, 0);
1109        let at = |x: usize| image.rgb[(10 * image.width + x) * 3];
1110        assert_eq!(at(10), 250);
1111        assert_eq!(at(15), 10);
1112        grid.caret = Some(Bounds::cells(1.5, 0.0, 0.0, 1.0));
1113        let image = r.row(&grid, 0);
1114        let at = |x: usize| image.rgb[(10 * image.width + x) * 3];
1115        assert_eq!(at(10), 10, "the exact caret replaces the cell one");
1116        assert_eq!(at(15), 250);
1117    }
1118
1119    #[test]
1120    fn labels_draw_without_their_cell_glyphs() {
1121        let Some(mut r) = rasterizer() else { return };
1122        let mut grid = Grid::new(20, 1, style());
1123        grid.label(1, 0, "Illi", style(), 20);
1124        assert!(grid.cell(1, 0).style.painted);
1125        let with_paint = r.row(&grid, 0);
1126        // Inter is proportional: this text is far narrower than four cells.
1127        let lit_right = (0..20)
1128            .flat_map(|y| (40..200).map(move |x| (x, y)))
1129            .any(|(x, y)| with_paint.rgb[(y * with_paint.width + x) * 3] > 128);
1130        assert!(!lit_right, "drew past the narrow label");
1131    }
1132
1133    /// Words are set at the size VS Code sets its own: 13 pt. A terminal set to 14 pt has a
1134    /// cell of 17 by 37 px at two pixels a point, and a capital of 13 pt Inter stands 19 px
1135    /// tall there, with as much of the row over it as under it. At three fifths of a row,
1136    /// as the words were, it stood 16.
1137    #[test]
1138    fn words_are_thirteen_points_in_a_terminal_set_to_fourteen() {
1139        use crate::measure::Measure as _;
1140        let Some(mut r) = SoftwareRasterizer::new(17, 37) else {
1141            return;
1142        };
1143        let mut grid = Grid::new(8, 1, style());
1144        grid.label(1, 0, "H", style(), 8);
1145        let image = r.row(&grid, 0);
1146        let inked: Vec<usize> = (0..image.height)
1147            .filter(|y| (0..image.width).any(|x| image.rgb[(y * image.width + x) * 3] > 128))
1148            .collect();
1149        let (top, bottom) = (inked[0], inked[inked.len() - 1]);
1150        let tall = bottom - top + 1;
1151        assert!((18..=20).contains(&tall), "a capital is {tall} px tall");
1152        let (over, under) = (top, image.height - 1 - bottom);
1153        assert!(
1154            over.abs_diff(under) <= 2,
1155            "{over} px over it, {under} under"
1156        );
1157        // And as wide as 13 pt is: the measure and the picture agree on it.
1158        let wide = crate::measure::FontMeasure::new(17, 37).width("H", Font::default()) * 17.0;
1159        assert!((17.0..21.0).contains(&wide), "an H is {wide} px wide");
1160    }
1161
1162    /// An emoji in a line of painted text keeps its own colours, where the machine has a
1163    /// font that holds them: the letters beside it take the text's.
1164    #[test]
1165    fn an_emoji_in_painted_text_keeps_its_own_colours() {
1166        let Some(mut r) = rasterizer() else { return };
1167        let mask = r.text_mask("ok πŸš€", Font::default());
1168        // Without a colour emoji font it's a blank, in the text's colour like the rest.
1169        let Some(own) = &mask.own else { return };
1170        let coloured = own.iter().flatten().filter(|rgb| rgb.0 != rgb.2).count();
1171        assert!(coloured > 10, "a rocket has red and blue in it: {coloured}");
1172        let plain = r.text_mask("ok", Font::default());
1173        assert!(plain.own.is_none(), "letters have no colour of their own");
1174        // Drawn in dark text on light, the letters are dark and the emoji is still itself.
1175        let mut grid = Grid::new(12, 1, style());
1176        let dark = Style {
1177            fg: Rgb(10, 10, 10),
1178            bg: Rgb(240, 240, 240),
1179            ..Style::default()
1180        };
1181        grid.fill(Rect::new(0, 0, 12, 1), dark);
1182        grid.label(0, 0, "ok πŸš€", dark, 12);
1183        let image = r.row(&grid, 0);
1184        let pixels: Vec<Rgb> = image.rgb.chunks(3).map(|p| Rgb(p[0], p[1], p[2])).collect();
1185        let tinted = |p: &&Rgb| p.0.abs_diff(p.2) > 60;
1186        assert!(pixels.iter().filter(tinted).count() > 10);
1187    }
1188
1189    #[test]
1190    fn panels_have_rounded_corners() {
1191        let Some(mut r) = rasterizer() else { return };
1192        let mut grid = Grid::new(10, 1, style());
1193        grid.panel(
1194            crate::paint::Bounds::cells(1.0, 0.0, 8.0, 1.0),
1195            40,
1196            Some(Rgb(255, 0, 0)),
1197            None,
1198        );
1199        let image = r.row(&grid, 0);
1200        let red = |x: usize, y: usize| image.rgb[(y * image.width + x) * 3];
1201        assert_eq!(red(50, 10), 255, "the middle is filled");
1202        assert_eq!(red(10, 0), 10, "the corner is cut");
1203    }
1204
1205    #[test]
1206    fn a_wash_lets_what_is_under_it_show() {
1207        let Some(mut r) = rasterizer() else { return };
1208        let mut grid = Grid::new(20, 2, style());
1209        let bounds = crate::paint::Bounds::cells(1.0, 0.0, 18.0, 2.0);
1210        grid.wash(bounds, 10, (Rgb(255, 0, 0), 64), Some(Rgb(0, 0, 255)));
1211        let image = r.row(&grid, 0);
1212        let at = |x: usize, y: usize| {
1213            let i = (y * image.width + x) * 3;
1214            (image.rgb[i], image.rgb[i + 1], image.rgb[i + 2])
1215        };
1216        let middle = at(image.width / 2, image.height - 1);
1217        assert!(middle.0 > 0 && middle.0 < 200, "a little red: {middle:?}");
1218        let edge = at(image.width / 2, 0);
1219        assert!(edge.2 > 200, "the border: {edge:?}");
1220    }
1221
1222    #[test]
1223    fn a_dashed_border_has_gaps() {
1224        let Some(mut r) = rasterizer() else { return };
1225        let mut grid = Grid::new(20, 1, style());
1226        grid.dashed_panel(
1227            crate::paint::Bounds::cells(1.0, 0.0, 18.0, 1.0),
1228            10,
1229            None,
1230            Rgb(255, 0, 0),
1231        );
1232        let image = r.row(&grid, 0);
1233        // Along the top edge, past the corner: some pixels inked, some left.
1234        let y = 0;
1235        let reds: Vec<u8> = (30..170)
1236            .map(|x| image.rgb[(y * image.width + x) * 3])
1237            .collect();
1238        assert!(reds.iter().any(|r| *r > 200), "dashes are drawn");
1239        assert!(reds.iter().any(|r| *r < 60), "with gaps between them");
1240    }
1241
1242    /// The emoji font in the binary draws in colour with none of the machine's fonts, which
1243    /// is what a server reached over SSH has, and holds the eight emoji that stand under a
1244    /// comment being written.
1245    #[test]
1246    fn the_emoji_font_in_the_binary_draws_in_colour_by_itself() {
1247        let mut db = fontdb::Database::new();
1248        for data in [INTER, INTER_ITALIC, MONO, MONO_ITALIC, EMOJI] {
1249            db.load_font_data(data.to_vec());
1250        }
1251        db.set_monospace_family("JetBrains Mono");
1252        db.set_sans_serif_family("Inter Variable");
1253        let mut fonts = FontSystem::new_with_locale_and_db("en-US".to_string(), db);
1254        assert!(draws_colour(&mut fonts, BUILT_IN_EMOJI));
1255        let found = find_emoji_font(&mut fonts).map(|(family, _)| family);
1256        assert_eq!(found.as_deref(), Some(BUILT_IN_EMOJI));
1257        for emoji in ["πŸ‘", "πŸ’―", "❀\u{fe0f}", "πŸŽ‰", "πŸ˜„", "πŸ‘€", "πŸš€", "βœ…"] {
1258            assert!(
1259                set_in(&mut fonts, BUILT_IN_EMOJI, emoji).is_some(),
1260                "{emoji}"
1261            );
1262        }
1263        // A family the machine doesn't have draws nothing in colour.
1264        assert!(!draws_colour(&mut fonts, "No Such Emoji"));
1265        // It holds a flag and a family whole, and not an emoji newer than it is.
1266        for emoji in ["πŸ‡ΉπŸ‡·", "πŸ‘©\u{200d}πŸ’»", "❀\u{fe0f}", "1\u{fe0f}\u{20e3}"] {
1267            assert!(built_in_emoji_holds(emoji), "{emoji}");
1268        }
1269        assert!(
1270            !built_in_emoji_holds("🫨"),
1271            "a face from a year after the font"
1272        );
1273        assert!(!built_in_emoji_holds("ok"));
1274        // And through the rasterizer itself: a line of words with two in it.
1275        let metrics = fit_font(&mut fonts, 10, 20).unwrap();
1276        let mut r = SoftwareRasterizer {
1277            fonts,
1278            emoji: Some(BUILT_IN_EMOJI.to_string()),
1279            swash: SwashCache::new(),
1280            metrics,
1281            cell: (10, 20),
1282            masks: HashMap::new(),
1283            painted: HashMap::new(),
1284            text: HashMap::new(),
1285        };
1286        let mask = r.text_mask("ok πŸš€ ❀\u{fe0f}", Font::default());
1287        let own = mask
1288            .own
1289            .as_ref()
1290            .expect("the emoji have colours of their own");
1291        let red = own
1292            .iter()
1293            .flatten()
1294            .filter(|rgb| rgb.0 > 150 && rgb.2 < 120);
1295        assert!(red.count() > 10, "a heart and a rocket's flame are red");
1296    }
1297
1298    #[test]
1299    fn fonts_ship_in_the_binary() {
1300        let mut r = SoftwareRasterizer::new(10, 20).unwrap();
1301        assert!(
1302            r.fonts
1303                .db()
1304                .faces()
1305                .any(|f| f.families.iter().any(|(n, _)| n.contains("Inter")))
1306        );
1307        assert!(
1308            r.text_mask("x", Font::default())
1309                .alpha
1310                .iter()
1311                .any(|a| *a > 0)
1312        );
1313    }
1314
1315    #[test]
1316    fn unknown_cell_size_refuses_pixels() {
1317        assert!(SoftwareRasterizer::new(0, 20).is_none());
1318    }
1319}