cranpose-render-common 0.1.164

Common rendering contracts for Cranpose
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
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
use cranpose_ui::text::{RangeStyle, SpanStyle};
use cranpose_ui_graphics::Point;

use super::*;

fn count_ink_pixels(image: &ImageBitmap) -> usize {
    image
        .pixels()
        .as_chunks::<4>()
        .0
        .iter()
        .filter(|px| px[3] > 0)
        .count()
}

#[test]
fn software_glyph_raster_cache_reuses_static_masks_across_positions() {
    let font = default_software_text_font().expect("bundled default font");
    let style = TextStyle::default();
    let rect = Rect {
        x: 0.0,
        y: 0.0,
        width: 160.0,
        height: 32.0,
    };
    let mut cache = SoftwareGlyphRasterCache::with_capacity_at_least_one(64);

    let uncached = rasterize_text_to_image(
        "aaaa",
        rect,
        &style,
        Color(1.0, 1.0, 1.0, 1.0),
        18.0,
        1.0,
        &font,
    )
    .expect("uncached image");
    let cached = rasterize_text_to_image_with_glyph_cache(
        "aaaa",
        rect,
        &style,
        Color(1.0, 1.0, 1.0, 1.0),
        18.0,
        1.0,
        &font,
        &mut cache,
    )
    .expect("cached image");

    assert_eq!(cached.pixels(), uncached.pixels());
    let stats = cache.stats();
    assert_eq!(stats.entries, 1);
    assert_eq!(stats.misses, 1);
    assert_eq!(stats.hits, 3);

    let shifted_rect = Rect {
        x: 24.0,
        y: 17.0,
        ..rect
    };
    let _ = rasterize_text_to_image_with_glyph_cache(
        "aaaa",
        shifted_rect,
        &style,
        Color(1.0, 1.0, 1.0, 1.0),
        18.0,
        1.0,
        &font,
        &mut cache,
    )
    .expect("cached shifted image");

    let shifted_stats = cache.stats();
    assert_eq!(shifted_stats.entries, 1);
    assert_eq!(shifted_stats.misses, 1);
    assert_eq!(shifted_stats.hits, 7);
}

#[test]
fn annotated_solid_text_direct_raster_matches_plain_text_pixels() {
    let font = default_software_text_font().expect("bundled default font");
    let font_set = SoftwareTextFontSet::from_font(font.clone());
    let style = TextStyle::default();
    let rect = Rect {
        x: 0.0,
        y: 0.0,
        width: 240.0,
        height: 40.0,
    };
    let color = Color(1.0, 1.0, 1.0, 1.0);
    let annotated = AnnotatedString {
        text: "plain link".to_string(),
        span_styles: vec![RangeStyle {
            item: SpanStyle {
                color: Some(color),
                ..Default::default()
            },
            range: 0..10,
        }],
        ..Default::default()
    };
    let mut cache = SoftwareGlyphRasterCache::with_capacity_at_least_one(64);

    let plain = rasterize_text_to_image(
        annotated.text.as_str(),
        rect,
        &style,
        color,
        18.0,
        1.0,
        &font,
    )
    .expect("plain text image");
    let direct = rasterize_annotated_text_to_image_with_glyph_cache(
        &annotated, rect, &style, color, 18.0, 1.0, &font_set, &mut cache,
    )
    .expect("annotated text image");

    assert_eq!(direct.pixels(), plain.pixels());
}

#[test]
fn solid_annotated_text_collects_atlas_glyphs_with_stable_keys() {
    let font = default_software_text_font().expect("bundled default font");
    let font_set = SoftwareTextFontSet::from_font(font);
    let style = TextStyle::default();
    let rect = Rect {
        x: 12.0,
        y: 4.0,
        width: 260.0,
        height: 48.0,
    };
    let annotated = AnnotatedString {
        text: "markdown link".to_string(),
        span_styles: vec![RangeStyle {
            item: SpanStyle {
                color: Some(Color(0.4, 0.7, 1.0, 1.0)),
                ..Default::default()
            },
            range: 9..13,
        }],
        ..Default::default()
    };
    let mut cache = SoftwareGlyphRasterCache::with_capacity_at_least_one(64);
    let mut glyphs = Vec::new();

    collect_solid_text_atlas_glyphs(
        &annotated,
        rect,
        &style,
        Color::WHITE,
        18.0,
        1.0,
        &font_set,
        &mut cache,
        &mut glyphs,
    )
    .expect("solid styled text is atlas-eligible");

    assert!(!glyphs.is_empty());
    assert!(glyphs.iter().all(|glyph| glyph.mask.width > 0));
    assert!(glyphs.iter().all(|glyph| glyph.mask.height > 0));
    assert!(
        glyphs
            .iter()
            .any(|glyph| glyph.color == Color(0.4, 0.7, 1.0, 1.0))
    );
    assert!(cache.stats().entries > 0);
}

#[test]
fn cached_atlas_placements_reuse_existing_glyph_masks_without_payloads() {
    let font = default_software_text_font().expect("bundled default font");
    let font_set = SoftwareTextFontSet::from_font(font);
    let style = TextStyle::default();
    let rect = Rect {
        x: 12.0,
        y: 4.0,
        width: 260.0,
        height: 48.0,
    };
    let annotated = AnnotatedString {
        text: "markdown link".to_string(),
        span_styles: vec![RangeStyle {
            item: SpanStyle {
                color: Some(Color(0.4, 0.7, 1.0, 1.0)),
                ..Default::default()
            },
            range: 9..13,
        }],
        ..Default::default()
    };
    let mut cache = SoftwareGlyphRasterCache::with_capacity_at_least_one(64);
    let mut placements = Vec::new();

    assert!(
        collect_cached_solid_text_atlas_placements(
            &annotated,
            rect,
            &style,
            Color::WHITE,
            18.0,
            1.0,
            &font_set,
            &mut cache,
            &mut placements,
        )
        .is_none(),
        "placement-only collection requires retained glyph masks"
    );
    assert!(placements.is_empty());

    let mut glyphs = Vec::new();
    collect_solid_text_atlas_glyphs(
        &annotated,
        rect,
        &style,
        Color::WHITE,
        18.0,
        1.0,
        &font_set,
        &mut cache,
        &mut glyphs,
    )
    .expect("solid styled text is atlas-eligible");

    collect_cached_solid_text_atlas_placements(
        &annotated,
        rect,
        &style,
        Color::WHITE,
        18.0,
        1.0,
        &font_set,
        &mut cache,
        &mut placements,
    )
    .expect("cached masks provide placement-only atlas glyphs");

    assert_eq!(placements.len(), glyphs.len());
    assert!(
        placements
            .iter()
            .zip(glyphs.iter())
            .all(|(placement, glyph)| {
                placement.key == glyph.key
                    && placement.x == glyph.x
                    && placement.y == glyph.y
                    && placement.width == glyph.mask.width
                    && placement.height == glyph.mask.height
                    && placement.color == glyph.color
            })
    );
    let recovered = cache
        .atlas_glyph_for_placement(&placements[0])
        .expect("placement should recover retained mask payload");
    assert_eq!(recovered.key, glyphs[0].key);
    assert_eq!(recovered.x, glyphs[0].x);
    assert_eq!(recovered.y, glyphs[0].y);
    assert_eq!(recovered.mask.width, glyphs[0].mask.width);
    assert_eq!(recovered.mask.height, glyphs[0].mask.height);
    assert_eq!(recovered.mask.alpha, glyphs[0].mask.alpha);
    assert_eq!(recovered.color, glyphs[0].color);
}

#[test]
fn atlas_glyph_collection_rejects_shadow_and_gradient_without_partial_output() {
    let font = default_software_text_font().expect("bundled default font");
    let font_set = SoftwareTextFontSet::from_font(font);
    let rect = Rect {
        x: 0.0,
        y: 0.0,
        width: 240.0,
        height: 40.0,
    };
    let mut cache = SoftwareGlyphRasterCache::with_capacity_at_least_one(64);
    let mut glyphs = Vec::new();
    glyphs.push(SoftwareGlyphAtlasGlyph {
        key: SoftwareGlyphAtlasKey {
            font_hash: 1,
            glyph_id: 1,
            scale_x_bits: 1,
            scale_y_bits: 1,
            embolden_px_bits: 0,
            slant_bits: 0,
        },
        mask: SoftwareGlyphAtlasMask {
            alpha: Arc::from([1.0f32]),
            width: 1,
            height: 1,
        },
        x: 0,
        y: 0,
        color: Color::WHITE,
    });
    let initial_len = glyphs.len();

    let shadow_style = TextStyle::from_span_style(SpanStyle {
        shadow: Some(Shadow {
            color: Color(0.0, 0.0, 0.0, 0.5),
            offset: Point::new(1.0, 1.0),
            blur_radius: 0.0,
        }),
        ..Default::default()
    });
    assert!(
        collect_solid_text_atlas_glyphs(
            &AnnotatedString::new("shadow".to_string()),
            rect,
            &shadow_style,
            Color::WHITE,
            18.0,
            1.0,
            &font_set,
            &mut cache,
            &mut glyphs,
        )
        .is_none()
    );
    assert_eq!(glyphs.len(), initial_len);

    let gradient_style = TextStyle::from_span_style(SpanStyle {
        brush: Some(Brush::linear_gradient(vec![Color::WHITE, Color::BLACK])),
        ..Default::default()
    });
    assert!(
        collect_solid_text_atlas_glyphs(
            &AnnotatedString::new("gradient".to_string()),
            rect,
            &gradient_style,
            Color::WHITE,
            18.0,
            1.0,
            &font_set,
            &mut cache,
            &mut glyphs,
        )
        .is_none()
    );
    assert_eq!(glyphs.len(), initial_len);
}

fn average_ink_rgb(
    image: &ImageBitmap,
    x_start: u32,
    x_end: u32,
    y_start: u32,
    y_end: u32,
) -> Option<[f32; 3]> {
    let width = image.width();
    let height = image.height();
    let mut sums = [0.0f32; 3];
    let mut count = 0usize;
    let pixels = image.pixels();

    let x_end = x_end.min(width);
    let y_end = y_end.min(height);
    for y in y_start.min(height)..y_end {
        for x in x_start.min(width)..x_end {
            let idx = ((y * width + x) * 4) as usize;
            let alpha = pixels[idx + 3];
            if alpha == 0 {
                continue;
            }
            sums[0] += pixels[idx] as f32 / 255.0;
            sums[1] += pixels[idx + 1] as f32 / 255.0;
            sums[2] += pixels[idx + 2] as f32 / 255.0;
            count += 1;
        }
    }

    if count == 0 {
        return None;
    }
    Some([
        sums[0] / count as f32,
        sums[1] / count as f32,
        sums[2] / count as f32,
    ])
}

fn ink_x_range(image: &ImageBitmap) -> Option<(u32, u32)> {
    let width = image.width();
    let height = image.height();
    let pixels = image.pixels();
    let mut min_x = u32::MAX;
    let mut max_x = 0u32;
    let mut found = false;
    for y in 0..height {
        for x in 0..width {
            let idx = ((y * width + x) * 4) as usize;
            if pixels[idx + 3] > 0 {
                min_x = min_x.min(x);
                max_x = max_x.max(x + 1);
                found = true;
            }
        }
    }
    found.then_some((min_x, max_x))
}

fn ink_y_range(image: &ImageBitmap) -> Option<(u32, u32)> {
    let width = image.width();
    let height = image.height();
    let pixels = image.pixels();
    let mut min_y = u32::MAX;
    let mut max_y = 0u32;
    let mut found = false;
    for y in 0..height {
        for x in 0..width {
            let idx = ((y * width + x) * 4) as usize;
            if pixels[idx + 3] > 0 {
                min_y = min_y.min(y);
                max_y = max_y.max(y + 1);
                found = true;
            }
        }
    }
    found.then_some((min_y, max_y))
}

fn ink_centroid_x(image: &ImageBitmap, y_start: u32, y_end: u32) -> Option<f32> {
    let width = image.width();
    let height = image.height();
    let pixels = image.pixels();
    let mut weighted_x = 0.0f32;
    let mut total_alpha = 0.0f32;

    for y in y_start.min(height)..y_end.min(height) {
        for x in 0..width {
            let idx = ((y * width + x) * 4) as usize;
            let alpha = pixels[idx + 3] as f32 / 255.0;
            if alpha <= 0.0 {
                continue;
            }
            weighted_x += x as f32 * alpha;
            total_alpha += alpha;
        }
    }

    (total_alpha > 0.0).then_some(weighted_x / total_alpha)
}

fn vertical_slant_delta(image: &ImageBitmap) -> f32 {
    let (top, bottom) = ink_y_range(image).expect("image should contain ink");
    let mid = top + (bottom - top).max(1) / 2;
    let top_x = ink_centroid_x(image, top, mid).expect("top ink centroid");
    let bottom_x = ink_centroid_x(image, mid, bottom).expect("bottom ink centroid");
    top_x - bottom_x
}

fn top_ink_row(image: &ImageBitmap) -> Option<u32> {
    let width = image.width();
    let height = image.height();
    let pixels = image.pixels();
    for y in 0..height {
        for x in 0..width {
            let idx = ((y * width + x) * 4) as usize;
            if pixels[idx + 3] > 0 {
                return Some(y);
            }
        }
    }
    None
}

fn reference_dilation_offsets(radius: i32) -> Vec<(i32, i32)> {
    let mut offsets = Vec::new();
    let squared_radius = radius * radius;
    for dy in -radius..=radius {
        for dx in -radius..=radius {
            if dx * dx + dy * dy <= squared_radius {
                offsets.push((dx, dy));
            }
        }
    }
    if offsets.is_empty() {
        offsets.push((0, 0));
    }
    offsets
}

fn reference_dilation_stroke_mask(fill: &GlyphMask, stroke_width: f32) -> GlyphMask {
    let radius = (stroke_width * 0.5).ceil() as i32;
    let offsets = reference_dilation_offsets(radius);
    let out_width = fill.width as i32 + radius * 2;
    let out_height = fill.height as i32 + radius * 2;
    let fill_width_i32 = fill.width as i32;
    let fill_height_i32 = fill.height as i32;
    let mut alpha = vec![0.0f32; (out_width * out_height) as usize];

    for out_y in 0..out_height {
        let oy = out_y - radius;
        for out_x in 0..out_width {
            let ox = out_x - radius;
            let base_alpha = if ox >= 0 && oy >= 0 && ox < fill_width_i32 && oy < fill_height_i32 {
                fill.alpha[oy as usize * fill.width + ox as usize]
            } else {
                0.0
            };

            let mut dilated_alpha = 0.0f32;
            for (dx, dy) in &offsets {
                let sx = ox + dx;
                let sy = oy + dy;
                if sx < 0 || sy < 0 || sx >= fill_width_i32 || sy >= fill_height_i32 {
                    continue;
                }
                let sample = fill.alpha[sy as usize * fill.width + sx as usize];
                if sample > dilated_alpha {
                    dilated_alpha = sample;
                    if dilated_alpha >= 0.999 {
                        break;
                    }
                }
            }
            alpha[out_y as usize * out_width as usize + out_x as usize] =
                (dilated_alpha - base_alpha).max(0.0);
        }
    }

    GlyphMask {
        alpha: Arc::from(alpha),
        width: out_width as usize,
        height: out_height as usize,
        origin_x: fill.origin_x - radius,
        origin_y: fill.origin_y - radius,
    }
}

fn rasterize_reference_dilation_stroke(
    text: &str,
    rect: Rect,
    font_size: f32,
    stroke_width: f32,
    font: &impl Font,
) -> ImageBitmap {
    let width = rect.width.ceil().max(1.0) as u32;
    let height = rect.height.ceil().max(1.0) as u32;
    let mut canvas = vec![[0.0f32; 4]; (width * height) as usize];

    let metrics = vertical_metrics(font, font_size);
    let baseline = line_box_for(&TextStyle::default(), metrics, font_size * 1.4, 1.0).baseline;
    for glyph in layout_line_glyphs(font, text, font_size, point(0.0, baseline)) {
        let Some((outlined, bounds)) = outline_glyph_with_bounds(font, &glyph) else {
            continue;
        };
        let Some(fill) = build_fill_mask(&outlined, bounds) else {
            continue;
        };
        let reference = reference_dilation_stroke_mask(&fill, stroke_width);
        draw_mask_glyph(
            &mut canvas,
            width,
            height,
            &reference,
            &Brush::solid(Color::WHITE),
            1.0,
            rect,
        );
    }

    let mut rgba = vec![0u8; canvas.len() * 4];
    for (index, pixel) in canvas.iter().enumerate() {
        let base = index * 4;
        rgba[base] = (pixel[0].clamp(0.0, 1.0) * 255.0).round() as u8;
        rgba[base + 1] = (pixel[1].clamp(0.0, 1.0) * 255.0).round() as u8;
        rgba[base + 2] = (pixel[2].clamp(0.0, 1.0) * 255.0).round() as u8;
        rgba[base + 3] = (pixel[3].clamp(0.0, 1.0) * 255.0).round() as u8;
    }
    ImageBitmap::from_rgba8(width, height, rgba).expect("reference dilation image")
}

fn test_font() -> ab_glyph::FontRef<'static> {
    ab_glyph::FontRef::try_from_slice(include_bytes!("../../assets/NotoSansMerged.ttf"))
        .expect("font")
}

fn test_software_font() -> SoftwareTextFont {
    SoftwareTextFont::from_bytes(include_bytes!("../../assets/NotoSansMerged.ttf").to_vec())
        .expect("font")
}

#[test]
fn software_text_font_rejects_invalid_bytes() {
    assert!(SoftwareTextFont::from_bytes(vec![0, 1, 2, 3]).is_err());
}

#[test]
fn default_software_text_font_has_no_process_global_cache() {
    let source = include_str!("../software_text_raster.rs");
    let once_lock = ["Once", "Lock"].concat();
    let cached_default = ["static ", "FONT"].concat();
    let default_font_fn = ["fn ", "default_font()"].concat();

    assert!(
        !source.contains(&cached_default)
            && !source.contains(&default_font_fn)
            && !source.contains(&once_lock),
        "default software text font construction must be explicit renderer/app-owned state, not a process-global cache"
    );
}

#[test]
fn software_text_measurer_empty_font_set_uses_deterministic_fallback_without_panicking() {
    let measurer = SoftwareTextMeasurer::from_font_set(SoftwareTextFontSet::empty(), 4);
    let style = TextStyle {
        span_style: SpanStyle {
            font_size: cranpose_ui::text::TextUnit::Sp(20.0),
            ..Default::default()
        },
        ..Default::default()
    };
    let text = AnnotatedString::from("ab\nc");

    let metrics = measurer.measure(&text, &style);
    assert_eq!(metrics.line_count, 2);
    assert!(metrics.width > 0.0);
    assert!(metrics.height >= metrics.line_height * 2.0);

    let cursor_x = measurer.get_cursor_x_for_offset(&text, &style, 2);
    assert!(cursor_x > 0.0);
    let second_line_offset =
        measurer.get_offset_for_position(&text, &style, 0.0, metrics.line_height);
    assert!(
        second_line_offset >= "ab\n".len(),
        "fallback hit testing should resolve into the second line: {second_line_offset}"
    );

    let layout = measurer.layout(&text, &style);
    assert_eq!(layout.lines.len(), 2);
    assert_eq!(layout.glyph_layouts().len(), 3);
}

#[test]
fn software_text_metrics_layout_and_cursor_share_font_backend() {
    let font = test_software_font();
    let style = TextStyle {
        span_style: SpanStyle {
            font_size: cranpose_ui::text::TextUnit::Sp(18.0),
            ..Default::default()
        },
        ..Default::default()
    };
    let text = "Text\nBackend";

    let metrics = measure_text_with_font(text, &style, 18.0, &font);
    let layout = layout_text_with_font(text, &style, &font);

    assert!(metrics.width > 0.0);
    assert_eq!(metrics.line_count, 2);
    assert_eq!(layout.lines.len(), 2);
    assert_eq!(layout.height, metrics.height);
    assert!(layout.glyph_layouts().len() >= "TextBackend".len());

    let offset = text_offset_for_position_with_font(text, &style, 0.0, metrics.line_height, &font);
    assert!(
        offset >= "Text\n".len(),
        "second-line hit testing should return a byte offset on the second line: {offset}"
    );
    let cursor_x = cursor_x_for_offset_with_font(text, &style, "Text".len(), &font);
    assert!(cursor_x > 0.0);
}

#[test]
fn software_text_metrics_keep_requested_font_size_for_default_font() {
    let font = default_software_text_font().expect("bundled default test font");
    let style = TextStyle {
        span_style: SpanStyle {
            font_size: cranpose_ui::text::TextUnit::Sp(14.0),
            ..Default::default()
        },
        ..Default::default()
    };

    let metrics = measure_text_with_font("Counter App", &style, 14.0, &font);
    assert!(
        (metrics.width - 83.16).abs() < 0.05 && (metrics.height - 19.6).abs() < 0.05,
        "14sp demo text must use font em metrics, not ab_glyph height units: {metrics:?}"
    );
}

#[test]
fn software_text_synthesizes_missing_bold_weight() {
    let font = test_software_font();
    let normal_style = TextStyle {
        span_style: SpanStyle {
            font_size: cranpose_ui::text::TextUnit::Sp(20.0),
            ..Default::default()
        },
        ..Default::default()
    };
    let bold_style = TextStyle {
        span_style: SpanStyle {
            font_size: cranpose_ui::text::TextUnit::Sp(20.0),
            font_weight: Some(FontWeight::BOLD),
            ..Default::default()
        },
        ..Default::default()
    };
    let no_synthesis_style = TextStyle {
        span_style: SpanStyle {
            font_size: cranpose_ui::text::TextUnit::Sp(20.0),
            font_weight: Some(FontWeight::BOLD),
            font_synthesis: Some(FontSynthesis::None),
            ..Default::default()
        },
        ..Default::default()
    };

    let normal = measure_text_with_font("Save Raster WebP", &normal_style, 20.0, &font);
    let synthesized = measure_text_with_font("Save Raster WebP", &bold_style, 20.0, &font);
    let disabled = measure_text_with_font("Save Raster WebP", &no_synthesis_style, 20.0, &font);

    assert!(
        synthesized.width > normal.width * 1.04,
        "bold fallback should synthesize heavier advances: normal={normal:?} synthesized={synthesized:?}"
    );
    assert!(
        (disabled.width - normal.width).abs() < 0.01,
        "explicit FontSynthesis::None should preserve regular metrics: normal={normal:?} disabled={disabled:?}"
    );
}

#[test]
fn rasterized_synthetic_bold_adds_ink_without_changing_line_box() {
    let font = test_software_font();
    let normal_style = TextStyle {
        span_style: SpanStyle {
            font_size: cranpose_ui::text::TextUnit::Sp(20.0),
            ..Default::default()
        },
        ..Default::default()
    };
    let bold_style = TextStyle {
        span_style: SpanStyle {
            font_size: cranpose_ui::text::TextUnit::Sp(20.0),
            font_weight: Some(FontWeight::BOLD),
            ..Default::default()
        },
        ..Default::default()
    };
    let normal_metrics = measure_text_with_font("Composer", &normal_style, 20.0, &font);
    let bold_metrics = measure_text_with_font("Composer", &bold_style, 20.0, &font);

    let normal = rasterize_text_to_image(
        "Composer",
        Rect {
            x: 0.0,
            y: 0.0,
            width: normal_metrics.width.ceil(),
            height: normal_metrics.height.ceil(),
        },
        &normal_style,
        Color::WHITE,
        20.0,
        1.0,
        &font,
    )
    .expect("normal text image");
    let bold = rasterize_text_to_image(
        "Composer",
        Rect {
            x: 0.0,
            y: 0.0,
            width: bold_metrics.width.ceil(),
            height: bold_metrics.height.ceil(),
        },
        &bold_style,
        Color::WHITE,
        20.0,
        1.0,
        &font,
    )
    .expect("bold text image");

    assert_eq!(bold.height(), normal.height());
    assert!(
        count_ink_pixels(&bold) > count_ink_pixels(&normal),
        "synthetic bold should increase rasterized ink coverage"
    );
}

#[test]
fn software_text_synthesizes_missing_italic_style() {
    let font = test_software_font();
    let normal_style = TextStyle {
        span_style: SpanStyle {
            font_size: cranpose_ui::text::TextUnit::Sp(36.0),
            ..Default::default()
        },
        ..Default::default()
    };
    let italic_style = TextStyle {
        span_style: SpanStyle {
            font_size: cranpose_ui::text::TextUnit::Sp(36.0),
            font_style: Some(FontStyle::Italic),
            ..Default::default()
        },
        ..Default::default()
    };
    let no_synthesis_style = TextStyle {
        span_style: SpanStyle {
            font_size: cranpose_ui::text::TextUnit::Sp(36.0),
            font_style: Some(FontStyle::Italic),
            font_synthesis: Some(FontSynthesis::None),
            ..Default::default()
        },
        ..Default::default()
    };

    let normal_metrics = measure_text_with_font("Italic", &normal_style, 36.0, &font);
    let italic_metrics = measure_text_with_font("Italic", &italic_style, 36.0, &font);
    let disabled_metrics = measure_text_with_font("Italic", &no_synthesis_style, 36.0, &font);

    assert!(
        italic_metrics.width > normal_metrics.width + 6.0,
        "italic fallback should reserve slanted visual overhang: normal={normal_metrics:?} italic={italic_metrics:?}"
    );
    assert!(
        (disabled_metrics.width - normal_metrics.width).abs() < 0.01,
        "explicit FontSynthesis::None should preserve regular metrics: normal={normal_metrics:?} disabled={disabled_metrics:?}"
    );

    let normal = rasterize_text_to_image(
        "Italic",
        Rect {
            x: 0.0,
            y: 0.0,
            width: normal_metrics.width.ceil(),
            height: normal_metrics.height.ceil(),
        },
        &normal_style,
        Color::WHITE,
        36.0,
        1.0,
        &font,
    )
    .expect("normal text image");
    let italic = rasterize_text_to_image(
        "Italic",
        Rect {
            x: 0.0,
            y: 0.0,
            width: italic_metrics.width.ceil(),
            height: italic_metrics.height.ceil(),
        },
        &italic_style,
        Color::WHITE,
        36.0,
        1.0,
        &font,
    )
    .expect("italic text image");
    let disabled = rasterize_text_to_image(
        "Italic",
        Rect {
            x: 0.0,
            y: 0.0,
            width: disabled_metrics.width.ceil(),
            height: disabled_metrics.height.ceil(),
        },
        &no_synthesis_style,
        Color::WHITE,
        36.0,
        1.0,
        &font,
    )
    .expect("disabled italic text image");

    assert_eq!(
        normal.pixels(),
        disabled.pixels(),
        "FontSynthesis::None must not synthesize oblique glyphs"
    );
    assert!(
        vertical_slant_delta(&italic) > vertical_slant_delta(&normal) + 2.0,
        "synthetic italic should visibly lean top ink to the right"
    );
}

#[test]
fn rasterized_default_text_fills_expected_visual_height() {
    let font = default_software_text_font().expect("bundled default test font");
    let style = TextStyle {
        span_style: SpanStyle {
            font_size: cranpose_ui::text::TextUnit::Sp(14.0),
            ..Default::default()
        },
        ..Default::default()
    };
    let metrics = measure_text_with_font("Counter App", &style, 14.0, &font);
    let image = rasterize_text_to_image(
        "Counter App",
        Rect {
            x: 0.0,
            y: 0.0,
            width: metrics.width.ceil(),
            height: metrics.height.ceil(),
        },
        &style,
        Color::WHITE,
        14.0,
        1.0,
        &font,
    )
    .expect("text image");
    let (top, bottom) = ink_y_range(&image).expect("text should contain ink");
    let ink_height = bottom - top;

    assert!(
        ink_height >= 13,
        "14sp default text ink should keep visual height parity with the WGPU baseline: top={top} bottom={bottom} image={}x{}",
        image.width(),
        image.height()
    );
}

#[test]
fn software_text_font_selection_preserves_first_complete_default_face() {
    let regular =
        SoftwareTextFont::from_bytes(include_bytes!("../../assets/NotoSansMerged.ttf").to_vec())
            .expect("regular test font should load");
    let font = software_text_font_from_fonts_or_default(&[
        include_bytes!("../../assets/NotoSansMerged.ttf"),
        include_bytes!("../../assets/NotoSansBold.ttf"),
        include_bytes!("../../assets/TwemojiMozilla.ttf"),
    ])
    .expect("font selection should resolve a test font");
    let style = TextStyle {
        span_style: SpanStyle {
            font_size: cranpose_ui::text::TextUnit::Sp(18.0),
            ..Default::default()
        },
        ..Default::default()
    };

    let regular_metrics = measure_text_with_font("UNDER", &style, 18.0, &regular);
    let metrics = measure_text_with_font("UNDER", &style, 18.0, &font);
    assert!(
        (metrics.width - regular_metrics.width).abs() < 0.01,
        "font selection should keep the declared regular face for default text: selected={metrics:?}, regular={regular_metrics:?}"
    );
}

#[test]
fn software_text_font_resolution_reuses_cached_font_score() {
    let font = test_software_font();
    assert!(
        font.score.is_complete_default_face(),
        "test font should cache complete Latin coverage at load time: supported={} width={}",
        font.score.supported_latin_chars,
        font.score.latin_sample_width
    );

    let fonts = SoftwareTextFontSet::from_font(font.clone());
    let resolved = fonts
        .resolve(&TextStyle {
            span_style: SpanStyle {
                font_weight: Some(FontWeight::BOLD),
                ..Default::default()
            },
            ..Default::default()
        })
        .expect("font set should resolve a test font");

    assert_eq!(
        resolved.score.supported_latin_chars,
        font.score.supported_latin_chars
    );
    assert_eq!(
        resolved.score.latin_sample_width,
        font.score.latin_sample_width
    );
}

#[test]
fn software_text_font_set_resolves_requested_weight() {
    let fonts = software_text_font_set_from_fonts_or_default(&[
        include_bytes!("../../assets/NotoSansMerged.ttf"),
        include_bytes!("../../assets/NotoSansBold.ttf"),
        include_bytes!("../../assets/TwemojiMozilla.ttf"),
    ]);
    let regular = fonts
        .resolve(&TextStyle::default())
        .expect("font set should resolve regular test font");
    let bold_style = TextStyle {
        span_style: SpanStyle {
            font_weight: Some(FontWeight::BOLD),
            ..Default::default()
        },
        ..Default::default()
    };
    let bold = fonts
        .resolve(&bold_style)
        .expect("font set should resolve bold test font");

    assert_eq!(regular.weight(), FontWeight::NORMAL);
    assert_eq!(bold.weight(), FontWeight::BOLD);

    let regular_metrics =
        measure_text_with_font("Counter App", &TextStyle::default(), 18.0, regular);
    let bold_metrics = measure_text_with_font("Counter App", &bold_style, 18.0, bold);
    assert!(
        bold_metrics.width > regular_metrics.width,
        "bold face resolution should affect real text metrics: regular={regular_metrics:?} bold={bold_metrics:?}"
    );
}

fn registered_face(family: &FontFamily, weight: FontWeight) -> SoftwareTextFont {
    SoftwareTextFont::from_registered_bytes(
        family,
        weight,
        FontStyle::Normal,
        include_bytes!("../../assets/NotoSansMerged.ttf").to_vec(),
    )
    .expect("registered test face")
}

fn style_naming(family: &FontFamily) -> TextStyle {
    TextStyle {
        span_style: SpanStyle {
            font_family: Some(family.clone()),
            ..Default::default()
        },
        ..Default::default()
    }
}

fn unregistered_face() -> SoftwareTextFont {
    SoftwareTextFont::from_bytes(include_bytes!("../../assets/NotoSansBold.ttf").to_vec())
        .expect("unregistered test face")
}

#[test]
fn a_named_family_resolves_the_face_registered_under_it() {
    let family = FontFamily::named("Game UI");
    let fonts = SoftwareTextFontSet::from_faces(vec![
        unregistered_face(),
        registered_face(&family, FontWeight::NORMAL),
    ]);

    let resolved = fonts
        .resolve(&style_naming(&family))
        .expect("registered face");
    assert_eq!(
        resolved.registered_family(),
        Some(FontFamilyKey::of(&family))
    );
}

#[test]
fn a_file_backed_family_never_resolves_a_face_filed_under_another_one() {
    let mine = FontFamily::loaded_typeface_path("/fonts/Mine.ttf");
    let theirs = FontFamily::loaded_typeface_path("/fonts/Theirs.ttf");
    let fallback =
        SoftwareTextFont::from_bytes(include_bytes!("../../assets/NotoSansMerged.ttf").to_vec())
            .expect("fallback test face");
    let theirs_face = SoftwareTextFont::from_registered_bytes(
        &theirs,
        FontWeight::BOLD,
        FontStyle::Normal,
        include_bytes!("../../assets/NotoSansBold.ttf").to_vec(),
    )
    .expect("registered test face");
    let fonts = SoftwareTextFontSet::from_faces(vec![fallback.clone(), theirs_face]);

    assert_eq!(
        fonts
            .resolve(&style_naming(&mine))
            .expect("fallback face")
            .content_hash(),
        fallback.content_hash(),
        "an unregistered family must fall back rather than borrow someone else's face"
    );
    assert_eq!(
        fonts
            .resolve(&style_naming(&theirs))
            .expect("registered face")
            .registered_family(),
        Some(FontFamilyKey::of(&theirs)),
        "the family that was registered still resolves to its own face"
    );
}

#[test]
fn a_generic_family_only_constrains_the_set_once_a_face_is_registered_for_it() {
    let bold_sans_serif = TextStyle {
        span_style: SpanStyle {
            font_family: Some(FontFamily::SansSerif),
            font_weight: Some(FontWeight::BOLD),
            ..Default::default()
        },
        ..Default::default()
    };

    let unclaimed = software_text_font_set_from_fonts_or_default(&[
        include_bytes!("../../assets/NotoSansMerged.ttf"),
        include_bytes!("../../assets/NotoSansBold.ttf"),
    ]);
    assert_eq!(
        unclaimed
            .resolve(&bold_sans_serif)
            .expect("bold face")
            .weight(),
        FontWeight::BOLD
    );

    let claimed = SoftwareTextFontSet::from_faces(vec![
        SoftwareTextFont::from_bytes(include_bytes!("../../assets/NotoSansBold.ttf").to_vec())
            .expect("bold test face"),
        registered_face(&FontFamily::SansSerif, FontWeight::NORMAL),
    ]);
    let resolved = claimed.resolve(&bold_sans_serif).expect("system face");
    assert_eq!(
        resolved.registered_family(),
        Some(FontFamilyKey::of(&FontFamily::SansSerif))
    );
}

#[test]
fn an_app_supplied_family_measures_once_and_is_served_from_the_metrics_cache() {
    let family = FontFamily::named("Game UI");
    let measurer = SoftwareTextMeasurer::from_font_set(
        SoftwareTextFontSet::from_faces(vec![registered_face(&family, FontWeight::NORMAL)]),
        64,
    );
    let style = style_naming(&family);
    let text = AnnotatedString::from("SCORE 1234");

    let first = measurer.measure(&text, &style);
    let stats_after_first = measurer.lock_cache().glyph_metrics.stats();
    for _ in 0..60 {
        assert_eq!(measurer.measure(&text, &style), first);
    }

    assert_eq!(
        measurer.lock_cache().glyph_metrics.stats(),
        stats_after_first,
        "repeat frames of an unchanged string must not re-shape against the app face"
    );
}

#[test]
fn a_font_size_animation_measures_each_glyph_once_rather_than_once_per_size() {
    let font = default_software_text_font().expect("bundled default test font");
    let measurer = SoftwareTextMeasurer::new(font, 64);
    let text = AnnotatedString::from("Scaling list row");

    let sized = |size: f32| TextStyle {
        span_style: SpanStyle {
            font_size: cranpose_ui::text::TextUnit::Sp(size),
            ..Default::default()
        },
        ..Default::default()
    };

    let first = measurer.measure(&text, &sized(14.0));
    let after_first = measurer.lock_cache().glyph_metrics.stats();

    for step in 0..120 {
        let size = 14.0 + step as f32 * 0.137;
        let measured = measurer.measure(&text, &sized(size));
        assert!(
            measured.width > 0.0,
            "a scaled measurement must still produce a width"
        );
    }

    let after_scaling = measurer.lock_cache().glyph_metrics.stats();
    assert_eq!(
        (after_scaling.glyph_misses, after_scaling.kern_misses),
        (after_first.glyph_misses, after_first.kern_misses),
        "measuring the same glyphs at a new size must not re-read the font: {after_scaling:?}"
    );
    assert!(
        after_scaling.glyph_hits > after_first.glyph_hits,
        "the scaled measurements must have come from the cache"
    );

    let single = measurer.measure(&AnnotatedString::from("W"), &sized(20.0));
    let double = measurer.measure(&AnnotatedString::from("W"), &sized(40.0));
    let ratio = double.width / single.width.max(f32::EPSILON);
    assert!(
        (ratio - 2.0).abs() < 0.01,
        "advances must scale with the font size: {single:?} -> {double:?} (ratio {ratio})"
    );
    let _ = first;
}

#[test]
fn software_text_metrics_use_largest_annotated_span_font_size() {
    let font = default_software_text_font().expect("bundled default test font");
    let text = AnnotatedString::builder()
        .push_style(SpanStyle {
            font_size: cranpose_ui::text::TextUnit::Sp(30.0),
            ..Default::default()
        })
        .append("BIG ")
        .pop()
        .push_style(SpanStyle {
            font_size: cranpose_ui::text::TextUnit::Sp(10.0),
            ..Default::default()
        })
        .append("small")
        .pop()
        .to_annotated_string();

    let metrics = measure_annotated_text_with_font(&text, &TextStyle::default(), 14.0, &font);

    assert!(
        metrics.height >= 30.0,
        "rich text metrics must include the largest span height: {metrics:?}"
    );
    assert!(
        metrics.width > 48.0,
        "rich text metrics should measure run widths at their span sizes: {metrics:?}"
    );
}

#[test]
fn software_text_line_height_matches_full_measurement_without_width_layout() {
    let measurer = SoftwareTextMeasurer::new(
        default_software_text_font().expect("bundled default test font"),
        8,
    );
    let text = AnnotatedString::builder()
        .append("normal ")
        .push_style(SpanStyle {
            font_size: cranpose_ui::text::TextUnit::Sp(32.0),
            ..Default::default()
        })
        .append("large")
        .pop()
        .append("\nsecond line")
        .to_annotated_string();
    let style = TextStyle::default();

    let measured = measurer.measure(&text, &style);
    let line_height = measurer.line_height(&text, &style);

    assert_eq!(line_height, measured.line_height);
    assert!(
        line_height > measurer.line_height(&AnnotatedString::from("normal"), &style),
        "span font size should affect fast line-height lookup"
    );
}

#[test]
fn solid_text_atlas_line_advance_matches_measured_line_height() {
    let font = default_software_text_font().expect("bundled default test font");
    let fonts = SoftwareTextFontSet::from_font(font);
    let style = TextStyle::default();
    let text = AnnotatedString::from("A\nA\nA\nA");
    let font_size = style.resolve_font_size(14.0);
    let metrics = measure_annotated_text_with_font_set(&text, &style, font_size, &fonts);
    let rect = Rect {
        x: 0.0,
        y: 0.0,
        width: 120.0,
        height: metrics.height,
    };
    let mut glyph_cache = SoftwareGlyphRasterCache::with_capacity_at_least_one(16);
    let mut run = Vec::new();

    collect_solid_text_atlas_run(
        &text,
        rect,
        &style,
        Color(1.0, 1.0, 1.0, 1.0),
        font_size,
        1.0,
        &fonts,
        &mut glyph_cache,
        &mut run,
    )
    .expect("atlas-compatible text");

    let mut glyph_y: Vec<i32> = run.iter().map(|glyph| glyph.placement().y).collect();
    glyph_y.sort_unstable();
    glyph_y.dedup();
    assert_eq!(glyph_y.len(), 4);
    for window in glyph_y.windows(2) {
        let advance = (window[1] - window[0]) as f32;
        assert!(
            (advance - metrics.line_height).abs() <= 1.0,
            "glyph advance {advance} should match measured line height {}",
            metrics.line_height
        );
    }
}

#[test]
fn software_text_metrics_cache_keys_include_span_styles() {
    let measurer = SoftwareTextMeasurer::new(
        default_software_text_font().expect("bundled default test font"),
        8,
    );
    let plain = AnnotatedString::from("BIG small");
    let rich = AnnotatedString::builder()
        .push_style(SpanStyle {
            font_size: cranpose_ui::text::TextUnit::Sp(30.0),
            ..Default::default()
        })
        .append("BIG ")
        .pop()
        .append("small")
        .to_annotated_string();

    let plain_metrics = measurer.measure(&plain, &TextStyle::default());
    let rich_metrics = measurer.measure(&rich, &TextStyle::default());

    assert!(
        rich_metrics.height > plain_metrics.height,
        "cached plain text metrics must not be reused for styled text: plain={plain_metrics:?} rich={rich_metrics:?}"
    );
}

#[test]
fn software_text_metrics_cache_recovers_after_poison() {
    let measurer = SoftwareTextMeasurer::new(
        default_software_text_font().expect("bundled default test font"),
        8,
    );
    let text = AnnotatedString::from("Recovered text metrics");

    let poison_result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
        let _guard = measurer
            .cache
            .lock()
            .unwrap_or_else(PoisonError::into_inner);
        panic!("poison software text metrics cache for recovery test");
    }));

    assert!(poison_result.is_err());

    let metrics = measurer.measure(&text, &TextStyle::default());
    assert!(metrics.width > 0.0);
    assert!(metrics.height > 0.0);

    let subset = measurer.measure_subsequence(&text, 0.."Recovered".len(), &TextStyle::default());
    assert!(subset.width > 0.0);
    assert!(subset.width < metrics.width);
}

#[test]
fn software_text_prefix_widths_match_subsequence_measurement() {
    let measurer = SoftwareTextMeasurer::new(
        default_software_text_font().expect("bundled default test font"),
        8,
    );
    let style = TextStyle {
        span_style: SpanStyle {
            font_size: cranpose_ui::text::TextUnit::Sp(18.0),
            ..Default::default()
        },
        ..Default::default()
    };
    let text = AnnotatedString::from("Hello Prefix Widths");
    let widths = measurer
        .measure_line_prefix_widths(&text, 0..text.text.len(), &style)
        .expect("uniform line should expose prefix widths");

    let start = "Hello ".len();
    let end = "Hello Prefix".len();
    let expected = measurer
        .measure_subsequence(&text, start..end, &style)
        .width;
    let actual = widths
        .width_for_char_range(6, 12)
        .expect("valid char range");

    assert!(
        (actual - expected).abs() < 0.01,
        "prefix width should match exact subsequence width: actual={actual}, expected={expected}"
    );
}

#[test]
fn software_text_line_width_and_prefix_width_share_cached_plan() {
    let measurer = SoftwareTextMeasurer::new(
        default_software_text_font().expect("bundled default test font"),
        8,
    );
    let style = TextStyle::default();
    let text = AnnotatedString::from("shared prefix plan ".repeat(32).as_str());
    let line_range = 0..text.text.len();

    let width = measurer
        .measure_line_width(&text, line_range.clone(), &style)
        .expect("software text should expose a line width");
    let stats_after_width = {
        let cache = measurer.lock_cache();
        assert_eq!(cache.line_prefix_widths.len(), 1);
        cache.glyph_metrics.stats()
    };

    let widths = measurer
        .measure_line_prefix_widths(&text, line_range, &style)
        .expect("line width probe should cache the prefix plan");
    let stats_after_prefix = measurer.lock_cache().glyph_metrics.stats();

    assert_eq!(stats_after_prefix, stats_after_width);
    assert!(
        (width - widths.width_for_char_range(0, widths.char_count()).unwrap()).abs() < 0.01,
        "cached line-width probe and prefix plan must agree"
    );
}

#[test]
fn software_text_glyph_metrics_cache_reuses_common_glyphs_across_unique_lines() {
    let measurer = SoftwareTextMeasurer::new(
        default_software_text_font().expect("bundled default test font"),
        8,
    );
    let style = TextStyle::default();
    let first = AnnotatedString::from("algorithm data structure ".repeat(24).as_str());
    let second = AnnotatedString::from("algorithmic structures repeat data ".repeat(24).as_str());

    measurer
        .measure_line_prefix_widths(&first, 0..first.text.len(), &style)
        .expect("first unique line should measure");
    let stats_after_first = measurer.lock_cache().glyph_metrics.stats();

    measurer
        .measure_line_prefix_widths(&second, 0..second.text.len(), &style)
        .expect("second unique line should measure");
    let stats_after_second = measurer.lock_cache().glyph_metrics.stats();

    assert!(
        stats_after_second.glyph_hits > stats_after_first.glyph_hits,
        "unique markdown rows should reuse retained glyph metrics: first={stats_after_first:?} second={stats_after_second:?}"
    );
    assert!(
        stats_after_second.kern_hits > stats_after_first.kern_hits,
        "unique markdown rows should reuse retained kerning metrics: first={stats_after_first:?} second={stats_after_second:?}"
    );
}

#[test]
fn rasterized_gradient_text_shows_color_transition() {
    let font = test_font();
    let plain_style = TextStyle::default();
    let probe = rasterize_text_to_image_with_font(
        "MMMMMMMM",
        Rect {
            x: 0.0,
            y: 0.0,
            width: 320.0,
            height: 96.0,
        },
        &plain_style,
        Color::WHITE,
        48.0,
        1.0,
        &font,
    )
    .expect("probe image");
    let (ink_x_min, ink_x_max) = ink_x_range(&probe).expect("probe must contain ink");
    let gradient_end = ink_x_max as f32;

    let style = TextStyle {
        span_style: SpanStyle {
            brush: Some(Brush::linear_gradient_range(
                vec![Color::RED, Color::BLUE],
                Point::new(0.0, 0.0),
                Point::new(gradient_end, 0.0),
            )),
            ..Default::default()
        },
        ..Default::default()
    };

    let image = rasterize_text_to_image_with_font(
        "MMMMMMMM",
        Rect {
            x: 0.0,
            y: 0.0,
            width: 320.0,
            height: 96.0,
        },
        &style,
        Color::WHITE,
        48.0,
        1.0,
        &font,
    )
    .expect("rasterized image");

    let ink_span = ink_x_max.saturating_sub(ink_x_min).max(1);
    let left_end = ink_x_min + ink_span * 3 / 10;
    let right_start = ink_x_max.saturating_sub(ink_span * 3 / 10);
    let left = average_ink_rgb(&image, ink_x_min, left_end, 8, 90).expect("left ink");
    let right = average_ink_rgb(&image, right_start, ink_x_max, 8, 90).expect("right ink");
    assert!(
        left[0] > left[2] * 1.1,
        "left region should be red dominant, got {left:?}"
    );
    assert!(
        right[2] > right[0] * 1.1,
        "right region should be blue dominant, got {right:?}"
    );
}

#[test]
fn rasterized_stroke_and_fill_ink_coverage_differs() {
    let font = test_font();
    let fill_style = TextStyle::default();
    let stroke_style = TextStyle {
        span_style: SpanStyle {
            draw_style: Some(TextDrawStyle::Stroke { width: 6.0 }),
            ..Default::default()
        },
        ..Default::default()
    };
    let rect = Rect {
        x: 0.0,
        y: 0.0,
        width: 320.0,
        height: 96.0,
    };

    let fill = rasterize_text_to_image_with_font(
        "MMMMMMMM",
        rect,
        &fill_style,
        Color::WHITE,
        48.0,
        1.0,
        &font,
    )
    .expect("fill image");
    let stroke = rasterize_text_to_image_with_font(
        "MMMMMMMM",
        rect,
        &stroke_style,
        Color::WHITE,
        48.0,
        1.0,
        &font,
    )
    .expect("stroke image");

    let fill_ink = count_ink_pixels(&fill);
    let stroke_ink = count_ink_pixels(&stroke);
    assert_ne!(fill.pixels(), stroke.pixels());
    assert!(
        fill_ink.abs_diff(stroke_ink) > 300,
        "fill/stroke ink coverage should differ; fill={fill_ink}, stroke={stroke_ink}"
    );
}

#[test]
fn stroke_path_uses_miter_join_for_acute_apexes() {
    let font = test_font();
    let fill_style = TextStyle::default();
    let stroke_width = 12.0;
    let stroke_style = TextStyle {
        span_style: SpanStyle {
            draw_style: Some(TextDrawStyle::Stroke {
                width: stroke_width,
            }),
            ..Default::default()
        },
        ..Default::default()
    };
    let rect = Rect {
        x: 0.0,
        y: 0.0,
        width: 180.0,
        height: 140.0,
    };

    let fill =
        rasterize_text_to_image_with_font("A", rect, &fill_style, Color::WHITE, 110.0, 1.0, &font)
            .expect("fill image");
    let stroke = rasterize_text_to_image_with_font(
        "A",
        rect,
        &stroke_style,
        Color::WHITE,
        110.0,
        1.0,
        &font,
    )
    .expect("stroke image");

    let fill_top = top_ink_row(&fill).expect("fill top row");
    let stroke_top = top_ink_row(&stroke).expect("stroke top row");
    let reference_dilation =
        rasterize_reference_dilation_stroke("A", rect, 110.0, stroke_width, &font);
    let reference_top = top_ink_row(&reference_dilation).expect("reference top row");
    let extra_extension = fill_top.saturating_sub(stroke_top) as f32;
    let half_stroke = stroke_width * 0.5;
    assert!(
        extra_extension >= half_stroke - 0.25,
        "stroke apex should extend by roughly at least half stroke width; fill_top={fill_top}, stroke_top={stroke_top}, half_stroke={half_stroke:.2}"
    );
    assert!(
        stroke.pixels() != reference_dilation.pixels(),
        "path stroke should diverge from mask-dilation reference output"
    );
    assert!(
        stroke_top <= reference_top,
        "miter stroke should keep acute apex at least as extended as mask-dilation reference; stroke_top={stroke_top}, reference_top={reference_top}"
    );
}

#[test]
fn shadow_blur_radius_changes_spread_for_shared_raster_path() {
    let font = test_font();
    let base_shadow = Shadow {
        color: Color(0.0, 0.0, 0.0, 0.9),
        offset: Point::new(5.5, 4.25),
        blur_radius: 0.0,
    };
    let hard_shadow_style = TextStyle {
        span_style: SpanStyle {
            shadow: Some(base_shadow),
            ..Default::default()
        },
        ..Default::default()
    };
    let blurred_shadow_style = TextStyle {
        span_style: SpanStyle {
            shadow: Some(Shadow {
                blur_radius: 9.0,
                ..base_shadow
            }),
            ..Default::default()
        },
        ..Default::default()
    };
    let rect = Rect {
        x: 0.0,
        y: 0.0,
        width: 320.0,
        height: 120.0,
    };

    let hard_shadow = rasterize_text_to_image_with_font(
        "Shared shadow",
        rect,
        &hard_shadow_style,
        Color::TRANSPARENT,
        48.0,
        1.0,
        &font,
    )
    .expect("hard shadow image");
    let blurred_shadow = rasterize_text_to_image_with_font(
        "Shared shadow",
        rect,
        &blurred_shadow_style,
        Color::TRANSPARENT,
        48.0,
        1.0,
        &font,
    )
    .expect("blurred shadow image");

    let hard_ink = count_ink_pixels(&hard_shadow);
    let blurred_ink = count_ink_pixels(&blurred_shadow);
    assert_ne!(
        hard_shadow.pixels(),
        blurred_shadow.pixels(),
        "blur radius should change rasterized shadow output"
    );
    assert!(
        blurred_ink > hard_ink,
        "blurred shadow should spread to more pixels; hard={hard_ink}, blurred={blurred_ink}"
    );
}

#[test]
fn text_motion_changes_fractional_shadow_sampling() {
    let font = test_font();
    let base_shadow = Shadow {
        color: Color(0.0, 0.0, 0.0, 0.9),
        offset: Point::new(3.35, 2.65),
        blur_radius: 6.0,
    };
    let static_style = TextStyle {
        span_style: SpanStyle {
            shadow: Some(base_shadow),
            ..Default::default()
        },
        paragraph_style: cranpose_ui::text::ParagraphStyle {
            text_motion: Some(TextMotion::Static),
            ..Default::default()
        },
    };
    let animated_style = TextStyle {
        span_style: SpanStyle {
            shadow: Some(base_shadow),
            ..Default::default()
        },
        paragraph_style: cranpose_ui::text::ParagraphStyle {
            text_motion: Some(TextMotion::Animated),
            ..Default::default()
        },
    };
    let rect = Rect {
        x: 11.35,
        y: 7.65,
        width: 280.0,
        height: 120.0,
    };

    let static_image = rasterize_text_to_image_with_font(
        "Motion shadow",
        rect,
        &static_style,
        Color::TRANSPARENT,
        42.0,
        1.0,
        &font,
    )
    .expect("static image");
    let animated_image = rasterize_text_to_image_with_font(
        "Motion shadow",
        rect,
        &animated_style,
        Color::TRANSPARENT,
        42.0,
        1.0,
        &font,
    )
    .expect("animated image");

    assert_ne!(
        static_image.pixels(),
        animated_image.pixels(),
        "TextMotion::Static should quantize shadow placement while Animated keeps fractional sampling"
    );
}

#[test]
fn static_text_motion_aligns_glyph_positions_to_pixel_grid() {
    let font = test_font();
    let base_glyph = layout_line_glyphs(&font, "A", 17.0, point(0.0, 13.37))
        .into_iter()
        .next()
        .expect("glyph");
    let static_aligned = align_glyph_for_text_motion(base_glyph, true);
    let static_position = static_aligned.position;
    assert!(
        (static_position.x - static_position.x.round()).abs() < f32::EPSILON,
        "static text should snap glyph x to pixel grid"
    );
    assert!(
        (static_position.y - static_position.y.round()).abs() < f32::EPSILON,
        "static text should snap glyph y to pixel grid"
    );

    let animated_source = layout_line_glyphs(&font, "A", 17.0, point(0.0, 13.37))
        .into_iter()
        .next()
        .expect("glyph");
    let animated_aligned = align_glyph_for_text_motion(animated_source, false);
    let animated_position = animated_aligned.position;
    assert!(
        (animated_position.y - 13.37).abs() < 1e-3,
        "animated text should preserve fractional glyph position"
    );
}