Skip to main content

cellix_render/
raster.rs

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