retroglyph-core 0.6.0

A 2D pseudographic terminal library -- core types, no backend
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
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
use crate::backend::Headless;
use crate::color::Style;
use crate::color::{Color, Tint};
use crate::grid::{Grid, Offset, Pos, Rect};
use crate::terminal::Terminal;
use crate::text::Line;
use crate::tile::Tile;

use super::{Layer, Surface};

fn screen(grid: &mut Grid) -> Surface<'_> {
    let area = grid.size().to_rect();
    Surface::new(grid, area, 0)
}

/// Renders a `'w' x 'h'` block of `ch` at this surface's own local top-left corner, i.e.
/// the way a widget written against `area().at_origin()`/`width()`/`height()` (rather than
/// `area()`'s absolute `left()`/`top()`) is supposed to place itself: correctly regardless
/// of where this surface's own `area` sits on the underlying grid.
fn render_local_top_left(surface: &mut Surface<'_>, ch: char) {
    let local = surface.area().at_origin();
    surface.put((local.left(), local.top()), ch, Style::default());
}

#[test]
fn local_area_is_always_zero_origin_regardless_of_where_area_sits() {
    let mut grid = Grid::new(10, 10);
    let mut surface = screen(&mut grid);
    let scoped = surface.scope(Rect::new(3, 4, 5, 6));

    assert_eq!(scoped.area(), Rect::new(3, 4, 5, 6));
    assert_eq!(scoped.area().at_origin(), Rect::new(0, 0, 5, 6));
}

#[test]
fn a_widget_placed_via_local_area_lands_the_same_way_at_the_origin_and_at_an_offset() {
    // At the grid origin, local and absolute coordinates coincide: this is the case #697
    // warned degenerates into never exercising the mismatch.
    let mut grid_origin = Grid::new(4, 4);
    render_local_top_left(&mut screen(&mut grid_origin), 'X');

    // Scoped away from the origin: a widget built on `area().at_origin()`/`put`'s local
    // coordinate space should draw identically relative to its own area, unlike one built on
    // `area().left()`/`area().top()`, which would silently miss here.
    let mut grid_offset = Grid::new(10, 10);
    {
        let mut surface = screen(&mut grid_offset);
        let mut scoped = surface.scope(Rect::new(3, 3, 4, 4));
        render_local_top_left(&mut scoped, 'X');
    }

    assert_eq!(grid_origin[Pos::new(0, 0)].glyph(), 'X');
    assert_eq!(grid_offset[Pos::new(3, 3)].glyph(), 'X');
}

#[test]
fn blit_reads_the_sources_layer_0_even_when_this_surface_is_on_a_different_layer() {
    // The retroglyph#824 regression: `src` (a standalone, layer-0-only `Grid`, like
    // `BoxStyle::render`'s output) must still land when the destination surface is on a
    // layer other than 0.
    let mut src = Grid::new(2, 2);
    src.put_tile(0, (0, 0), Tile::new('x', Style::default()));

    let mut dst = Grid::new(4, 4);
    let mut surface = Surface::new(&mut dst, Rect::new(0, 0, 4, 4), 0);
    surface.on_layer(3).blit(&src, 1, 1);

    assert_eq!(dst.tile(3, (1, 1)).map(Tile::glyph), Some('x'));
    // Never touched layer 0 (always allocated, but untouched cells stay their default).
    assert_eq!(dst.tile(0, (1, 1)).map(Tile::glyph), Some(' '));
}

#[test]
fn blit_stamps_a_grid_at_a_local_offset() {
    let mut src = Grid::new(2, 2);
    src.put_tile(0, (0, 0), Tile::new('x', Style::default()));
    src.put_tile(0, (1, 1), Tile::new('y', Style::default()));

    let mut dst = Grid::new(5, 5);
    screen(&mut dst).blit(&src, 2, 1);

    assert_eq!(dst[Pos::new(2, 1)].glyph(), 'x');
    assert_eq!(dst[Pos::new(3, 2)].glyph(), 'y');
    // Untouched cells stay whatever the destination started with.
    assert_eq!(dst[Pos::new(0, 0)].glyph(), ' ');
}

#[test]
fn blit_clips_to_this_surfaces_clip_instead_of_skipping_the_whole_call() {
    let mut src = Grid::new(3, 3);
    for y in 0..3 {
        for x in 0..3 {
            src.put_tile(0, (x, y), Tile::new('#', Style::default()));
        }
    }

    let mut dst = Grid::new(5, 5);
    {
        let mut surface = screen(&mut dst);
        // Clip to a 2x2 window starting at (1, 1): only the top-left quadrant of `src`'s
        // footprint at (0, 0) is visible.
        surface.clip(Rect::new(1, 1, 2, 2)).blit(&src, 0, 0);
    }

    assert_eq!(dst[Pos::new(1, 1)].glyph(), '#');
    assert_eq!(dst[Pos::new(2, 2)].glyph(), '#');
    // Outside the clip: never written, even though it's inside `src`'s own footprint.
    assert_eq!(dst[Pos::new(2, 0)].glyph(), ' ');
    assert_eq!(dst[Pos::new(0, 2)].glyph(), ' ');
}

#[test]
fn blit_is_a_no_op_for_a_zero_sized_grid() {
    let src = Grid::new(1, 0);
    let mut dst = Grid::new(4, 4);
    screen(&mut dst).blit(&src, 0, 0);

    assert_eq!(dst[Pos::new(0, 0)].glyph(), ' ');
}

#[test]
fn blit_is_a_no_op_when_the_whole_footprint_is_cropped_before_the_translated_origin() {
    let mut src = Grid::new(2, 2);
    src.put_tile(0, (0, 0), Tile::new('x', Style::default()));

    let mut dst = Grid::new(4, 4);
    {
        let mut surface = screen(&mut dst);
        // Translating by +100 columns shifts `(0, 0)` to local `-100`: the whole 2-wide
        // footprint falls left of the origin, so `crop_left` (100) reaches past `w` (2).
        let mut view = surface.translate((100, 0));
        view.blit(&src, 0, 0);
    }

    assert_eq!(dst[Pos::new(0, 0)].glyph(), ' ');
}

#[test]
fn blit_is_a_no_op_when_the_shifted_x_origin_overflows_u16() {
    let mut src = Grid::new(2, 2);
    src.put_tile(0, (0, 0), Tile::new('x', Style::default()));

    let mut dst = Grid::new(4, 4);
    {
        let mut surface = screen(&mut dst);
        // Translating by -100_000 pushes the shifted local x past `u16::MAX`, which
        // `u16::try_from` refuses (distinct from the ordinary negative-crop path above).
        let mut view = surface.translate((-100_000, 0));
        view.blit(&src, 0, 0);
    }

    assert_eq!(dst[Pos::new(0, 0)].glyph(), ' ');
}

#[test]
fn blit_is_a_no_op_when_the_shifted_y_origin_overflows_u16() {
    let mut src = Grid::new(2, 2);
    src.put_tile(0, (0, 0), Tile::new('x', Style::default()));

    let mut dst = Grid::new(4, 4);
    {
        let mut surface = screen(&mut dst);
        // Same as the x-overflow case above, but on the y axis, which `blit` checks
        // separately (only after the x shift already succeeded).
        let mut view = surface.translate((0, -100_000));
        view.blit(&src, 0, 0);
    }

    assert_eq!(dst[Pos::new(0, 0)].glyph(), ' ');
}

#[test]
fn blit_is_a_no_op_when_the_destination_footprint_misses_the_clip_entirely() {
    let mut src = Grid::new(2, 2);
    src.put_tile(0, (0, 0), Tile::new('x', Style::default()));

    let mut dst = Grid::new(5, 5);
    {
        let mut surface = screen(&mut dst);
        // Clipped to the top-left cell only; the blit lands at (3, 3), whose footprint
        // doesn't overlap the clip at all (unlike the partial-overlap case tested above).
        let mut clipped = surface.clip(Rect::new(0, 0, 1, 1));
        clipped.blit(&src, 3, 3);
    }

    assert_eq!(dst[Pos::new(3, 3)].glyph(), ' ');
}

#[test]
fn put_span_takes_any_as_ref_str_row() {
    use alloc::string::String;
    use alloc::vec::Vec;

    let mut grid = Grid::new(4, 4);
    // A footprint computed at runtime: owned rows, no borrowing pass over them.
    let rows: Vec<String> = (0..2)
        .map(|row| {
            (0..2)
                .map(|col| if (row, col) == (0, 0) { 'C' } else { ' ' })
                .collect()
        })
        .collect();

    assert_eq!(
        screen(&mut grid).put_span((0, 0), &rows, Style::default()),
        Some(())
    );
    assert_eq!(grid[Pos::new(0, 0)].span(), (2, 2));
}

#[test]
fn put_span_reports_why_a_span_did_not_draw() {
    let mut grid = Grid::new(4, 4);
    let area = Rect::new(0, 0, 2, 2);
    let mut surface = Surface::new(&mut grid, area, 0);
    let style = Style::default();

    assert_eq!(surface.put_span((0, 0), &[] as &[&str], style), None);
    assert_eq!(surface.put_span((0, 0), &[""], style), None);
    // Ragged rows are refused by the grid, and that answer is passed through.
    assert_eq!(surface.put_span((0, 0), &["ab", "c"], style), None);
    // Fits the grid, but leaves the surface's own area.
    assert_eq!(surface.put_span((1, 1), &["ab"], style), None);
    assert_eq!(surface.put_span((0, 0), &["ab"], style), Some(()));
}

#[test]
fn put_span_refuses_an_axis_wider_than_255_cells() {
    let mut grid = Grid::new(300, 2);
    let mut surface = screen(&mut grid);
    let row = "a".repeat(256);

    // Fits the surface's own clip (300 columns), but 256 columns is one past what a span's
    // footprint can represent (`Tile` stores each span dimension in a `u8`).
    assert_eq!(
        surface.put_span((0, 0), &[row.as_str()], Style::default()),
        None
    );
    assert_eq!(grid[Pos::new(0, 0)].glyph(), ' ');
}

#[test]
fn put_span_refuses_and_writes_nothing_when_a_later_row_is_longer_than_the_first() {
    let mut grid = Grid::new(4, 4);
    let mut surface = screen(&mut grid);

    // `span_fits` measures the footprint against the first row ("ab", 2 cols) and it fits;
    // `Grid::write_span` is what actually rejects the ragged second row ("abc", 3 cols), so
    // the refusal happens after the fits check has already passed, not before it.
    assert_eq!(
        surface.put_span((0, 0), &["ab", "abc"], Style::default()),
        None
    );
    assert_eq!(grid[Pos::new(0, 0)].glyph(), ' ');
    assert_eq!(grid[Pos::new(0, 1)].glyph(), ' ');
}

#[test]
fn put_span_uniform_writes_the_anchor_once_and_fills_the_rest() {
    let mut grid = Grid::new(4, 4);
    assert_eq!(
        screen(&mut grid).put_span_uniform((1, 1), (2, 2), 'C', '.', Style::default()),
        Some(())
    );

    assert_eq!(grid[Pos::new(1, 1)].glyph(), 'C');
    assert_eq!(grid[Pos::new(1, 1)].span(), (2, 2));
    assert_eq!(grid[Pos::new(2, 2)].glyph(), '.');
    assert_eq!(grid.span_owner(0, 2, 2), Some(Pos::new(1, 1)));
}

#[test]
fn put_span_uniform_writes_to_this_surfaces_layer() {
    let mut grid = Grid::new(4, 4);
    {
        let mut surface = screen(&mut grid);
        surface
            .on_layer(2)
            .put_span_uniform((0, 0), (2, 1), 'C', ' ', Style::default())
            .expect("span write");
    }

    assert_eq!(grid.span_owner(2, 1, 0), Some(Pos::new(0, 0)));
    assert_eq!(grid.span_owner(0, 1, 0), None);
}

#[test]
fn put_span_uniform_refuses_a_footprint_that_leaves_the_surfaces_area() {
    let mut grid = Grid::new(4, 4);
    let area = Rect::new(0, 0, 2, 2);
    let mut surface = Surface::new(&mut grid, area, 0);
    let style = Style::default();

    // Both fit the grid; neither fits the area.
    assert_eq!(
        surface.put_span_uniform((1, 0), (2, 1), 'C', ' ', style),
        None
    );
    assert_eq!(
        surface.put_span_uniform((0, 1), (1, 2), 'C', ' ', style),
        None
    );
    assert_eq!(
        surface.put_span_uniform((0, 0), (0, 1), 'C', ' ', style),
        None
    );
    assert_eq!(
        surface.put_span_uniform((0, 0), (2, 2), 'C', ' ', style),
        Some(())
    );
}

#[test]
fn styled_surface_forwards_both_span_calls() {
    let mut grid = Grid::new(4, 4);
    {
        let mut surface = screen(&mut grid);
        let mut styled = surface.with_style(Style::new().fg(Color::RED));
        styled.put_span((0, 0), &["ab"]).expect("span write");
        styled
            .put_span_uniform((0, 1), (2, 1), 'C', ' ')
            .expect("span write");
    }

    assert_eq!(grid[Pos::new(0, 0)].style().foreground(), Color::RED);
    assert_eq!(grid[Pos::new(0, 1)].style().foreground(), Color::RED);
    assert_eq!(grid[Pos::new(0, 1)].span(), (2, 1));
}

#[test]
fn styled_surface_forwards_put_print_fill_rect_and_put_offset() {
    let style = Style::new().fg(Color::RED);
    let mut grid = Grid::new(6, 4);
    {
        let mut surface = screen(&mut grid);
        let mut styled = surface.with_style(style);
        assert_eq!(styled.style(), style);

        styled.put((0, 0), 'a');
        styled.print((1, 0), "bc");
        styled.fill_rect(Rect::new(0, 1, 2, 1), '#');
        styled.put_offset((0, 2), Offset::new(3, -3), 'x');
        // `surface()` reaches back to the underlying `Surface` for a call `StyledSurface`
        // doesn't expose, e.g. `print_line`'s per-span styles.
        styled.surface().print_line((0, 3), &Line::from("d"));
    }

    assert_eq!(grid[Pos::new(0, 0)].glyph(), 'a');
    assert_eq!(grid[Pos::new(0, 0)].style().foreground(), Color::RED);
    assert_eq!(grid[Pos::new(1, 0)].glyph(), 'b');
    assert_eq!(grid[Pos::new(2, 0)].glyph(), 'c');
    assert_eq!(grid[Pos::new(0, 1)].glyph(), '#');
    assert_eq!(grid[Pos::new(1, 1)].glyph(), '#');
    let tile = grid.tile(0, Pos::new(0, 2)).unwrap();
    assert_eq!((tile.dx(), tile.dy()), (3, -3));
    assert_eq!(grid[Pos::new(0, 3)].glyph(), 'd');
}

#[test]
fn with_tint_applies_to_the_cell_it_writes() {
    let mut grid = Grid::new(4, 4);
    {
        let mut surface = screen(&mut grid);
        surface
            .with_tint(Tint::multiply(128, 64, 32))
            .put((1, 1), '@', Style::default());
    }

    assert_eq!(grid[Pos::new(1, 1)].glyph(), '@');
    assert_eq!(grid.tint(0, 1, 1), Tint::multiply(128, 64, 32));
}

#[test]
fn an_untinted_surface_leaves_the_side_table_alone() {
    let mut grid = Grid::new(4, 4);
    screen(&mut grid).put((1, 1), '@', Style::default());

    assert_eq!(grid.tint(0, 1, 1), Tint::None);
}

/// `fill_rect`'s batch fast path only applies when the surface is untinted: a tinted surface
/// must fall back to the per-cell loop, or every cell `fill_rect` touches would silently lose
/// its tint.
#[test]
fn with_tint_applies_to_every_cell_fill_rect_touches() {
    let mut grid = Grid::new(4, 4);
    {
        let mut surface = screen(&mut grid);
        surface.with_tint(Tint::multiply(128, 64, 32)).fill_rect(
            Rect::new(1, 1, 2, 2),
            '#',
            Style::default(),
        );
    }

    for (x, y) in [(1, 1), (2, 1), (1, 2), (2, 2)] {
        assert_eq!(grid[Pos::new(x, y)].glyph(), '#');
        assert_eq!(grid.tint(0, x, y), Tint::multiply(128, 64, 32));
    }
}

/// `fill_rect`'s batch fast path only applies to a single-column glyph: a wide glyph must
/// fall back to the per-cell `put` loop, not the batch `Tile::new` write (which carries no
/// wide-char bookkeeping at all).
#[test]
fn fill_rect_with_a_wide_glyph_falls_back_to_the_put_loop() {
    let rect = Rect::new(0, 0, 6, 1);

    let mut via_fill_rect = Grid::new(8, 1);
    screen(&mut via_fill_rect).fill_rect(rect, '\u{6f22}', Style::default());

    let mut via_put = Grid::new(8, 1);
    {
        let mut surface = screen(&mut via_put);
        for pos in rect {
            surface.put(pos, '\u{6f22}', Style::default());
        }
    }

    for x in 0..8 {
        assert_eq!(
            via_fill_rect[Pos::new(x, 0)],
            via_put[Pos::new(x, 0)],
            "cell ({x}, 0)"
        );
    }
}

/// A translated view's `fill_rect`/`clear_region` fallback loop must clip to this surface's own
/// bounds before iterating, not iterate the caller's full `rect`: a `rect` far larger than the
/// area (the documented "fill the world rect and let the surface clip" camera idiom) would
/// otherwise run billions of no-op iterations. See retroglyph#1000.
#[test]
fn translated_fill_rect_and_clear_region_clip_a_rect_much_larger_than_the_area() {
    let mut grid = Grid::new(4, 4);
    {
        let mut surface = screen(&mut grid);
        let mut view = surface.translate((1, 1));
        view.fill_rect(Rect::new(0, 0, 60_000, 60_000), '#', Style::default());
    }
    for y in 0..4 {
        for x in 0..4 {
            assert_eq!(grid[Pos::new(x, y)].glyph(), '#', "cell ({x}, {y})");
        }
    }

    let mut grid = Grid::new(4, 4);
    {
        let mut surface = screen(&mut grid);
        surface.fill_rect(Rect::new(0, 0, 4, 4), '#', Style::default());
        let mut view = surface.translate((1, 1));
        view.clear_region(Rect::new(0, 0, 60_000, 60_000));
    }
    for y in 0..4 {
        for x in 0..4 {
            assert_eq!(grid[Pos::new(x, y)].glyph(), ' ', "cell ({x}, {y})");
        }
    }
}

/// A tinted surface's `fill_rect` fallback loop must clip to this surface's own bounds before
/// iterating, not iterate the caller's full `rect`. See retroglyph#1000.
#[test]
fn tinted_fill_rect_clips_a_rect_much_larger_than_the_area() {
    let mut grid = Grid::new(4, 4);
    {
        let mut surface = screen(&mut grid);
        surface.with_tint(Tint::multiply(128, 64, 32)).fill_rect(
            Rect::new(0, 0, 60_000, 60_000),
            '#',
            Style::default(),
        );
    }
    for y in 0..4 {
        for x in 0..4 {
            assert_eq!(grid[Pos::new(x, y)].glyph(), '#', "cell ({x}, {y})");
            assert_eq!(
                grid.tint(0, x, y),
                Tint::multiply(128, 64, 32),
                "cell ({x}, {y})"
            );
        }
    }
}

/// A wide-glyph `fill_rect` fallback loop must clip to this surface's own bounds before
/// iterating, not iterate the caller's full `rect`. See retroglyph#1000.
#[test]
fn wide_glyph_fill_rect_clips_a_rect_much_larger_than_the_area() {
    let mut via_fill_rect = Grid::new(4, 4);
    screen(&mut via_fill_rect).fill_rect(
        Rect::new(0, 0, 60_000, 60_000),
        '\u{6f22}',
        Style::default(),
    );

    // Same expectation as `fill_rect_with_a_wide_glyph_falls_back_to_the_put_loop`: a
    // rect-clipped-to-the-area `put` loop, not "every cell holds the glyph" (a 2-column glyph
    // overwrites every other cell's spacer as the loop advances).
    let mut via_put = Grid::new(4, 4);
    {
        let mut surface = screen(&mut via_put);
        for y in 0..4 {
            for x in 0..4 {
                surface.put((x, y), '\u{6f22}', Style::default());
            }
        }
    }

    for y in 0..4 {
        for x in 0..4 {
            assert_eq!(
                via_fill_rect[Pos::new(x, y)],
                via_put[Pos::new(x, y)],
                "cell ({x}, {y})"
            );
        }
    }
}

/// `fill_rect`, `clear`, and `clear_region` all route through `Grid::fill_region`, which must
/// clear any span the fill partially overwrites the same way the per-cell loop it replaced
/// did, or the surviving span's anchor would keep claiming cells the fill just overwrote.
#[test]
fn fill_rect_clears_a_span_it_partially_overwrites() {
    use crate::tile::TileFlags;

    let mut grid = Grid::new(4, 4);
    {
        let mut surface = screen(&mut grid);
        surface
            .put_span((0, 0), &["C=", "[]"], Style::default())
            .expect("2x2 span fits in a 4x4 grid");
        surface.fill_rect(Rect::new(1, 0, 3, 3), '#', Style::default());
    }

    assert!(
        !grid
            .tile(0, (0, 0))
            .unwrap()
            .flags()
            .contains(TileFlags::SPAN_ANCHOR)
    );
}

#[test]
fn clear_region_clears_a_span_it_partially_overwrites() {
    use crate::tile::TileFlags;

    let mut grid = Grid::new(4, 4);
    {
        let mut surface = screen(&mut grid);
        surface
            .put_span((0, 0), &["C=", "[]"], Style::default())
            .expect("2x2 span fits in a 4x4 grid");
        surface.clear_region(Rect::new(1, 0, 3, 3));
    }

    assert!(
        !grid
            .tile(0, (0, 0))
            .unwrap()
            .flags()
            .contains(TileFlags::SPAN_ANCHOR)
    );
}

#[test]
fn fill_rect_with_a_zero_sized_rect_is_a_no_op() {
    let mut grid = Grid::new(4, 4);
    {
        let mut surface = screen(&mut grid);
        surface.fill_rect(Rect::new(1, 1, 0, 3), '#', Style::default());
        surface.fill_rect(Rect::new(1, 1, 3, 0), '#', Style::default());
    }

    for y in 0..4 {
        for x in 0..4 {
            assert_eq!(grid[Pos::new(x, y)].glyph(), ' ', "cell ({x}, {y})");
        }
    }
}

#[test]
fn clear_region_with_a_zero_sized_rect_is_a_no_op() {
    let mut grid = Grid::new(4, 4);
    {
        let mut surface = screen(&mut grid);
        surface.fill_rect(Rect::new(0, 0, 4, 4), '#', Style::default());
        surface.clear_region(Rect::new(1, 1, 0, 2));
        surface.clear_region(Rect::new(1, 1, 2, 0));
    }

    for y in 0..4 {
        for x in 0..4 {
            assert_eq!(grid[Pos::new(x, y)].glyph(), '#', "cell ({x}, {y})");
        }
    }
}

#[test]
fn with_tint_lands_on_the_span_anchor_only() {
    let mut grid = Grid::new(4, 4);
    {
        let mut surface = screen(&mut grid);
        surface
            .with_tint(Tint::multiply(200, 200, 200))
            .put_span((0, 0), &["ab", "cd"], Style::default())
            .expect("span write");
    }

    // A pixel backend draws the whole footprint from the anchor, so that is the only cell
    // with a sprite to recolour.
    assert_eq!(grid.tint(0, 0, 0), Tint::multiply(200, 200, 200));
    assert_eq!(grid.tint(0, 1, 0), Tint::None);
    assert_eq!(grid.tint(0, 1, 1), Tint::None);
}

#[test]
fn with_tint_applies_to_a_uniform_span_anchor() {
    let mut grid = Grid::new(4, 4);
    {
        let mut surface = screen(&mut grid);
        surface
            .with_tint(Tint::mix(255, 0, 0, 128))
            .put_span_uniform((1, 1), (2, 2), 'C', '.', Style::default())
            .expect("span write");
    }

    assert_eq!(grid.tint(0, 1, 1), Tint::mix(255, 0, 0, 128));
    assert_eq!(grid.tint(0, 2, 2), Tint::None);
}

#[test]
fn with_tint_is_not_applied_to_a_refused_span() {
    let mut grid = Grid::new(4, 4);
    let area = Rect::new(0, 0, 2, 2);
    {
        let mut surface = Surface::new(&mut grid, area, 0);
        // Fits the grid, leaves the area: nothing is written, so nothing is tinted.
        assert_eq!(
            surface
                .with_tint(Tint::multiply(1, 2, 3))
                .put_span((1, 1), &["ab"], Style::default()),
            None
        );
    }

    assert_eq!(grid.tint(0, 1, 1), Tint::None);
}

#[test]
fn with_tint_survives_clip_and_on_layer() {
    let mut grid = Grid::new(8, 4);
    {
        let mut surface = screen(&mut grid);
        let mut tinted = surface.with_tint(Tint::multiply(9, 9, 9));
        assert_eq!(tinted.tint(), Tint::multiply(9, 9, 9));
        assert_eq!(
            tinted.clip(Rect::new(0, 0, 4, 4)).tint(),
            Tint::multiply(9, 9, 9)
        );
        assert_eq!(tinted.on_layer(2).tint(), Tint::multiply(9, 9, 9));

        tinted.on_layer(2).put((1, 1), '@', Style::default());
    }

    assert_eq!(grid.tint(2, 1, 1), Tint::multiply(9, 9, 9));
}

#[test]
fn with_tint_on_a_write_outside_the_clip_does_not_allocate_the_layer() {
    // retroglyph#1012: the tint is only applied after a write actually lands (see
    // `apply_tint`'s own doc comment), so a tinted write refused by the clip must not touch a
    // layer it never wrote to, on a layer that has never been allocated before.
    let mut grid = Grid::new(4, 4);
    {
        let mut surface = screen(&mut grid);
        surface
            .on_layer(7)
            .with_tint(Tint::multiply(9, 9, 9))
            .clip(Rect::new(0, 0, 2, 2))
            .put((10, 10), '@', Style::default());
    }
    assert_eq!(grid.max_layer(), 0);
    assert!(grid.tile(7, (0, 0)).is_none());
}

#[test]
fn with_tint_replaces_rather_than_composes() {
    let mut grid = Grid::new(4, 4);
    {
        let mut surface = screen(&mut grid);
        let mut outer = surface.with_tint(Tint::multiply(128, 128, 128));
        // Unlike `clip`, a nested tint substitutes: two tints have no meaningful product.
        outer
            .with_tint(Tint::mix(255, 0, 0, 64))
            .put((0, 0), '@', Style::default());
    }

    assert_eq!(grid.tint(0, 0, 0), Tint::mix(255, 0, 0, 64));
}

#[test]
fn clip_narrows_the_visible_rect_but_not_the_area() {
    let mut grid = Grid::new(8, 4);
    let area = Rect::new(0, 0, 8, 4);
    let mut surface = screen(&mut grid);
    let sub = surface.clip(Rect::new(2, 1, 4, 2));

    assert_eq!(sub.clip_rect(), Rect::new(2, 1, 4, 2));
    // `area` reports what the surface represents, unaffected by `clip`.
    assert_eq!(sub.area(), area);
    assert_eq!(sub.width(), 8);
    assert_eq!(sub.height(), 4);
}

#[test]
fn clip_keeps_the_layer() {
    let mut grid = Grid::new(4, 4);
    let mut surface = screen(&mut grid);
    let mut layer1 = surface.on_layer(1);

    assert_eq!(layer1.clip(Rect::new(0, 0, 2, 2)).layer(), 1);
}

#[test]
fn layer_variants_order_low_to_high() {
    assert!(Layer::World < Layer::Hud);
    assert!(Layer::Hud < Layer::Overlay);
    assert!(Layer::Overlay < Layer::Debug);
}

#[test]
fn layer_as_u8_matches_the_documented_grid_layer_ids() {
    assert_eq!(Layer::World.as_u8(), 0);
    assert_eq!(Layer::Hud.as_u8(), 1);
    assert_eq!(Layer::Overlay.as_u8(), 2);
    assert_eq!(Layer::Debug.as_u8(), 3);
}

#[test]
fn layer_default_is_world() {
    assert_eq!(Layer::default(), Layer::World);
}

#[test]
fn layer_into_u8_matches_as_u8() {
    assert_eq!(u8::from(Layer::Overlay), Layer::Overlay.as_u8());
}

#[test]
fn on_tier_matches_on_layer_with_the_tiers_u8() {
    let mut grid = Grid::new(4, 4);
    let mut surface = screen(&mut grid);

    assert_eq!(surface.on_tier(Layer::Overlay).layer(), 2);
    assert_eq!(
        surface.on_layer(2).layer(),
        surface.on_tier(Layer::Overlay).layer()
    );
}

#[test]
fn on_tier_writes_land_on_the_tiers_grid_layer() {
    let mut grid = Grid::new(4, 4);
    {
        let mut surface = screen(&mut grid);
        surface
            .on_tier(Layer::Overlay)
            .put((0, 0), '@', Style::default());
    }

    assert_eq!(grid.tile(2, Pos::new(0, 0)).map(Tile::glyph), Some('@'));
    // Untouched on lower tiers: `on_tier` switches layers, it doesn't also write there.
    // Layer 0 is always allocated (empty), layer 1 was never written so stays unallocated.
    assert_eq!(grid.tile(0, Pos::new(0, 0)).map(Tile::glyph), Some(' '));
    assert_eq!(grid.tile(1, Pos::new(0, 0)), None);
}

#[test]
fn a_wide_char_at_the_clip_edge_refuses_to_write_its_spacer_outside_the_clip() {
    let mut grid = Grid::new(8, 1);
    let mut surface = Surface::new(&mut grid, Rect::new(0, 0, 8, 1), 0);

    // Clip is columns 0..4; the wide char's primary cell (column 3) is inside the clip, but
    // its spacer would land at column 4, outside it. The whole write is refused.
    surface
        .clip(Rect::new(0, 0, 4, 1))
        .put((3, 0), '\u{6f22}', Style::default());

    assert_eq!(grid.tile(0, Pos::new(3, 0)).map(Tile::glyph), Some(' '));
    assert!(
        !grid
            .tile(0, Pos::new(4, 0))
            .is_some_and(|t| t.flags().contains(crate::tile::TileFlags::WIDE_CHAR_SPACER)),
        "spacer must not be written outside the clip"
    );
}

// Gated to the non-egc build: under `egc`, `put`/`put_signed` go through `write_grapheme_at`
// instead of `Grid::put_tile`, which has the same unfixed shape (retroglyph#1045 only covers
// the non-egc branches, matching #998's own scope for `put_offset`).
#[test]
#[cfg(not(feature = "egc"))]
fn put_does_not_tint_a_foreign_tile_when_put_tile_refuses_the_write() {
    // Unlike the clip-edge test above, `wide_spacer_fits` only refuses a write when the
    // *clip* excludes the spacer column; here the clip is wider than the grid itself, so
    // `wide_spacer_fits` passes and it is `Grid::put_tile`'s own last-column refusal
    // (retroglyph#1045) that has to stop `apply_tint` from re-tinting the existing tile.
    let mut grid = Grid::new(4, 1);
    {
        let mut surface = Surface::new(&mut grid, Rect::new(0, 0, 8, 1), 0);
        surface
            .with_tint(Tint::multiply(128, 64, 32))
            .put((3, 0), 'X', Style::default());
        surface
            .with_tint(Tint::multiply(1, 2, 3))
            .put((3, 0), '\u{6f22}', Style::default());
    }

    assert_eq!(grid[Pos::new(3, 0)].glyph(), 'X');
    assert_eq!(grid.tint(0, 3, 0), Tint::multiply(128, 64, 32));
}

// egc counterpart of the non-egc test above (retroglyph#1090): under `egc`, `put` goes through
// `write_grapheme_at`/`Grid::write_grapheme` instead of `Grid::put_tile`, which had the same
// unfixed shape. As above, the clip is wider than the grid, so `wide_spacer_fits` passes and it
// is `Grid::write_grapheme`'s own out-of-bounds refusal that has to stop `apply_tint` from
// re-tinting the existing tile.
#[test]
#[cfg(feature = "egc")]
fn put_does_not_tint_a_foreign_tile_when_write_grapheme_refuses_the_write() {
    let mut grid = Grid::new(4, 1);
    {
        let mut surface = Surface::new(&mut grid, Rect::new(0, 0, 8, 1), 0);
        surface
            .with_tint(Tint::multiply(128, 64, 32))
            .put((3, 0), 'X', Style::default());
        surface
            .with_tint(Tint::multiply(1, 2, 3))
            .put((3, 0), '\u{6f22}', Style::default());
    }

    assert_eq!(grid[Pos::new(3, 0)].glyph(), 'X');
    assert_eq!(grid.tint(0, 3, 0), Tint::multiply(128, 64, 32));
}

#[test]
fn clip_intersects_rather_than_replaces_so_it_cannot_widen() {
    let mut grid = Grid::new(8, 4);
    let area = Rect::new(2, 1, 4, 2);
    let mut surface = Surface::new(&mut grid, area, 0);

    // A rect reaching outside the surface's own clip only ever tightens it.
    assert_eq!(surface.clip(Rect::new(0, 0, 8, 4)).clip_rect(), area);
    assert_eq!(
        surface.clip(Rect::new(0, 0, 4, 4)).clip_rect(),
        Rect::new(2, 1, 2, 2)
    );
}

#[test]
fn clip_does_not_widen_the_visible_region_after_scope_narrows_it() {
    let mut grid = Grid::new(8, 4);
    let mut surface = screen(&mut grid);
    let mut scoped = surface.scope(Rect::new(1, 1, 2, 2));

    // `clip` on an already-scoped surface can only tighten what was already visible, even
    // when asked for a rect that reaches back out past it.
    assert_eq!(
        scoped.clip(Rect::new(0, 0, 8, 4)).clip_rect(),
        Rect::new(1, 1, 2, 2)
    );
}

#[test]
fn scope_sets_the_area_and_intersects_the_clip() {
    let mut grid = Grid::new(8, 4);
    let mut surface = screen(&mut grid);
    let mut clipped = surface.clip(Rect::new(0, 0, 4, 4));

    // `scope` widens `area` to a rect the parent's clip does not fully cover...
    let scoped = clipped.scope(Rect::new(2, 0, 4, 4));
    assert_eq!(scoped.area(), Rect::new(2, 0, 4, 4));
    // ...but the visible region still cannot exceed the parent's own clip.
    assert_eq!(scoped.clip_rect(), Rect::new(2, 0, 2, 4));
}

#[test]
fn scope_inside_a_clipped_surface_cannot_widen_the_visible_region() {
    let mut grid = Grid::new(8, 4);
    let mut surface = screen(&mut grid);
    let mut clipped = surface.clip(Rect::new(2, 1, 2, 2));

    // Even a `scope` rect that reaches well outside the parent's clip only ever tightens
    // what is visible; `area` still becomes exactly the requested rect.
    let scoped = clipped.scope(Rect::new(0, 0, 8, 4));
    assert_eq!(scoped.area(), Rect::new(0, 0, 8, 4));
    assert_eq!(scoped.clip_rect(), Rect::new(2, 1, 2, 2));
}

#[test]
fn scope_writes_outside_the_inherited_clip_are_dropped() {
    let mut grid = Grid::new(8, 4);
    {
        let mut surface = screen(&mut grid);
        let mut clipped = surface.clip(Rect::new(0, 0, 4, 4));
        let mut scoped = clipped.scope(Rect::new(0, 0, 8, 4));
        // Inside the requested `area`, outside the inherited clip.
        scoped.put((5, 0), 'a', Style::default());
        scoped.put((1, 0), 'b', Style::default());
    }

    assert_eq!(grid[Pos::new(5, 0)].glyph(), ' ');
    assert_eq!(grid[Pos::new(1, 0)].glyph(), 'b');
}

#[test]
fn clip_writes_outside_the_sub_rect_are_dropped() {
    let mut grid = Grid::new(4, 2);
    {
        let mut surface = screen(&mut grid);
        let mut top = surface.clip(Rect::new(0, 0, 4, 1));
        top.put((1, 0), 'a', Style::default());
        // Inside the surface's own area, outside the clip.
        top.put((1, 1), 'b', Style::default());
    }

    assert_eq!(grid[Pos::new(1, 0)].glyph(), 'a');
    assert_eq!(grid[Pos::new(1, 1)].glyph(), ' ');
}

#[test]
fn clip_to_one_row_drops_print_overflow_instead_of_wrapping_it() {
    let mut grid = Grid::new(4, 2);
    {
        let mut surface = screen(&mut grid);
        surface
            .clip(Rect::new(0, 0, 4, 1))
            .print((0, 0), "abcdef", Style::default());
    }

    assert_eq!(grid[Pos::new(3, 0)].glyph(), 'd');
    // "ef" wrapped onto row 1, which the clip excludes.
    assert_eq!(grid[Pos::new(0, 1)].glyph(), ' ');
}

#[test]
fn print_wraps_at_the_surfaces_own_width_not_at_clip_right() {
    // `area` starts at column 4, so the surface-local wrap column (4) is smaller than the
    // absolute grid column `clip.right()` resolves to (8). Wrapping must use the former.
    let mut grid = Grid::new(8, 2);
    let mut surface = Surface::new(&mut grid, Rect::new(4, 0, 4, 2), 0);
    surface.print((0, 0), "abcdef", Style::default());

    assert_eq!(grid[Pos::new(4, 0)].glyph(), 'a');
    assert_eq!(grid[Pos::new(7, 0)].glyph(), 'd');
    assert_eq!(grid[Pos::new(4, 1)].glyph(), 'e');
    assert_eq!(grid[Pos::new(5, 1)].glyph(), 'f');
}

#[test]
fn print_advances_past_an_embedded_newline_to_the_next_row_at_the_original_column() {
    let mut grid = Grid::new(4, 4);
    let mut surface = Surface::new(&mut grid, Rect::new(1, 0, 3, 4), 0);
    surface.print((0, 0), "ab\ncd", Style::default());

    // "ab" on row 0 starting at local column 0 (absolute column 1).
    assert_eq!(grid[Pos::new(1, 0)].glyph(), 'a');
    assert_eq!(grid[Pos::new(2, 0)].glyph(), 'b');
    // The embedded "\n" resets to the original local column (0) on the next row, not to
    // wherever "ab" left off.
    assert_eq!(grid[Pos::new(1, 1)].glyph(), 'c');
    assert_eq!(grid[Pos::new(2, 1)].glyph(), 'd');
    assert_eq!(grid[Pos::new(3, 1)].glyph(), ' ');
}

#[test]
fn print_skips_a_leading_zero_width_grapheme_without_writing_or_advancing_the_column() {
    let mut grid = Grid::new(4, 1);
    screen(&mut grid).print((0, 0), "\u{0301}ab", Style::default());

    // A combining mark with no preceding base character to attach to is its own extended
    // grapheme cluster (`egc`) / `char` (otherwise), and either way `unicode-width` reports
    // it as 0 columns wide, so it must be skipped instead of writing a cell or advancing
    // past column 0, matching `w == 0` in both `print_egc` and `print_chars`.
    assert_eq!(grid[Pos::new(0, 0)].glyph(), 'a');
    assert_eq!(grid[Pos::new(1, 0)].glyph(), 'b');
    assert_eq!(grid[Pos::new(2, 0)].glyph(), ' ');
}

#[test]
fn print_line_measures_its_span_skip_threshold_against_the_surfaces_own_width() {
    // `area` starts at column 4, so the surface-local skip column (4) is smaller than the
    // absolute grid column `clip.right()` resolves to (8). The second span starts at local
    // column 3, which is inside the 4-wide area, so it must still print.
    use crate::text::Span;
    use alloc::vec;

    let mut grid = Grid::new(8, 1);
    let mut surface = Surface::new(&mut grid, Rect::new(4, 0, 4, 1), 0);
    let line = Line::from(vec![Span::raw("ab"), Span::raw("cd")]);
    surface.print_line((0, 0), &line);

    assert_eq!(grid[Pos::new(4, 0)].glyph(), 'a');
    assert_eq!(grid[Pos::new(5, 0)].glyph(), 'b');
    assert_eq!(grid[Pos::new(6, 0)].glyph(), 'c');
    assert_eq!(grid[Pos::new(7, 0)].glyph(), 'd');
}

#[test]
fn clip_makes_put_span_measure_its_footprint_against_the_sub_rect() {
    let mut grid = Grid::new(4, 3);
    {
        let mut surface = screen(&mut grid);
        // Fits the grid, but reserves a cell on the bottom row the clip excludes.
        surface
            .clip(Rect::new(0, 0, 4, 2))
            .put_span((0, 1), &["ab", "cd"], Style::default());
    }

    assert_eq!(grid[Pos::new(0, 1)].glyph(), ' ');

    let mut surface = screen(&mut grid);
    surface
        .clip(Rect::new(0, 0, 4, 2))
        .put_span((0, 0), &["ab", "cd"], Style::default());

    assert_eq!(grid[Pos::new(0, 0)].span(), (2, 2));
}

#[test]
fn clip_makes_put_span_uniform_measure_its_footprint_against_the_sub_rect() {
    let mut grid = Grid::new(4, 3);
    let style = Style::default();
    {
        let mut surface = screen(&mut grid);
        let mut content = surface.clip(Rect::new(0, 0, 4, 2));
        // Fits the grid, but reserves a cell on the bottom row the clip excludes.
        assert_eq!(
            content.put_span_uniform((0, 1), (2, 2), 'C', '.', style),
            None
        );
        assert_eq!(
            content.put_span_uniform((0, 0), (2, 2), 'C', '.', style),
            Some(())
        );
    }

    assert_eq!(grid[Pos::new(0, 0)].span(), (2, 2));
    assert_eq!(grid[Pos::new(0, 2)].glyph(), ' ');
}

#[test]
fn clip_to_a_disjoint_rect_is_empty_and_drops_every_write() {
    let mut grid = Grid::new(8, 4);
    {
        let mut surface = Surface::new(&mut grid, Rect::new(0, 0, 4, 4), 0);
        let mut sub = surface.clip(Rect::new(4, 0, 4, 4));
        assert_eq!(sub.clip_rect(), Rect::EMPTY);
        sub.print((0, 0), "abc", Style::default());
    }

    assert_eq!(grid[Pos::new(0, 0)].glyph(), ' ');
}

#[test]
fn clip_to_a_zero_width_rect_is_empty_and_drops_every_write() {
    let mut grid = Grid::new(4, 4);
    {
        let mut surface = screen(&mut grid);
        let mut sub = surface.clip(Rect::new(1, 1, 0, 2));
        assert_eq!(sub.clip_rect(), Rect::EMPTY);
        sub.put((1, 1), 'X', Style::default());
    }

    assert_eq!(grid[Pos::new(1, 1)].glyph(), ' ');
}

#[test]
fn scope_to_a_zero_height_rect_is_empty_and_drops_every_write() {
    let mut grid = Grid::new(4, 4);
    {
        let mut surface = screen(&mut grid);
        let mut sub = surface.scope(Rect::new(1, 1, 2, 0));
        assert_eq!(sub.area(), Rect::new(1, 1, 2, 0));
        assert_eq!(sub.clip_rect(), Rect::EMPTY);
        sub.put((0, 0), 'X', Style::default());
    }

    assert_eq!(grid[Pos::new(1, 1)].glyph(), ' ');
}

#[test]
fn print_with_an_empty_string_is_a_no_op() {
    let mut grid = Grid::new(4, 4);
    screen(&mut grid).print((0, 0), "", Style::default());

    for y in 0..4 {
        for x in 0..4 {
            assert_eq!(grid[Pos::new(x, y)].glyph(), ' ', "cell ({x}, {y})");
        }
    }
}

#[test]
fn print_line_with_an_empty_line_is_a_no_op() {
    let mut grid = Grid::new(4, 4);
    screen(&mut grid).print_line((0, 0), &Line::default());

    assert_eq!(grid[Pos::new(0, 0)].glyph(), ' ');
}

#[test]
fn print_and_fill_rect_are_no_ops_on_a_surface_with_an_empty_area() {
    let mut grid = Grid::new(4, 4);
    {
        let mut surface = Surface::new(&mut grid, Rect::EMPTY, 0);
        surface.print((0, 0), "hi", Style::default());
        surface.fill_rect(Rect::new(0, 0, 4, 4), '#', Style::default());
    }

    for y in 0..4 {
        for x in 0..4 {
            assert_eq!(grid[Pos::new(x, y)].glyph(), ' ', "cell ({x}, {y})");
        }
    }
}

#[test]
fn put_signed_drops_a_negative_coordinate() {
    let mut grid = Grid::new(4, 4);
    let mut surface = screen(&mut grid);

    surface.put_signed((-1, 0), 'X', Style::default());
    surface.put_signed((0, -1), 'X', Style::default());

    assert_eq!(grid[Pos::new(0, 0)].glyph(), ' ');
}

#[test]
fn put_signed_lands_a_valid_coordinate_at_the_area_origin() {
    let mut grid = Grid::new(4, 4);
    let area = Rect::new(1, 1, 2, 2);
    let mut surface = Surface::new(&mut grid, area, 0);

    // (0, 0) relative to the area's own origin is grid position (1, 1).
    surface.put_signed((0, 0), 'X', Style::default());

    assert_eq!(grid[Pos::new(1, 1)].glyph(), 'X');
}

#[test]
fn put_signed_drops_a_coordinate_past_this_surfaces_width_or_height() {
    let mut grid = Grid::new(4, 4);
    let area = Rect::new(0, 0, 2, 2);
    let mut surface = Surface::new(&mut grid, area, 0);

    // Fits the grid, but not this surface's own (relative) width/height.
    surface.put_signed((2, 0), 'X', Style::default());
    surface.put_signed((0, 2), 'X', Style::default());

    assert_eq!(grid[Pos::new(2, 0)].glyph(), ' ');
    assert_eq!(grid[Pos::new(0, 2)].glyph(), ' ');
}

#[test]
fn put_signed_drops_a_coordinate_whose_shifted_offset_overflows_u16() {
    let mut grid = Grid::new(4, 4);
    let mut surface = screen(&mut grid);

    // Non-negative (so it clears the `x < 0` check first), but still far past `u16::MAX`
    // once shifted by `origin_offset`: `u16::try_from` refuses it, distinct from the
    // plain-negative path tested above.
    surface.put_signed((100_000, 0), 'X', Style::default());

    assert_eq!(grid[Pos::new(0, 0)].glyph(), ' ');
}

#[test]
fn put_signed_drops_a_coordinate_inside_area_but_outside_a_narrower_clip() {
    let mut grid = Grid::new(4, 4);
    {
        let mut surface = screen(&mut grid);
        // (3, 0) fits this surface's own (4x4) width/height, but the clip narrows visibility
        // to the first 2 columns: the final `clip.contains` check rejects it, distinct from
        // the width/height check above.
        surface
            .clip(Rect::new(0, 0, 2, 4))
            .put_signed((3, 0), 'X', Style::default());
    }

    assert_eq!(grid[Pos::new(3, 0)].glyph(), ' ');
}

// Not gated behind `egc`: `Tile::new` sets `WIDE_CHAR`/`WIDE_CHAR_SPACER` on every feature
// combination (unlike the clip-edge tests above, this bookkeeping goes through
// `Grid::put_tile` either way, not through the `egc`-only grapheme path).
#[test]
fn put_signed_does_wide_char_bookkeeping_like_put() {
    use crate::tile::TileFlags;

    let mut grid = Grid::new(8, 2);
    {
        let mut surface = screen(&mut grid);

        // A wide char via `put`: primary at (0, 0), spacer at (1, 0).
        surface.put((0, 0), '\u{6f22}', Style::default());
        // Overwriting the primary cell via `put_signed` must clear the orphaned spacer too.
        surface.put_signed((0, 0), 'a', Style::default());
    }
    assert!(
        !grid[Pos::new(1, 0)]
            .flags()
            .contains(TileFlags::WIDE_CHAR_SPACER)
    );

    // Writing a wide char via `put_signed` must set the flags and spacer `put` would.
    screen(&mut grid).put_signed((3, 0), '\u{6f22}', Style::default());
    assert!(grid[Pos::new(3, 0)].flags().contains(TileFlags::WIDE_CHAR));
    assert!(
        grid[Pos::new(4, 0)]
            .flags()
            .contains(TileFlags::WIDE_CHAR_SPACER)
    );
}

#[test]
#[cfg(not(feature = "egc"))]
fn put_signed_does_not_tint_a_foreign_tile_when_put_tile_refuses_the_write() {
    // Same reproduction as `put`'s own version above, through `put_signed`'s non-egc branch.
    let mut grid = Grid::new(4, 1);
    {
        let mut surface = Surface::new(&mut grid, Rect::new(0, 0, 8, 1), 0);
        surface
            .with_tint(Tint::multiply(128, 64, 32))
            .put_signed((3, 0), 'X', Style::default());
        surface
            .with_tint(Tint::multiply(1, 2, 3))
            .put_signed((3, 0), '\u{6f22}', Style::default());
    }

    assert_eq!(grid[Pos::new(3, 0)].glyph(), 'X');
    assert_eq!(grid.tint(0, 3, 0), Tint::multiply(128, 64, 32));
}

#[test]
fn put_offset_applies_the_surfaces_tint() {
    let mut grid = Grid::new(4, 4);
    {
        let mut surface = screen(&mut grid);
        surface.with_tint(Tint::multiply(128, 64, 32)).put_offset(
            (1, 1),
            Offset::new(2, -2),
            'X',
            Style::default(),
        );
    }

    assert_eq!(grid.tint(0, 1, 1), Tint::multiply(128, 64, 32));
}

#[test]
fn put_offset_still_carries_the_pixel_offset() {
    let mut grid = Grid::new(4, 4);
    let mut surface = screen(&mut grid);

    surface.put_offset((1, 1), Offset::new(2, -2), 'X', Style::default());

    let tile = grid.tile(0, Pos::new(1, 1)).unwrap();
    assert_eq!((tile.dx(), tile.dy()), (2, -2));
}

#[test]
#[cfg(feature = "egc")]
fn put_offset_does_not_move_a_pre_existing_tile_when_its_own_write_is_refused() {
    let mut grid = Grid::new(8, 1);
    let mut surface = Surface::new(&mut grid, Rect::new(0, 0, 8, 1), 0);

    surface.put((3, 0), 'Z', Style::default());

    // Clip is columns 0..4; the wide char's primary cell (column 3) is inside the clip, but
    // its spacer would land at column 4, outside it. The whole write is refused, so `put_offset`
    // must not touch the tile `put` above just placed.
    surface.clip(Rect::new(0, 0, 4, 1)).put_offset(
        (3, 0),
        Offset::new(7, -7),
        '\u{6f22}',
        Style::default(),
    );

    let tile = grid.tile(0, Pos::new(3, 0)).unwrap();
    assert_eq!(tile.glyph(), 'Z');
    assert_eq!((tile.dx(), tile.dy()), (0, 0));
}

#[test]
#[cfg(not(feature = "egc"))]
fn put_offset_does_not_move_a_pre_existing_tile_when_its_own_write_is_refused() {
    let mut grid = Grid::new(4, 1);
    let mut surface = screen(&mut grid);

    surface.put((3, 0), 'Z', Style::default());

    // A 2-column glyph at the grid's last column needs a spacer at column 4, which does not
    // exist: `Grid::put_tile` refuses the write. `put_offset` must not touch the tile `put`
    // above just placed.
    surface.put_offset((3, 0), Offset::new(7, -7), '\u{6f22}', Style::default());

    let tile = grid.tile(0, Pos::new(3, 0)).unwrap();
    assert_eq!(tile.glyph(), 'Z');
    assert_eq!((tile.dx(), tile.dy()), (0, 0));
}

#[test]
fn put_offset_on_a_refused_write_leaves_the_targets_glyph_and_offset_alone() {
    let mut grid = Grid::new(4, 4);
    {
        let mut surface = screen(&mut grid);
        let mut clipped = surface.clip(Rect::new(0, 0, 2, 2));
        clipped.put((1, 1), 'X', Style::default());
        // (3, 3) is inside the grid but outside the clip: refused entirely (retroglyph#998:
        // this used to still set `dx`/`dy` on a cell the glyph write itself never touched).
        clipped.put_offset((3, 3), Offset::new(5, -5), 'Y', Style::default());
    }

    // Nothing was ever written at the refused write's own target.
    let target = grid.tile(0, Pos::new(3, 3)).unwrap();
    assert_eq!(target.glyph(), ' ');
    assert_eq!((target.dx(), target.dy()), (0, 0));
    // The glyph inside the clip is unaffected.
    assert_eq!(grid[Pos::new(1, 1)].glyph(), 'X');
}

#[test]
fn translate_does_not_change_area_width_or_height() {
    let mut grid = Grid::new(10, 10);
    let mut surface = screen(&mut grid);
    let mut scoped = surface.scope(Rect::new(5, 5, 4, 4));
    let view = scoped.translate((-5, -5));

    assert_eq!(view.area(), Rect::new(5, 5, 4, 4));
    assert_eq!(view.clip_rect(), Rect::new(5, 5, 4, 4));
    assert_eq!(view.width(), 4);
    assert_eq!(view.height(), 4);
}

#[test]
fn clip_translate_does_not_change_area_local_area_width_or_height() {
    let mut grid = Grid::new(10, 10);
    let mut surface = screen(&mut grid);
    let view = surface.clip_translate(Rect::new(5, 5, 4, 4), (-5, -5));

    assert_eq!(view.area(), Rect::new(5, 5, 4, 4));
    assert_eq!(view.area().at_origin(), Rect::new(0, 0, 4, 4));
    assert_eq!(view.width(), 4);
    assert_eq!(view.height(), 4);
}

#[test]
fn translate_saturates_at_i32_max_across_repeated_calls_instead_of_overflowing() {
    let mut grid = Grid::new(4, 4);
    let mut surface = screen(&mut grid);
    // Composing `(i32::MAX - 1, 0)` then `(5, 0)` would overflow a plain `+` past `i32::MAX`;
    // `saturating_add` instead pins the composed origin at `i32::MAX`.
    let mut once = surface.translate((i32::MAX - 1, 0));
    let mut view = once.translate((5, 0));

    // Every coordinate this surface can express (`u16`) minus an origin pinned at `i32::MAX`
    // stays deeply negative, so every write is dropped rather than landing somewhere
    // unexpected, or panicking on the intermediate overflow.
    view.put((0, 0), 'A', Style::default());
    view.put((3, 3), 'B', Style::default());

    assert_eq!(grid[Pos::new(0, 0)].glyph(), ' ');
    assert_eq!(grid[Pos::new(3, 3)].glyph(), ' ');
}

#[test]
fn translate_saturates_at_i32_min_across_repeated_calls_instead_of_overflowing() {
    let mut grid = Grid::new(4, 4);
    let mut surface = screen(&mut grid);
    let mut once = surface.translate((i32::MIN + 1, 0));
    let mut view = once.translate((-5, 0));

    // Pinned at `i32::MIN`: `shift`'s `checked_sub` cannot represent `x - i32::MIN` in an
    // `i32` for any grid coordinate, so it returns `None` and the write is dropped rather
    // than panicking on the subtraction.
    view.put((0, 0), 'A', Style::default());

    assert_eq!(grid[Pos::new(0, 0)].glyph(), ' ');
}

#[test]
fn translate_composes_with_scope_and_clip_rect() {
    let mut grid = Grid::new(10, 10);
    let mut surface = screen(&mut grid);
    let mut clipped = surface.clip(Rect::new(0, 0, 6, 6));
    // `scope` widens `area` past the parent's clip; `translate` on top must not change
    // either `area` or the still-narrower `clip_rect` it composed with.
    let mut scoped = clipped.scope(Rect::new(4, 4, 4, 4));
    let view = scoped.translate((-4, -4));

    assert_eq!(view.area(), Rect::new(4, 4, 4, 4));
    assert_eq!(view.clip_rect(), Rect::new(4, 4, 2, 2));
}

#[test]
fn translate_shifts_put_by_subtracting_the_origin() {
    let mut grid = Grid::new(10, 10);
    {
        let mut surface = screen(&mut grid);
        let mut view = surface.translate((3, 3));

        // (3, 3) minus the translate origin (3, 3) is (0, 0).
        view.put((3, 3), 'A', Style::default());
        // (2, 3) minus (3, 3) is negative on the x axis: out of bounds, dropped.
        view.put((2, 3), 'B', Style::default());
    }

    assert_eq!(grid[Pos::new(0, 0)].glyph(), 'A');
    assert_eq!(grid[Pos::new(0, 3)].glyph(), ' ');
}

#[test]
fn translate_composes_with_scope_and_lets_a_negative_signed_coordinate_land() {
    let mut grid = Grid::new(10, 10);
    {
        let mut surface = screen(&mut grid);
        let mut scoped = surface.scope(Rect::new(5, 5, 4, 4));
        let mut view = scoped.translate((-5, -5));

        // -5 minus the translate origin (-5) is 0: the viewport's own local origin, landing
        // at the scoped area's top-left grid cell.
        view.put_signed((-5, -5), 'X', Style::default());
        // -6 minus -5 is still -1: still negative, so still out of bounds.
        view.put_signed((-6, -6), 'Y', Style::default());
    }

    assert_eq!(grid[Pos::new(5, 5)].glyph(), 'X');
    assert_eq!(grid[Pos::new(4, 4)].glyph(), ' ');
}

#[test]
fn translate_composes_with_clip_and_shifts_put_the_same_way_as_put_signed() {
    // A regression test for a `shift` bug: `clip`'s area does not start at the grid's own
    // `(0, 0)` (unlike every other `clip` + `translate` test above), and the translate origin
    // is not simply `-area.left()`, so `put` must re-derive the same absolute cell
    // `put_signed` already did rather than landing on the clipped area's raw absolute
    // coordinates.
    let mut grid = Grid::new(20, 20);
    {
        let mut surface = screen(&mut grid);
        let mut view = surface.clip_translate(Rect::new(5, 5, 10, 10), (45, 45));

        // (50, 50) minus the origin (45, 45) is (5, 5): the clipped area's local (5, 5),
        // landing at absolute grid (10, 10), not at (5, 5), which is what the pre-fix
        // `shift` incorrectly produced by using the clip's raw absolute bounds instead of
        // re-adding the area's own top-left.
        view.put((50, 50), '@', Style::default());
    }

    assert_eq!(grid[Pos::new(10, 10)].glyph(), '@');
    assert_eq!(grid[Pos::new(5, 5)].glyph(), ' ');
}

#[test]
fn translate_composes_additively_across_two_calls() {
    let mut grid = Grid::new(10, 10);
    {
        let mut surface = screen(&mut grid);
        let mut once = surface.translate((2, 0));
        let mut twice = once.translate((1, 0));

        // Composed origin is (3, 0): (3, 0) minus (3, 0) is (0, 0).
        twice.put((3, 0), 'A', Style::default());
    }

    assert_eq!(grid[Pos::new(0, 0)].glyph(), 'A');
}

#[test]
fn translate_shifts_fill_rect_print_and_clear_region_via_put() {
    let mut grid = Grid::new(10, 10);
    {
        let mut surface = screen(&mut grid);
        let mut view = surface.translate((5, 5));
        view.fill_rect(Rect::new(5, 5, 2, 2), '#', Style::default());
        view.print((5, 6), "a", Style::default());
    }

    assert_eq!(grid[Pos::new(0, 0)].glyph(), '#');
    assert_eq!(grid[Pos::new(1, 1)].glyph(), '#');
    assert_eq!(grid[Pos::new(0, 1)].glyph(), 'a');
}

#[test]
fn translate_shifts_print_wrap_to_the_areas_own_width_not_the_local_offset_width() {
    // retroglyph#991: the wrap threshold used to stay in area-local space while `cx` advanced
    // in translated space, so it fired `origin_offset.0` columns early instead of at the
    // area's own 10-column width.
    let mut grid = Grid::new(10, 4);
    {
        let mut surface = screen(&mut grid);
        let mut view = surface.translate((5, 0));
        view.print((5, 0), "abcdefghij", Style::default());
    }

    // All 10 characters fit on row 0; nothing wraps to row 1.
    assert_eq!(grid[Pos::new(0, 0)].glyph(), 'a');
    assert_eq!(grid[Pos::new(9, 0)].glyph(), 'j');
    assert_eq!(grid[Pos::new(0, 1)].glyph(), ' ');
}

#[test]
fn translate_shifts_print_line_which_still_emits_its_spans() {
    // retroglyph#991: the span-skip threshold had the same area-local-vs-translated mismatch,
    // so on a translated surface `cx >= right` was true immediately and every span was
    // dropped instead of printed.
    use crate::text::Span;
    use alloc::vec;

    let mut grid = Grid::new(4, 1);
    {
        let mut surface = screen(&mut grid);
        let mut view = surface.translate((10, 0));
        let line = Line::from(vec![Span::raw("ab"), Span::raw("cd")]);
        view.print_line((10, 0), &line);
    }

    assert_eq!(grid[Pos::new(0, 0)].glyph(), 'a');
    assert_eq!(grid[Pos::new(1, 0)].glyph(), 'b');
    assert_eq!(grid[Pos::new(2, 0)].glyph(), 'c');
    assert_eq!(grid[Pos::new(3, 0)].glyph(), 'd');
}

#[test]
fn translate_shifts_clear_region() {
    let mut grid = Grid::new(10, 10);
    {
        let mut surface = screen(&mut grid);
        surface.fill_rect(Rect::new(0, 0, 4, 4), '#', Style::default());
        let mut view = surface.translate((2, 2));
        // Clears grid (0..2, 0..2) once shifted by the translate origin.
        view.clear_region(Rect::new(2, 2, 2, 2));
    }

    assert_eq!(grid[Pos::new(0, 0)].glyph(), ' ');
    assert_eq!(grid[Pos::new(1, 1)].glyph(), ' ');
    assert_eq!(grid[Pos::new(2, 2)].glyph(), '#');
}

#[test]
fn translate_shifts_put_span_and_put_span_uniform() {
    let mut grid = Grid::new(10, 10);
    {
        let mut surface = screen(&mut grid);
        let mut view = surface.translate((4, 4));
        assert_eq!(view.put_span((4, 4), &["ab"], Style::default()), Some(()));
        assert_eq!(
            view.put_span_uniform((6, 4), (2, 1), 'C', ' ', Style::default()),
            Some(())
        );
    }

    assert_eq!(grid[Pos::new(0, 0)].glyph(), 'a');
    assert_eq!(grid[Pos::new(2, 0)].glyph(), 'C');
}

#[test]
fn translate_shifts_print_and_still_wraps_at_the_surfaces_own_width() {
    // A 5-char string, unlike `translate_shifts_fill_rect_print_and_clear_region_via_put`'s
    // one-character print, is long enough to actually cross the wrap column at the area's own
    // 4-column width.
    let mut grid = Grid::new(4, 4);
    {
        let mut surface = Surface::new(&mut grid, Rect::new(0, 0, 4, 2), 0);
        let mut view = surface.translate((2, 0));
        view.print((2, 0), "abcde", Style::default());
    }

    assert_eq!(grid[Pos::new(0, 0)].glyph(), 'a');
    assert_eq!(grid[Pos::new(1, 0)].glyph(), 'b');
    assert_eq!(grid[Pos::new(2, 0)].glyph(), 'c');
    assert_eq!(grid[Pos::new(3, 0)].glyph(), 'd');
    // Wrapped to row 1 at the area's own width (4 columns, retroglyph#991's fix), still
    // shifted by the translate origin rather than one column early or late.
    assert_eq!(grid[Pos::new(0, 1)].glyph(), 'e');
}

#[test]
fn translate_shifts_print_line() {
    use crate::text::Span;
    use alloc::vec;

    let mut grid = Grid::new(6, 4);
    {
        let mut surface = screen(&mut grid);
        let mut view = surface.translate((2, 0));
        let line = Line::from(vec![Span::raw("ab"), Span::raw("cd")]);
        view.print_line((2, 0), &line);
    }

    assert_eq!(grid[Pos::new(0, 0)].glyph(), 'a');
    assert_eq!(grid[Pos::new(1, 0)].glyph(), 'b');
    assert_eq!(grid[Pos::new(2, 0)].glyph(), 'c');
    assert_eq!(grid[Pos::new(3, 0)].glyph(), 'd');
}

// `print_aligned` x `translate` is covered by
// `print_aligned_ignores_translate_and_still_lands_at_the_plain_local_position` above:
// retroglyph#993 made `print_aligned`'s `rect` deliberately ignore any outstanding
// `translate`, so this file's own translate-composition test for it was superseded by that
// fix rather than merged alongside it.

#[test]
fn translate_composes_with_with_style() {
    let mut grid = Grid::new(10, 10);
    {
        let mut surface = screen(&mut grid);
        let mut view = surface.translate((3, 3));
        let mut styled = view.with_style(Style::new().fg(Color::RED));
        styled.put((3, 3), 'A');
    }

    assert_eq!(grid[Pos::new(0, 0)].glyph(), 'A');
    assert_eq!(grid[Pos::new(0, 0)].style().foreground(), Color::RED);
}

#[test]
fn clear_is_unaffected_by_translate() {
    let mut grid = Grid::new(4, 4);
    {
        let mut surface = screen(&mut grid);
        surface.fill_rect(Rect::new(0, 0, 4, 4), '#', Style::default());
        let mut view = surface.translate((100, 100));
        // `clear` takes no coordinate, so the translate offset does not apply to it: it
        // always clears this surface's own area.
        view.clear();
    }

    assert_eq!(grid[Pos::new(0, 0)].glyph(), ' ');
    assert_eq!(grid[Pos::new(3, 3)].glyph(), ' ');
}

#[test]
fn clear_only_clears_the_intersection_of_area_and_clip() {
    let mut grid = Grid::new(6, 6);
    {
        let mut surface = screen(&mut grid);
        surface.fill_rect(Rect::new(0, 0, 6, 6), '#', Style::default());
        // `area` is the whole grid; `clip` narrows to a 2x2 window inside it.
        surface.clip(Rect::new(2, 2, 2, 2)).clear();
    }

    // Inside `area \u2229 clip`: cleared.
    assert_eq!(grid[Pos::new(2, 2)].glyph(), ' ');
    assert_eq!(grid[Pos::new(3, 3)].glyph(), ' ');
    // Inside `area`, outside `clip`: untouched.
    assert_eq!(grid[Pos::new(0, 0)].glyph(), '#');
    assert_eq!(grid[Pos::new(5, 5)].glyph(), '#');
}

#[test]
fn clear_on_a_scoped_surface_clears_the_scoped_area_intersected_with_the_parent_clip() {
    let mut grid = Grid::new(6, 6);
    {
        let mut surface = screen(&mut grid);
        surface.fill_rect(Rect::new(0, 0, 6, 6), '#', Style::default());
        let mut clipped = surface.clip(Rect::new(0, 0, 4, 4));
        // `scope` widens `area` to a rect the parent's clip does not fully cover.
        clipped.scope(Rect::new(2, 2, 4, 4)).clear();
    }

    // `area \u2229 clip` == (2, 2, 2, 2): cleared.
    assert_eq!(grid[Pos::new(2, 2)].glyph(), ' ');
    assert_eq!(grid[Pos::new(3, 3)].glyph(), ' ');
    // Inside the scoped `area` but outside the parent's clip: untouched.
    assert_eq!(grid[Pos::new(5, 5)].glyph(), '#');
    // Outside the scoped `area` entirely: untouched.
    assert_eq!(grid[Pos::new(0, 0)].glyph(), '#');
}

#[test]
fn grid_is_the_read_only_counterpart_of_grid_mut() {
    let mut grid = Grid::new(4, 4);
    let mut surface = screen(&mut grid);
    surface.put((1, 1), 'X', Style::default());

    assert_eq!(surface.grid()[Pos::new(1, 1)].glyph(), 'X');
}

#[test]
fn print_aligned_left_aligns_by_default() {
    let mut grid = Grid::new(8, 1);
    {
        let mut surface = screen(&mut grid);
        surface.print_aligned(
            Rect::new(0, 0, 8, 1),
            "hi",
            crate::layout::HAlign::Left,
            Style::default(),
        );
    }

    assert_eq!(grid[Pos::new(0, 0)].glyph(), 'h');
    assert_eq!(grid[Pos::new(1, 0)].glyph(), 'i');
    assert_eq!(grid[Pos::new(2, 0)].glyph(), ' ');
}

#[test]
fn print_aligned_centers_matching_text_layouts_own_saturating_formula() {
    let mut grid = Grid::new(6, 1);
    {
        let mut surface = screen(&mut grid);
        surface.print_aligned(
            Rect::new(0, 0, 6, 1),
            "hi",
            crate::layout::HAlign::Center,
            Style::default(),
        );
    }

    // (6 - 2) / 2 == 2 columns of left padding, matching `HAlign::Center` in `align.rs`.
    assert_eq!(grid[Pos::new(2, 0)].glyph(), 'h');
    assert_eq!(grid[Pos::new(3, 0)].glyph(), 'i');
}

#[test]
fn print_aligned_right_aligns_flush_to_the_rects_right_edge() {
    let mut grid = Grid::new(6, 1);
    {
        let mut surface = screen(&mut grid);
        surface.print_aligned(
            Rect::new(0, 0, 6, 1),
            "hi",
            crate::layout::HAlign::Right,
            Style::default(),
        );
    }

    assert_eq!(grid[Pos::new(4, 0)].glyph(), 'h');
    assert_eq!(grid[Pos::new(5, 0)].glyph(), 'i');
}

#[test]
fn print_aligned_does_not_panic_or_underflow_on_text_wider_than_the_rect() {
    let mut grid = Grid::new(4, 1);
    {
        let mut surface = screen(&mut grid);
        // "hello" is wider than the 4-column rect on every alignment: this must not panic
        // (a plain `rect.width() - text_width` would underflow) and instead left-aligns and
        // lets `print` clip the overflow.
        surface.print_aligned(
            Rect::new(0, 0, 4, 1),
            "hello",
            crate::layout::HAlign::Center,
            Style::default(),
        );
    }

    assert_eq!(grid[Pos::new(0, 0)].glyph(), 'h');
    assert_eq!(grid[Pos::new(3, 0)].glyph(), 'l');
}

#[test]
fn print_aligned_clips_to_this_surfaces_own_area_as_well_as_rect() {
    let mut grid = Grid::new(4, 1);
    {
        let mut surface = Surface::new(&mut grid, Rect::new(0, 0, 2, 1), 0);
        // `rect` extends past this surface's own area; the write is still clipped to it.
        surface.print_aligned(
            Rect::new(0, 0, 4, 1),
            "hi",
            crate::layout::HAlign::Right,
            Style::default(),
        );
    }

    assert_eq!(grid[Pos::new(0, 0)].glyph(), ' ');
    assert_eq!(grid[Pos::new(1, 0)].glyph(), ' ');
}

#[test]
fn print_aligned_right_on_an_offset_surface_uses_area_local_coordinates() {
    let mut grid = Grid::new(8, 1);
    {
        // `area` starts at column 2, not 0: local and absolute coordinates now differ.
        let mut surface = Surface::new(&mut grid, Rect::new(2, 0, 6, 1), 0);
        surface.print_aligned(
            Rect::new(0, 0, 6, 1),
            "hi",
            crate::layout::HAlign::Right,
            Style::default(),
        );
    }

    // `rect` (0, 0, 6, 1) is local to `area`, spanning it exactly; right-aligning "hi"
    // within it puts it at local columns 4..6, i.e. absolute columns 6..8.
    assert_eq!(grid[Pos::new(6, 0)].glyph(), 'h');
    assert_eq!(grid[Pos::new(7, 0)].glyph(), 'i');
}

#[test]
fn print_aligned_center_on_an_offset_surface_uses_area_local_coordinates() {
    let mut grid = Grid::new(8, 1);
    {
        let mut surface = Surface::new(&mut grid, Rect::new(2, 0, 6, 1), 0);
        surface.print_aligned(
            Rect::new(0, 0, 6, 1),
            "hi",
            crate::layout::HAlign::Center,
            Style::default(),
        );
    }

    // (6 - 2) / 2 == 2 columns of left padding within `rect`, local columns 2..4, i.e.
    // absolute columns 4..6.
    assert_eq!(grid[Pos::new(4, 0)].glyph(), 'h');
    assert_eq!(grid[Pos::new(5, 0)].glyph(), 'i');
}

#[test]
fn print_aligned_ignores_translate_and_still_lands_at_the_plain_local_position() {
    let mut grid = Grid::new(10, 1);
    {
        let mut surface = Surface::new(&mut grid, Rect::new(0, 0, 10, 1), 0);
        // `rect` is local to `area` and deliberately independent of any outstanding
        // `translate`: without cancelling `origin_offset` before delegating to `print`,
        // this would drop the text entirely (see issue #993).
        surface.translate((5, 0)).print_aligned(
            Rect::new(0, 0, 10, 1),
            "hi",
            crate::layout::HAlign::Left,
            Style::default(),
        );
    }

    assert_eq!(grid[Pos::new(0, 0)].glyph(), 'h');
    assert_eq!(grid[Pos::new(1, 0)].glyph(), 'i');
}

#[test]
fn clip_nests_monotonically() {
    let mut grid = Grid::new(8, 4);
    let mut surface = screen(&mut grid);
    let mut outer = surface.clip(Rect::new(1, 1, 4, 2));
    let inner = outer.clip(Rect::new(0, 0, 8, 4));

    assert_eq!(inner.clip_rect(), Rect::new(1, 1, 4, 2));
}

// --- unicode width ---
//
// Driven through `Terminal::draw`/`Terminal::surface` rather than a bare `Surface` over a
// standalone `Grid`, since these exercise `put`/`print`'s wide-character handling end to end,
// including the grid readback `Terminal` provides.

#[test]
fn test_put_wide_char_sets_continuation() {
    use crate::tile::TileFlags;

    let mut term = Terminal::new(Headless::new(10, 3));
    term.surface().put((0, 0), '\u{4e2d}', Style::default()); // '中', width 2
    assert_eq!(term.grid()[Pos::new(0, 0)].glyph(), '\u{4e2d}');
    // Both with and without `egc`: `put` (via `Grid::put_tile`, which is wide-char aware on
    // every feature combination) lays down an explicit spacer, flagged `WIDE_CHAR_SPACER`,
    // glyph space.
    assert!(
        term.grid()[Pos::new(1, 0)]
            .flags()
            .contains(TileFlags::WIDE_CHAR_SPACER)
    );
    assert_eq!(term.grid()[Pos::new(1, 0)].glyph(), ' ');
    assert_eq!(term.grid()[Pos::new(2, 0)].glyph(), ' '); // untouched
}

#[test]
fn test_print_advances_by_char_width() {
    use crate::tile::TileFlags;

    let mut term = Terminal::new(Headless::new(10, 3));
    term.surface().print((0, 0), "\u{4e2d}x", Style::default()); // '中' (2) then 'x' at col 2
    assert_eq!(term.grid()[Pos::new(0, 0)].glyph(), '\u{4e2d}');
    // See `test_put_wide_char_sets_continuation` for why the neighbor is a spacer regardless
    // of feature.
    assert!(
        term.grid()[Pos::new(1, 0)]
            .flags()
            .contains(TileFlags::WIDE_CHAR_SPACER)
    );
    assert_eq!(term.grid()[Pos::new(2, 0)].glyph(), 'x');
}

#[test]
fn test_put_accepts_a_pos_or_a_tuple() {
    // `put` takes `impl Into<Pos>`, so a `Pos` and an equivalent `(u16, u16)` tuple must
    // write the same cell.
    let mut term = Terminal::new(Headless::new(10, 3));
    let mut s = term.surface();
    s.put(Pos::new(2, 1), 'X', Style::default());
    s.put((3, 1), 'Y', Style::default());
    assert_eq!(term.grid()[Pos::new(2, 1)].glyph(), 'X');
    assert_eq!(term.grid()[Pos::new(3, 1)].glyph(), 'Y');
}

#[test]
fn test_put_offset_accepts_pos_and_offset_tuples() {
    // `put_offset` takes `impl Into<Pos>` and `impl Into<Offset>`, so `Pos`/`Offset` values
    // and equivalent tuples must produce the same tile.
    let mut term = Terminal::new(Headless::new(4, 1));
    let mut s = term.surface();
    s.put_offset(Pos::new(1, 0), Offset::new(3, -2), 'X', Style::default());
    s.put_offset((2, 0), (-1, 4), 'Y', Style::default());
    assert_eq!(term.grid()[Pos::new(1, 0)].glyph(), 'X');
    assert_eq!(term.grid()[Pos::new(1, 0)].dx(), 3);
    assert_eq!(term.grid()[Pos::new(1, 0)].dy(), -2);

    assert_eq!(term.grid()[Pos::new(2, 0)].glyph(), 'Y');
    assert_eq!(term.grid()[Pos::new(2, 0)].dx(), -1);
    assert_eq!(term.grid()[Pos::new(2, 0)].dy(), 4);
}

#[test]
fn test_put_wide_char_at_last_column_does_not_overflow() {
    // Wide char placed at the last column: can't place a spacer, so the write is refused
    // outright (nothing written), on every feature combination. `write_grapheme` (egc-only)
    // and `Grid::put_tile` (used by `put` on every feature combination) both refuse rather
    // than leave an orphaned primary cell with no spacer.
    let mut term = Terminal::new(Headless::new(4, 1));
    term.surface().put((3, 0), '\u{4e2d}', Style::default()); // col 3 is last; need col 4 for spacer
    assert_eq!(term.grid()[Pos::new(3, 0)].glyph(), ' '); // nothing written
}

// --- styled spans ---

#[test]
fn test_print_styled_basic() {
    use crate::text::Span;
    use alloc::vec;

    let mut term = Terminal::new(Headless::new(20, 3));
    let line = Line::from(vec![
        Span::raw("HP: "),
        Span::styled("100", Style::new().fg(Color::GREEN)),
    ]);
    term.surface().print_line((0, 0), &line);
    assert_eq!(term.grid()[Pos::new(0, 0)].glyph(), 'H');
    assert_eq!(term.grid()[Pos::new(3, 0)].glyph(), ' ');
    assert_eq!(term.grid()[Pos::new(4, 0)].glyph(), '1');
    assert_eq!(term.grid()[Pos::new(4, 0)].style.fg, Color::GREEN);
    assert_eq!(term.grid()[Pos::new(6, 0)].glyph(), '0');
}

#[test]
fn test_print_styled_wide_chars() {
    use crate::tile::TileFlags;
    use alloc::vec;

    let mut term = Terminal::new(Headless::new(10, 3));
    let line = Line::from(vec![crate::text::Span::raw("\u{4e2d}x")]);
    term.surface().print_line((0, 0), &line);
    assert_eq!(term.grid()[Pos::new(0, 0)].glyph(), '\u{4e2d}');
    // See `test_put_wide_char_sets_continuation` for why the neighbor is a spacer regardless
    // of feature.
    assert!(
        term.grid()[Pos::new(1, 0)]
            .flags()
            .contains(TileFlags::WIDE_CHAR_SPACER)
    );
    assert_eq!(term.grid()[Pos::new(2, 0)].glyph(), 'x');
}

#[test]
fn test_print_str_styled_applies_style_to_every_cell() {
    let mut term = Terminal::new(Headless::new(20, 3));
    term.surface()
        .print((0, 0), "HP", Style::new().fg(Color::GREEN));
    assert_eq!(term.grid()[Pos::new(0, 0)].glyph(), 'H');
    assert_eq!(term.grid()[Pos::new(0, 0)].style.fg, Color::GREEN);
    assert_eq!(term.grid()[Pos::new(1, 0)].glyph(), 'P');
    assert_eq!(term.grid()[Pos::new(1, 0)].style.fg, Color::GREEN);
}