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};
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}
56
57/// Fonts that hold Chinese and Japanese. The usual choices can be on-demand downloads a
58/// machine doesn't have, and a missing one leaves the text blank.
59const CJK_FONTS: [&str; 9] = [
60    "PingFang SC",
61    "Hiragino Sans",
62    "Hiragino Sans GB",
63    "Songti SC",
64    "Heiti SC",
65    "Arial Unicode MS",
66    "Noto Sans CJK SC",
67    "Noto Sans CJK JP",
68    "WenQuanYi Micro Hei",
69];
70
71/// The platform's fallback, with a longer list for the scripts it runs out of.
72struct WiderFallback(PlatformFallback);
73
74impl Fallback for WiderFallback {
75    fn common_fallback(&self) -> &[&'static str] {
76        self.0.common_fallback()
77    }
78
79    fn forbidden_fallback(&self) -> &[&'static str] {
80        self.0.forbidden_fallback()
81    }
82
83    fn script_fallback(&self, script: Script, locale: &str) -> &[&'static str] {
84        match script {
85            Script::Han | Script::Hiragana | Script::Katakana => &CJK_FONTS,
86            other => self.0.script_fallback(other, locale),
87        }
88    }
89}
90
91fn system_fonts() -> fontdb::Database {
92    let mut db = fontdb::Database::new();
93    db.load_system_fonts();
94    db
95}
96
97/// How dark a floating panel's shadow is at its edge, out of 255.
98const DARK_SHADOW: f32 = 110.0;
99const LIGHT_SHADOW: f32 = 38.0;
100/// Interface text is drawn at this size relative to the row height.
101pub const INTERFACE_SIZE: f32 = 0.60;
102/// Cached text lines before the cache is dropped, so a long session can't grow it forever.
103const MAX_TEXT_MASKS: usize = 4096;
104
105pub(crate) const INTER: &[u8] = include_bytes!("../fonts/InterVariable.ttf");
106pub(crate) const INTER_ITALIC: &[u8] = include_bytes!("../fonts/InterVariable-Italic.ttf");
107pub(crate) const MONO: &[u8] = include_bytes!("../fonts/JetBrainsMonoVariable.ttf");
108pub(crate) const MONO_ITALIC: &[u8] = include_bytes!("../fonts/JetBrainsMonoVariable-Italic.ttf");
109
110/// The pixel size painted text is drawn at, for a row height and font.
111pub(crate) fn text_pixels(row_height: usize, font: Font) -> f32 {
112    row_height as f32 * INTERFACE_SIZE * font.size as f32 / 100.0
113}
114
115/// CPU rendering. Glyphs are rasterized once and blended into their cells, so text stays
116/// locked to the grid and a row costs little more than a copy.
117pub struct SoftwareRasterizer {
118    fonts: FontSystem,
119    swash: SwashCache,
120    metrics: Metrics,
121    cell: (usize, usize),
122    masks: HashMap<GlyphKey, Mask>,
123    /// Glyphs with colours of their own, such as emoji, as pixels with those colours.
124    painted: HashMap<GlyphKey, Painted>,
125    text: HashMap<TextKey, Rc<TextMask>>,
126}
127
128impl SoftwareRasterizer {
129    /// The fonts ship in the binary, because pixels are drawn on the remote host over SSH
130    /// and servers rarely have any. Returns None only when the cell size is unknown.
131    pub fn new(cell_width: usize, cell_height: usize) -> Option<Self> {
132        if cell_width == 0 || cell_height == 0 {
133            return None;
134        }
135        let mut fonts = FontSystem::new_with_locale_and_db_and_fallback(
136            "en-US".to_string(),
137            system_fonts(),
138            WiderFallback(PlatformFallback),
139        );
140        let db = fonts.db_mut();
141        db.load_font_data(INTER.to_vec());
142        db.load_font_data(INTER_ITALIC.to_vec());
143        db.load_font_data(MONO.to_vec());
144        db.load_font_data(MONO_ITALIC.to_vec());
145        db.set_monospace_family("JetBrains Mono");
146        db.set_sans_serif_family("Inter Variable");
147        let metrics = fit_font(&mut fonts, cell_width, cell_height)?;
148        Some(Self {
149            fonts,
150            swash: SwashCache::new(),
151            metrics,
152            cell: (cell_width, cell_height),
153            masks: HashMap::new(),
154            painted: HashMap::new(),
155            text: HashMap::new(),
156        })
157    }
158
159    fn mask(&mut self, key: &GlyphKey) -> Mask {
160        if let Some(mask) = self.masks.get(key) {
161            return mask.clone();
162        }
163        let (width, height) = (self.cell.0 * 2, self.cell.1);
164        let mut buffer = Buffer::new(&mut self.fonts, self.metrics);
165        buffer.set_size(Some(width as f32 * 2.0), Some(height as f32));
166        // Asked for a monospaced Han glyph, the search stops at a font that only has blanks.
167        // A wide glyph fills its two cells whatever font it's from.
168        let family = if UnicodeWidthStr::width(key.symbol.as_str()) > 1 {
169            Family::SansSerif
170        } else {
171            Family::Monospace
172        };
173        let mut attrs = Attrs::new().family(family);
174        if key.bold {
175            attrs = attrs.weight(Weight::BOLD);
176        }
177        if key.italic {
178            attrs = attrs.style(FontStyle::Italic);
179        }
180        let rich = std::iter::once((key.symbol.as_str(), attrs.clone()));
181        buffer.set_rich_text(rich, &attrs, Shaping::Advanced, None);
182        buffer.shape_until_scroll(&mut self.fonts, false);
183        let mut pixels = Vec::new();
184        let mut coloured = Vec::new();
185        let white = Color::rgb(255, 255, 255);
186        buffer.draw(
187            &mut self.fonts,
188            &mut self.swash,
189            white,
190            |x, y, w, h, color| {
191                if color.a() == 0 {
192                    return;
193                }
194                for py in y..y + h as i32 {
195                    for px in x..x + w as i32 {
196                        if px >= 0 && py >= 0 && (px as usize) < width && (py as usize) < height {
197                            pixels.push((px as u16, py as u16, color.a()));
198                            let rgb = Rgb(color.r(), color.g(), color.b());
199                            coloured.push((px as u16, py as u16, rgb, color.a()));
200                        }
201                    }
202                }
203            },
204        );
205        // Text comes out white, ready to take any colour. Anything else is the glyph's own.
206        if coloured
207            .iter()
208            .any(|(_, _, rgb, _)| *rgb != Rgb(255, 255, 255))
209        {
210            self.painted.insert(key.clone(), Rc::new(coloured));
211        }
212        let mask = Rc::new(pixels);
213        self.masks.insert(key.clone(), mask.clone());
214        mask
215    }
216
217    /// A line of painted text, tall enough for its size.
218    fn text_mask(&mut self, text: &str, font: Font) -> Rc<TextMask> {
219        let key = TextKey {
220            text: text.to_string(),
221            font,
222        };
223        if let Some(mask) = self.text.get(&key) {
224            return mask.clone();
225        }
226        if self.text.len() >= MAX_TEXT_MASKS {
227            self.text.clear();
228        }
229        let px = text_pixels(self.cell.1, font);
230        let height = self.cell.1.max((px * 1.45).ceil() as usize);
231        let mut buffer = Buffer::new(&mut self.fonts, Metrics::new(px, height as f32));
232        buffer.set_size(None, Some(height as f32));
233        let style = attrs(font);
234        let rich = std::iter::once((text, style.clone()));
235        buffer.set_rich_text(rich, &style, Shaping::Advanced, None);
236        buffer.shape_until_scroll(&mut self.fonts, false);
237        let width = buffer
238            .layout_runs()
239            .next()
240            .map_or(0.0, |run| run.line_w)
241            .ceil() as usize
242            + 2;
243        let mut alpha = vec![0; width * height];
244        let white = Color::rgb(255, 255, 255);
245        buffer.draw(
246            &mut self.fonts,
247            &mut self.swash,
248            white,
249            |x, y, w, h, color| {
250                for py in y..y + h as i32 {
251                    for px in x..x + w as i32 {
252                        if px >= 0 && py >= 0 && (px as usize) < width && (py as usize) < height {
253                            let at = py as usize * width + px as usize;
254                            alpha[at] = alpha[at].max(color.a());
255                        }
256                    }
257                }
258            },
259        );
260        let mask = Rc::new(TextMask {
261            width,
262            height,
263            alpha,
264        });
265        self.text.insert(key, mask.clone());
266        mask
267    }
268
269    fn draw_paint(&mut self, target: &mut Target, paint: &Paint) {
270        let (cw, ch) = (self.cell.0 as f32, self.cell.1 as f32);
271        let scale = |v: i32, cell: f32| v as f32 * cell / UNIT as f32;
272        match paint {
273            Paint::Panel {
274                bounds,
275                radius,
276                fill,
277                border,
278                shadow,
279                dashed,
280            } => {
281                let shape = Shape {
282                    x: scale(bounds.x, cw),
283                    y: scale(bounds.y, ch),
284                    w: scale(bounds.w, cw),
285                    h: scale(bounds.h, ch),
286                    radius: *radius as f32 * ch / 100.0,
287                };
288                target.panel(shape, (*fill, *border), *shadow, *dashed, ch);
289            }
290            Paint::Wash {
291                bounds,
292                radius,
293                color,
294                alpha,
295                border,
296            } => {
297                let shape = Shape {
298                    x: scale(bounds.x, cw),
299                    y: scale(bounds.y, ch),
300                    w: scale(bounds.w, cw),
301                    h: scale(bounds.h, ch),
302                    radius: *radius as f32 * ch / 100.0,
303                };
304                target.wash(shape, (*color, *alpha), *border, ch);
305            }
306            Paint::Hairline { bounds, color } => {
307                let thickness = (ch / 24.0).ceil().max(1.0);
308                let shape = Shape {
309                    x: scale(bounds.x, cw),
310                    y: scale(bounds.y, ch),
311                    w: scale(bounds.w, cw).max(thickness),
312                    h: scale(bounds.h, ch).max(thickness),
313                    radius: 0.0,
314                };
315                target.panel(shape, (Some(*color), None), false, false, ch);
316            }
317            Paint::Text {
318                x,
319                y,
320                max_width,
321                text,
322                color,
323                font,
324                align_right,
325                centred,
326                underline,
327            } => {
328                let mask = self.text_mask(text, *font);
329                let mut left = scale(*x, cw).round() as i32;
330                if *align_right {
331                    left -= mask.width as i32;
332                } else if *centred {
333                    left -= mask.width as i32 / 2;
334                }
335                // Tall text stays centred on its row.
336                let lift = (mask.height as i32 - ch as i32) / 2;
337                let top = scale(*y, ch).round() as i32 - lift;
338                let limit = scale(*max_width, cw).max(0.0) as usize;
339                target.blit(&mask, left, top, limit, *color);
340                if *underline {
341                    let thickness = (ch / 24.0).ceil().max(1.0);
342                    let shape = Shape {
343                        x: left as f32,
344                        y: scale(*y, ch) + ch * 0.78,
345                        w: mask.width.saturating_sub(2).min(limit) as f32,
346                        h: thickness,
347                        radius: 0.0,
348                    };
349                    target.panel(shape, (Some(*color), None), false, false, ch);
350                }
351            }
352            Paint::Icon {
353                bounds,
354                icon,
355                color,
356            } => {
357                let side = scale(bounds.h, ch);
358                let left = scale(bounds.x, cw);
359                let top = scale(bounds.y, ch);
360                target.icon(*icon, left, top, side, *color);
361            }
362            Paint::Corners {
363                bounds,
364                radius,
365                color,
366                which,
367            } => {
368                let shape = Shape {
369                    x: scale(bounds.x, cw),
370                    y: scale(bounds.y, ch),
371                    w: scale(bounds.w, cw),
372                    h: scale(bounds.h, ch),
373                    radius: *radius as f32 * ch / 100.0,
374                };
375                target.corners(&shape, *color, *which);
376            }
377            Paint::Image {
378                bounds,
379                clip,
380                bitmap,
381                color,
382            } => {
383                let shape = Shape {
384                    x: scale(bounds.x, cw),
385                    y: scale(bounds.y, ch),
386                    w: scale(bounds.w, cw),
387                    h: scale(bounds.h, ch),
388                    radius: 0.0,
389                };
390                let across = (
391                    scale(clip.x, cw) as i32,
392                    scale(clip.x + clip.w, cw).ceil() as i32,
393                );
394                let down = (
395                    scale(clip.y, ch) as i32,
396                    scale(clip.y + clip.h, ch).ceil() as i32,
397                );
398                target.image(&shape, (across, down), bitmap, *color);
399            }
400            Paint::Strips { bounds, strips } => {
401                let (left, top) = (scale(bounds.x, cw), scale(bounds.y, ch));
402                let (width, height) = (scale(bounds.w, cw), scale(bounds.h, ch));
403                let thickness = (ch / 24.0).ceil().max(1.0);
404                for strip in strips {
405                    let shape = Shape {
406                        x: left + strip.x as f32 * width / 256.0,
407                        y: top + strip.y as f32 * height / 256.0,
408                        w: (strip.w as f32 * width / 256.0).max(1.0),
409                        h: thickness,
410                        radius: 0.0,
411                    };
412                    target.panel(shape, (Some(strip.color), None), false, false, ch);
413                }
414            }
415        }
416    }
417}
418
419/// Where the caret goes: its exact place, or the cell the cursor is in.
420fn caret_bounds(grid: &Grid) -> Option<Bounds> {
421    grid.caret.or_else(|| {
422        let (x, y) = grid.cursor?;
423        Some(Bounds::cells(x as f32, y as f32 + 0.08, 0.0, 0.84))
424    })
425}
426
427fn caret_color(grid: &Grid) -> Rgb {
428    let Some((x, y)) = grid.cursor else {
429        return Rgb(255, 255, 255);
430    };
431    grid.cell(x.min(grid.width().saturating_sub(1)), y).style.fg
432}
433
434struct Shape {
435    x: f32,
436    y: f32,
437    w: f32,
438    h: f32,
439    radius: f32,
440}
441
442/// Distance from a point to a rounded box's edge, negative inside.
443fn rounded_distance(shape: &Shape, x: f32, y: f32) -> f32 {
444    let (cx, cy) = (shape.x + shape.w / 2.0, shape.y + shape.h / 2.0);
445    let qx = (x - cx).abs() - shape.w / 2.0 + shape.radius;
446    let qy = (y - cy).abs() - shape.h / 2.0 + shape.radius;
447    let outside = (qx.max(0.0).powi(2) + qy.max(0.0).powi(2)).sqrt();
448    outside + qx.max(qy).min(0.0) - shape.radius
449}
450
451/// The part of the screen one row's tile covers, in screen pixels.
452struct Target<'a> {
453    rgb: &'a mut [u8],
454    width: usize,
455    height: usize,
456    top: i32,
457}
458
459impl Target<'_> {
460    fn corners(&mut self, s: &Shape, color: Rgb, which: u8) {
461        let r = s.radius;
462        let spots = [
463            (TOP_LEFT, s.x, s.y, s.x + r, s.y + r),
464            (TOP_RIGHT, s.x + s.w - r, s.y, s.x + s.w - r, s.y + r),
465            (
466                BOTTOM_RIGHT,
467                s.x + s.w - r,
468                s.y + s.h - r,
469                s.x + s.w - r,
470                s.y + s.h - r,
471            ),
472            (BOTTOM_LEFT, s.x, s.y + s.h - r, s.x + r, s.y + s.h - r),
473        ];
474        for (flag, left, top, cx, cy) in spots {
475            if which & flag == 0 {
476                continue;
477            }
478            for y in top.floor() as i32..(top + r).ceil() as i32 {
479                for x in left.floor() as i32..(left + r).ceil() as i32 {
480                    let d = ((x as f32 + 0.5 - cx).powi(2) + (y as f32 + 0.5 - cy).powi(2)).sqrt();
481                    let outside = (d - r + 0.5).clamp(0.0, 1.0);
482                    self.blend(x, y, color, (outside * 255.0) as u8);
483                }
484            }
485        }
486    }
487
488    fn blend(&mut self, x: i32, y: i32, color: Rgb, alpha: u8) {
489        let row = y - self.top;
490        if alpha == 0 || x < 0 || row < 0 || x as usize >= self.width || row as usize >= self.height
491        {
492            return;
493        }
494        let at = (row as usize * self.width + x as usize) * 3;
495        self.rgb[at] = blend(color.0, self.rgb[at], alpha);
496        self.rgb[at + 1] = blend(color.1, self.rgb[at + 1], alpha);
497        self.rgb[at + 2] = blend(color.2, self.rgb[at + 2], alpha);
498    }
499
500    fn panel(
501        &mut self,
502        s: Shape,
503        (fill, border): (Option<Rgb>, Option<Rgb>),
504        shadow: bool,
505        dashed: bool,
506        row: f32,
507    ) {
508        // Dashes a quarter of a row long, with gaps as long, measured along the edge so every
509        // row of a tall panel continues the same pattern.
510        let dash = (row / 4.0).max(2.0);
511        let on_dash = |x: f32, y: f32| {
512            let along_top = x > s.x + s.radius && x < s.x + s.w - s.radius;
513            let run = if along_top { x - s.x } else { y - s.y };
514            (run / dash).floor() as i64 % 2 == 0
515        };
516        let reach = if shadow { row * 0.6 } else { 1.0 };
517        let (x0, x1) = (
518            (s.x - reach).floor() as i32,
519            (s.x + s.w + reach).ceil() as i32,
520        );
521        let y0 = ((s.y - reach).floor() as i32).max(self.top);
522        let y1 = ((s.y + s.h + reach).ceil() as i32).min(self.top + self.height as i32);
523        let stroke = (row / 30.0).max(1.0);
524        for y in y0..y1 {
525            for x in x0..x1 {
526                let d = rounded_distance(&s, x as f32 + 0.5, y as f32 + 0.5);
527                if shadow && d > 0.0 {
528                    let fade = (1.0 - d / reach).clamp(0.0, 1.0);
529                    // A shadow heavy enough for dark surfaces is a grey halo on light ones.
530                    let light = fill.is_some_and(|f| f.0 > 180);
531                    let depth = if light { LIGHT_SHADOW } else { DARK_SHADOW };
532                    self.blend(x, y, Rgb(0, 0, 0), (fade * fade * depth) as u8);
533                }
534                let inside = ((0.5 - d) * 255.0).clamp(0.0, 255.0) as u8;
535                if let Some(color) = fill {
536                    self.blend(x, y, color, inside);
537                }
538                if let Some(color) = border
539                    && (!dashed || on_dash(x as f32 + 0.5, y as f32 + 0.5))
540                {
541                    let edge = ((0.5 - (d + stroke / 2.0).abs() + stroke / 2.0) * 255.0)
542                        .clamp(0.0, 255.0) as u8;
543                    self.blend(x, y, color, edge);
544                }
545            }
546        }
547    }
548
549    /// A see-through fill with round corners, and a border twice a panel's weight.
550    fn wash(&mut self, s: Shape, (color, alpha): (Rgb, u8), border: Option<Rgb>, row: f32) {
551        let (x0, x1) = (s.x.floor() as i32 - 1, (s.x + s.w).ceil() as i32 + 1);
552        let y0 = (s.y.floor() as i32 - 1).max(self.top);
553        let y1 = ((s.y + s.h).ceil() as i32 + 1).min(self.top + self.height as i32);
554        let stroke = (row / 15.0).max(2.0);
555        for y in y0..y1 {
556            for x in x0..x1 {
557                let d = rounded_distance(&s, x as f32 + 0.5, y as f32 + 0.5);
558                let inside = (0.5 - d).clamp(0.0, 1.0);
559                self.blend(x, y, color, (inside * alpha as f32) as u8);
560                if let Some(edge_color) = border {
561                    // The border runs just inside the edge.
562                    let along = (0.5 - (d + stroke / 2.0).abs() + stroke / 2.0).clamp(0.0, 1.0);
563                    self.blend(x, y, edge_color, (along * 255.0) as u8);
564                }
565            }
566        }
567    }
568
569    fn blit(&mut self, mask: &TextMask, left: i32, top: i32, limit: usize, color: Rgb) {
570        let from = (self.top - top).max(0) as usize;
571        let to = ((self.top + self.height as i32 - top).max(0) as usize).min(mask.height);
572        for y in from..to {
573            for x in 0..mask.width.min(limit) {
574                let alpha = mask.alpha[y * mask.width + x];
575                self.blend(left + x as i32, top + y as i32, color, alpha);
576            }
577        }
578    }
579
580    /// Scales a bitmap into `s`, sampling between its pixels so nothing shimmers.
581    fn image(&mut self, s: &Shape, clip: ((i32, i32), (i32, i32)), bitmap: &Bitmap, color: Rgb) {
582        let (width, height) = (bitmap.width as usize, bitmap.height as usize);
583        if width == 0 || height == 0 || s.w <= 0.0 || s.h <= 0.0 {
584            return;
585        }
586        let channels = match bitmap.kind {
587            Pixels::Coverage => 1,
588            Pixels::Rgba => 4,
589        };
590        let at = |x: usize, y: usize, c: usize| -> f32 {
591            let index = (y.min(height - 1) * width + x.min(width - 1)) * channels + c;
592            bitmap.pixels.get(index).copied().unwrap_or(0) as f32
593        };
594        let sample = |u: f32, v: f32, c: usize| -> f32 {
595            let (fx, fy) = (u.max(0.0), v.max(0.0));
596            let (x, y) = (fx as usize, fy as usize);
597            let (dx, dy) = (fx - x as f32, fy - y as f32);
598            let top = at(x, y, c) * (1.0 - dx) + at(x + 1, y, c) * dx;
599            let bottom = at(x, y + 1, c) * (1.0 - dx) + at(x + 1, y + 1, c) * dx;
600            top * (1.0 - dy) + bottom * dy
601        };
602        let ((left, right), (top, bottom)) = clip;
603        let y0 = (s.y.floor() as i32).max(self.top).max(top);
604        let y1 = ((s.y + s.h).ceil() as i32)
605            .min(self.top + self.height as i32)
606            .min(bottom);
607        let x0 = (s.x.floor() as i32).max(0).max(left);
608        let x1 = ((s.x + s.w).ceil() as i32)
609            .min(self.width as i32)
610            .min(right);
611        let (ax, ay) = (width as f32 / s.w, height as f32 / s.h);
612        // A frame made for exactly this size is a copy, which keeps a live page cheap.
613        if bitmap.kind == Pixels::Rgba && (ax - 1.0).abs() < 0.002 && (ay - 1.0).abs() < 0.002 {
614            let (left, top) = (s.x.round() as i32, s.y.round() as i32);
615            for y in y0..y1 {
616                for x in x0..x1 {
617                    let (u, v) = (x - left, y - top);
618                    if u < 0 || v < 0 || u as usize >= width || v as usize >= height {
619                        continue;
620                    }
621                    let at = (v as usize * width + u as usize) * 4;
622                    if let Some(p) = bitmap.pixels.get(at..at + 4) {
623                        self.blend(x, y, Rgb(p[0], p[1], p[2]), p[3]);
624                    }
625                }
626            }
627            return;
628        }
629        for y in y0..y1 {
630            for x in x0..x1 {
631                let u = (x as f32 + 0.5 - s.x) * ax - 0.5;
632                let v = (y as f32 + 0.5 - s.y) * ay - 0.5;
633                match bitmap.kind {
634                    Pixels::Coverage => self.blend(x, y, color, sample(u, v, 0) as u8),
635                    Pixels::Rgba => {
636                        let ink = Rgb(
637                            sample(u, v, 0) as u8,
638                            sample(u, v, 1) as u8,
639                            sample(u, v, 2) as u8,
640                        );
641                        self.blend(x, y, ink, sample(u, v, 3) as u8);
642                    }
643                }
644            }
645        }
646    }
647
648    fn icon(&mut self, icon: Icon, left: f32, top: f32, side: f32, color: Rgb) {
649        // Five by five keeps thin curved strokes smooth, and tiles only draw this once.
650        const SAMPLES: usize = 5;
651        let y0 = (top.floor() as i32).max(self.top);
652        let y1 = ((top + side).ceil() as i32).min(self.top + self.height as i32);
653        for y in y0..y1 {
654            for x in left.floor() as i32..(left + side).ceil() as i32 {
655                let mut hits = 0;
656                for sy in 0..SAMPLES {
657                    for sx in 0..SAMPLES {
658                        let u = (x as f32 + (sx as f32 + 0.5) / SAMPLES as f32 - left) / side;
659                        let v = (y as f32 + (sy as f32 + 0.5) / SAMPLES as f32 - top) / side;
660                        if (0.0..1.0).contains(&u) && (0.0..1.0).contains(&v) && inked(icon, u, v) {
661                            hits += 1;
662                        }
663                    }
664                }
665                self.blend(x, y, color, (hits * 255 / (SAMPLES * SAMPLES)) as u8);
666            }
667        }
668    }
669}
670
671/// Picks the largest font whose advance fits the cell and whose height fits the row.
672fn fit_font(fonts: &mut FontSystem, cell_width: usize, cell_height: usize) -> Option<Metrics> {
673    const PROBE: f32 = 100.0;
674    let mut buffer = Buffer::new(fonts, Metrics::new(PROBE, PROBE * 1.2));
675    buffer.set_size(Some(PROBE * 4.0), Some(PROBE * 2.0));
676    let attrs = Attrs::new().family(Family::Monospace);
677    buffer.set_rich_text(
678        std::iter::once(("M", attrs.clone())),
679        &attrs,
680        Shaping::Advanced,
681        None,
682    );
683    buffer.shape_until_scroll(fonts, false);
684    let advance = buffer.layout_runs().next()?.line_w;
685    if advance <= 0.0 {
686        return None;
687    }
688    let by_width = cell_width as f32 * PROBE / advance;
689    let by_height = cell_height as f32 * 0.8;
690    Some(Metrics::new(by_width.min(by_height), cell_height as f32))
691}
692
693/// Inks this cell's share of an icon, supersampled so curves stay smooth.
694fn draw_icon(
695    rgb: &mut [u8],
696    stride: usize,
697    left: usize,
698    cell: (usize, usize),
699    piece: Piece,
700    fg: Rgb,
701) {
702    const SAMPLES: usize = 4;
703    let (cw, ch) = cell;
704    let (full_w, full_h) = (cw * piece.width as usize, ch * piece.height as usize);
705    let side = full_w.min(full_h) as f32 * 0.94;
706    let (off_x, off_y) = ((full_w as f32 - side) / 2.0, (full_h as f32 - side) / 2.0);
707    for y in 0..ch {
708        for x in 0..cw {
709            let mut hits = 0;
710            for sy in 0..SAMPLES {
711                for sx in 0..SAMPLES {
712                    let px = (piece.column as usize * cw + x) as f32
713                        + (sx as f32 + 0.5) / SAMPLES as f32;
714                    let py =
715                        (piece.row as usize * ch + y) as f32 + (sy as f32 + 0.5) / SAMPLES as f32;
716                    let (u, v) = ((px - off_x) / side, (py - off_y) / side);
717                    if (0.0..1.0).contains(&u) && (0.0..1.0).contains(&v) && inked(piece.icon, u, v)
718                    {
719                        hits += 1;
720                    }
721                }
722            }
723            if hits > 0 {
724                let alpha = (hits * 255 / (SAMPLES * SAMPLES)) as u8;
725                let at = (y * stride + left + x) * 3;
726                rgb[at] = blend(fg.0, rgb[at], alpha);
727                rgb[at + 1] = blend(fg.1, rgb[at + 1], alpha);
728                rgb[at + 2] = blend(fg.2, rgb[at + 2], alpha);
729            }
730        }
731    }
732}
733
734fn blend(fg: u8, bg: u8, alpha: u8) -> u8 {
735    let a = alpha as u32;
736    ((fg as u32 * a + bg as u32 * (255 - a)) / 255) as u8
737}
738
739fn fill(rgb: &mut [u8], stride: usize, x: usize, y: usize, w: usize, h: usize, color: Rgb) {
740    for row in y..y + h {
741        for px in x..x + w {
742            let i = (row * stride + px) * 3;
743            if i + 2 < rgb.len() {
744                rgb[i..i + 3].copy_from_slice(&[color.0, color.1, color.2]);
745            }
746        }
747    }
748}
749
750impl Rasterizer for SoftwareRasterizer {
751    fn row(&mut self, grid: &Grid, y: u16) -> Image {
752        let cells = grid.row(y);
753        let (cw, ch) = self.cell;
754        let width = cw * cells.len();
755        let mut rgb = vec![0; width * ch * 3];
756        // Backgrounds first: a wide glyph runs into the next cell, whose colour would cut it.
757        for (i, cell) in cells.iter().enumerate() {
758            fill(&mut rgb, width, i * cw, 0, cw, ch, cell.style.bg);
759        }
760        for (i, cell) in cells.iter().enumerate() {
761            let fg = cell.style.fg;
762            if cell.symbol.is_empty() || cell.symbol == " " || cell.style.painted {
763                continue;
764            }
765            // Drawn rather than taken from a font, so stacked rows join with no gap.
766            if cell.symbol == "▌" {
767                fill(&mut rgb, width, i * cw, 0, cw.div_ceil(5), ch, fg);
768                continue;
769            }
770            if let Some(piece) = Piece::decode(&cell.symbol) {
771                draw_icon(&mut rgb, width, i * cw, (cw, ch), piece, fg);
772                continue;
773            }
774            let key = GlyphKey {
775                symbol: cell.symbol.clone(),
776                bold: cell.style.bold,
777                italic: cell.style.italic,
778            };
779            let mask = self.mask(&key);
780            if let Some(painted) = self.painted.get(&key) {
781                for &(x, y, color, alpha) in painted.iter() {
782                    let at = (y as usize * width + i * cw + x as usize) * 3;
783                    if at + 2 < rgb.len() && (i * cw + x as usize) < width {
784                        rgb[at] = blend(color.0, rgb[at], alpha);
785                        rgb[at + 1] = blend(color.1, rgb[at + 1], alpha);
786                        rgb[at + 2] = blend(color.2, rgb[at + 2], alpha);
787                    }
788                }
789                continue;
790            }
791            for &(x, y, alpha) in mask.iter() {
792                let at = (y as usize * width + i * cw + x as usize) * 3;
793                if at + 2 < rgb.len() && (i * cw + x as usize) < width {
794                    rgb[at] = blend(fg.0, rgb[at], alpha);
795                    rgb[at + 1] = blend(fg.1, rgb[at + 1], alpha);
796                    rgb[at + 2] = blend(fg.2, rgb[at + 2], alpha);
797                }
798            }
799        }
800        for (i, cell) in cells.iter().enumerate() {
801            // Painted text underlines itself, at its true width.
802            if cell.style.underline && !cell.style.painted {
803                fill(&mut rgb, width, i * cw, ch - 2, cw, 1, cell.style.fg);
804            }
805        }
806        let paint: Vec<Paint> = grid.paint_on_row(y).cloned().collect();
807        let mut target = Target {
808            rgb: &mut rgb,
809            width,
810            height: ch,
811            top: y as i32 * ch as i32,
812        };
813        for item in &paint {
814            self.draw_paint(&mut target, item);
815        }
816        // A thin caret, as in a real editor, not a terminal's block.
817        if let Some(bounds) = caret_bounds(grid) {
818            let row = (y as i32 * UNIT, (y as i32 + 1) * UNIT);
819            if bounds.y < row.1 && bounds.y + bounds.h > row.0 {
820                let shape = Shape {
821                    x: bounds.x as f32 * cw as f32 / UNIT as f32,
822                    y: bounds.y as f32 * ch as f32 / UNIT as f32,
823                    w: (cw as f32 / 9.0).max(2.0),
824                    h: bounds.h as f32 * ch as f32 / UNIT as f32,
825                    radius: 0.0,
826                };
827                let mut target = Target {
828                    rgb: &mut rgb,
829                    width,
830                    height: ch,
831                    top: y as i32 * ch as i32,
832                };
833                target.panel(
834                    shape,
835                    (Some(caret_color(grid)), None),
836                    false,
837                    false,
838                    ch as f32,
839                );
840            }
841        }
842        Image {
843            width,
844            height: ch,
845            rgb,
846        }
847    }
848}
849
850#[cfg(test)]
851mod tests {
852    use super::*;
853    use crate::grid::{Grid, Style};
854
855    fn rasterizer() -> Option<SoftwareRasterizer> {
856        SoftwareRasterizer::new(10, 20)
857    }
858
859    fn style() -> Style {
860        Style {
861            fg: Rgb(250, 250, 250),
862            bg: Rgb(10, 20, 30),
863            ..Style::default()
864        }
865    }
866
867    fn lit(image: &Image, cell: usize, width: usize) -> usize {
868        let mut count = 0;
869        for y in 0..image.height {
870            for x in cell * width..(cell + 1) * width {
871                let i = (y * image.width + x) * 3;
872                count += usize::from(image.rgb[i] > 128);
873            }
874        }
875        count
876    }
877
878    #[test]
879    fn row_image_is_exactly_the_grid_size() {
880        let Some(mut r) = rasterizer() else { return };
881        let grid = Grid::new(8, 1, style());
882        let image = r.row(&grid, 0);
883        assert_eq!((image.width, image.height), (80, 20));
884        assert_eq!(image.rgb.len(), 80 * 20 * 3);
885    }
886
887    #[test]
888    fn han_characters_are_drawn_in_the_cells() {
889        let Some(mut r) = rasterizer() else { return };
890        let fonts = system_fonts();
891        let has_han = fonts.faces().any(|face| {
892            let name = &face.families[0].0;
893            CJK_FONTS.iter().any(|font| font == name)
894        });
895        if !has_han {
896            return;
897        }
898        let mut grid = Grid::new(4, 1, style());
899        grid.put_str(0, 0, "中", style(), 4);
900        let image = r.row(&grid, 0);
901        assert!(lit(&image, 0, 10) > 10);
902    }
903
904    #[test]
905    fn a_wide_glyph_keeps_its_right_half() {
906        let Some(mut r) = rasterizer() else { return };
907        let mut grid = Grid::new(4, 1, style());
908        grid.put_str(1, 0, "MM", style(), 4);
909        let image = r.row(&grid, 0);
910        assert!(lit(&image, 1, 10) > 10);
911        assert!(
912            lit(&image, 2, 10) > 10,
913            "the next cell's colour didn't cover it"
914        );
915    }
916
917    #[test]
918    fn glyphs_land_in_their_own_cells() {
919        let Some(mut r) = rasterizer() else { return };
920        let mut grid = Grid::new(4, 1, style());
921        grid.put_str(2, 0, "M", style(), 4);
922        let image = r.row(&grid, 0);
923        assert_eq!(lit(&image, 0, 10), 0);
924        assert!(lit(&image, 2, 10) > 10, "M drew nothing");
925        assert_eq!(lit(&image, 3, 10), 0, "M spilled into the next cell");
926    }
927
928    #[test]
929    fn the_caret_is_a_thin_line() {
930        let Some(mut r) = rasterizer() else { return };
931        let mut grid = Grid::new(3, 1, style());
932        grid.cursor = Some((1, 0));
933        let image = r.row(&grid, 0);
934        let at = |x: usize| image.rgb[(10 * image.width + x) * 3];
935        assert_eq!(at(10), 250);
936        assert_eq!(at(15), 10);
937        grid.caret = Some(Bounds::cells(1.5, 0.0, 0.0, 1.0));
938        let image = r.row(&grid, 0);
939        let at = |x: usize| image.rgb[(10 * image.width + x) * 3];
940        assert_eq!(at(10), 10, "the exact caret replaces the cell one");
941        assert_eq!(at(15), 250);
942    }
943
944    #[test]
945    fn labels_draw_without_their_cell_glyphs() {
946        let Some(mut r) = rasterizer() else { return };
947        let mut grid = Grid::new(20, 1, style());
948        grid.label(1, 0, "Illi", style(), 20);
949        assert!(grid.cell(1, 0).style.painted);
950        let with_paint = r.row(&grid, 0);
951        // Inter is proportional: this text is far narrower than four cells.
952        let lit_right = (0..20)
953            .flat_map(|y| (40..200).map(move |x| (x, y)))
954            .any(|(x, y)| with_paint.rgb[(y * with_paint.width + x) * 3] > 128);
955        assert!(!lit_right, "drew past the narrow label");
956    }
957
958    #[test]
959    fn panels_have_rounded_corners() {
960        let Some(mut r) = rasterizer() else { return };
961        let mut grid = Grid::new(10, 1, style());
962        grid.panel(
963            crate::paint::Bounds::cells(1.0, 0.0, 8.0, 1.0),
964            40,
965            Some(Rgb(255, 0, 0)),
966            None,
967        );
968        let image = r.row(&grid, 0);
969        let red = |x: usize, y: usize| image.rgb[(y * image.width + x) * 3];
970        assert_eq!(red(50, 10), 255, "the middle is filled");
971        assert_eq!(red(10, 0), 10, "the corner is cut");
972    }
973
974    #[test]
975    fn a_wash_lets_what_is_under_it_show() {
976        let Some(mut r) = rasterizer() else { return };
977        let mut grid = Grid::new(20, 2, style());
978        let bounds = crate::paint::Bounds::cells(1.0, 0.0, 18.0, 2.0);
979        grid.wash(bounds, 10, (Rgb(255, 0, 0), 64), Some(Rgb(0, 0, 255)));
980        let image = r.row(&grid, 0);
981        let at = |x: usize, y: usize| {
982            let i = (y * image.width + x) * 3;
983            (image.rgb[i], image.rgb[i + 1], image.rgb[i + 2])
984        };
985        let middle = at(image.width / 2, image.height - 1);
986        assert!(middle.0 > 0 && middle.0 < 200, "a little red: {middle:?}");
987        let edge = at(image.width / 2, 0);
988        assert!(edge.2 > 200, "the border: {edge:?}");
989    }
990
991    #[test]
992    fn a_dashed_border_has_gaps() {
993        let Some(mut r) = rasterizer() else { return };
994        let mut grid = Grid::new(20, 1, style());
995        grid.dashed_panel(
996            crate::paint::Bounds::cells(1.0, 0.0, 18.0, 1.0),
997            10,
998            None,
999            Rgb(255, 0, 0),
1000        );
1001        let image = r.row(&grid, 0);
1002        // Along the top edge, past the corner: some pixels inked, some left.
1003        let y = 0;
1004        let reds: Vec<u8> = (30..170)
1005            .map(|x| image.rgb[(y * image.width + x) * 3])
1006            .collect();
1007        assert!(reds.iter().any(|r| *r > 200), "dashes are drawn");
1008        assert!(reds.iter().any(|r| *r < 60), "with gaps between them");
1009    }
1010
1011    #[test]
1012    fn fonts_ship_in_the_binary() {
1013        let mut r = SoftwareRasterizer::new(10, 20).unwrap();
1014        assert!(
1015            r.fonts
1016                .db()
1017                .faces()
1018                .any(|f| f.families.iter().any(|(n, _)| n.contains("Inter")))
1019        );
1020        assert!(
1021            r.text_mask("x", Font::default())
1022                .alpha
1023                .iter()
1024                .any(|a| *a > 0)
1025        );
1026    }
1027
1028    #[test]
1029    fn unknown_cell_size_refuses_pixels() {
1030        assert!(SoftwareRasterizer::new(0, 20).is_none());
1031    }
1032}