cellix-render 0.9.2

Cell grid and pixel rasterizing for Cellix
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
use std::collections::HashMap;
use std::rc::Rc;

use compact_str::CompactString;
use cosmic_text::{
    Attrs, Buffer, Color, Fallback, Family, FontSystem, Metrics, PlatformFallback, Shaping,
    Style as FontStyle, SwashCache, Weight, fontdb,
};
use unicode_script::Script;
use unicode_width::UnicodeWidthStr;

use crate::grid::{Grid, Rgb};
use crate::icon::{Icon, Piece, inked};
use crate::measure::{Font, attrs, emoji_letter, runs};
use crate::paint::{
    BOTTOM_LEFT, BOTTOM_RIGHT, Bitmap, Bounds, Paint, Pixels, TOP_LEFT, TOP_RIGHT, UNIT,
};

/// A tightly packed RGB image, matching the Kitty protocol's `f=24`.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Image {
    pub width: usize,
    pub height: usize,
    pub rgb: Vec<u8>,
}

/// Turns one row of a grid into an image.
pub trait Rasterizer {
    fn row(&mut self, grid: &Grid, y: u16) -> Image;
}

#[derive(Clone, Hash, PartialEq, Eq)]
struct GlyphKey {
    symbol: CompactString,
    bold: bool,
    italic: bool,
}

/// Coverage of one glyph: pixel offsets from the cell's corner, with alpha.
type Mask = Rc<Vec<(u16, u16, u8)>>;
/// A colour glyph: pixel offsets, colours and alpha.
type Painted = Rc<Vec<(u16, u16, Rgb, u8)>>;

#[derive(Clone, Hash, PartialEq, Eq)]
struct TextKey {
    text: String,
    font: Font,
}

/// A line of interface text, drawn once and blended wherever it's used.
struct TextMask {
    width: usize,
    height: usize,
    alpha: Vec<u8>,
    /// The colour of each pixel that has one of its own, as an emoji's do, where the line
    /// holds any. The rest take the text's.
    own: Option<Vec<Option<Rgb>>>,
}

/// Fonts that hold Chinese and Japanese. The usual choices can be on-demand downloads a
/// machine doesn't have, and a missing one leaves the text blank.
const CJK_FONTS: [&str; 9] = [
    "PingFang SC",
    "Hiragino Sans",
    "Hiragino Sans GB",
    "Songti SC",
    "Heiti SC",
    "Arial Unicode MS",
    "Noto Sans CJK SC",
    "Noto Sans CJK JP",
    "WenQuanYi Micro Hei",
];

/// The platform's fallback, with a longer list for the scripts it runs out of.
struct WiderFallback(PlatformFallback);

impl Fallback for WiderFallback {
    fn common_fallback(&self) -> &[&'static str] {
        self.0.common_fallback()
    }

    fn forbidden_fallback(&self) -> &[&'static str] {
        self.0.forbidden_fallback()
    }

    fn script_fallback(&self, script: Script, locale: &str) -> &[&'static str] {
        match script {
            Script::Han | Script::Hiragana | Script::Katakana => &CJK_FONTS,
            other => self.0.script_fallback(other, locale),
        }
    }
}

fn system_fonts() -> fontdb::Database {
    let mut db = fontdb::Database::new();
    db.load_system_fonts();
    db
}

/// The fonts text is drawn with: the ones in the binary, and behind them whatever the
/// machine has, for the scripts those don't hold and for emoji in the machine's own style.
fn drawing_fonts() -> FontSystem {
    let mut fonts = FontSystem::new_with_locale_and_db_and_fallback(
        "en-US".to_string(),
        system_fonts(),
        WiderFallback(PlatformFallback),
    );
    let db = fonts.db_mut();
    db.load_font_data(INTER.to_vec());
    db.load_font_data(INTER_ITALIC.to_vec());
    db.load_font_data(MONO.to_vec());
    db.load_font_data(MONO_ITALIC.to_vec());
    db.load_font_data(EMOJI.to_vec());
    db.set_monospace_family("JetBrains Mono");
    db.set_sans_serif_family("Inter Variable");
    if EMOJI_FONT.get().is_none() {
        let found = find_emoji_font(&mut fonts);
        EMOJI_FONT.get_or_init(|| found);
    }
    fonts
}

/// The font emoji are drawn in, as its family and where it's read from. Found once: finding
/// it means looking at every font there is, which the rasterizer does as it starts.
static EMOJI_FONT: std::sync::OnceLock<Option<(String, fontdb::Source)>> =
    std::sync::OnceLock::new();

/// The machine's own emoji fonts, in the order they're reached for, so emoji look here as
/// they do in its other programs.
const SYSTEM_EMOJI: [&str; 3] = ["Apple Color Emoji", "Noto Color Emoji", "Segoe UI Emoji"];
/// What the emoji font in the binary calls itself: Twemoji, as Mozilla builds it.
const BUILT_IN_EMOJI: &str = "Twemoji Mozilla";

/// A line of emoji set in one family, when every one of them came from it and not from a
/// font the search fell back to.
fn set_in(fonts: &mut FontSystem, family: &str, emoji: &str) -> Option<Buffer> {
    let mut buffer = Buffer::new(fonts, Metrics::new(32.0, 40.0));
    buffer.set_size(None, Some(40.0));
    let attrs = Attrs::new().family(Family::Name(family));
    let rich = std::iter::once((emoji, attrs.clone()));
    buffer.set_rich_text(rich, &attrs, Shaping::Advanced, None);
    buffer.shape_until_scroll(fonts, false);
    let from_it = |glyph: &cosmic_text::LayoutGlyph| {
        let face = fonts.db().face(glyph.font_id);
        glyph.glyph_id != 0
            && face.is_some_and(|face| face.families.iter().any(|(name, _)| name == family))
    };
    let glyphs: Vec<&cosmic_text::LayoutGlyph> = buffer
        .layout_runs()
        .flat_map(|run| run.glyphs.iter())
        .collect();
    let whole = !glyphs.is_empty() && glyphs.into_iter().all(from_it);
    whole.then_some(buffer)
}

/// Whether the emoji font in the binary holds an emoji, whole: one it only has the parts of
/// would be drawn as those, side by side. This is what a machine with no emoji font of its
/// own can show, so it's what's worth offering.
pub fn built_in_emoji_holds(emoji: &str) -> bool {
    thread_local! {
        static FONTS: std::cell::RefCell<FontSystem> = std::cell::RefCell::new({
            let mut db = fontdb::Database::new();
            db.load_font_data(EMOJI.to_vec());
            FontSystem::new_with_locale_and_db("en-US".to_string(), db)
        });
    }
    FONTS.with(|fonts| {
        let set = set_in(&mut fonts.borrow_mut(), BUILT_IN_EMOJI, emoji);
        set.is_some_and(|buffer| {
            let glyphs = buffer.layout_runs().flat_map(|run| run.glyphs.iter());
            glyphs.filter(|glyph| glyph.w > 0.0).count() == 1
        })
    })
}

/// Whether a family's emoji come out in colour here. A font in a format the rasterizer
/// can't read, as a newer Noto Color Emoji is, draws nothing or a plain shape.
fn draws_colour(fonts: &mut FontSystem, family: &str) -> bool {
    let Some(mut buffer) = set_in(fonts, family, "👍") else {
        return false;
    };
    let mut coloured = false;
    let mut swash = SwashCache::new();
    let white = Color::rgb(255, 255, 255);
    buffer.draw(fonts, &mut swash, white, |_, _, _, _, color| {
        coloured |= color.a() > 0 && (color.r(), color.g(), color.b()) != (255, 255, 255);
    });
    coloured
}

/// The machine's own emoji font where it has one this can draw, and the one in the binary
/// where it doesn't: a server reached over SSH rarely has any.
fn find_emoji_font(fonts: &mut FontSystem) -> Option<(String, fontdb::Source)> {
    // `CELLIX_EMOJI=built-in` keeps to the one in the binary, for the same emoji on every
    // machine.
    let built_in_only = std::env::var("CELLIX_EMOJI").is_ok_and(|choice| choice == "built-in");
    let own = SYSTEM_EMOJI.iter().copied().filter(|_| !built_in_only);
    for family in own.chain([BUILT_IN_EMOJI]) {
        let source = fonts
            .db()
            .faces()
            .find(|face| face.families.iter().any(|(name, _)| name == family))
            .map(|face| face.source.clone());
        if let Some(source) = source
            && draws_colour(fonts, family)
        {
            return Some((family.to_string(), source));
        }
    }
    None
}

/// The font emoji are drawn in. Whatever measures text sets its emoji in the same one, or a
/// caret after an emoji stands in the wrong place.
pub(crate) fn emoji_font() -> Option<&'static (String, fontdb::Source)> {
    if EMOJI_FONT.get().is_none() {
        drop(drawing_fonts());
    }
    EMOJI_FONT.get().and_then(Option::as_ref)
}

/// How dark a floating panel's shadow is at its edge, out of 255.
const DARK_SHADOW: f32 = 110.0;
const LIGHT_SHADOW: f32 = 38.0;
/// Interface text is drawn at this size relative to the row height: 13 pt in a terminal set
/// to 14 pt, whose row is 18.5 pt, which is the size VS Code sets its own words at.
pub const INTERFACE_SIZE: f32 = 0.70;
/// Cached text lines before the cache is dropped, so a long session can't grow it forever.
const MAX_TEXT_MASKS: usize = 4096;

pub(crate) const INTER: &[u8] = include_bytes!("../fonts/InterVariable.ttf");
pub(crate) const INTER_ITALIC: &[u8] = include_bytes!("../fonts/InterVariable-Italic.ttf");
pub(crate) const MONO: &[u8] = include_bytes!("../fonts/JetBrainsMonoVariable.ttf");
pub(crate) const MONO_ITALIC: &[u8] = include_bytes!("../fonts/JetBrainsMonoVariable-Italic.ttf");
/// Twemoji, for emoji on a machine with no emoji font of its own.
pub(crate) const EMOJI: &[u8] = include_bytes!("../fonts/TwemojiMozilla.ttf");

/// The pixel size painted text is drawn at, for a row height and font.
pub(crate) fn text_pixels(row_height: usize, font: Font) -> f32 {
    row_height as f32 * INTERFACE_SIZE * font.size as f32 / 100.0
}

/// CPU rendering. Glyphs are rasterized once and blended into their cells, so text stays
/// locked to the grid and a row costs little more than a copy.
pub struct SoftwareRasterizer {
    fonts: FontSystem,
    /// The font emoji are drawn in, where the machine has one.
    emoji: Option<String>,
    swash: SwashCache,
    metrics: Metrics,
    cell: (usize, usize),
    masks: HashMap<GlyphKey, Mask>,
    /// Glyphs with colours of their own, such as emoji, as pixels with those colours.
    painted: HashMap<GlyphKey, Painted>,
    text: HashMap<TextKey, Rc<TextMask>>,
}

impl SoftwareRasterizer {
    /// The fonts ship in the binary, because pixels are drawn on the remote host over SSH
    /// and servers rarely have any. Returns None only when the cell size is unknown.
    pub fn new(cell_width: usize, cell_height: usize) -> Option<Self> {
        if cell_width == 0 || cell_height == 0 {
            return None;
        }
        let mut fonts = drawing_fonts();
        let metrics = fit_font(&mut fonts, cell_width, cell_height)?;
        let emoji = emoji_font().map(|(family, _)| family.clone());
        Some(Self {
            fonts,
            emoji,
            swash: SwashCache::new(),
            metrics,
            cell: (cell_width, cell_height),
            masks: HashMap::new(),
            painted: HashMap::new(),
            text: HashMap::new(),
        })
    }

    fn mask(&mut self, key: &GlyphKey) -> Mask {
        if let Some(mask) = self.masks.get(key) {
            return mask.clone();
        }
        let (width, height) = (self.cell.0 * 2, self.cell.1);
        let mut buffer = Buffer::new(&mut self.fonts, self.metrics);
        buffer.set_size(Some(width as f32 * 2.0), Some(height as f32));
        // Asked for a monospaced Han glyph, the search stops at a font that only has blanks.
        // A wide glyph fills its two cells whatever font it's from.
        // And an emoji is drawn in the emoji font: a text font may hold a plain form of it.
        let emoji = self.emoji.clone().filter(|_| emoji_letter(&key.symbol));
        let family = if let Some(emoji) = &emoji {
            Family::Name(emoji)
        } else if UnicodeWidthStr::width(key.symbol.as_str()) > 1 {
            Family::SansSerif
        } else {
            Family::Monospace
        };
        let mut attrs = Attrs::new().family(family);
        if key.bold {
            attrs = attrs.weight(Weight::BOLD);
        }
        if key.italic {
            attrs = attrs.style(FontStyle::Italic);
        }
        let rich = std::iter::once((key.symbol.as_str(), attrs.clone()));
        buffer.set_rich_text(rich, &attrs, Shaping::Advanced, None);
        buffer.shape_until_scroll(&mut self.fonts, false);
        let mut pixels = Vec::new();
        let mut coloured = Vec::new();
        let white = Color::rgb(255, 255, 255);
        buffer.draw(
            &mut self.fonts,
            &mut self.swash,
            white,
            |x, y, w, h, color| {
                if color.a() == 0 {
                    return;
                }
                for py in y..y + h as i32 {
                    for px in x..x + w as i32 {
                        if px >= 0 && py >= 0 && (px as usize) < width && (py as usize) < height {
                            pixels.push((px as u16, py as u16, color.a()));
                            let rgb = Rgb(color.r(), color.g(), color.b());
                            coloured.push((px as u16, py as u16, rgb, color.a()));
                        }
                    }
                }
            },
        );
        // Text comes out white, ready to take any colour. Anything else is the glyph's own.
        if coloured
            .iter()
            .any(|(_, _, rgb, _)| *rgb != Rgb(255, 255, 255))
        {
            self.painted.insert(key.clone(), Rc::new(coloured));
        }
        let mask = Rc::new(pixels);
        self.masks.insert(key.clone(), mask.clone());
        mask
    }

    /// A line of painted text, tall enough for its size.
    fn text_mask(&mut self, text: &str, font: Font) -> Rc<TextMask> {
        let key = TextKey {
            text: text.to_string(),
            font,
        };
        if let Some(mask) = self.text.get(&key) {
            return mask.clone();
        }
        if self.text.len() >= MAX_TEXT_MASKS {
            self.text.clear();
        }
        let px = text_pixels(self.cell.1, font);
        let height = self.cell.1.max((px * 1.45).ceil() as usize);
        let mut buffer = Buffer::new(&mut self.fonts, Metrics::new(px, height as f32));
        buffer.set_size(None, Some(height as f32));
        let emoji = self.emoji.clone();
        let rich = runs(text, font, emoji.as_deref());
        buffer.set_rich_text(rich, &attrs(font), Shaping::Advanced, None);
        buffer.shape_until_scroll(&mut self.fonts, false);
        let width = buffer
            .layout_runs()
            .next()
            .map_or(0.0, |run| run.line_w)
            .ceil() as usize
            + 2;
        let mut alpha = vec![0; width * height];
        // Text comes out in the colour it's asked for, and an emoji in its own. Drawn in
        // white, anything that isn't white is an emoji's.
        let white = Rgb(255, 255, 255);
        let mut drawn = vec![white; width * height];
        let mut tinted = false;
        buffer.draw(
            &mut self.fonts,
            &mut self.swash,
            Color::rgb(255, 255, 255),
            |x, y, w, h, color| {
                let rgb = Rgb(color.r(), color.g(), color.b());
                tinted |= color.a() > 0 && rgb != white;
                for at in spots((width, height), (x, y), (w, h)) {
                    if color.a() >= alpha[at] {
                        drawn[at] = rgb;
                    }
                    alpha[at] = alpha[at].max(color.a());
                }
            },
        );
        // An emoji has white of its own too, which drawn in white can't be told from text.
        // Drawn again in black, what turned black is text and what stayed is the emoji's.
        let own = tinted.then(|| {
            let black = Rgb(0, 0, 0);
            let mut own = vec![None; width * height];
            buffer.draw(
                &mut self.fonts,
                &mut self.swash,
                Color::rgb(0, 0, 0),
                |x, y, w, h, color| {
                    let rgb = Rgb(color.r(), color.g(), color.b());
                    for at in spots((width, height), (x, y), (w, h)) {
                        if color.a() > 0 && (rgb != black || drawn[at] != white) {
                            own[at] = Some(drawn[at]);
                        }
                    }
                },
            );
            own
        });
        let mask = Rc::new(TextMask {
            width,
            height,
            alpha,
            own,
        });
        self.text.insert(key, mask.clone());
        mask
    }

    fn draw_paint(&mut self, target: &mut Target, paint: &Paint) {
        let (cw, ch) = (self.cell.0 as f32, self.cell.1 as f32);
        let scale = |v: i32, cell: f32| v as f32 * cell / UNIT as f32;
        match paint {
            Paint::Panel {
                bounds,
                radius,
                fill,
                border,
                shadow,
                dashed,
            } => {
                let mut shape = Shape {
                    x: scale(bounds.x, cw),
                    y: scale(bounds.y, ch),
                    w: scale(bounds.w, cw),
                    h: scale(bounds.h, ch),
                    radius: *radius as f32 * ch / 100.0,
                };
                // A panel with a line round it stands on whole pixels, so the line is one
                // pixel of its own colour on every side. Between pixels it was two rows at
                // half strength on one side and one at full on the other.
                if border.is_some() {
                    let right = (shape.x + shape.w).round();
                    let bottom = (shape.y + shape.h).round();
                    shape.x = shape.x.round();
                    shape.y = shape.y.round();
                    shape.w = right - shape.x;
                    shape.h = bottom - shape.y;
                }
                target.panel(shape, (*fill, *border), *shadow, *dashed, ch);
            }
            Paint::Wash {
                bounds,
                radius,
                color,
                alpha,
                border,
            } => {
                let shape = Shape {
                    x: scale(bounds.x, cw),
                    y: scale(bounds.y, ch),
                    w: scale(bounds.w, cw),
                    h: scale(bounds.h, ch),
                    radius: *radius as f32 * ch / 100.0,
                };
                target.wash(shape, (*color, *alpha), *border, ch);
            }
            Paint::Hairline { bounds, color } => {
                let thickness = (ch / 24.0).ceil().max(1.0);
                let shape = Shape {
                    x: scale(bounds.x, cw),
                    y: scale(bounds.y, ch),
                    w: scale(bounds.w, cw).max(thickness),
                    h: scale(bounds.h, ch).max(thickness),
                    radius: 0.0,
                };
                target.panel(shape, (Some(*color), None), false, false, ch);
            }
            Paint::Text {
                x,
                y,
                max_width,
                text,
                color,
                font,
                align_right,
                centred,
                underline,
            } => {
                let mask = self.text_mask(text, *font);
                let mut left = scale(*x, cw).round() as i32;
                if *align_right {
                    left -= mask.width as i32;
                } else if *centred {
                    left -= mask.width as i32 / 2;
                }
                // Tall text stays centred on its row.
                let lift = (mask.height as i32 - ch as i32) / 2;
                let top = scale(*y, ch).round() as i32 - lift;
                let limit = scale(*max_width, cw).max(0.0) as usize;
                target.blit(&mask, left, top, limit, *color);
                if *underline {
                    let thickness = (ch / 24.0).ceil().max(1.0);
                    let shape = Shape {
                        x: left as f32,
                        y: scale(*y, ch) + ch * 0.78,
                        w: mask.width.saturating_sub(2).min(limit) as f32,
                        h: thickness,
                        radius: 0.0,
                    };
                    target.panel(shape, (Some(*color), None), false, false, ch);
                }
            }
            Paint::Icon {
                bounds,
                icon,
                color,
            } => {
                let side = scale(bounds.h, ch);
                let left = scale(bounds.x, cw);
                let top = scale(bounds.y, ch);
                target.icon(*icon, left, top, side, *color);
            }
            Paint::Corners {
                bounds,
                radius,
                color,
                which,
            } => {
                let shape = Shape {
                    x: scale(bounds.x, cw),
                    y: scale(bounds.y, ch),
                    w: scale(bounds.w, cw),
                    h: scale(bounds.h, ch),
                    radius: *radius as f32 * ch / 100.0,
                };
                target.corners(&shape, *color, *which);
            }
            Paint::Image {
                bounds,
                clip,
                bitmap,
                color,
            } => {
                let shape = Shape {
                    x: scale(bounds.x, cw),
                    y: scale(bounds.y, ch),
                    w: scale(bounds.w, cw),
                    h: scale(bounds.h, ch),
                    radius: 0.0,
                };
                let across = (
                    scale(clip.x, cw) as i32,
                    scale(clip.x + clip.w, cw).ceil() as i32,
                );
                let down = (
                    scale(clip.y, ch) as i32,
                    scale(clip.y + clip.h, ch).ceil() as i32,
                );
                target.image(&shape, (across, down), bitmap, *color);
            }
            Paint::Strips { bounds, strips } => {
                let (left, top) = (scale(bounds.x, cw), scale(bounds.y, ch));
                let (width, height) = (scale(bounds.w, cw), scale(bounds.h, ch));
                let thickness = (ch / 24.0).ceil().max(1.0);
                for strip in strips {
                    let shape = Shape {
                        x: left + strip.x as f32 * width / 256.0,
                        y: top + strip.y as f32 * height / 256.0,
                        w: (strip.w as f32 * width / 256.0).max(1.0),
                        h: thickness,
                        radius: 0.0,
                    };
                    target.panel(shape, (Some(strip.color), None), false, false, ch);
                }
            }
        }
    }
}

/// The places in a `size` image that a box at `at`, `by` across and down, covers.
fn spots(
    (width, height): (usize, usize),
    (x, y): (i32, i32),
    (w, h): (u32, u32),
) -> impl Iterator<Item = usize> {
    let across = x.max(0) as usize..((x + w as i32).max(0) as usize).min(width);
    let down = y.max(0) as usize..((y + h as i32).max(0) as usize).min(height);
    down.flat_map(move |py| across.clone().map(move |px| py * width + px))
}

/// Where the caret goes: its exact place, or the cell the cursor is in.
fn caret_bounds(grid: &Grid) -> Option<Bounds> {
    grid.caret.or_else(|| {
        let (x, y) = grid.cursor?;
        Some(Bounds::cells(x as f32, y as f32 + 0.08, 0.0, 0.84))
    })
}

fn caret_color(grid: &Grid) -> Rgb {
    let Some((x, y)) = grid.cursor else {
        return Rgb(255, 255, 255);
    };
    grid.cell(x.min(grid.width().saturating_sub(1)), y).style.fg
}

struct Shape {
    x: f32,
    y: f32,
    w: f32,
    h: f32,
    radius: f32,
}

/// Distance from a point to a rounded box's edge, negative inside.
fn rounded_distance(shape: &Shape, x: f32, y: f32) -> f32 {
    let (cx, cy) = (shape.x + shape.w / 2.0, shape.y + shape.h / 2.0);
    let qx = (x - cx).abs() - shape.w / 2.0 + shape.radius;
    let qy = (y - cy).abs() - shape.h / 2.0 + shape.radius;
    let outside = (qx.max(0.0).powi(2) + qy.max(0.0).powi(2)).sqrt();
    outside + qx.max(qy).min(0.0) - shape.radius
}

/// The part of the screen one row's tile covers, in screen pixels.
struct Target<'a> {
    rgb: &'a mut [u8],
    width: usize,
    height: usize,
    top: i32,
}

impl Target<'_> {
    fn corners(&mut self, s: &Shape, color: Rgb, which: u8) {
        let r = s.radius;
        let spots = [
            (TOP_LEFT, s.x, s.y, s.x + r, s.y + r),
            (TOP_RIGHT, s.x + s.w - r, s.y, s.x + s.w - r, s.y + r),
            (
                BOTTOM_RIGHT,
                s.x + s.w - r,
                s.y + s.h - r,
                s.x + s.w - r,
                s.y + s.h - r,
            ),
            (BOTTOM_LEFT, s.x, s.y + s.h - r, s.x + r, s.y + s.h - r),
        ];
        for (flag, left, top, cx, cy) in spots {
            if which & flag == 0 {
                continue;
            }
            for y in top.floor() as i32..(top + r).ceil() as i32 {
                for x in left.floor() as i32..(left + r).ceil() as i32 {
                    let d = ((x as f32 + 0.5 - cx).powi(2) + (y as f32 + 0.5 - cy).powi(2)).sqrt();
                    let outside = (d - r + 0.5).clamp(0.0, 1.0);
                    self.blend(x, y, color, (outside * 255.0) as u8);
                }
            }
        }
    }

    fn blend(&mut self, x: i32, y: i32, color: Rgb, alpha: u8) {
        let row = y - self.top;
        if alpha == 0 || x < 0 || row < 0 || x as usize >= self.width || row as usize >= self.height
        {
            return;
        }
        let at = (row as usize * self.width + x as usize) * 3;
        self.rgb[at] = blend(color.0, self.rgb[at], alpha);
        self.rgb[at + 1] = blend(color.1, self.rgb[at + 1], alpha);
        self.rgb[at + 2] = blend(color.2, self.rgb[at + 2], alpha);
    }

    fn panel(
        &mut self,
        s: Shape,
        (fill, border): (Option<Rgb>, Option<Rgb>),
        shadow: bool,
        dashed: bool,
        row: f32,
    ) {
        // Dashes a quarter of a row long, with gaps as long, measured along the edge so every
        // row of a tall panel continues the same pattern.
        let dash = (row / 4.0).max(2.0);
        let on_dash = |x: f32, y: f32| {
            let along_top = x > s.x + s.radius && x < s.x + s.w - s.radius;
            let run = if along_top { x - s.x } else { y - s.y };
            (run / dash).floor() as i64 % 2 == 0
        };
        // A shadow falls down and to the sides, never up onto what opened the panel.
        let reach = if shadow { row * 0.35 } else { 1.0 };
        let (x0, x1) = (
            (s.x - reach).floor() as i32,
            (s.x + s.w + reach).ceil() as i32,
        );
        let above = if shadow { 1.0 } else { reach };
        let y0 = ((s.y - above).floor() as i32).max(self.top);
        let y1 = ((s.y + s.h + reach).ceil() as i32).min(self.top + self.height as i32);
        let stroke = (row / 30.0).max(1.0);
        for y in y0..y1 {
            for x in x0..x1 {
                let d = rounded_distance(&s, x as f32 + 0.5, y as f32 + 0.5);
                if shadow && d > 0.0 && y as f32 + 0.5 > s.y + s.radius {
                    let fade = (1.0 - d / reach).clamp(0.0, 1.0);
                    // A shadow heavy enough for dark surfaces is a grey halo on light ones.
                    let light = fill.is_some_and(|f| f.0 > 180);
                    let depth = if light { LIGHT_SHADOW } else { DARK_SHADOW };
                    self.blend(x, y, Rgb(0, 0, 0), (fade * fade * depth) as u8);
                }
                let inside = ((0.5 - d) * 255.0).clamp(0.0, 255.0) as u8;
                if let Some(color) = fill {
                    self.blend(x, y, color, inside);
                }
                if let Some(color) = border
                    && (!dashed || on_dash(x as f32 + 0.5, y as f32 + 0.5))
                {
                    let edge = ((0.5 - (d + stroke / 2.0).abs() + stroke / 2.0) * 255.0)
                        .clamp(0.0, 255.0) as u8;
                    self.blend(x, y, color, edge);
                }
            }
        }
    }

    /// A see-through fill with round corners, and a border twice a panel's weight.
    fn wash(&mut self, s: Shape, (color, alpha): (Rgb, u8), border: Option<Rgb>, row: f32) {
        let (x0, x1) = (s.x.floor() as i32 - 1, (s.x + s.w).ceil() as i32 + 1);
        let y0 = (s.y.floor() as i32 - 1).max(self.top);
        let y1 = ((s.y + s.h).ceil() as i32 + 1).min(self.top + self.height as i32);
        let stroke = (row / 15.0).max(2.0);
        for y in y0..y1 {
            for x in x0..x1 {
                let d = rounded_distance(&s, x as f32 + 0.5, y as f32 + 0.5);
                let inside = (0.5 - d).clamp(0.0, 1.0);
                self.blend(x, y, color, (inside * alpha as f32) as u8);
                if let Some(edge_color) = border {
                    // The border runs just inside the edge.
                    let along = (0.5 - (d + stroke / 2.0).abs() + stroke / 2.0).clamp(0.0, 1.0);
                    self.blend(x, y, edge_color, (along * 255.0) as u8);
                }
            }
        }
    }

    fn blit(&mut self, mask: &TextMask, left: i32, top: i32, limit: usize, color: Rgb) {
        let from = (self.top - top).max(0) as usize;
        let to = ((self.top + self.height as i32 - top).max(0) as usize).min(mask.height);
        for y in from..to {
            for x in 0..mask.width.min(limit) {
                let at = y * mask.width + x;
                let ink = mask.own.as_ref().and_then(|own| own[at]).unwrap_or(color);
                self.blend(left + x as i32, top + y as i32, ink, mask.alpha[at]);
            }
        }
    }

    /// Scales a bitmap into `s`, sampling between its pixels so nothing shimmers.
    fn image(&mut self, s: &Shape, clip: ((i32, i32), (i32, i32)), bitmap: &Bitmap, color: Rgb) {
        let (width, height) = (bitmap.width as usize, bitmap.height as usize);
        if width == 0 || height == 0 || s.w <= 0.0 || s.h <= 0.0 {
            return;
        }
        let channels = match bitmap.kind {
            Pixels::Coverage => 1,
            Pixels::Rgba => 4,
        };
        let at = |x: usize, y: usize, c: usize| -> f32 {
            let index = (y.min(height - 1) * width + x.min(width - 1)) * channels + c;
            bitmap.pixels.get(index).copied().unwrap_or(0) as f32
        };
        let sample = |u: f32, v: f32, c: usize| -> f32 {
            let (fx, fy) = (u.max(0.0), v.max(0.0));
            let (x, y) = (fx as usize, fy as usize);
            let (dx, dy) = (fx - x as f32, fy - y as f32);
            let top = at(x, y, c) * (1.0 - dx) + at(x + 1, y, c) * dx;
            let bottom = at(x, y + 1, c) * (1.0 - dx) + at(x + 1, y + 1, c) * dx;
            top * (1.0 - dy) + bottom * dy
        };
        let ((left, right), (top, bottom)) = clip;
        let y0 = (s.y.floor() as i32).max(self.top).max(top);
        let y1 = ((s.y + s.h).ceil() as i32)
            .min(self.top + self.height as i32)
            .min(bottom);
        let x0 = (s.x.floor() as i32).max(0).max(left);
        let x1 = ((s.x + s.w).ceil() as i32)
            .min(self.width as i32)
            .min(right);
        let (ax, ay) = (width as f32 / s.w, height as f32 / s.h);
        // A frame made for exactly this size is a copy, which keeps a live page cheap.
        if bitmap.kind == Pixels::Rgba && (ax - 1.0).abs() < 0.002 && (ay - 1.0).abs() < 0.002 {
            let (left, top) = (s.x.round() as i32, s.y.round() as i32);
            for y in y0..y1 {
                for x in x0..x1 {
                    let (u, v) = (x - left, y - top);
                    if u < 0 || v < 0 || u as usize >= width || v as usize >= height {
                        continue;
                    }
                    let at = (v as usize * width + u as usize) * 4;
                    if let Some(p) = bitmap.pixels.get(at..at + 4) {
                        self.blend(x, y, Rgb(p[0], p[1], p[2]), p[3]);
                    }
                }
            }
            return;
        }
        for y in y0..y1 {
            for x in x0..x1 {
                let u = (x as f32 + 0.5 - s.x) * ax - 0.5;
                let v = (y as f32 + 0.5 - s.y) * ay - 0.5;
                match bitmap.kind {
                    Pixels::Coverage => self.blend(x, y, color, sample(u, v, 0) as u8),
                    Pixels::Rgba => {
                        let ink = Rgb(
                            sample(u, v, 0) as u8,
                            sample(u, v, 1) as u8,
                            sample(u, v, 2) as u8,
                        );
                        self.blend(x, y, ink, sample(u, v, 3) as u8);
                    }
                }
            }
        }
    }

    fn icon(&mut self, icon: Icon, left: f32, top: f32, side: f32, color: Rgb) {
        // Five by five keeps thin curved strokes smooth, and tiles only draw this once.
        const SAMPLES: usize = 5;
        let y0 = (top.floor() as i32).max(self.top);
        let y1 = ((top + side).ceil() as i32).min(self.top + self.height as i32);
        for y in y0..y1 {
            for x in left.floor() as i32..(left + side).ceil() as i32 {
                let mut hits = 0;
                for sy in 0..SAMPLES {
                    for sx in 0..SAMPLES {
                        let u = (x as f32 + (sx as f32 + 0.5) / SAMPLES as f32 - left) / side;
                        let v = (y as f32 + (sy as f32 + 0.5) / SAMPLES as f32 - top) / side;
                        if (0.0..1.0).contains(&u) && (0.0..1.0).contains(&v) && inked(icon, u, v) {
                            hits += 1;
                        }
                    }
                }
                self.blend(x, y, color, (hits * 255 / (SAMPLES * SAMPLES)) as u8);
            }
        }
    }
}

/// Picks the largest font whose advance fits the cell and whose height fits the row.
fn fit_font(fonts: &mut FontSystem, cell_width: usize, cell_height: usize) -> Option<Metrics> {
    const PROBE: f32 = 100.0;
    let mut buffer = Buffer::new(fonts, Metrics::new(PROBE, PROBE * 1.2));
    buffer.set_size(Some(PROBE * 4.0), Some(PROBE * 2.0));
    let attrs = Attrs::new().family(Family::Monospace);
    buffer.set_rich_text(
        std::iter::once(("M", attrs.clone())),
        &attrs,
        Shaping::Advanced,
        None,
    );
    buffer.shape_until_scroll(fonts, false);
    let advance = buffer.layout_runs().next()?.line_w;
    if advance <= 0.0 {
        return None;
    }
    let by_width = cell_width as f32 * PROBE / advance;
    let by_height = cell_height as f32 * 0.8;
    Some(Metrics::new(by_width.min(by_height), cell_height as f32))
}

/// Inks this cell's share of an icon, supersampled so curves stay smooth.
fn draw_icon(
    rgb: &mut [u8],
    stride: usize,
    left: usize,
    cell: (usize, usize),
    piece: Piece,
    fg: Rgb,
) {
    const SAMPLES: usize = 4;
    let (cw, ch) = cell;
    let (full_w, full_h) = (cw * piece.width as usize, ch * piece.height as usize);
    let side = full_w.min(full_h) as f32 * 0.94;
    let (off_x, off_y) = ((full_w as f32 - side) / 2.0, (full_h as f32 - side) / 2.0);
    for y in 0..ch {
        for x in 0..cw {
            let mut hits = 0;
            for sy in 0..SAMPLES {
                for sx in 0..SAMPLES {
                    let px = (piece.column as usize * cw + x) as f32
                        + (sx as f32 + 0.5) / SAMPLES as f32;
                    let py =
                        (piece.row as usize * ch + y) as f32 + (sy as f32 + 0.5) / SAMPLES as f32;
                    let (u, v) = ((px - off_x) / side, (py - off_y) / side);
                    if (0.0..1.0).contains(&u) && (0.0..1.0).contains(&v) && inked(piece.icon, u, v)
                    {
                        hits += 1;
                    }
                }
            }
            if hits > 0 {
                let alpha = (hits * 255 / (SAMPLES * SAMPLES)) as u8;
                let at = (y * stride + left + x) * 3;
                rgb[at] = blend(fg.0, rgb[at], alpha);
                rgb[at + 1] = blend(fg.1, rgb[at + 1], alpha);
                rgb[at + 2] = blend(fg.2, rgb[at + 2], alpha);
            }
        }
    }
}

fn blend(fg: u8, bg: u8, alpha: u8) -> u8 {
    let a = alpha as u32;
    ((fg as u32 * a + bg as u32 * (255 - a)) / 255) as u8
}

fn fill(rgb: &mut [u8], stride: usize, x: usize, y: usize, w: usize, h: usize, color: Rgb) {
    for row in y..y + h {
        for px in x..x + w {
            let i = (row * stride + px) * 3;
            if i + 2 < rgb.len() {
                rgb[i..i + 3].copy_from_slice(&[color.0, color.1, color.2]);
            }
        }
    }
}

impl Rasterizer for SoftwareRasterizer {
    fn row(&mut self, grid: &Grid, y: u16) -> Image {
        let cells = grid.row(y);
        let (cw, ch) = self.cell;
        let width = cw * cells.len();
        let mut rgb = vec![0; width * ch * 3];
        // Backgrounds first: a wide glyph runs into the next cell, whose colour would cut it.
        for (i, cell) in cells.iter().enumerate() {
            fill(&mut rgb, width, i * cw, 0, cw, ch, cell.style.bg);
        }
        for (i, cell) in cells.iter().enumerate() {
            let fg = cell.style.fg;
            if cell.symbol.is_empty() || cell.symbol == " " || cell.style.painted {
                continue;
            }
            // Drawn rather than taken from a font, so stacked rows join with no gap.
            if cell.symbol == "▌" {
                fill(&mut rgb, width, i * cw, 0, cw.div_ceil(5), ch, fg);
                continue;
            }
            if let Some(piece) = Piece::decode(&cell.symbol) {
                draw_icon(&mut rgb, width, i * cw, (cw, ch), piece, fg);
                continue;
            }
            let key = GlyphKey {
                symbol: cell.symbol.clone(),
                bold: cell.style.bold,
                italic: cell.style.italic,
            };
            let mask = self.mask(&key);
            if let Some(painted) = self.painted.get(&key) {
                for &(x, y, color, alpha) in painted.iter() {
                    let at = (y as usize * width + i * cw + x as usize) * 3;
                    if at + 2 < rgb.len() && (i * cw + x as usize) < width {
                        rgb[at] = blend(color.0, rgb[at], alpha);
                        rgb[at + 1] = blend(color.1, rgb[at + 1], alpha);
                        rgb[at + 2] = blend(color.2, rgb[at + 2], alpha);
                    }
                }
                continue;
            }
            for &(x, y, alpha) in mask.iter() {
                let at = (y as usize * width + i * cw + x as usize) * 3;
                if at + 2 < rgb.len() && (i * cw + x as usize) < width {
                    rgb[at] = blend(fg.0, rgb[at], alpha);
                    rgb[at + 1] = blend(fg.1, rgb[at + 1], alpha);
                    rgb[at + 2] = blend(fg.2, rgb[at + 2], alpha);
                }
            }
        }
        for (i, cell) in cells.iter().enumerate() {
            // Painted text underlines itself, at its true width.
            if cell.style.underline && !cell.style.painted {
                fill(&mut rgb, width, i * cw, ch - 2, cw, 1, cell.style.fg);
            }
        }
        let paint: Vec<Paint> = grid.paint_on_row(y).cloned().collect();
        let mut target = Target {
            rgb: &mut rgb,
            width,
            height: ch,
            top: y as i32 * ch as i32,
        };
        for item in &paint {
            self.draw_paint(&mut target, item);
        }
        // A thin caret, as in a real editor, not a terminal's block.
        if let Some(bounds) = caret_bounds(grid) {
            let row = (y as i32 * UNIT, (y as i32 + 1) * UNIT);
            if bounds.y < row.1 && bounds.y + bounds.h > row.0 {
                let shape = Shape {
                    x: bounds.x as f32 * cw as f32 / UNIT as f32,
                    y: bounds.y as f32 * ch as f32 / UNIT as f32,
                    w: (cw as f32 / 9.0).max(2.0),
                    h: bounds.h as f32 * ch as f32 / UNIT as f32,
                    radius: 0.0,
                };
                let mut target = Target {
                    rgb: &mut rgb,
                    width,
                    height: ch,
                    top: y as i32 * ch as i32,
                };
                target.panel(
                    shape,
                    (Some(caret_color(grid)), None),
                    false,
                    false,
                    ch as f32,
                );
            }
        }
        Image {
            width,
            height: ch,
            rgb,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::grid::{Grid, Rect, Style};

    fn rasterizer() -> Option<SoftwareRasterizer> {
        SoftwareRasterizer::new(10, 20)
    }

    fn style() -> Style {
        Style {
            fg: Rgb(250, 250, 250),
            bg: Rgb(10, 20, 30),
            ..Style::default()
        }
    }

    fn lit(image: &Image, cell: usize, width: usize) -> usize {
        let mut count = 0;
        for y in 0..image.height {
            for x in cell * width..(cell + 1) * width {
                let i = (y * image.width + x) * 3;
                count += usize::from(image.rgb[i] > 128);
            }
        }
        count
    }

    #[test]
    fn row_image_is_exactly_the_grid_size() {
        let Some(mut r) = rasterizer() else { return };
        let grid = Grid::new(8, 1, style());
        let image = r.row(&grid, 0);
        assert_eq!((image.width, image.height), (80, 20));
        assert_eq!(image.rgb.len(), 80 * 20 * 3);
    }

    #[test]
    fn han_characters_are_drawn_in_the_cells() {
        let Some(mut r) = rasterizer() else { return };
        let fonts = system_fonts();
        let has_han = fonts.faces().any(|face| {
            let name = &face.families[0].0;
            CJK_FONTS.iter().any(|font| font == name)
        });
        if !has_han {
            return;
        }
        let mut grid = Grid::new(4, 1, style());
        grid.put_str(0, 0, "中", style(), 4);
        let image = r.row(&grid, 0);
        assert!(lit(&image, 0, 10) > 10);
    }

    #[test]
    fn a_wide_glyph_keeps_its_right_half() {
        let Some(mut r) = rasterizer() else { return };
        let mut grid = Grid::new(4, 1, style());
        grid.put_str(1, 0, "MM", style(), 4);
        let image = r.row(&grid, 0);
        assert!(lit(&image, 1, 10) > 10);
        assert!(
            lit(&image, 2, 10) > 10,
            "the next cell's colour didn't cover it"
        );
    }

    #[test]
    fn glyphs_land_in_their_own_cells() {
        let Some(mut r) = rasterizer() else { return };
        let mut grid = Grid::new(4, 1, style());
        grid.put_str(2, 0, "M", style(), 4);
        let image = r.row(&grid, 0);
        assert_eq!(lit(&image, 0, 10), 0);
        assert!(lit(&image, 2, 10) > 10, "M drew nothing");
        assert_eq!(lit(&image, 3, 10), 0, "M spilled into the next cell");
    }

    #[test]
    fn the_caret_is_a_thin_line() {
        let Some(mut r) = rasterizer() else { return };
        let mut grid = Grid::new(3, 1, style());
        grid.cursor = Some((1, 0));
        let image = r.row(&grid, 0);
        let at = |x: usize| image.rgb[(10 * image.width + x) * 3];
        assert_eq!(at(10), 250);
        assert_eq!(at(15), 10);
        grid.caret = Some(Bounds::cells(1.5, 0.0, 0.0, 1.0));
        let image = r.row(&grid, 0);
        let at = |x: usize| image.rgb[(10 * image.width + x) * 3];
        assert_eq!(at(10), 10, "the exact caret replaces the cell one");
        assert_eq!(at(15), 250);
    }

    #[test]
    fn labels_draw_without_their_cell_glyphs() {
        let Some(mut r) = rasterizer() else { return };
        let mut grid = Grid::new(20, 1, style());
        grid.label(1, 0, "Illi", style(), 20);
        assert!(grid.cell(1, 0).style.painted);
        let with_paint = r.row(&grid, 0);
        // Inter is proportional: this text is far narrower than four cells.
        let lit_right = (0..20)
            .flat_map(|y| (40..200).map(move |x| (x, y)))
            .any(|(x, y)| with_paint.rgb[(y * with_paint.width + x) * 3] > 128);
        assert!(!lit_right, "drew past the narrow label");
    }

    /// Words are set at the size VS Code sets its own: 13 pt. A terminal set to 14 pt has a
    /// cell of 17 by 37 px at two pixels a point, and a capital of 13 pt Inter stands 19 px
    /// tall there, with as much of the row over it as under it. At three fifths of a row,
    /// as the words were, it stood 16.
    #[test]
    fn words_are_thirteen_points_in_a_terminal_set_to_fourteen() {
        use crate::measure::Measure as _;
        let Some(mut r) = SoftwareRasterizer::new(17, 37) else {
            return;
        };
        let mut grid = Grid::new(8, 1, style());
        grid.label(1, 0, "H", style(), 8);
        let image = r.row(&grid, 0);
        let inked: Vec<usize> = (0..image.height)
            .filter(|y| (0..image.width).any(|x| image.rgb[(y * image.width + x) * 3] > 128))
            .collect();
        let (top, bottom) = (inked[0], inked[inked.len() - 1]);
        let tall = bottom - top + 1;
        assert!((18..=20).contains(&tall), "a capital is {tall} px tall");
        let (over, under) = (top, image.height - 1 - bottom);
        assert!(
            over.abs_diff(under) <= 2,
            "{over} px over it, {under} under"
        );
        // And as wide as 13 pt is: the measure and the picture agree on it.
        let wide = crate::measure::FontMeasure::new(17, 37).width("H", Font::default()) * 17.0;
        assert!((17.0..21.0).contains(&wide), "an H is {wide} px wide");
    }

    /// An emoji in a line of painted text keeps its own colours, where the machine has a
    /// font that holds them: the letters beside it take the text's.
    #[test]
    fn an_emoji_in_painted_text_keeps_its_own_colours() {
        let Some(mut r) = rasterizer() else { return };
        let mask = r.text_mask("ok 🚀", Font::default());
        // Without a colour emoji font it's a blank, in the text's colour like the rest.
        let Some(own) = &mask.own else { return };
        let coloured = own.iter().flatten().filter(|rgb| rgb.0 != rgb.2).count();
        assert!(coloured > 10, "a rocket has red and blue in it: {coloured}");
        let plain = r.text_mask("ok", Font::default());
        assert!(plain.own.is_none(), "letters have no colour of their own");
        // Drawn in dark text on light, the letters are dark and the emoji is still itself.
        let mut grid = Grid::new(12, 1, style());
        let dark = Style {
            fg: Rgb(10, 10, 10),
            bg: Rgb(240, 240, 240),
            ..Style::default()
        };
        grid.fill(Rect::new(0, 0, 12, 1), dark);
        grid.label(0, 0, "ok 🚀", dark, 12);
        let image = r.row(&grid, 0);
        let pixels: Vec<Rgb> = image.rgb.chunks(3).map(|p| Rgb(p[0], p[1], p[2])).collect();
        let tinted = |p: &&Rgb| p.0.abs_diff(p.2) > 60;
        assert!(pixels.iter().filter(tinted).count() > 10);
    }

    #[test]
    fn panels_have_rounded_corners() {
        let Some(mut r) = rasterizer() else { return };
        let mut grid = Grid::new(10, 1, style());
        grid.panel(
            crate::paint::Bounds::cells(1.0, 0.0, 8.0, 1.0),
            40,
            Some(Rgb(255, 0, 0)),
            None,
        );
        let image = r.row(&grid, 0);
        let red = |x: usize, y: usize| image.rgb[(y * image.width + x) * 3];
        assert_eq!(red(50, 10), 255, "the middle is filled");
        assert_eq!(red(10, 0), 10, "the corner is cut");
    }

    #[test]
    fn a_wash_lets_what_is_under_it_show() {
        let Some(mut r) = rasterizer() else { return };
        let mut grid = Grid::new(20, 2, style());
        let bounds = crate::paint::Bounds::cells(1.0, 0.0, 18.0, 2.0);
        grid.wash(bounds, 10, (Rgb(255, 0, 0), 64), Some(Rgb(0, 0, 255)));
        let image = r.row(&grid, 0);
        let at = |x: usize, y: usize| {
            let i = (y * image.width + x) * 3;
            (image.rgb[i], image.rgb[i + 1], image.rgb[i + 2])
        };
        let middle = at(image.width / 2, image.height - 1);
        assert!(middle.0 > 0 && middle.0 < 200, "a little red: {middle:?}");
        let edge = at(image.width / 2, 0);
        assert!(edge.2 > 200, "the border: {edge:?}");
    }

    #[test]
    fn a_dashed_border_has_gaps() {
        let Some(mut r) = rasterizer() else { return };
        let mut grid = Grid::new(20, 1, style());
        grid.dashed_panel(
            crate::paint::Bounds::cells(1.0, 0.0, 18.0, 1.0),
            10,
            None,
            Rgb(255, 0, 0),
        );
        let image = r.row(&grid, 0);
        // Along the top edge, past the corner: some pixels inked, some left.
        let y = 0;
        let reds: Vec<u8> = (30..170)
            .map(|x| image.rgb[(y * image.width + x) * 3])
            .collect();
        assert!(reds.iter().any(|r| *r > 200), "dashes are drawn");
        assert!(reds.iter().any(|r| *r < 60), "with gaps between them");
    }

    /// The emoji font in the binary draws in colour with none of the machine's fonts, which
    /// is what a server reached over SSH has, and holds the eight emoji that stand under a
    /// comment being written.
    #[test]
    fn the_emoji_font_in_the_binary_draws_in_colour_by_itself() {
        let mut db = fontdb::Database::new();
        for data in [INTER, INTER_ITALIC, MONO, MONO_ITALIC, EMOJI] {
            db.load_font_data(data.to_vec());
        }
        db.set_monospace_family("JetBrains Mono");
        db.set_sans_serif_family("Inter Variable");
        let mut fonts = FontSystem::new_with_locale_and_db("en-US".to_string(), db);
        assert!(draws_colour(&mut fonts, BUILT_IN_EMOJI));
        let found = find_emoji_font(&mut fonts).map(|(family, _)| family);
        assert_eq!(found.as_deref(), Some(BUILT_IN_EMOJI));
        for emoji in ["👍", "💯", "❤\u{fe0f}", "🎉", "😄", "👀", "🚀", "✅"] {
            assert!(
                set_in(&mut fonts, BUILT_IN_EMOJI, emoji).is_some(),
                "{emoji}"
            );
        }
        // A family the machine doesn't have draws nothing in colour.
        assert!(!draws_colour(&mut fonts, "No Such Emoji"));
        // It holds a flag and a family whole, and not an emoji newer than it is.
        for emoji in ["🇹🇷", "👩\u{200d}💻", "❤\u{fe0f}", "1\u{fe0f}\u{20e3}"] {
            assert!(built_in_emoji_holds(emoji), "{emoji}");
        }
        assert!(
            !built_in_emoji_holds("🫨"),
            "a face from a year after the font"
        );
        assert!(!built_in_emoji_holds("ok"));
        // And through the rasterizer itself: a line of words with two in it.
        let metrics = fit_font(&mut fonts, 10, 20).unwrap();
        let mut r = SoftwareRasterizer {
            fonts,
            emoji: Some(BUILT_IN_EMOJI.to_string()),
            swash: SwashCache::new(),
            metrics,
            cell: (10, 20),
            masks: HashMap::new(),
            painted: HashMap::new(),
            text: HashMap::new(),
        };
        let mask = r.text_mask("ok 🚀 ❤\u{fe0f}", Font::default());
        let own = mask
            .own
            .as_ref()
            .expect("the emoji have colours of their own");
        let red = own
            .iter()
            .flatten()
            .filter(|rgb| rgb.0 > 150 && rgb.2 < 120);
        assert!(red.count() > 10, "a heart and a rocket's flame are red");
    }

    #[test]
    fn fonts_ship_in_the_binary() {
        let mut r = SoftwareRasterizer::new(10, 20).unwrap();
        assert!(
            r.fonts
                .db()
                .faces()
                .any(|f| f.families.iter().any(|(n, _)| n.contains("Inter")))
        );
        assert!(
            r.text_mask("x", Font::default())
                .alpha
                .iter()
                .any(|a| *a > 0)
        );
    }

    #[test]
    fn unknown_cell_size_refuses_pixels() {
        assert!(SoftwareRasterizer::new(0, 20).is_none());
    }
}