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        // A shadow falls down and to the sides, never up onto what opened the panel.
517        let reach = if shadow { row * 0.35 } else { 1.0 };
518        let (x0, x1) = (
519            (s.x - reach).floor() as i32,
520            (s.x + s.w + reach).ceil() as i32,
521        );
522        let above = if shadow { 1.0 } else { reach };
523        let y0 = ((s.y - above).floor() as i32).max(self.top);
524        let y1 = ((s.y + s.h + reach).ceil() as i32).min(self.top + self.height as i32);
525        let stroke = (row / 30.0).max(1.0);
526        for y in y0..y1 {
527            for x in x0..x1 {
528                let d = rounded_distance(&s, x as f32 + 0.5, y as f32 + 0.5);
529                if shadow && d > 0.0 && y as f32 + 0.5 > s.y + s.radius {
530                    let fade = (1.0 - d / reach).clamp(0.0, 1.0);
531                    // A shadow heavy enough for dark surfaces is a grey halo on light ones.
532                    let light = fill.is_some_and(|f| f.0 > 180);
533                    let depth = if light { LIGHT_SHADOW } else { DARK_SHADOW };
534                    self.blend(x, y, Rgb(0, 0, 0), (fade * fade * depth) as u8);
535                }
536                let inside = ((0.5 - d) * 255.0).clamp(0.0, 255.0) as u8;
537                if let Some(color) = fill {
538                    self.blend(x, y, color, inside);
539                }
540                if let Some(color) = border
541                    && (!dashed || on_dash(x as f32 + 0.5, y as f32 + 0.5))
542                {
543                    let edge = ((0.5 - (d + stroke / 2.0).abs() + stroke / 2.0) * 255.0)
544                        .clamp(0.0, 255.0) as u8;
545                    self.blend(x, y, color, edge);
546                }
547            }
548        }
549    }
550
551    /// A see-through fill with round corners, and a border twice a panel's weight.
552    fn wash(&mut self, s: Shape, (color, alpha): (Rgb, u8), border: Option<Rgb>, row: f32) {
553        let (x0, x1) = (s.x.floor() as i32 - 1, (s.x + s.w).ceil() as i32 + 1);
554        let y0 = (s.y.floor() as i32 - 1).max(self.top);
555        let y1 = ((s.y + s.h).ceil() as i32 + 1).min(self.top + self.height as i32);
556        let stroke = (row / 15.0).max(2.0);
557        for y in y0..y1 {
558            for x in x0..x1 {
559                let d = rounded_distance(&s, x as f32 + 0.5, y as f32 + 0.5);
560                let inside = (0.5 - d).clamp(0.0, 1.0);
561                self.blend(x, y, color, (inside * alpha as f32) as u8);
562                if let Some(edge_color) = border {
563                    // The border runs just inside the edge.
564                    let along = (0.5 - (d + stroke / 2.0).abs() + stroke / 2.0).clamp(0.0, 1.0);
565                    self.blend(x, y, edge_color, (along * 255.0) as u8);
566                }
567            }
568        }
569    }
570
571    fn blit(&mut self, mask: &TextMask, left: i32, top: i32, limit: usize, color: Rgb) {
572        let from = (self.top - top).max(0) as usize;
573        let to = ((self.top + self.height as i32 - top).max(0) as usize).min(mask.height);
574        for y in from..to {
575            for x in 0..mask.width.min(limit) {
576                let alpha = mask.alpha[y * mask.width + x];
577                self.blend(left + x as i32, top + y as i32, color, alpha);
578            }
579        }
580    }
581
582    /// Scales a bitmap into `s`, sampling between its pixels so nothing shimmers.
583    fn image(&mut self, s: &Shape, clip: ((i32, i32), (i32, i32)), bitmap: &Bitmap, color: Rgb) {
584        let (width, height) = (bitmap.width as usize, bitmap.height as usize);
585        if width == 0 || height == 0 || s.w <= 0.0 || s.h <= 0.0 {
586            return;
587        }
588        let channels = match bitmap.kind {
589            Pixels::Coverage => 1,
590            Pixels::Rgba => 4,
591        };
592        let at = |x: usize, y: usize, c: usize| -> f32 {
593            let index = (y.min(height - 1) * width + x.min(width - 1)) * channels + c;
594            bitmap.pixels.get(index).copied().unwrap_or(0) as f32
595        };
596        let sample = |u: f32, v: f32, c: usize| -> f32 {
597            let (fx, fy) = (u.max(0.0), v.max(0.0));
598            let (x, y) = (fx as usize, fy as usize);
599            let (dx, dy) = (fx - x as f32, fy - y as f32);
600            let top = at(x, y, c) * (1.0 - dx) + at(x + 1, y, c) * dx;
601            let bottom = at(x, y + 1, c) * (1.0 - dx) + at(x + 1, y + 1, c) * dx;
602            top * (1.0 - dy) + bottom * dy
603        };
604        let ((left, right), (top, bottom)) = clip;
605        let y0 = (s.y.floor() as i32).max(self.top).max(top);
606        let y1 = ((s.y + s.h).ceil() as i32)
607            .min(self.top + self.height as i32)
608            .min(bottom);
609        let x0 = (s.x.floor() as i32).max(0).max(left);
610        let x1 = ((s.x + s.w).ceil() as i32)
611            .min(self.width as i32)
612            .min(right);
613        let (ax, ay) = (width as f32 / s.w, height as f32 / s.h);
614        // A frame made for exactly this size is a copy, which keeps a live page cheap.
615        if bitmap.kind == Pixels::Rgba && (ax - 1.0).abs() < 0.002 && (ay - 1.0).abs() < 0.002 {
616            let (left, top) = (s.x.round() as i32, s.y.round() as i32);
617            for y in y0..y1 {
618                for x in x0..x1 {
619                    let (u, v) = (x - left, y - top);
620                    if u < 0 || v < 0 || u as usize >= width || v as usize >= height {
621                        continue;
622                    }
623                    let at = (v as usize * width + u as usize) * 4;
624                    if let Some(p) = bitmap.pixels.get(at..at + 4) {
625                        self.blend(x, y, Rgb(p[0], p[1], p[2]), p[3]);
626                    }
627                }
628            }
629            return;
630        }
631        for y in y0..y1 {
632            for x in x0..x1 {
633                let u = (x as f32 + 0.5 - s.x) * ax - 0.5;
634                let v = (y as f32 + 0.5 - s.y) * ay - 0.5;
635                match bitmap.kind {
636                    Pixels::Coverage => self.blend(x, y, color, sample(u, v, 0) as u8),
637                    Pixels::Rgba => {
638                        let ink = Rgb(
639                            sample(u, v, 0) as u8,
640                            sample(u, v, 1) as u8,
641                            sample(u, v, 2) as u8,
642                        );
643                        self.blend(x, y, ink, sample(u, v, 3) as u8);
644                    }
645                }
646            }
647        }
648    }
649
650    fn icon(&mut self, icon: Icon, left: f32, top: f32, side: f32, color: Rgb) {
651        // Five by five keeps thin curved strokes smooth, and tiles only draw this once.
652        const SAMPLES: usize = 5;
653        let y0 = (top.floor() as i32).max(self.top);
654        let y1 = ((top + side).ceil() as i32).min(self.top + self.height as i32);
655        for y in y0..y1 {
656            for x in left.floor() as i32..(left + side).ceil() as i32 {
657                let mut hits = 0;
658                for sy in 0..SAMPLES {
659                    for sx in 0..SAMPLES {
660                        let u = (x as f32 + (sx as f32 + 0.5) / SAMPLES as f32 - left) / side;
661                        let v = (y as f32 + (sy as f32 + 0.5) / SAMPLES as f32 - top) / side;
662                        if (0.0..1.0).contains(&u) && (0.0..1.0).contains(&v) && inked(icon, u, v) {
663                            hits += 1;
664                        }
665                    }
666                }
667                self.blend(x, y, color, (hits * 255 / (SAMPLES * SAMPLES)) as u8);
668            }
669        }
670    }
671}
672
673/// Picks the largest font whose advance fits the cell and whose height fits the row.
674fn fit_font(fonts: &mut FontSystem, cell_width: usize, cell_height: usize) -> Option<Metrics> {
675    const PROBE: f32 = 100.0;
676    let mut buffer = Buffer::new(fonts, Metrics::new(PROBE, PROBE * 1.2));
677    buffer.set_size(Some(PROBE * 4.0), Some(PROBE * 2.0));
678    let attrs = Attrs::new().family(Family::Monospace);
679    buffer.set_rich_text(
680        std::iter::once(("M", attrs.clone())),
681        &attrs,
682        Shaping::Advanced,
683        None,
684    );
685    buffer.shape_until_scroll(fonts, false);
686    let advance = buffer.layout_runs().next()?.line_w;
687    if advance <= 0.0 {
688        return None;
689    }
690    let by_width = cell_width as f32 * PROBE / advance;
691    let by_height = cell_height as f32 * 0.8;
692    Some(Metrics::new(by_width.min(by_height), cell_height as f32))
693}
694
695/// Inks this cell's share of an icon, supersampled so curves stay smooth.
696fn draw_icon(
697    rgb: &mut [u8],
698    stride: usize,
699    left: usize,
700    cell: (usize, usize),
701    piece: Piece,
702    fg: Rgb,
703) {
704    const SAMPLES: usize = 4;
705    let (cw, ch) = cell;
706    let (full_w, full_h) = (cw * piece.width as usize, ch * piece.height as usize);
707    let side = full_w.min(full_h) as f32 * 0.94;
708    let (off_x, off_y) = ((full_w as f32 - side) / 2.0, (full_h as f32 - side) / 2.0);
709    for y in 0..ch {
710        for x in 0..cw {
711            let mut hits = 0;
712            for sy in 0..SAMPLES {
713                for sx in 0..SAMPLES {
714                    let px = (piece.column as usize * cw + x) as f32
715                        + (sx as f32 + 0.5) / SAMPLES as f32;
716                    let py =
717                        (piece.row as usize * ch + y) as f32 + (sy as f32 + 0.5) / SAMPLES as f32;
718                    let (u, v) = ((px - off_x) / side, (py - off_y) / side);
719                    if (0.0..1.0).contains(&u) && (0.0..1.0).contains(&v) && inked(piece.icon, u, v)
720                    {
721                        hits += 1;
722                    }
723                }
724            }
725            if hits > 0 {
726                let alpha = (hits * 255 / (SAMPLES * SAMPLES)) as u8;
727                let at = (y * stride + left + x) * 3;
728                rgb[at] = blend(fg.0, rgb[at], alpha);
729                rgb[at + 1] = blend(fg.1, rgb[at + 1], alpha);
730                rgb[at + 2] = blend(fg.2, rgb[at + 2], alpha);
731            }
732        }
733    }
734}
735
736fn blend(fg: u8, bg: u8, alpha: u8) -> u8 {
737    let a = alpha as u32;
738    ((fg as u32 * a + bg as u32 * (255 - a)) / 255) as u8
739}
740
741fn fill(rgb: &mut [u8], stride: usize, x: usize, y: usize, w: usize, h: usize, color: Rgb) {
742    for row in y..y + h {
743        for px in x..x + w {
744            let i = (row * stride + px) * 3;
745            if i + 2 < rgb.len() {
746                rgb[i..i + 3].copy_from_slice(&[color.0, color.1, color.2]);
747            }
748        }
749    }
750}
751
752impl Rasterizer for SoftwareRasterizer {
753    fn row(&mut self, grid: &Grid, y: u16) -> Image {
754        let cells = grid.row(y);
755        let (cw, ch) = self.cell;
756        let width = cw * cells.len();
757        let mut rgb = vec![0; width * ch * 3];
758        // Backgrounds first: a wide glyph runs into the next cell, whose colour would cut it.
759        for (i, cell) in cells.iter().enumerate() {
760            fill(&mut rgb, width, i * cw, 0, cw, ch, cell.style.bg);
761        }
762        for (i, cell) in cells.iter().enumerate() {
763            let fg = cell.style.fg;
764            if cell.symbol.is_empty() || cell.symbol == " " || cell.style.painted {
765                continue;
766            }
767            // Drawn rather than taken from a font, so stacked rows join with no gap.
768            if cell.symbol == "▌" {
769                fill(&mut rgb, width, i * cw, 0, cw.div_ceil(5), ch, fg);
770                continue;
771            }
772            if let Some(piece) = Piece::decode(&cell.symbol) {
773                draw_icon(&mut rgb, width, i * cw, (cw, ch), piece, fg);
774                continue;
775            }
776            let key = GlyphKey {
777                symbol: cell.symbol.clone(),
778                bold: cell.style.bold,
779                italic: cell.style.italic,
780            };
781            let mask = self.mask(&key);
782            if let Some(painted) = self.painted.get(&key) {
783                for &(x, y, color, alpha) in painted.iter() {
784                    let at = (y as usize * width + i * cw + x as usize) * 3;
785                    if at + 2 < rgb.len() && (i * cw + x as usize) < width {
786                        rgb[at] = blend(color.0, rgb[at], alpha);
787                        rgb[at + 1] = blend(color.1, rgb[at + 1], alpha);
788                        rgb[at + 2] = blend(color.2, rgb[at + 2], alpha);
789                    }
790                }
791                continue;
792            }
793            for &(x, y, alpha) in mask.iter() {
794                let at = (y as usize * width + i * cw + x as usize) * 3;
795                if at + 2 < rgb.len() && (i * cw + x as usize) < width {
796                    rgb[at] = blend(fg.0, rgb[at], alpha);
797                    rgb[at + 1] = blend(fg.1, rgb[at + 1], alpha);
798                    rgb[at + 2] = blend(fg.2, rgb[at + 2], alpha);
799                }
800            }
801        }
802        for (i, cell) in cells.iter().enumerate() {
803            // Painted text underlines itself, at its true width.
804            if cell.style.underline && !cell.style.painted {
805                fill(&mut rgb, width, i * cw, ch - 2, cw, 1, cell.style.fg);
806            }
807        }
808        let paint: Vec<Paint> = grid.paint_on_row(y).cloned().collect();
809        let mut target = Target {
810            rgb: &mut rgb,
811            width,
812            height: ch,
813            top: y as i32 * ch as i32,
814        };
815        for item in &paint {
816            self.draw_paint(&mut target, item);
817        }
818        // A thin caret, as in a real editor, not a terminal's block.
819        if let Some(bounds) = caret_bounds(grid) {
820            let row = (y as i32 * UNIT, (y as i32 + 1) * UNIT);
821            if bounds.y < row.1 && bounds.y + bounds.h > row.0 {
822                let shape = Shape {
823                    x: bounds.x as f32 * cw as f32 / UNIT as f32,
824                    y: bounds.y as f32 * ch as f32 / UNIT as f32,
825                    w: (cw as f32 / 9.0).max(2.0),
826                    h: bounds.h as f32 * ch as f32 / UNIT as f32,
827                    radius: 0.0,
828                };
829                let mut target = Target {
830                    rgb: &mut rgb,
831                    width,
832                    height: ch,
833                    top: y as i32 * ch as i32,
834                };
835                target.panel(
836                    shape,
837                    (Some(caret_color(grid)), None),
838                    false,
839                    false,
840                    ch as f32,
841                );
842            }
843        }
844        Image {
845            width,
846            height: ch,
847            rgb,
848        }
849    }
850}
851
852#[cfg(test)]
853mod tests {
854    use super::*;
855    use crate::grid::{Grid, Style};
856
857    fn rasterizer() -> Option<SoftwareRasterizer> {
858        SoftwareRasterizer::new(10, 20)
859    }
860
861    fn style() -> Style {
862        Style {
863            fg: Rgb(250, 250, 250),
864            bg: Rgb(10, 20, 30),
865            ..Style::default()
866        }
867    }
868
869    fn lit(image: &Image, cell: usize, width: usize) -> usize {
870        let mut count = 0;
871        for y in 0..image.height {
872            for x in cell * width..(cell + 1) * width {
873                let i = (y * image.width + x) * 3;
874                count += usize::from(image.rgb[i] > 128);
875            }
876        }
877        count
878    }
879
880    #[test]
881    fn row_image_is_exactly_the_grid_size() {
882        let Some(mut r) = rasterizer() else { return };
883        let grid = Grid::new(8, 1, style());
884        let image = r.row(&grid, 0);
885        assert_eq!((image.width, image.height), (80, 20));
886        assert_eq!(image.rgb.len(), 80 * 20 * 3);
887    }
888
889    #[test]
890    fn han_characters_are_drawn_in_the_cells() {
891        let Some(mut r) = rasterizer() else { return };
892        let fonts = system_fonts();
893        let has_han = fonts.faces().any(|face| {
894            let name = &face.families[0].0;
895            CJK_FONTS.iter().any(|font| font == name)
896        });
897        if !has_han {
898            return;
899        }
900        let mut grid = Grid::new(4, 1, style());
901        grid.put_str(0, 0, "中", style(), 4);
902        let image = r.row(&grid, 0);
903        assert!(lit(&image, 0, 10) > 10);
904    }
905
906    #[test]
907    fn a_wide_glyph_keeps_its_right_half() {
908        let Some(mut r) = rasterizer() else { return };
909        let mut grid = Grid::new(4, 1, style());
910        grid.put_str(1, 0, "MM", style(), 4);
911        let image = r.row(&grid, 0);
912        assert!(lit(&image, 1, 10) > 10);
913        assert!(
914            lit(&image, 2, 10) > 10,
915            "the next cell's colour didn't cover it"
916        );
917    }
918
919    #[test]
920    fn glyphs_land_in_their_own_cells() {
921        let Some(mut r) = rasterizer() else { return };
922        let mut grid = Grid::new(4, 1, style());
923        grid.put_str(2, 0, "M", style(), 4);
924        let image = r.row(&grid, 0);
925        assert_eq!(lit(&image, 0, 10), 0);
926        assert!(lit(&image, 2, 10) > 10, "M drew nothing");
927        assert_eq!(lit(&image, 3, 10), 0, "M spilled into the next cell");
928    }
929
930    #[test]
931    fn the_caret_is_a_thin_line() {
932        let Some(mut r) = rasterizer() else { return };
933        let mut grid = Grid::new(3, 1, style());
934        grid.cursor = Some((1, 0));
935        let image = r.row(&grid, 0);
936        let at = |x: usize| image.rgb[(10 * image.width + x) * 3];
937        assert_eq!(at(10), 250);
938        assert_eq!(at(15), 10);
939        grid.caret = Some(Bounds::cells(1.5, 0.0, 0.0, 1.0));
940        let image = r.row(&grid, 0);
941        let at = |x: usize| image.rgb[(10 * image.width + x) * 3];
942        assert_eq!(at(10), 10, "the exact caret replaces the cell one");
943        assert_eq!(at(15), 250);
944    }
945
946    #[test]
947    fn labels_draw_without_their_cell_glyphs() {
948        let Some(mut r) = rasterizer() else { return };
949        let mut grid = Grid::new(20, 1, style());
950        grid.label(1, 0, "Illi", style(), 20);
951        assert!(grid.cell(1, 0).style.painted);
952        let with_paint = r.row(&grid, 0);
953        // Inter is proportional: this text is far narrower than four cells.
954        let lit_right = (0..20)
955            .flat_map(|y| (40..200).map(move |x| (x, y)))
956            .any(|(x, y)| with_paint.rgb[(y * with_paint.width + x) * 3] > 128);
957        assert!(!lit_right, "drew past the narrow label");
958    }
959
960    #[test]
961    fn panels_have_rounded_corners() {
962        let Some(mut r) = rasterizer() else { return };
963        let mut grid = Grid::new(10, 1, style());
964        grid.panel(
965            crate::paint::Bounds::cells(1.0, 0.0, 8.0, 1.0),
966            40,
967            Some(Rgb(255, 0, 0)),
968            None,
969        );
970        let image = r.row(&grid, 0);
971        let red = |x: usize, y: usize| image.rgb[(y * image.width + x) * 3];
972        assert_eq!(red(50, 10), 255, "the middle is filled");
973        assert_eq!(red(10, 0), 10, "the corner is cut");
974    }
975
976    #[test]
977    fn a_wash_lets_what_is_under_it_show() {
978        let Some(mut r) = rasterizer() else { return };
979        let mut grid = Grid::new(20, 2, style());
980        let bounds = crate::paint::Bounds::cells(1.0, 0.0, 18.0, 2.0);
981        grid.wash(bounds, 10, (Rgb(255, 0, 0), 64), Some(Rgb(0, 0, 255)));
982        let image = r.row(&grid, 0);
983        let at = |x: usize, y: usize| {
984            let i = (y * image.width + x) * 3;
985            (image.rgb[i], image.rgb[i + 1], image.rgb[i + 2])
986        };
987        let middle = at(image.width / 2, image.height - 1);
988        assert!(middle.0 > 0 && middle.0 < 200, "a little red: {middle:?}");
989        let edge = at(image.width / 2, 0);
990        assert!(edge.2 > 200, "the border: {edge:?}");
991    }
992
993    #[test]
994    fn a_dashed_border_has_gaps() {
995        let Some(mut r) = rasterizer() else { return };
996        let mut grid = Grid::new(20, 1, style());
997        grid.dashed_panel(
998            crate::paint::Bounds::cells(1.0, 0.0, 18.0, 1.0),
999            10,
1000            None,
1001            Rgb(255, 0, 0),
1002        );
1003        let image = r.row(&grid, 0);
1004        // Along the top edge, past the corner: some pixels inked, some left.
1005        let y = 0;
1006        let reds: Vec<u8> = (30..170)
1007            .map(|x| image.rgb[(y * image.width + x) * 3])
1008            .collect();
1009        assert!(reds.iter().any(|r| *r > 200), "dashes are drawn");
1010        assert!(reds.iter().any(|r| *r < 60), "with gaps between them");
1011    }
1012
1013    #[test]
1014    fn fonts_ship_in_the_binary() {
1015        let mut r = SoftwareRasterizer::new(10, 20).unwrap();
1016        assert!(
1017            r.fonts
1018                .db()
1019                .faces()
1020                .any(|f| f.families.iter().any(|(n, _)| n.contains("Inter")))
1021        );
1022        assert!(
1023            r.text_mask("x", Font::default())
1024                .alpha
1025                .iter()
1026                .any(|a| *a > 0)
1027        );
1028    }
1029
1030    #[test]
1031    fn unknown_cell_size_refuses_pixels() {
1032        assert!(SoftwareRasterizer::new(0, 20).is_none());
1033    }
1034}