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