rotulus-layout 0.1.0

The layout engine behind the Rotulus chat view: message model, wrapping, height index, scroll anchoring
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
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
//! Unit tests for the layout engine.
//!
//! All of these run headless — that is the point of keeping the crate
//! free of GTK/Pango. Wrap assertions use [`FixedMeasure`] so they can
//! name exact byte offsets instead of "roughly here".

use crate::anchor::{Gravity, ScrollAnchor};
use crate::buffer::ChatBuffer;
use crate::index::HeightIndex;
use crate::markdown::{self, RawBlock};
use crate::measure::{FixedMeasure, TextMeasure};
use crate::message::{Block, ImageSize, Message, MessageId, Speaker};
use crate::span::{Attrs, ParsedText, Style};
use crate::wrap::{estimate_height, layout_message, LayoutGeneration, LayoutParams};

// ---------------------------------------------------------------- markdown

/// Assert the rendered text and the styled slices of a parse.
fn styled(p: &ParsedText) -> Vec<(&str, Attrs)> {
    p.spans
        .iter()
        .map(|s| (&p.text[s.range.clone()], s.style.attrs))
        .collect()
}

#[test]
fn md_plain_text_has_no_spans() {
    let p = markdown::parse_inline("just a normal chat line");
    assert_eq!(p.text, "just a normal chat line");
    assert!(p.spans.is_empty(), "plain text should not allocate spans");
}

#[test]
fn md_bold_italic_code_strike() {
    let p = markdown::parse_inline("a **b** c *d* e `f` g ~~h~~");
    assert_eq!(p.text, "a b c d e f g h");
    assert_eq!(
        styled(&p),
        vec![
            ("b", Attrs::BOLD),
            ("d", Attrs::ITALIC),
            ("f", Attrs::CODE),
            ("h", Attrs::STRIKETHROUGH),
        ]
    );
}

#[test]
fn md_nested_emphasis() {
    let p = markdown::parse_inline("**bold *and italic* still bold**");
    assert_eq!(p.text, "bold and italic still bold");
    assert_eq!(
        styled(&p),
        vec![
            ("bold ", Attrs::BOLD),
            ("and italic", Attrs::BOLD.union(Attrs::ITALIC)),
            (" still bold", Attrs::BOLD),
        ]
    );
}

#[test]
fn md_unmatched_delimiters_stay_literal() {
    // The single most important property: never eat a lone asterisk.
    for src in [
        "2 * 3 * 4",
        "a ** b",
        "**unclosed",
        "*unclosed",
        "~~unclosed",
        "`unclosed",
        "x_y",
        "a_b_c",
    ] {
        let p = markdown::parse_inline(src);
        assert_eq!(p.text, src, "input {src:?} should render literally");
        assert!(p.spans.is_empty(), "input {src:?} should have no spans");
    }
}

#[test]
fn md_underscore_respects_word_boundaries() {
    // snake_case must survive; this project's chat is full of it.
    let p = markdown::parse_inline("call rotulus_view_append please");
    assert_eq!(p.text, "call rotulus_view_append please");
    assert!(p.spans.is_empty());

    // But a real word-boundary underscore still emphasises.
    let p = markdown::parse_inline("this is _emphatic_ yes");
    assert_eq!(p.text, "this is emphatic yes");
    assert_eq!(styled(&p), vec![("emphatic", Attrs::ITALIC)]);
}

#[test]
fn md_code_span_suppresses_other_markup() {
    let p = markdown::parse_inline("use `a **b** c` here");
    assert_eq!(p.text, "use a **b** c here");
    assert_eq!(styled(&p), vec![("a **b** c", Attrs::CODE)]);
}

#[test]
fn md_code_span_matches_run_length() {
    // The delimiter is a *run*: N backticks open, the next run of
    // exactly N closes. Reading one backtick at a time turned this into
    // two empty spans with plain text between them, which is how
    // ``hello`` rendered as an unadorned hello.
    let p = markdown::parse_inline("``hello``");
    assert_eq!(p.text, "hello");
    assert_eq!(styled(&p), vec![("hello", Attrs::CODE)]);

    // The point of the longer run: it can hold a shorter one.
    let p = markdown::parse_inline("``a `b` c``");
    assert_eq!(p.text, "a `b` c");
    assert_eq!(styled(&p), vec![("a `b` c", Attrs::CODE)]);

    // A shorter run inside a longer one does not close it.
    let p = markdown::parse_inline("```x`y```");
    assert_eq!(p.text, "x`y");
    assert_eq!(styled(&p), vec![("x`y", Attrs::CODE)]);
}

#[test]
fn md_code_span_strips_one_pad_space() {
    // Both spaces or neither, and never from an all-space span — the
    // rule that lets a span carry a backtick of its own.
    let p = markdown::parse_inline("`` ` ``");
    assert_eq!(p.text, "`");
    assert_eq!(styled(&p), vec![("`", Attrs::CODE)]);

    let p = markdown::parse_inline("` a `");
    assert_eq!(p.text, "a");

    // One-sided padding is content, not padding.
    let p = markdown::parse_inline("` a`");
    assert_eq!(p.text, " a");
}

#[test]
fn md_unmatched_backtick_run_is_literal() {
    let p = markdown::parse_inline("``unclosed");
    assert_eq!(p.text, "``unclosed");
    assert!(p.spans.is_empty());

    // The run is skipped whole. Resuming inside it would let the second
    // backtick open a span that closes on the one further along.
    let p = markdown::parse_inline("``a `b` c");
    assert_eq!(p.text, "``a b c");
    assert_eq!(styled(&p), vec![("b", Attrs::CODE)]);
}

#[test]
fn md_escapes() {
    let p = markdown::parse_inline(r"literal \*stars\* and \`ticks\`");
    assert_eq!(p.text, "literal *stars* and `ticks`");
    assert!(p.spans.is_empty());
}

#[test]
fn md_backslash_before_ordinary_char_is_literal() {
    // Windows paths and regexes must not lose their backslashes.
    let p = markdown::parse_inline(r"C:\path\to\file and \d+");
    assert_eq!(p.text, r"C:\path\to\file and \d+");
}

#[test]
fn md_link_allowed_scheme() {
    let p = markdown::parse_inline("see [the docs](https://example.com/x) ok");
    assert_eq!(p.text, "see the docs ok");
    assert_eq!(p.links.len(), 1);
    assert_eq!(p.links[0].href, "https://example.com/x");
    assert_eq!(&p.text[p.links[0].range.clone()], "the docs");
    assert_eq!(p.style_at(4).link, Some(0));
}

#[test]
fn md_link_disallowed_scheme_renders_literally() {
    // The security property: a scheme we can't vouch for is shown as
    // typed, not turned into a link the user cannot inspect.
    for src in [
        "[click](javascript:alert(1))",
        "[click](data:text/html;base64,xx)",
        "[click](file:///etc/passwd)",
        "[click](vbscript:x)",
    ] {
        let p = markdown::parse_inline(src);
        assert_eq!(p.text, src, "{src} should render literally");
        assert!(p.links.is_empty(), "{src} should produce no link");
    }
}

#[test]
fn md_link_label_and_href_may_disagree() {
    // Allowed, but both are recorded so the view can warn.
    let p = markdown::parse_inline("[https://good.example](https://evil.example)");
    assert_eq!(p.text, "https://good.example");
    assert_eq!(p.links[0].href, "https://evil.example");
}

#[test]
fn md_images_are_not_links() {
    // `![]()` must not bypass the server-validated media pipeline.
    let p = markdown::parse_inline("![alt](https://example.com/x.png)");
    assert!(p.text.starts_with('!'));
    assert_eq!(p.links.len(), 1, "the bracket part still parses as a link");
    // What matters is that no image block is produced — this parser
    // cannot emit one at all.
}

#[test]
fn md_no_headings_or_rules() {
    for src in ["# not a heading", "--- not a rule", "=== nope"] {
        let blocks = markdown::split_blocks(src);
        assert_eq!(blocks, vec![RawBlock::Paragraph(src.to_string())]);
    }
}

#[test]
fn md_fenced_code_block() {
    let blocks = markdown::split_blocks("before\n```rust\nlet x = **y**;\n```\nafter");
    assert_eq!(
        blocks,
        vec![
            RawBlock::Paragraph("before".into()),
            RawBlock::Code {
                text: "let x = **y**;".into(),
                language: Some("rust".into())
            },
            RawBlock::Paragraph("after".into()),
        ]
    );
}

#[test]
fn md_unterminated_fence_runs_to_end() {
    let blocks = markdown::split_blocks("```\nstill typing");
    assert_eq!(
        blocks,
        vec![RawBlock::Code {
            text: "still typing".into(),
            language: None
        }]
    );
}

#[test]
fn md_quote_block() {
    let blocks = markdown::split_blocks("> a\n> b\nnormal");
    assert_eq!(
        blocks,
        vec![
            RawBlock::Quote {
                text: "a\nb".into(),
                depth: 1
            },
            RawBlock::Paragraph("normal".into()),
        ]
    );
}

#[test]
fn md_pathological_input_terminates() {
    // Guards against the recursion and scan-loop bugs this shape of
    // parser is prone to.
    for src in [
        "*".repeat(2000),
        "**".repeat(1000),
        "`".repeat(1000),
        "[".repeat(1000),
        "~~".repeat(1000),
        "\\".repeat(1000),
        format!("{}text{}", "**".repeat(64), "**".repeat(64)),
    ] {
        let p = markdown::parse_inline(&src);
        p.debug_assert_well_formed();
    }
}

#[test]
fn md_utf8_is_never_split() {
    let p = markdown::parse_inline("**héllo → wörld 😀**");
    assert_eq!(p.text, "héllo → wörld 😀");
    p.debug_assert_well_formed();
}

// -------------------------------------------------------------------- mIRC

// ------------------------------------------------------------------ measure

#[test]
fn fit_prefix_respects_char_boundaries() {
    let m = FixedMeasure::new(10);
    let (n, w) = m.fit_prefix("héllo", Style::default(), 25);
    assert!("héllo".is_char_boundary(n));
    assert!(w <= 25);
}

#[test]
fn image_scales_down_never_up() {
    let m = FixedMeasure::new(8);
    assert_eq!(m.image_size((100, 50), 200), (100, 50), "no upscale");
    assert_eq!(m.image_size((400, 200), 200), (200, 100), "aspect kept");
}

// -------------------------------------------------------------------- wrap

fn params(width: u32) -> LayoutParams {
    LayoutParams {
        width,
        indent: false,
        max_indent: 256,
        indent_width: 0,
        stamp_width: 0,
        gutter_gap: 6,
        quote_indent: 12,
        block_padding: 2,
        word_wrap: true,
        avatar_size: 0,
    }
}

#[test]
fn every_line_records_the_width_it_was_measured_at() {
    let m = FixedMeasure::new(10);
    let msg = Message::system(ParsedText::plain("aaa bbb ccc ddd"));
    let l = layout_message(&msg, &params(80), LayoutGeneration::default(), &m);
    for lb in &l.lines {
        let text = &"aaa bbb ccc ddd"[lb.range.clone()];
        assert_eq!(
            lb.width,
            m.run_width(text, Style::default()),
            "line {text:?} recorded a width it was not laid out at"
        );
        assert!(
            lb.width <= 80,
            "a line wider than the column escaped the wrap"
        );
    }
}

#[test]
fn a_code_block_is_only_as_wide_as_its_widest_line() {
    // What the view draws the box around. Before this, the box ran to
    // the right edge of the widget regardless of the code in it, so a
    // one-word block read as a full-width divider.
    let m = FixedMeasure::new(10);
    let mut msg = Message::system(ParsedText::plain(""));
    msg.blocks = vec![Block::Code {
        text: "hi\nlonger line\nx".to_string(),
        language: None,
    }]
    .into();
    let l = layout_message(&msg, &params(1000), LayoutGeneration::default(), &m);
    let widths: Vec<u32> = l.lines.iter().map(|lb| lb.width).collect();
    assert_eq!(widths, vec![20, 110, 10]);

    let widest = widths.iter().copied().max().unwrap();
    assert!(widest < 1000, "the box would still span the full column");
}

#[test]
fn wrap_breaks_on_word_boundary() {
    let m = FixedMeasure::new(10); // 10 px per char
    let msg = Message::system(ParsedText::plain("aaa bbb ccc ddd"));
    // 80 px = 8 chars per line.
    let l = layout_message(&msg, &params(80), LayoutGeneration::default(), &m);
    let texts: Vec<&str> = l
        .lines
        .iter()
        .map(|lb| &"aaa bbb ccc ddd"[lb.range.clone()])
        .collect();
    assert_eq!(texts, vec!["aaa bbb", "ccc ddd"]);
}

#[test]
fn wrap_hard_breaks_long_token() {
    let m = FixedMeasure::new(10);
    let word = "aaaaaaaaaaaaaaaaaaaa"; // 20 chars, no spaces
    let msg = Message::system(ParsedText::plain(word));
    let l = layout_message(&msg, &params(50), LayoutGeneration::default(), &m);
    assert!(
        l.lines.len() >= 4,
        "must break mid-token, got {:?}",
        l.lines
    );
    assert_eq!(l.height, l.lines.len() as u32 * m.metrics().line_height);
}

#[test]
fn wrap_honours_hard_newlines() {
    let m = FixedMeasure::new(10);
    let msg = Message::system(ParsedText::plain("a\nb\nc"));
    let l = layout_message(&msg, &params(500), LayoutGeneration::default(), &m);
    assert_eq!(l.lines.len(), 3);
}

/// A measurer whose per-character width depends on the *style*, not just
/// the text.
///
/// [`FixedMeasure`] can't catch a whole class of bug, because if every
/// character is the same width then measuring a run with the wrong style
/// still gives the right answer. Real fonts are not like that: bold and
/// monospace are wider than the base face. This measurer reproduces that,
/// and it is what makes the overflow assertions below meaningful.
#[derive(Clone, Copy, Debug)]
struct StyleMeasure {
    base: u32,
}

impl TextMeasure for StyleMeasure {
    fn metrics(&self) -> crate::measure::FontMetrics {
        crate::measure::FontMetrics {
            line_height: 16,
            ascent: 12,
            space_width: self.base,
        }
    }

    fn run_width(&self, text: &str, style: Style) -> u32 {
        let per = if style.attrs.contains(Attrs::BOLD) {
            self.base * 2
        } else if style.attrs.contains(Attrs::CODE) {
            self.base * 3
        } else {
            self.base
        };
        (text.chars().count() as u32) * per
    }
}

/// Every wrapped line's *actually rendered* width must fit the box.
///
/// This is the property the old break-point search violated: it measured
/// the remaining text with the style in effect at the line's start, so a
/// bold or code run later in the line was under-measured and the drawn
/// line overflowed.
fn assert_no_line_overflows(
    p: &ParsedText,
    lines: &[crate::wrap::LineBox],
    width: u32,
    m: &dyn TextMeasure,
) {
    for lb in lines {
        let mut w = 0u32;
        let mut cursor = lb.range.start;
        for s in &p.spans {
            if s.range.end <= cursor || s.range.start >= lb.range.end {
                continue;
            }
            if s.range.start > cursor {
                w += m.run_width(&p.text[cursor..s.range.start], Style::default());
                cursor = s.range.start;
            }
            let e = s.range.end.min(lb.range.end);
            if e > cursor {
                w += m.run_width(&p.text[cursor..e], s.style);
                cursor = e;
            }
        }
        if cursor < lb.range.end {
            w += m.run_width(&p.text[cursor..lb.range.end], Style::default());
        }
        assert!(
            w <= width,
            "line {:?} ({:?}) renders {w}px, over the {width}px box",
            lb.range,
            &p.text[lb.range.clone()]
        );
    }
}

#[test]
fn wrap_accounts_for_style_changes_mid_line() {
    let m = StyleMeasure { base: 10 };
    // Bold measures 2x, so a break point chosen from the leading plain
    // style overshoots badly.
    let p = markdown::parse_inline("aaa **bbbbbbbbbb** ccc");
    let msg = Message::system(p.clone());
    let l = layout_message(&msg, &params(100), LayoutGeneration::default(), &m);
    assert_no_line_overflows(&p, &l.lines, 100, &m);
}

#[test]
fn wrap_accounts_for_code_runs() {
    let m = StyleMeasure { base: 10 };
    // Code measures 3x.
    let p = markdown::parse_inline("run `rotulus_view_append_indent` now");
    let msg = Message::system(p.clone());
    let l = layout_message(&msg, &params(120), LayoutGeneration::default(), &m);
    assert_no_line_overflows(&p, &l.lines, 120, &m);
}

#[test]
fn wrap_style_at_the_very_start_of_a_line() {
    // The mirror case: the line *begins* bold and turns plain, where a
    // start-style-only search over-measures and wraps too early.
    let m = StyleMeasure { base: 10 };
    let p = markdown::parse_inline("**bb** aaaaaaaaaaaaaaaaaaaaaaaa");
    let msg = Message::system(p.clone());
    let l = layout_message(&msg, &params(100), LayoutGeneration::default(), &m);
    assert_no_line_overflows(&p, &l.lines, 100, &m);
    // And no content is lost across the wrap.
    let joined: String = l
        .lines
        .iter()
        .map(|lb| &p.text[lb.range.clone()])
        .collect::<Vec<_>>()
        .join("");
    assert_eq!(joined.replace(' ', ""), p.text.replace(' ', ""));
}

#[test]
fn empty_quote_still_has_a_line_box() {
    let m = FixedMeasure::new(8);
    let msg = Message {
        kind: crate::message::MessageKind::Live,
        timestamp: 0,
        speaker: None,
        gutter: None,
        blocks: vec![Block::Quote {
            content: ParsedText::plain(""),
            depth: 1,
        }]
        .into(),
        flags: MessageFlagsNone::NONE,
    };
    let l = layout_message(&msg, &params(400), LayoutGeneration::default(), &m);
    assert_eq!(
        l.lines.len(),
        1,
        "an empty quote occupies space, so it must be hit-testable"
    );
    assert_eq!(l.height, m.metrics().line_height);
}

#[test]
fn empty_alt_image_still_has_a_line_box() {
    let m = FixedMeasure::new(8);
    let msg = Message {
        kind: crate::message::MessageKind::Live,
        timestamp: 0,
        speaker: None,
        gutter: None,
        blocks: vec![Block::Image {
            token: 1,
            size: None,
            alt: String::new(),
        }]
        .into(),
        flags: MessageFlagsNone::NONE,
    };
    let l = layout_message(&msg, &params(400), LayoutGeneration::default(), &m);
    assert_eq!(
        l.lines.len(),
        1,
        "an undecoded image must stay clickable — that is how the \
         media dialog gets opened"
    );
}

#[test]
fn gutter_gets_its_own_line_box() {
    let m = FixedMeasure::new(8);
    let mut p = params(400);
    p.indent = true;
    p.indent_width = 80;
    let msg = Message {
        kind: crate::message::MessageKind::Live,
        timestamp: 0,
        speaker: None,
        gutter: Some(ParsedText::plain("<alice>")),
        blocks: vec![Block::Text(ParsedText::plain("hello"))].into(),
        flags: MessageFlagsNone::NONE,
    };
    let l = layout_message(&msg, &p, LayoutGeneration::default(), &m);
    assert_eq!(l.lines[0].source, crate::wrap::LineSource::Gutter);
    // Right-aligned against the body column, not pinned at 0 — the
    // latter was the bug that made "[hx]" drift away from its text as
    // the shared column grew.
    assert!(
        l.lines[0].x > 0 && l.lines[0].x < 80,
        "gutter x {} should sit inside the column, right-aligned",
        l.lines[0].x
    );
    assert_eq!(l.lines[1].x, 80, "body sits past the gutter");
    assert_eq!(l.lines[0].y, l.lines[1].y, "same visual row");
}

#[test]
fn wrap_disabled_produces_one_line() {
    let m = FixedMeasure::new(10);
    let mut p = params(50);
    p.word_wrap = false;
    let msg = Message::system(ParsedText::plain("aaa bbb ccc ddd eee"));
    let l = layout_message(&msg, &p, LayoutGeneration::default(), &m);
    // Without word_wrap we still break at the width (that is what xtext
    // does too — "wordwrap" selects word vs character breaking), but the
    // break points differ from the word-wrapped case.
    assert!(!l.lines.is_empty());
}

#[test]
fn image_block_has_real_pixel_height() {
    // The headline departure from xtext: not ceil(h / fontsize) blank
    // text rows, an actual height.
    let m = FixedMeasure::new(8);
    let msg = Message {
        kind: crate::message::MessageKind::Live,
        timestamp: 0,
        speaker: None,
        gutter: None,
        blocks: vec![Block::Image {
            token: 7,
            size: Some(ImageSize {
                width: 100,
                height: 240,
            }),
            alt: "[image]".into(),
        }]
        .into(),
        flags: MessageFlagsNone::NONE,
    };
    let l = layout_message(&msg, &params(400), LayoutGeneration::default(), &m);
    assert_eq!(l.height, 240 + 2 * 2, "image height plus padding");
    assert_eq!(l.lines.len(), 1);
    assert_eq!(l.lines[0].height, 240);
}

use crate::message::MessageFlags as MessageFlagsNone;

#[test]
fn undecoded_image_measures_as_placeholder() {
    let m = FixedMeasure::new(8);
    let msg = Message {
        kind: crate::message::MessageKind::Live,
        timestamp: 0,
        speaker: None,
        gutter: None,
        blocks: vec![Block::Image {
            token: 7,
            size: None,
            alt: "[image]".into(),
        }]
        .into(),
        flags: MessageFlagsNone::NONE,
    };
    let l = layout_message(&msg, &params(400), LayoutGeneration::default(), &m);
    assert_eq!(l.height, m.metrics().line_height);
}

// ------------------------------------------------------------------- index

#[test]
fn index_locate_and_offset_round_trip() {
    let mut ix = HeightIndex::new();
    for i in 0..1000u32 {
        ix.push_back(10 + (i % 7), true);
    }
    for row in [0usize, 1, 127, 128, 129, 500, 999] {
        let off = ix.offset_of(row);
        let hit = ix.locate(off).expect("in range");
        assert_eq!(hit.row, row, "offset {off} should land on row {row}");
        assert_eq!(hit.offset, 0);
    }
}

#[test]
fn index_total_matches_sum() {
    let mut ix = HeightIndex::new();
    let mut expect = 0u64;
    for i in 0..500u32 {
        let h = 5 + i % 20;
        ix.push_back(h, true);
        expect += u64::from(h);
    }
    assert_eq!(ix.total_height(), expect);
}

#[test]
fn index_push_front_shifts_nothing_else() {
    let mut ix = HeightIndex::new();
    for _ in 0..300 {
        ix.push_back(10, true);
    }
    let before = ix.total_height();
    ix.push_front(50, true);
    assert_eq!(ix.total_height(), before + 50);
    assert_eq!(ix.height_at(0), 50);
    assert_eq!(ix.height_at(1), 10);
    assert_eq!(ix.offset_of(1), 50);
}

#[test]
fn index_middle_insert() {
    let mut ix = HeightIndex::new();
    for _ in 0..300 {
        ix.push_back(10, true);
    }
    ix.insert(150, 33, true);
    assert_eq!(ix.len(), 301);
    assert_eq!(ix.height_at(150), 33);
    assert_eq!(ix.offset_of(150), 150 * 10);
    assert_eq!(ix.offset_of(151), 150 * 10 + 33);
    assert_eq!(ix.total_height(), 300 * 10 + 33);
}

#[test]
fn index_drain_front() {
    let mut ix = HeightIndex::new();
    for i in 0..500u32 {
        ix.push_back(i % 13 + 1, true);
    }
    let full = ix.total_height();
    let dropped: u64 = (0..200u32).map(|i| u64::from(i % 13 + 1)).sum();
    ix.drain_front(200);
    assert_eq!(ix.len(), 300);
    assert_eq!(ix.total_height(), full - dropped);
    assert_eq!(ix.offset_of(0), 0);
}

#[test]
fn index_remove_and_set_height() {
    let mut ix = HeightIndex::new();
    for _ in 0..10 {
        ix.push_back(10, true);
    }
    assert_eq!(ix.remove(5), Some(10));
    assert_eq!(ix.len(), 9);
    assert_eq!(ix.total_height(), 90);
    ix.set_height(0, 25, true);
    assert_eq!(ix.total_height(), 105);
    assert_eq!(ix.offset_of(1), 25);
}

#[test]
fn index_locate_past_end_clamps() {
    let mut ix = HeightIndex::new();
    ix.push_back(10, true);
    ix.push_back(10, true);
    let hit = ix.locate(1_000_000).expect("clamps rather than None");
    assert_eq!(hit.row, 1);
}

#[test]
fn index_invalidate_keeps_heights_as_estimates() {
    // The resize property: invalidation must not recompute or zero
    // anything, or the scrollbar collapses on every window drag.
    let mut ix = HeightIndex::new();
    for _ in 0..100 {
        ix.push_back(10, true);
    }
    let before = ix.total_height();
    ix.invalidate_all_measurements();
    assert_eq!(ix.total_height(), before, "heights survive as estimates");
    assert_eq!(ix.unmeasured_count(), 100);
    assert!(!ix.is_measured(0));
}

// ------------------------------------------------------------------ anchor

fn buf() -> (ChatBuffer, FixedMeasure) {
    let m = FixedMeasure::new(8);
    let mut b = ChatBuffer::new(params(400));
    for i in 0..200 {
        b.append(Message::system(ParsedText::plain(format!("line {i}"))), &m);
    }
    (b, m)
}

#[test]
fn anchor_follows_bottom_by_default() {
    let (mut b, m) = buf();
    assert!(b.is_following());
    let before = b.scroll_offset(100);
    b.append(Message::system(ParsedText::plain("new")), &m);
    let after = b.scroll_offset(100);
    assert!(after > before, "following should track the new bottom");
}

#[test]
fn anchor_holds_position_across_prepend() {
    // The chat-history Load-Older property, and the reason the anchor
    // exists at all.
    let (mut b, m) = buf();
    b.scroll_to(500, 100, 4);
    assert!(!b.is_following());
    let before = b.scroll_offset(100);
    let anchored = b.anchor().message;

    for i in 0..50 {
        let at = b.anchor().message;
        b.insert_before(
            at,
            Message::system(ParsedText::plain(format!("older {i}"))),
            &m,
        );
    }

    assert_eq!(b.anchor().message, anchored, "anchor row is unchanged");
    let after = b.scroll_offset(100);
    assert!(
        after > before,
        "content above grew, so the pixel offset must grow with it \
         ({before} -> {after}) — that is what keeps the row still"
    );
    // And the anchored row is still at the same place in the viewport.
    let row = b.row_of(anchored.unwrap()).unwrap();
    assert_eq!(
        b.index_mut().offset_of(row),
        after - u64::from(b.anchor().offset)
    );
}

#[test]
fn anchor_survives_resize() {
    let (mut b, m) = buf();
    b.scroll_to(400, 100, 4);
    let anchored = b.anchor().message.expect("anchored");
    b.set_width(200);
    let off = b.scroll_offset(100);
    b.ensure_visible(off, 100, &m);
    assert_eq!(b.anchor().message, Some(anchored));
}

#[test]
fn anchor_snaps_back_to_following_near_bottom() {
    let (mut b, _m) = buf();
    let total = b.total_height();
    b.scroll_to(total, 100, 4);
    assert!(b.is_following(), "landing at the end resumes following");
}

#[test]
fn anchor_falls_back_when_its_row_is_trimmed() {
    let (mut b, m) = buf();
    b.scroll_to(50, 100, 4);
    assert!(!b.is_following());
    b.set_max_rows(10, &m); // trims the anchored row away
    let _ = b.scroll_offset(100);
    // The anchored content is gone; the least surprising place is the
    // bottom, and crucially it must not panic or return garbage.
    let off = b.scroll_offset(100);
    assert!(off <= b.total_height());
    b.append(Message::system(ParsedText::plain("x")), &m);
}

// ------------------------------------------------------------------ buffer

#[test]
fn buffer_marks_are_stable_across_inserts() {
    let m = FixedMeasure::new(8);
    let mut b = ChatBuffer::new(params(400));
    let a = b.append(Message::system(ParsedText::plain("a")), &m);
    let c = b.append(Message::system(ParsedText::plain("c")), &m);
    let mid = b.insert_before(Some(c), Message::system(ParsedText::plain("b")), &m);

    assert_eq!(b.row_of(a), Some(0));
    assert_eq!(b.row_of(mid), Some(1));
    assert_eq!(b.row_of(c), Some(2));
    assert_eq!(b.message(a).unwrap().to_plain_text(), "a");
    assert_eq!(b.message(c).unwrap().to_plain_text(), "c");
}

#[test]
fn a_long_page_before_one_anchor_lands_in_order() {
    // A Load-older page: row after row inserted before the same anchor,
    // with other changes landing in between. Every insert must go directly
    // above the anchor, and every mark must still name its row.
    let m = FixedMeasure::new(8);
    let mut b = ChatBuffer::new(params(400));
    let anchor = b.append(Message::system(ParsedText::plain("anchor")), &m);
    for i in 0..40 {
        b.append(Message::system(ParsedText::plain(format!("live {i}"))), &m);
    }
    // Read from partway down, so the reading position is a real row the
    // inserts keep pushing further down.
    b.scroll_to(160, 100, 0);
    let mut page = Vec::new();
    for i in 0..300 {
        page.push(b.insert_before(
            Some(anchor),
            Message::system(ParsedText::plain(format!("old {i}"))),
            &m,
        ));
        // The reading position from the remembered row must match a full
        // rebuild's. Rebuilt only now and then, so the hints also have to
        // survive long stretches of shifts on their own.
        let fast = b.scroll_offset(100);
        if i % 37 == 0 {
            b.reindex();
            assert_eq!(fast, b.scroll_offset(100), "after insert {i}");
        }
        match i % 50 {
            // An append after the anchor leaves it where it is.
            10 => {
                b.append(Message::system(ParsedText::plain("new")), &m);
            }
            // A removal above the anchor moves it up by one.
            20 => assert!(b.remove(page[i - 5], &m)),
            _ => {}
        }
    }
    b.reindex();
    let order: Vec<String> = (0..b.len())
        .map(|r| b.message(b.id_at(r).unwrap()).unwrap().to_plain_text())
        .collect();
    let kept: Vec<String> = (0..300)
        .filter(|i| i % 50 != 15)
        .map(|i| format!("old {i}"))
        .collect();
    assert_eq!(&order[..kept.len()], &kept[..]);
    assert_eq!(order[kept.len()], "anchor");
    for r in 0..b.len() {
        assert_eq!(b.row_of(b.id_at(r).unwrap()), Some(r));
    }
}

#[test]
fn a_full_scrollback_trims_live_rows_and_keeps_loaded_history() {
    // A "Load older" page on a full scrollback used to be trimmed away,
    // whole, by the next live message. History doesn't count against the
    // cap; the oldest live row goes instead.
    let m = FixedMeasure::new(8);
    let mut b = ChatBuffer::new(params(400));
    b.set_max_rows(5, &m);
    let history = |t: &str| Message {
        kind: crate::MessageKind::History {
            server_message_id: 0,
        },
        ..Message::system(ParsedText::plain(t))
    };
    let live = |t: &str| Message {
        kind: crate::MessageKind::Live,
        ..Message::system(ParsedText::plain(t))
    };
    for i in 0..5 {
        b.append(live(&format!("live {i}")), &m);
    }
    let top = b.id_at(0);
    for i in 0..3 {
        b.insert_before(top, history(&format!("older {i}")), &m);
    }
    b.append(live("new"), &m);
    b.append(live("newer"), &m);
    b.reindex();
    let rows: Vec<String> = (0..b.len())
        .map(|r| b.message(b.id_at(r).unwrap()).unwrap().to_plain_text())
        .collect();
    assert_eq!(
        rows,
        ["older 0", "older 1", "older 2", "live 2", "live 3", "live 4", "new", "newer"]
    );
    for r in 0..b.len() {
        assert_eq!(b.row_of(b.id_at(r).unwrap()), Some(r));
    }

    // Live rows ahead of the history block still go first, the cheap way.
    let mut b = ChatBuffer::new(params(400));
    b.set_max_rows(3, &m);
    b.append(live("notice"), &m);
    b.append(history("history"), &m);
    for i in 0..3 {
        b.append(live(&format!("live {i}")), &m);
    }
    let rows: Vec<String> = (0..b.len())
        .map(|r| b.message(b.id_at(r).unwrap()).unwrap().to_plain_text())
        .collect();
    assert_eq!(rows, ["history", "live 0", "live 1", "live 2"]);

    // A history row replaced by a live one counts again.
    let id = b.id_at(0).unwrap();
    assert!(b.replace(id, live("was history"), &m));
    assert_eq!(b.len(), 3);
}

#[test]
fn buffer_stale_mark_is_inert_not_fatal() {
    // The whole reason marks replaced raw textentry pointers.
    let m = FixedMeasure::new(8);
    let mut b = ChatBuffer::new(params(400));
    let id = b.append(Message::system(ParsedText::plain("x")), &m);
    assert!(b.remove(id, &m));
    assert!(!b.remove(id, &m), "second remove is a no-op, not a crash");
    assert_eq!(b.row_of(id), None);
    assert!(b.message(id).is_none());
}

#[test]
fn buffer_trim_drops_oldest() {
    let m = FixedMeasure::new(8);
    let mut b = ChatBuffer::new(params(400));
    b.set_max_rows(50, &m);
    for i in 0..200 {
        b.append(Message::system(ParsedText::plain(format!("{i}"))), &m);
    }
    assert_eq!(b.len(), 50);
    assert_eq!(b.message_at(0).unwrap().to_plain_text(), "150");
    assert_eq!(b.message_at(49).unwrap().to_plain_text(), "199");
}

/// Trimming keeps the id → position map in step by offset rather than by
/// rebuild. Check every mark against the rows themselves after trims mixed
/// with the operations that do dirty the map, in both of its states.
#[test]
fn buffer_positions_survive_trims() {
    fn check(b: &mut ChatBuffer, ids: &[MessageId]) {
        for &id in ids {
            let scan = (0..b.len()).find(|&r| b.id_at(r) == Some(id));
            assert_eq!(b.row_of(id), scan, "row_of({id:?}) disagrees with the rows");
        }
    }
    let m = FixedMeasure::new(8);
    let mut b = ChatBuffer::new(params(400));
    b.set_max_rows(20, &m);
    let mut ids = Vec::new();
    for i in 0..300 {
        ids.push(b.append(Message::system(ParsedText::plain(format!("{i}"))), &m));
        match i % 37 {
            // Dirty the map, then keep trimming before anything reads it.
            5 => {
                let front = b.id_at(0);
                ids.push(b.insert_before(front, Message::system(ParsedText::plain("old")), &m));
            }
            // Remove from the middle; `remove` reindexes first.
            11 => {
                let mid = b.id_at(b.len() / 2).unwrap();
                assert!(b.remove(mid, &m));
            }
            // A read in the clean state, between trims.
            23 => b.reindex(),
            _ => {}
        }
        if i % 7 == 0 {
            check(&mut b, &ids);
        }
    }
    check(&mut b, &ids);
    b.clear();
    ids.push(b.append(Message::system(ParsedText::plain("fresh")), &m));
    check(&mut b, &ids);
}

#[test]
fn buffer_clear_invalidates_every_mark() {
    let m = FixedMeasure::new(8);
    let mut b = ChatBuffer::new(params(400));
    let id = b.append(Message::system(ParsedText::plain("x")), &m);
    b.clear();
    assert_eq!(b.row_of(id), None);
    assert_eq!(b.len(), 0);
    assert_eq!(b.total_height(), 0);
}

#[test]
fn buffer_image_decode_grows_the_row() {
    let m = FixedMeasure::new(8);
    let mut b = ChatBuffer::new(params(400));
    let msg = Message {
        kind: crate::message::MessageKind::Live,
        timestamp: 0,
        speaker: None,
        gutter: None,
        blocks: vec![Block::Image {
            token: 42,
            size: None,
            alt: "[image]".into(),
        }]
        .into(),
        flags: MessageFlagsNone::NONE,
    };
    let id = b.append(msg, &m);
    b.ensure_layout(0, &m);
    let before = b.total_height();

    assert_eq!(b.find_image(42), Some(id));
    assert!(b.set_image_size(
        id,
        42,
        Some(ImageSize {
            width: 200,
            height: 300
        }),
        &m
    ));
    b.ensure_layout(0, &m);
    let after = b.total_height();
    assert!(
        after > before + 200,
        "row must grow to the decoded height ({before} -> {after})"
    );
}

#[test]
fn buffer_resize_does_not_measure_everything() {
    // The O(visible) claim. After a width change every row is
    // unmeasured; laying out the visible slice must measure only that
    // slice, not the whole buffer.
    let m = FixedMeasure::new(8);
    let mut b = ChatBuffer::new(params(400));
    for i in 0..1000 {
        b.append(Message::system(ParsedText::plain(format!("line {i}"))), &m);
    }
    for r in 0..1000 {
        b.ensure_layout(r, &m);
    }
    assert_eq!(b.index_mut().unmeasured_count(), 0);

    b.set_width(200);
    assert_eq!(b.index_mut().unmeasured_count(), 1000);

    let off = b.scroll_offset(100);
    let visible = b.ensure_visible(off, 100, &m);
    assert!(visible.len() < 50, "only the viewport was laid out");
    let remaining = b.index_mut().unmeasured_count();
    assert!(
        remaining > 900,
        "the other ~1000 rows must stay unmeasured, {remaining} left"
    );
}

#[test]
fn buffer_indent_column_grows_to_widest_nick() {
    let m = FixedMeasure::new(8);
    let mut p = params(600);
    p.indent = true;
    let mut b = ChatBuffer::new(p);
    b.append(
        Message::live(Speaker::new(1, "al"), ParsedText::plain("hi")),
        &m,
    );
    b.ensure_layout(0, &m);
    let narrow = b.layout_at(0).unwrap().natural_indent;

    b.append(
        Message::live(
            Speaker::new(2, "a-very-long-nickname"),
            ParsedText::plain("hi"),
        ),
        &m,
    );
    b.ensure_layout(1, &m);
    let wide = b.layout_at(1).unwrap().natural_indent;
    assert!(wide > narrow);
}

#[test]
fn every_visible_row_has_a_layout_after_ensure_visible() {
    // The first-paint garble, reproduced.
    //
    // `ensure_layout` widens the shared gutter when it meets a wider
    // nick, and that invalidates every row's cached layout — including
    // rows laid out earlier in this same `ensure_visible` pass. The view
    // then finds `layout_at(row) == None` for them and skips drawing
    // them entirely, so the first paint of a fresh buffer comes out
    // shredded and the next message (by which time the gutter has
    // settled) looks fine.
    //
    // The contract `ensure_visible` owes its caller: every row it
    // returns is laid out and ready to draw.
    let m = FixedMeasure::new(8);
    let mut p = params(600);
    p.indent = true;
    let mut b = ChatBuffer::new(p);

    // Nicks get progressively wider, so the gutter grows repeatedly
    // partway through the visible range.
    for i in 0..30 {
        b.append(
            Message::live(
                Speaker::new(i as u64, "n".repeat(1 + i as usize)),
                ParsedText::plain("hello there"),
            ),
            &m,
        );
    }

    let off = b.scroll_offset(400);
    let rows = b.ensure_visible(off, 400, &m);
    assert!(!rows.is_empty());
    for r in &rows {
        assert!(
            b.layout_at(*r).is_some(),
            "row {r} was returned by ensure_visible but has no layout — \
             the view will skip it and the paint comes out garbled"
        );
    }
}

#[test]
fn buffer_indent_column_is_capped() {
    let m = FixedMeasure::new(8);
    let mut p = params(2000);
    p.indent = true;
    p.max_indent = 64;
    let mut b = ChatBuffer::new(p);
    b.append(
        Message::live(
            Speaker::new(1, "an-extremely-long-nickname-that-should-be-clamped"),
            ParsedText::plain("hi"),
        ),
        &m,
    );
    b.ensure_layout(0, &m);
    assert_eq!(b.layout_at(0).unwrap().natural_indent, 64);
}

#[test]
fn buffer_zoom_invalidates_layout() {
    let m = FixedMeasure::new(8);
    let mut b = ChatBuffer::new(params(400));
    b.append(Message::system(ParsedText::plain("hello")), &m);
    b.ensure_layout(0, &m);
    assert_eq!(b.index_mut().unmeasured_count(), 0);
    b.set_zoom_permille(1500);
    assert_eq!(
        b.index_mut().unmeasured_count(),
        1,
        "a zoom change must invalidate cached layout"
    );
}

#[test]
fn buffer_scroll_offset_never_exceeds_extent() {
    let (mut b, _m) = buf();
    for y in [0u64, 10, 1000, 100_000, u64::MAX / 2] {
        b.scroll_to(y, 100, 4);
        let off = b.scroll_offset(100);
        assert!(off <= b.total_height(), "offset {off} out of range");
    }
}

#[test]
fn anchor_default_is_following() {
    let a = ScrollAnchor::default();
    assert_eq!(a.gravity, Gravity::Bottom);
    assert!(a.is_following());
    assert!(a.message.is_none());
}

// ---------------------------------------------------------------- selection

use crate::select::{Caret, RowSelection, Selection};
use crate::wrap::LineSource;

fn sel_buf() -> (ChatBuffer, FixedMeasure) {
    let m = FixedMeasure::new(10);
    let mut p = params(500);
    p.indent = false;
    let mut b = ChatBuffer::new(p);
    for s in ["alpha", "bravo", "charlie"] {
        b.append(Message::system(ParsedText::plain(s)), &m);
    }
    for r in 0..3 {
        b.ensure_layout(r, &m);
    }
    (b, m)
}

fn caret(b: &ChatBuffer, row: usize, offset: usize) -> Caret {
    Caret {
        message: b.id_at(row).unwrap(),
        source: LineSource::Block(0),
        offset,
    }
}

#[test]
fn hit_test_maps_pixels_to_offsets() {
    let (mut b, m) = sel_buf();
    // Row 0 spans y 0..16 with a 10px-per-char measurer.
    let c = b.hit_test(0, 0, &m).expect("hit");
    assert_eq!(c.offset, 0);
    let c = b.hit_test(25, 0, &m).expect("hit");
    assert_eq!(c.offset, 2, "25px in is two characters at 10px each");
    // Far right of a short line selects through its end.
    let c = b.hit_test(9999, 0, &m).expect("hit");
    assert_eq!(c.offset, 5, "past the end clamps to the line length");
}

#[test]
fn hit_test_past_the_bottom_clamps_to_the_last_row() {
    // A drag that runs off the bottom must keep selecting, not stop.
    let (mut b, m) = sel_buf();
    let last = b.id_at(2).unwrap();
    let c = b.hit_test(0, 1_000_000, &m).expect("clamps");
    assert_eq!(c.message, last);
}

#[test]
fn hit_test_on_empty_buffer_is_none() {
    let m = FixedMeasure::new(10);
    let mut b = ChatBuffer::new(params(500));
    assert!(b.hit_test(0, 0, &m).is_none());
}

#[test]
fn selection_within_one_row() {
    let (b, _m) = sel_buf();
    let sel = Selection::new(caret(&b, 0, 1), caret(&b, 0, 4));
    assert_eq!(
        b.row_selection(0, &sel),
        RowSelection::Partial {
            start: (LineSource::Block(0), 1),
            end: (LineSource::Block(0), 4),
        }
    );
    assert_eq!(b.row_selection(1, &sel), RowSelection::None);
    assert_eq!(b.selected_text(&sel), "lph");
}

#[test]
fn selection_across_rows_joins_with_newlines() {
    let (b, _m) = sel_buf();
    let sel = Selection::new(caret(&b, 0, 2), caret(&b, 2, 4));
    assert_eq!(b.row_selection(1, &sel), RowSelection::All);
    assert_eq!(b.selected_text(&sel), "pha\nbravo\nchar");
}

#[test]
fn selection_dragged_upwards_is_the_same_range() {
    // anchor after focus in document order — dragging up must not
    // produce an empty or inverted selection.
    let (b, _m) = sel_buf();
    let down = Selection::new(caret(&b, 0, 2), caret(&b, 2, 4));
    let up = Selection::new(caret(&b, 2, 4), caret(&b, 0, 2));
    assert_eq!(b.selected_text(&down), b.selected_text(&up));
}

#[test]
fn selection_orders_by_row_not_by_message_id() {
    // The trap: ids are allocated in *creation* order, but a
    // chat-history batch inserts *older* messages with *higher* ids.
    // Ordering by id would invert the selection after a backfill.
    let m = FixedMeasure::new(10);
    let mut p = params(500);
    p.indent = false;
    let mut b = ChatBuffer::new(p);
    let live = b.append(Message::system(ParsedText::plain("live")), &m);
    // Higher id, but lands *above* the live row.
    let older = b.insert_before(Some(live), Message::system(ParsedText::plain("older")), &m);
    assert!(older.0 > live.0, "the backfilled id is the higher one");
    b.reindex();
    assert_eq!(b.row_of(older), Some(0));

    let sel = Selection::new(
        Caret {
            message: older,
            source: LineSource::Block(0),
            offset: 0,
        },
        Caret {
            message: live,
            source: LineSource::Block(0),
            offset: 4,
        },
    );
    let (start, end) = sel.ordered(|id| b.row_of(id));
    assert_eq!(start.message, older, "document order, not id order");
    assert_eq!(end.message, live);
    assert_eq!(b.selected_text(&sel), "older\nlive");
}

#[test]
fn empty_selection_yields_nothing() {
    let (b, _m) = sel_buf();
    let sel = Selection::new(caret(&b, 1, 3), caret(&b, 1, 3));
    assert!(sel.is_empty());
    assert_eq!(b.selected_text(&sel), "");
    assert_eq!(b.row_selection(1, &sel), RowSelection::None);
}

#[test]
fn selection_over_an_image_copies_its_alt_text() {
    // Not all-or-nothing like xtext: dragging across a picture should
    // put something meaningful on the clipboard.
    let m = FixedMeasure::new(10);
    let mut p = params(500);
    p.indent = false;
    let mut b = ChatBuffer::new(p);
    b.append(Message::system(ParsedText::plain("before")), &m);
    b.append(
        Message {
            kind: crate::message::MessageKind::Live,
            timestamp: 0,
            speaker: None,
            gutter: None,
            blocks: vec![Block::Image {
                token: 1,
                size: Some(ImageSize {
                    width: 40,
                    height: 40,
                }),
                alt: "[image: cat.png]".into(),
            }]
            .into(),
            flags: MessageFlagsNone::NONE,
        },
        &m,
    );
    b.append(Message::system(ParsedText::plain("after")), &m);
    b.reindex();

    let sel = Selection::new(caret(&b, 0, 0), caret(&b, 2, 5));
    assert!(
        b.selected_text(&sel).contains("[image: cat.png]"),
        "got {:?}",
        b.selected_text(&sel)
    );
}

#[test]
fn selection_survives_a_resize() {
    // The reason a Caret names (message, source, offset) rather than
    // pixels: re-wrapping must not move the selection.
    let (mut b, m) = sel_buf();
    let sel = Selection::new(caret(&b, 0, 1), caret(&b, 2, 4));
    let before = b.selected_text(&sel);
    b.set_width(80);
    for r in 0..3 {
        b.ensure_layout(r, &m);
    }
    assert_eq!(b.selected_text(&sel), before, "resize moved the selection");
}

#[test]
fn gutter_is_right_aligned_against_the_body_column() {
    // The bug from the first live screenshots: the gutter drew hard left
    // while message bodies moved right as the shared column grew, so
    // "[hx]" and its text drifted apart as soon as a wider nick arrived.
    //
    // Root cause was the view deriving the gutter x from
    // params().indent_width, which ensure_layout only ever set on a
    // local copy — so it read back 0 forever. The x now comes from the
    // line box, computed here, and this pins it.
    let m = FixedMeasure::new(10);
    let mut p = params(600);
    p.indent = true;
    p.indent_width = 200;
    p.gutter_gap = 6;
    let msg = Message {
        kind: crate::message::MessageKind::Live,
        timestamp: 0,
        speaker: None,
        gutter: Some(ParsedText::plain("<alice>")), // 7 chars = 70px
        blocks: vec![Block::Text(ParsedText::plain("hi"))].into(),
        flags: MessageFlagsNone::NONE,
    };
    let l = layout_message(&msg, &p, LayoutGeneration::default(), &m);
    let g = l
        .lines
        .iter()
        .find(|lb| lb.source == crate::wrap::LineSource::Gutter)
        .expect("gutter line box");
    assert_eq!(
        g.x, 124,
        "gutter should end one gap short of the body column \
         (200 - 70 - 6), not sit at 0"
    );
    let body = l
        .lines
        .iter()
        .find(|lb| matches!(lb.source, crate::wrap::LineSource::Block(_)))
        .expect("body line box");
    assert_eq!(body.x, 200);
    assert!(
        g.x + 70 <= body.x,
        "gutter must not overlap the body column"
    );
}

#[test]
fn hit_test_distinguishes_gutter_from_body_on_the_same_line() {
    // The other half of the same bug: gutter and first body line share a
    // y band, so picking by y alone always returned whichever was pushed
    // first — which made nicks unselectable.
    let m = FixedMeasure::new(10);
    let mut p = params(600);
    p.indent = true;
    let mut b = ChatBuffer::new(p);
    b.append(
        Message {
            kind: crate::message::MessageKind::Live,
            timestamp: 0,
            speaker: None,
            gutter: Some(ParsedText::plain("<alice>")),
            blocks: vec![Block::Text(ParsedText::plain("hello"))].into(),
            flags: MessageFlagsNone::NONE,
        },
        &m,
    );
    b.ensure_layout(0, &m);
    let layout = b.layout_at(0).unwrap().clone();
    let g = layout
        .lines
        .iter()
        .find(|l| l.source == crate::wrap::LineSource::Gutter)
        .unwrap();
    let body = layout
        .lines
        .iter()
        .find(|l| matches!(l.source, crate::wrap::LineSource::Block(_)))
        .unwrap();

    let in_gutter = b.hit_test(g.x as i32 + 5, 0, &m).expect("hit");
    assert_eq!(
        in_gutter.source,
        crate::wrap::LineSource::Gutter,
        "a click on the nick must resolve to the gutter"
    );
    let in_body = b.hit_test(body.x as i32 + 5, 0, &m).expect("hit");
    assert!(
        matches!(in_body.source, crate::wrap::LineSource::Block(_)),
        "a click on the message must resolve to the body"
    );
}

#[test]
fn selecting_a_nick_yields_the_nick_text() {
    let m = FixedMeasure::new(10);
    let mut p = params(600);
    p.indent = true;
    let mut b = ChatBuffer::new(p);
    b.append(
        Message {
            kind: crate::message::MessageKind::Live,
            timestamp: 0,
            speaker: None,
            gutter: Some(ParsedText::plain("<alice>")),
            blocks: vec![Block::Text(ParsedText::plain("hello"))].into(),
            flags: MessageFlagsNone::NONE,
        },
        &m,
    );
    b.ensure_layout(0, &m);
    b.reindex();
    let id = b.id_at(0).unwrap();
    let sel = Selection::new(
        Caret {
            message: id,
            source: crate::wrap::LineSource::Gutter,
            offset: 0,
        },
        Caret {
            message: id,
            source: crate::wrap::LineSource::Gutter,
            offset: 7,
        },
    );
    assert_eq!(b.selected_text(&sel), "<alice>");
}

// ------------------------------------------------------------------- links

#[test]
fn add_link_over_plain_text() {
    let mut p = ParsedText::plain("see https://example.com now");
    let id = p.add_link(4..23, "https://example.com").expect("link");
    assert_eq!(id, 0);
    assert_eq!(p.links[0].href, "https://example.com");
    assert_eq!(p.style_at(4).link, Some(0));
    assert!(p.style_at(4).attrs.contains(Attrs::UNDERLINE));
    assert_eq!(p.style_at(0).link, None, "text before is untouched");
    assert_eq!(p.style_at(24).link, None, "text after is untouched");
    assert_eq!(
        p.link_at(10).map(|l| l.href.as_str()),
        Some("https://example.com")
    );
}

#[test]
fn add_link_inside_a_styled_run_keeps_the_style() {
    // A URL inside a bold message should stay bold *and* become a link.
    let mut p = markdown::parse_inline("**see https://example.com ok**");
    let start = p.text.find("https").unwrap();
    let end = start + "https://example.com".len();
    p.add_link(start..end, "https://example.com").unwrap();
    let s = p.style_at(start);
    assert!(s.attrs.contains(Attrs::BOLD), "lost the bold");
    assert!(s.attrs.contains(Attrs::UNDERLINE));
    assert_eq!(s.link, Some(0));
    // And the bold either side survives without the link.
    assert!(p.style_at(0).attrs.contains(Attrs::BOLD));
    assert_eq!(p.style_at(0).link, None);
}

#[test]
fn add_link_straddling_a_style_boundary() {
    // The case that makes naive span rewriting corrupt the list.
    let mut p = markdown::parse_inline("**bold**plain");
    assert_eq!(p.text, "boldplain");
    p.add_link(2..9, "https://x.example").unwrap();
    p.debug_assert_well_formed();
    assert_eq!(p.style_at(2).link, Some(0));
    assert_eq!(p.style_at(8).link, Some(0));
    assert!(
        p.style_at(2).attrs.contains(Attrs::BOLD),
        "still bold inside"
    );
    assert!(
        !p.style_at(8).attrs.contains(Attrs::BOLD),
        "not bold outside"
    );
}

#[test]
fn add_link_rejects_bad_ranges() {
    let mut p = ParsedText::plain("héllo");
    assert!(p.add_link(5..5, "x").is_none(), "empty range");
    assert!(p.add_link(0..999, "x").is_none(), "out of bounds");
    assert!(p.add_link(0..2, "x").is_none(), "splits a codepoint");
    assert!(p.links.is_empty());
}

#[test]
fn multiple_links_in_one_message() {
    let mut p = ParsedText::plain("a https://one.example b https://two.example");
    p.add_link(2..21, "https://one.example").unwrap();
    let s2 = p.text.rfind("https").unwrap();
    p.add_link(s2..p.text.len(), "https://two.example").unwrap();
    p.debug_assert_well_formed();
    assert_eq!(
        p.link_at(3).map(|l| l.href.as_str()),
        Some("https://one.example")
    );
    assert_eq!(
        p.link_at(s2 + 2).map(|l| l.href.as_str()),
        Some("https://two.example")
    );
    assert_eq!(p.link_at(22), None, "the space between is not a link");
}

// -------------------------------------------------------------- word_at

fn word_buf(text: &str) -> (ChatBuffer, FixedMeasure, Caret) {
    let m = FixedMeasure::new(10);
    let mut p = params(2000);
    p.indent = false;
    let mut b = ChatBuffer::new(p);
    b.append(Message::system(ParsedText::plain(text)), &m);
    b.ensure_layout(0, &m);
    b.reindex();
    let id = b.id_at(0).unwrap();
    (
        b,
        m,
        Caret {
            message: id,
            source: LineSource::Block(0),
            offset: 0,
        },
    )
}

fn word_at(text: &str, offset: usize) -> Option<String> {
    let (b, _m, mut c) = word_buf(text);
    c.offset = offset;
    b.word_at(&c)
}

#[test]
fn word_at_splits_like_xtext() {
    // xtext's is_del is space, newline, '<', '>' and NUL — angle
    // brackets included, which is what makes "<nick>" yield a bare
    // "nick". The C handlers match their targets by string, so this has
    // to agree byte-for-byte or hxmedia:N and the load-older sentinel
    // stop being recognised.
    assert_eq!(word_at("hello world", 0).as_deref(), Some("hello"));
    assert_eq!(word_at("hello world", 7).as_deref(), Some("world"));
    assert_eq!(word_at("<misha> hi", 2).as_deref(), Some("misha"));
    assert_eq!(word_at("a\nb", 2).as_deref(), Some("b"));
}

#[test]
fn word_at_finds_a_media_token() {
    // The exact shape inline_media_chat_word_click looks for.
    let w = word_at("see hxmedia:7 here", 6);
    assert_eq!(w.as_deref(), Some("hxmedia:7"));
}

#[test]
fn word_at_keeps_nbsp_joined_sentinels_whole() {
    // The chat-history sentinel is deliberately NBSP-joined so xtext's
    // tokenizer treats it as one word. NBSP is not an ASCII space, so it
    // must not split here either.
    let sentinel = "\u{2191}\u{a0}Load\u{a0}older\u{a0}messages";
    let line = format!("--- {sentinel} ---");
    let at = line.find('\u{2191}').unwrap();
    assert_eq!(word_at(&line, at).as_deref(), Some(sentinel));
}

#[test]
fn word_at_on_a_delimiter_or_empty_text() {
    assert_eq!(word_at("a b", 1), None, "the space itself is not a word");
    assert_eq!(word_at("", 0), None);
}

#[test]
fn word_at_handles_multibyte() {
    let (b, _m, mut c) = word_buf("héllo wörld");
    c.offset = 0;
    assert_eq!(b.word_at(&c).as_deref(), Some("héllo"));
    c.offset = 7; // inside "wörld"
    assert_eq!(b.word_at(&c).as_deref(), Some("wörld"));
}

#[test]
fn a_decoded_image_grows_its_row_without_moving_the_anchor() {
    // The thing xtext was worst at: a decode landing
    // *above* the viewport must not shift what the user is reading.
    // xtext had to recompute the entry's subline list, diff the count,
    // and patch num_lines plus every scroll anchor by hand; here the
    // anchor names a row, so it absorbs the change.
    let m = FixedMeasure::new(10);
    let mut p = params(400);
    p.indent = false;
    let mut b = ChatBuffer::new(p);

    let img = b.append(
        Message {
            kind: crate::message::MessageKind::Live,
            timestamp: 0,
            speaker: None,
            gutter: None,
            blocks: vec![Block::Image {
                token: 9,
                size: None,
                alt: "[image]".into(),
            }]
            .into(),
            flags: MessageFlagsNone::NONE,
        },
        &m,
    );
    for i in 0..40 {
        b.append(Message::system(ParsedText::plain(format!("line {i}"))), &m);
    }
    b.reindex();

    // Park the viewport well below the image.
    b.scroll_to(300, 100, 4);
    let anchored = b.anchor().message.expect("anchored");
    let anchor_row = b.row_of(anchored).unwrap();
    let offset_before = b.index_mut().offset_of(anchor_row);

    assert!(b.set_image_size(
        img,
        9,
        Some(ImageSize {
            width: 200,
            height: 300
        }),
        &m
    ));
    b.ensure_layout(0, &m);

    // The anchored row is still the same row, and still the same
    // distance into the buffer *relative to itself* — the content above
    // grew, so its absolute offset must have grown with it.
    assert_eq!(b.anchor().message, Some(anchored), "anchor changed rows");
    let after_row = b.row_of(anchored).unwrap();
    let offset_after = b.index_mut().offset_of(after_row);
    assert!(
        offset_after > offset_before,
        "the image grew above the viewport, so the anchored row must \
         have moved down in absolute terms ({offset_before} -> {offset_after})"
    );
}

// ---- selection across the gutter (the "drag left then up" bug) -------

fn gutter_buf() -> (ChatBuffer, FixedMeasure) {
    let m = FixedMeasure::new(10);
    let mut p = params(800);
    p.indent = true;
    let mut b = ChatBuffer::new(p);
    for nick in ["<a>", "<b>", "<c>"] {
        b.append(
            Message {
                kind: crate::message::MessageKind::Live,
                timestamp: 0,
                speaker: None,
                gutter: Some(ParsedText::plain(nick)),
                blocks: vec![Block::Text(ParsedText::plain("hello"))].into(),
                flags: MessageFlagsNone::NONE,
            },
            &m,
        );
    }
    for r in 0..3 {
        b.ensure_layout(r, &m);
    }
    b.reindex();
    (b, m)
}

#[test]
fn dragging_up_into_a_gutter_selects_the_rest_of_that_row() {
    // The reported bug. Dragging left-then-up puts the *start* of the
    // selection in row 0's gutter and the end in row 2's body. Row 0
    // should then be selected from that point in the gutter through the
    // end of its body — but RowSelection could only name one source, so
    // it highlighted the gutter and left the body unselected, which
    // reads as an inverted/partial selection.
    let (b, _m) = gutter_buf();
    let r0 = b.id_at(0).unwrap();
    let r2 = b.id_at(2).unwrap();
    let sel = Selection::new(
        // anchor: body of the last row (drag started here)
        Caret {
            message: r2,
            source: LineSource::Block(0),
            offset: 3,
        },
        // focus: gutter of the first row (dragged left and up)
        Caret {
            message: r0,
            source: LineSource::Gutter,
            offset: 1,
        },
    );
    let text = b.selected_text(&sel);
    assert!(
        text.contains("hello"),
        "row 0's body must be selected too, got {text:?}"
    );
    assert!(
        text.starts_with("a>"),
        "should start mid-gutter, got {text:?}"
    );
}

#[test]
fn same_row_gutter_to_body_orders_by_source_not_offset() {
    // Within one row the gutter precedes the body, but the two offset
    // spaces are unrelated — comparing them numerically (which is what
    // the tie-break did) can invert the selection.
    let (b, _m) = gutter_buf();
    let id = b.id_at(0).unwrap();
    let from_gutter = Caret {
        message: id,
        source: LineSource::Gutter,
        offset: 2,
    };
    let into_body = Caret {
        message: id,
        source: LineSource::Block(0),
        offset: 1,
    };

    let forward = Selection::new(from_gutter, into_body);
    let backward = Selection::new(into_body, from_gutter);
    assert_eq!(
        b.selected_text(&forward),
        b.selected_text(&backward),
        "dragging the same span in either direction must select the same text"
    );
    let t = b.selected_text(&forward);
    assert!(
        t.starts_with('>'),
        "starts partway into the gutter, got {t:?}"
    );
    assert!(t.ends_with('h'), "ends one char into the body, got {t:?}");
}

#[test]
fn a_row_with_no_gutter_still_reserves_the_stamp_column() {
    // Info lines (`[hx] …`) are appended with no nick column at all.
    // They still carry a timestamp, so the gutter has to be wide enough
    // for it — otherwise the body starts at 0 and the stamp draws
    // underneath the text.
    //
    // The rendering half of this was the actual reported bug: the view
    // drew the stamp only when a Gutter line box existed, so info lines
    // never got one.
    let m = FixedMeasure::new(10);
    let mut p = params(600);
    p.indent = true;
    p.stamp_width = 90;

    let bare = Message::system(ParsedText::plain("connecting..."));
    let l = layout_message(&bare, &p, LayoutGeneration::default(), &m);
    assert_eq!(
        l.natural_indent, 90,
        "a gutterless row must still reserve the stamp column"
    );

    // And a row *with* a nick reserves stamp + nick, not just the nick.
    let with_nick = Message {
        kind: crate::message::MessageKind::Live,
        timestamp: 0,
        speaker: None,
        gutter: Some(ParsedText::plain("<alice>")), // 70px
        blocks: vec![Block::Text(ParsedText::plain("hi"))].into(),
        flags: MessageFlagsNone::NONE,
    };
    let l2 = layout_message(&with_nick, &p, LayoutGeneration::default(), &m);
    assert!(
        l2.natural_indent >= 90 + 70,
        "stamp and nick share the gutter, got {}",
        l2.natural_indent
    );
}

// ---- word / line select ---------------------------------------------

#[test]
fn double_click_selects_the_word() {
    let (b, _m, mut c) = word_buf("hello brave world");
    c.offset = 8; // inside "brave"
    let sel = b.select_word(&c).expect("word");
    assert_eq!(b.selected_text(&sel), "brave");
}

#[test]
fn double_click_on_a_nick_selects_just_the_nick() {
    // xtext's tokenizer treats '<' and '>' as delimiters, which is what
    // makes double-clicking "<alice>" give you a bare nick to paste.
    let (b, _m) = gutter_buf();
    let id = b.id_at(0).unwrap();
    let c = Caret {
        message: id,
        source: LineSource::Gutter,
        offset: 1,
    };
    let sel = b.select_word(&c).expect("word");
    assert_eq!(b.selected_text(&sel), "a");
}

#[test]
fn double_click_on_whitespace_selects_nothing() {
    let (b, _m, mut c) = word_buf("a b");
    c.offset = 1;
    assert!(b.select_word(&c).is_none());
}

#[test]
fn triple_click_selects_the_whole_row_including_the_gutter() {
    let (b, _m) = gutter_buf();
    let sel = b.select_row(1).expect("row");
    let text = b.selected_text(&sel);
    assert!(text.contains("<b>"), "gutter missing from {text:?}");
    assert!(text.contains("hello"), "body missing from {text:?}");
}

#[test]
fn triple_click_past_the_end_is_none() {
    let (b, _m) = gutter_buf();
    assert!(b.select_row(99).is_none());
}

#[test]
fn selected_rows_keeps_row_boundaries_across_embedded_newlines() {
    // The autocopy-timestamp bug in miniature: a row whose text spans
    // several lines. Splitting the joined output by '\n' would report
    // more "rows" than exist and desynchronise anything keyed on row
    // index — which is exactly how stamps ended up on the wrong lines.
    let m = FixedMeasure::new(10);
    let mut p = params(2000);
    p.indent = false;
    let mut b = ChatBuffer::new(p);
    b.append(Message::system(ParsedText::plain("one\ntwo\nthree")), &m);
    b.append(Message::system(ParsedText::plain("second")), &m);
    b.reindex();
    for r in 0..2 {
        b.ensure_layout(r, &m);
    }

    let sel = Selection::new(
        Caret {
            message: b.id_at(0).unwrap(),
            source: LineSource::Block(0),
            offset: 0,
        },
        Caret {
            message: b.id_at(1).unwrap(),
            source: LineSource::Block(0),
            offset: 6,
        },
    );

    let rows = b.selected_rows(&sel);
    assert_eq!(
        rows.len(),
        2,
        "two rows selected, whatever their line count"
    );
    assert_eq!(rows[0].0, 0);
    assert_eq!(rows[0].1, "one\ntwo\nthree");
    assert_eq!(rows[1].0, 1);
    assert_eq!(rows[1].1, "second");

    // And the joined form has more lines than rows, which is precisely
    // why callers must not infer one from the other.
    let joined = b.selected_text(&sel);
    assert_eq!(joined.lines().count(), 4);
    assert!(joined.lines().count() > rows.len());
}

#[test]
fn selected_rows_separates_blocks_the_way_to_plain_text_does() {
    // Whole-row copying used Message::to_plain_text, which puts a
    // newline between blocks. Rebuilding the text span-by-span for
    // partial selections must not quietly change that: joining every
    // source with a space runs a code block into the paragraph after
    // it. The gutter is the one place a space is right — nick and body
    // read as a single line.
    let m = FixedMeasure::new(10);
    let mut p = params(2000);
    p.indent = true;
    let mut b = ChatBuffer::new(p);
    let msg = Message {
        kind: crate::message::MessageKind::Live,
        timestamp: 0,
        speaker: None,
        gutter: Some(ParsedText::plain("<a>")),
        blocks: vec![
            Block::Text(ParsedText::plain("look:")),
            Block::Code {
                text: "int x;".into(),
                language: None,
            },
            Block::Text(ParsedText::plain("done")),
        ]
        .into(),
        flags: MessageFlagsNone::NONE,
    };
    let id = b.append(msg, &m);
    b.reindex();
    b.ensure_layout(0, &m);

    let sel = Selection::new(
        Caret {
            message: id,
            source: LineSource::Gutter,
            offset: 0,
        },
        Caret {
            message: id,
            source: LineSource::Block(2),
            offset: 4,
        },
    );
    let rows = b.selected_rows(&sel);
    assert_eq!(rows.len(), 1);
    assert_eq!(rows[0].1, "<a> look:\nint x;\ndone");

    // And a whole-row select agrees with the model's own rendering.
    let whole = b.select_row(0).expect("row 0 selectable");
    let rows = b.selected_rows(&whole);
    let plain = b.message(id).unwrap().to_plain_text();
    assert_eq!(rows[0].1, format!("<a> {plain}"));
}

#[test]
fn word_bounds_does_not_panic_on_a_caret_inside_a_codepoint() {
    // caret.offset arrives from C through the FFI and is not guaranteed
    // to sit on a char boundary. Slicing off one panics, and a panic
    // here unwinds into GTK and aborts the process, so clamp instead.
    let m = FixedMeasure::new(10);
    let mut p = params(2000);
    p.indent = false;
    let mut b = ChatBuffer::new(p);
    // "naïve" — the ï is two bytes at 2..4.
    let id = b.append(Message::system(ParsedText::plain("naïve word")), &m);
    b.reindex();
    b.ensure_layout(0, &m);

    let mid = Caret {
        message: id,
        source: LineSource::Block(0),
        offset: 3,
    };
    assert_eq!(
        b.word_bounds(&mid),
        Some((0, 6)),
        "clamps down into 'naïve'"
    );

    // Past the end clamps to the end, which is not inside a word.
    let past = Caret {
        message: id,
        source: LineSource::Block(0),
        offset: 999,
    };
    assert!(b.word_bounds(&past).is_none());

    // And select_word off the same caret yields the whole word.
    let sel = b.select_word(&mid).expect("word selected");
    assert_eq!(b.selected_rows(&sel)[0].1, "naïve");
}

#[test]
fn dragging_the_separator_pins_the_gutter() {
    // The gutter auto-grows to fit the widest nick. Once the user drags
    // the separator, that has to stop: xtext kept auto-growing after a
    // drag, so a long nick would silently undo a narrowing the user had
    // just made by hand.
    let m = FixedMeasure::new(10);
    let mut p = params(1200);
    p.indent = true;
    p.max_indent = 400;
    let mut b = ChatBuffer::new(p);

    let say = |nick: &str| Message {
        kind: crate::message::MessageKind::Live,
        timestamp: 0,
        speaker: None,
        gutter: Some(ParsedText::plain(nick)),
        blocks: vec![Block::Text(ParsedText::plain("hi"))].into(),
        flags: MessageFlagsNone::NONE,
    };

    b.append(say("<a>"), &m);
    b.ensure_layout(0, &m);
    let auto = b.indent_width();
    assert!(auto > 0 && !b.indent_pinned());

    // A longer nick still widens it while unpinned.
    b.append(say("<averyverylongnick>"), &m);
    b.ensure_layout(1, &m);
    assert!(b.indent_width() > auto, "gutter should auto-grow");

    // Pin it narrower than the widest nick.
    assert!(b.set_indent_width(40));
    assert!(b.indent_pinned());
    assert_eq!(b.indent_width(), 40);

    // Now an even longer nick must not move it.
    b.append(say("<anevenlongernickthanbefore>"), &m);
    b.reindex();
    for r in 0..3 {
        b.ensure_layout(r, &m);
    }
    assert_eq!(b.indent_width(), 40, "pinned gutter must not auto-grow");

    // Neither must a clear or a stamp-width change, both of which reset
    // the auto-sized gutter.
    b.set_stamp_width(60);
    assert_eq!(b.indent_width(), 40, "stamp width must not unpin");
    b.clear();
    assert_eq!(b.indent_width(), 40, "clearing the buffer must not unpin");

    // Unpinning hands it back to the auto path.
    b.unpin_indent();
    assert!(!b.indent_pinned());
    b.append(say("<a>"), &m);
    b.ensure_layout(0, &m);
    assert_ne!(b.indent_width(), 40);
}

#[test]
fn a_pinned_gutter_has_a_floor() {
    // Dragging the separator to zero would leave nothing to grab, so the
    // divider could never be dragged back out.
    let m = FixedMeasure::new(10);
    let mut p = params(1200);
    p.indent = true;
    let mut b = ChatBuffer::new(p);
    b.set_indent_width(0);
    assert_eq!(b.indent_width(), crate::buffer::MIN_INDENT);
    let _ = &m;
}

#[test]
fn selected_rows_omits_rows_that_contribute_nothing() {
    // A selection that starts at the very end of one row and ends at the
    // very start of another *covers* three rows but only one of them has
    // any selected text in it. Reporting the empty two puts blank lines
    // in the clipboard and, worse, gives AUTOCOPY_STAMP two rows to
    // prefix timestamps onto that have nothing in them.
    let m = FixedMeasure::new(10);
    let mut p = params(2000);
    p.indent = false;
    let mut b = ChatBuffer::new(p);
    for t in ["first", "middle", "last"] {
        b.append(Message::system(ParsedText::plain(t)), &m);
    }
    b.reindex();
    for r in 0..3 {
        b.ensure_layout(r, &m);
    }

    let sel = Selection::new(
        Caret {
            message: b.id_at(0).unwrap(),
            source: LineSource::Block(0),
            offset: 5, // end of "first"
        },
        Caret {
            message: b.id_at(2).unwrap(),
            source: LineSource::Block(0),
            offset: 0, // start of "last"
        },
    );

    let rows = b.selected_rows(&sel);
    assert_eq!(rows.len(), 1, "only the middle row has selected text");
    assert_eq!(rows[0], (1, "middle".to_string()));
    assert_eq!(
        b.selected_text(&sel),
        "middle",
        "no leading/trailing blanks"
    );
}

#[test]
fn selected_rows_keeps_a_genuinely_empty_row() {
    // The converse: a blank line inside a selection is real content and
    // has to survive, so the skip above must key on "had text and none
    // of it was selected" rather than "produced no text".
    let m = FixedMeasure::new(10);
    let mut p = params(2000);
    p.indent = false;
    let mut b = ChatBuffer::new(p);
    for t in ["above", "", "below"] {
        b.append(Message::system(ParsedText::plain(t)), &m);
    }
    b.reindex();
    for r in 0..3 {
        b.ensure_layout(r, &m);
    }

    let sel = Selection::new(
        Caret {
            message: b.id_at(0).unwrap(),
            source: LineSource::Block(0),
            offset: 0,
        },
        Caret {
            message: b.id_at(2).unwrap(),
            source: LineSource::Block(0),
            offset: 5,
        },
    );
    let rows = b.selected_rows(&sel);
    assert_eq!(rows.len(), 3, "the blank line is content");
    assert_eq!(rows[1], (1, String::new()));
    assert_eq!(b.selected_text(&sel), "above\n\nbelow");
}

// ---------------------------------------------------------------- search

use crate::search::{self, SearchState};

#[test]
fn find_all_is_literal_and_non_overlapping() {
    assert_eq!(search::find_all("aaaa", "aa", true), vec![(0, 2), (2, 4)]);
    assert_eq!(
        search::find_all("abcabc", "abc", true),
        vec![(0, 3), (3, 6)]
    );
    assert_eq!(search::find_all("abc", "", true), vec![]);
    assert_eq!(search::find_all("", "abc", true), vec![]);
    // No regex vocabulary: metacharacters are just characters.
    assert_eq!(search::find_all("a.c", ".", true), vec![(1, 2)]);
    assert_eq!(search::find_all("abc", ".", true), vec![]);
}

#[test]
fn find_all_case_insensitive_returns_offsets_into_the_original() {
    // The trap this is written to avoid: lowercasing the haystack and
    // searching *that* gives offsets into a string the caller doesn't
    // have, because lowercasing can change byte length. U+0130 (İ) is
    // two bytes and lowercases to two *chars* (i + U+0307), so any
    // offset past it in a lowercased copy is wrong for the original.
    let hay = "İstanbul and stanbul";
    let hits = search::find_all(hay, "STANBUL", false);
    assert_eq!(hits.len(), 2);
    for (a, b) in hits {
        assert_eq!(
            &hay[a..b].to_lowercase(),
            "stanbul",
            "offsets must index the original"
        );
    }

    // Same-length folds work in both directions.
    assert_eq!(search::find_all("Grüße", "GRÜ", false), vec![(0, 4)]);
    assert_eq!(search::find_all("ÉCOLE", "école", false), vec![(0, 6)]);
}

#[test]
fn find_all_never_splits_a_codepoint() {
    // Every returned offset has to be a char boundary, or the renderer
    // slices off one and panics into GTK.
    let hay = "aé—b日本語aé";
    for needle in ["a", "é", "—", "本", "aé"] {
        for cs in [true, false] {
            for (a, b) in search::find_all(hay, needle, cs) {
                assert!(hay.is_char_boundary(a), "{needle:?} start {a}");
                assert!(hay.is_char_boundary(b), "{needle:?} end {b}");
            }
        }
    }
}

#[test]
fn search_cursor_wraps_in_both_directions() {
    let m = FixedMeasure::new(10);
    let mut p = params(2000);
    p.indent = false;
    let mut b = ChatBuffer::new(p);
    for t in ["needle one", "nothing", "needle two", "needle three"] {
        b.append(Message::system(ParsedText::plain(t)), &m);
    }
    b.reindex();

    let hits = b.search("needle", false);
    assert_eq!(hits.len(), 3, "one per matching row");

    let mut st = SearchState::new();
    st.set_results("needle", false, hits);
    assert_eq!(st.len(), 3);
    assert!(st.current().is_none(), "no match is current until stepped");

    // Forward from nothing selects the first, then wraps at the end.
    assert_eq!(st.step(1), Some(st.matches()[0]));
    assert_eq!(st.ordinal(), Some(1));
    st.step(1);
    st.step(1);
    assert_eq!(st.ordinal(), Some(3));
    st.step(1);
    assert_eq!(st.ordinal(), Some(1), "forward wraps to the first");

    // Backward from the first wraps to the last.
    st.step(-1);
    assert_eq!(st.ordinal(), Some(3));

    // Backward from nothing selects the last.
    let mut st2 = SearchState::new();
    st2.set_results("needle", false, b.search("needle", false));
    assert_eq!(st2.step(-1), st2.matches().last().copied());
}

#[test]
fn search_walks_rows_in_reading_order_including_gutters() {
    // Matches have to come back in the order the eye reads them —
    // gutter before body, row by row — or stepping through them jumps
    // around the screen.
    let m = FixedMeasure::new(10);
    let mut p = params(2000);
    p.indent = true;
    let mut b = ChatBuffer::new(p);
    for (nick, body) in [("<sam>", "hello sam"), ("<pat>", "sam said hi")] {
        b.append(
            Message {
                kind: crate::message::MessageKind::Live,
                timestamp: 0,
                speaker: None,
                gutter: Some(ParsedText::plain(nick)),
                blocks: vec![Block::Text(ParsedText::plain(body))].into(),
                flags: MessageFlagsNone::NONE,
            },
            &m,
        );
    }
    b.reindex();

    let hits = b.search("sam", false);
    let shape: Vec<_> = hits
        .iter()
        .map(|h| (b.row_of(h.message).unwrap(), h.source, h.start))
        .collect();
    assert_eq!(
        shape,
        vec![
            (0, LineSource::Gutter, 1),   // <sam>
            (0, LineSource::Block(0), 6), // hello sam
            (1, LineSource::Block(0), 0), // sam said hi
        ]
    );
}

#[test]
fn search_reaches_rows_that_were_never_laid_out() {
    // Searching the layout instead of the model would only ever find
    // what you had already scrolled to, which defeats the point.
    let m = FixedMeasure::new(10);
    let mut p = params(2000);
    p.indent = false;
    let mut b = ChatBuffer::new(p);
    for i in 0..500 {
        b.append(Message::system(ParsedText::plain(format!("line {i}"))), &m);
    }
    b.reindex();
    // Lay out only the first handful.
    for r in 0..5 {
        b.ensure_layout(r, &m);
    }
    let hits = b.search("line 499", false);
    assert_eq!(hits.len(), 1);
    assert_eq!(b.row_of(hits[0].message), Some(499));
}

#[test]
fn seek_from_starts_at_the_viewport_rather_than_the_top() {
    let m = FixedMeasure::new(10);
    let mut p = params(2000);
    p.indent = false;
    let mut b = ChatBuffer::new(p);
    for i in 0..20 {
        b.append(
            Message::system(ParsedText::plain(if i % 5 == 0 { "hit" } else { "miss" })),
            &m,
        );
    }
    b.reindex();

    let mut st = SearchState::new();
    st.set_results("hit", false, b.search("hit", false));
    assert_eq!(st.len(), 4); // rows 0, 5, 10, 15

    st.seek_from(|id| b.row_of(id), 7);
    assert_eq!(b.row_of(st.current().unwrap().message), Some(10));

    // Everything above the viewport: fall back to the last match, since
    // scrollback's interesting end is the recent one.
    st.seek_from(|id| b.row_of(id), 18);
    assert_eq!(b.row_of(st.current().unwrap().message), Some(15));
}

#[test]
fn reveal_leaves_an_already_visible_row_alone() {
    let m = FixedMeasure::new(10);
    let mut p = params(2000);
    p.indent = false;
    let mut b = ChatBuffer::new(p);
    for i in 0..200 {
        b.append(Message::system(ParsedText::plain(format!("line {i}"))), &m);
    }
    b.reindex();
    for r in 0..200 {
        b.ensure_layout(r, &m);
    }

    let vh = 100u32;
    // Park the viewport exactly on a row boundary so row 40 is *fully*
    // inside it — "visible" means the whole row, and picking an offset
    // at random lands on a row straddling the top edge.
    let top40 = b.index_mut().offset_of(40);
    b.scroll_to(top40, vh, 0);
    let before = b.scroll_offset(vh);
    assert_eq!(before, top40);

    let id = b.id_at(40).unwrap();
    b.reveal(id, vh, &m);
    assert_eq!(
        b.scroll_offset(vh),
        before,
        "fully visible row must not scroll"
    );

    // A row far away gets centred.
    let far = b.id_at(190).unwrap();
    b.reveal(far, vh, &m);
    let after = b.scroll_offset(vh);
    assert_ne!(after, before);
    let top = b.index_mut().offset_of(190);
    assert!(
        top >= after && top < after + vh as u64,
        "row 190 (at {top}) must be inside [{after}, {})",
        after + vh as u64
    );
}

#[test]
fn reveal_pulls_a_half_visible_row_fully_into_view() {
    // The converse of the case above, and the reason "visible" is the
    // whole row rather than any part of it: stepping onto a match whose
    // row is clipped by the top edge should show you the whole row, not
    // leave you reading the bottom half of it.
    let m = FixedMeasure::new(10);
    let mut p = params(2000);
    p.indent = false;
    let mut b = ChatBuffer::new(p);
    for i in 0..200 {
        b.append(Message::system(ParsedText::plain(format!("line {i}"))), &m);
    }
    b.reindex();
    for r in 0..200 {
        b.ensure_layout(r, &m);
    }

    let vh = 100u32;
    let top40 = b.index_mut().offset_of(40);
    let h40 = b.index_mut().height_at(40) as u64;
    assert!(h40 > 1, "need a row with height to clip");

    // Scroll so row 40 is cut in half by the top edge.
    b.scroll_to(top40 + h40 / 2, vh, 0);
    b.reveal(b.id_at(40).unwrap(), vh, &m);

    let after = b.scroll_offset(vh);
    assert!(
        top40 >= after && top40 + h40 <= after + vh as u64,
        "row 40 ({top40}..{}) must be wholly inside [{after}, {})",
        top40 + h40,
        after + vh as u64
    );
}

#[test]
fn scan_delims_reports_source_offsets_and_respects_flanking() {
    use crate::markdown::scan_delims;

    let src = "a **bold** b";
    let got = scan_delims(src);
    let shape: Vec<_> = got
        .iter()
        .map(|s| (&src[s.start..s.end], s.attrs, s.delim))
        .collect();
    assert_eq!(
        shape,
        vec![
            ("**", Attrs::BOLD, true),
            ("bold", Attrs::BOLD, false),
            ("**", Attrs::BOLD, true),
        ]
    );

    // The flanking rules are shared with the renderer, so arithmetic is
    // left alone here too — this is the one thing the tinting must not
    // get wrong, since it would light up ordinary prose.
    assert!(scan_delims("2 * 3 * 4").is_empty());
    assert!(scan_delims("a * b *").is_empty());
    // snake_case survives, same as in the renderer.
    assert!(scan_delims("some_var_name").is_empty());
    // Backslash hides a delimiter from tinting.
    assert!(scan_delims(r"\*not em\*").is_empty());
}

#[test]
fn scan_delims_agrees_with_the_renderer_on_what_is_styled() {
    // The two are separate passes (one reports source offsets, one
    // rendered offsets), so this pins the cases where they must agree:
    // whether a delimiter is live at all, and what attribute it carries.
    use crate::markdown::{parse_inline, scan_delims};
    for src in [
        "**bold**",
        "*it*",
        "`code`",
        "plain text",
        "2 * 3 * 4",
        "a **b** c *d* e",
        "snake_case_word",
    ] {
        let rendered = parse_inline(src);
        let styled_attrs: std::collections::BTreeSet<u8> = rendered
            .spans
            .iter()
            .map(|s| s.style.attrs.0)
            .filter(|a| *a != 0)
            .collect();
        let tinted_attrs: std::collections::BTreeSet<u8> = scan_delims(src)
            .iter()
            .filter(|s| !s.delim)
            .map(|s| s.attrs.0)
            .collect();
        assert_eq!(
            styled_attrs, tinted_attrs,
            "{src:?}: renderer and tinting disagree on what is styled"
        );
    }
}

#[test]
fn ensure_visible_can_widen_the_gutter_so_read_it_after() {
    // The fact behind a draw-ordering bug in the view: laying out a row
    // with a wider nick than any seen so far widens the *shared* gutter,
    // so `indent_width()` read before `ensure_visible` is stale for the
    // frame being drawn. The separator rule was read early and the rows
    // late, so on the first message that widened the gutter the rule
    // drew in the wrong place for exactly one frame.
    //
    // This pins the property rather than the pixel: if `ensure_visible`
    // ever stops being able to move the gutter, the ordering constraint
    // in `snapshot_content` can be relaxed — and if it can still move
    // it, the separator must keep being drawn afterwards.
    let m = FixedMeasure::new(10);
    let mut p = params(2000);
    p.indent = true;
    let mut b = ChatBuffer::new(p);

    // An info-shaped row with no gutter, then a real nick.
    b.append(Message::system(ParsedText::plain("connecting")), &m);
    b.append(
        Message {
            kind: crate::message::MessageKind::Live,
            timestamp: 0,
            speaker: None,
            gutter: Some(ParsedText::plain("<misha>")),
            blocks: vec![Block::Text(ParsedText::plain("hello hello"))].into(),
            flags: MessageFlagsNone::NONE,
        },
        &m,
    );
    b.reindex();

    let before = b.indent_width();
    let rows = b.ensure_visible(0, 10_000, &m);
    let after = b.indent_width();

    assert_eq!(rows.len(), 2, "both rows visible");
    assert!(
        after > before,
        "the nick row must widen the gutter ({before} -> {after})"
    );
}

// ---- message grouping ------------------------------------------------

fn said(uid: u16, nick: &str, body: &str, at: i64) -> Message {
    Message {
        kind: crate::message::MessageKind::Live,
        timestamp: at,
        speaker: if uid == 0 {
            None
        } else {
            Some(crate::message::Speaker::new(u64::from(uid), nick))
        },
        gutter: Some(ParsedText::plain(format!("<{nick}>"))),
        blocks: vec![Block::Text(ParsedText::plain(body))].into(),
        flags: MessageFlagsNone::NONE,
    }
}

fn grouped(b: &ChatBuffer, row: usize) -> bool {
    b.message_at(row)
        .unwrap()
        .flags
        .contains(MessageFlagsNone::GROUPED)
}

#[test]
fn consecutive_messages_from_one_speaker_group() {
    // The reported case: "hai / hai / hai" should read as one block
    // under one name, not repeat the nick three times.
    let m = FixedMeasure::new(10);
    let mut p = params(2000);
    p.indent = true;
    let mut b = ChatBuffer::new(p);
    for i in 0..4 {
        b.append(said(7, "misha", "hai", 1000 + i), &m);
    }
    b.reindex();

    assert!(!grouped(&b, 0), "the first of a run always shows its nick");
    for r in 1..4 {
        assert!(grouped(&b, r), "row {r} continues the run");
    }
}

#[test]
fn a_different_speaker_or_a_long_gap_breaks_the_run() {
    let m = FixedMeasure::new(10);
    let mut p = params(2000);
    p.indent = true;
    let mut b = ChatBuffer::new(p);
    b.append(said(7, "misha", "one", 1000), &m);
    b.append(said(7, "misha", "two", 1001), &m);
    b.append(said(9, "alice", "hi", 1002), &m); // different speaker
    b.append(said(7, "misha", "back", 1003), &m); // misha again, but after alice
    b.append(said(7, "misha", "later", 1003 + 9999), &m); // long gap
    b.reindex();

    assert!(!grouped(&b, 0));
    assert!(grouped(&b, 1));
    assert!(!grouped(&b, 2), "alice starts her own run");
    assert!(
        !grouped(&b, 3),
        "misha's return is a new run, not a continuation"
    );
    assert!(!grouped(&b, 4), "a long gap breaks the run");
}

#[test]
fn removing_a_runs_head_promotes_the_next_row() {
    // Same invariant as trimming, reached through remove: the row that
    // moves up into the head's place must show its nick again.
    let m = FixedMeasure::new(10);
    let mut p = params(2000);
    p.indent = true;
    let mut b = ChatBuffer::new(p);
    let head = b.append(said(7, "misha", "hai", 1000), &m);
    b.append(said(7, "misha", "hai", 1005), &m);
    b.reindex();
    assert!(grouped(&b, 1));
    assert!(b.remove(head, &m));
    assert!(!grouped(&b, 0), "the new head must show its nick");
}

#[test]
fn trimming_a_runs_head_promotes_the_next_row() {
    // The invariant that makes grouping safe: a row that suppresses its
    // nick must always have a row above it that showed one. Trim can
    // delete the head, and without re-deciding, every remaining message
    // in that run would render anonymously.
    let m = FixedMeasure::new(10);
    let mut p = params(2000);
    p.indent = true;
    let mut b = ChatBuffer::new(p);
    b.set_max_rows(3, &m);
    for i in 0..3 {
        b.append(said(7, "misha", "hai", 1000 + i), &m);
    }
    b.reindex();
    assert!(!grouped(&b, 0));
    assert!(grouped(&b, 1) && grouped(&b, 2));

    // One more message trims the head away.
    b.append(said(7, "misha", "hai", 1003), &m);
    b.reindex();
    assert_eq!(b.len(), 3);
    assert!(
        !grouped(&b, 0),
        "the new front row must show its nick — nothing above it can"
    );
    assert!(grouped(&b, 1) && grouped(&b, 2));
}

/// Trims and inserts regroup only the rows whose predecessor changed.
/// That is only sound because the flag depends on nothing further up, so
/// check it: after a mixed run of appends at the cap, mid-buffer inserts
/// and a history-style insert at the front, every flag must match what a
/// full re-evaluation of the buffer produces.
#[test]
fn local_regrouping_matches_a_full_pass() {
    let m = FixedMeasure::new(10);
    let mut p = params(2000);
    p.indent = true;
    let mut b = ChatBuffer::new(p);
    b.set_max_rows(40, &m);
    let speakers = [(7, "misha"), (7, "misha"), (9, "al"), (7, "misha")];
    let mut t = 1000;
    for i in 0..200usize {
        let (uid, nick) = speakers[i % speakers.len()];
        t += if i % 11 == 0 { 3600 } else { 5 };
        b.append(said(uid, nick, "hai", t), &m);
        if i % 13 == 0 {
            let at = b.id_at(b.len() / 3);
            let (uid, nick) = speakers[(i / 13) % speakers.len()];
            b.insert_before(at, said(uid, nick, "older", t - 7), &m);
        }
        if i % 17 == 0 {
            let front = b.id_at(0);
            b.insert_before(front, said(7, "misha", "history", 900), &m);
        }
    }
    let local: Vec<bool> = (0..b.len()).map(|r| grouped(&b, r)).collect();
    let gap = b.group_gap_secs();
    b.set_group_gap_secs(0, &m);
    b.set_group_gap_secs(gap, &m);
    let full: Vec<bool> = (0..b.len()).map(|r| grouped(&b, r)).collect();
    assert!(
        local.iter().any(|&g| g),
        "the corpus should produce some runs"
    );
    assert_eq!(local, full);
}

#[test]
fn inserting_before_re_decides_both_sides() {
    // Load-older inserts land in the middle of the buffer and can split
    // a run: the row below is no longer adjacent to what it continued.
    let m = FixedMeasure::new(10);
    let mut p = params(2000);
    p.indent = true;
    let mut b = ChatBuffer::new(p);
    let first = b.append(said(7, "misha", "one", 1000), &m);
    b.append(said(7, "misha", "two", 1001), &m);
    b.reindex();
    assert!(grouped(&b, 1));

    // Someone else's message arrives between them.
    b.insert_before(Some(b.id_at(1).unwrap()), said(9, "alice", "hi", 1000), &m);
    b.reindex();
    assert_eq!(b.len(), 3);
    assert_eq!(b.row_of(first), Some(0));
    assert!(!grouped(&b, 1), "alice does not continue misha");
    assert!(!grouped(&b, 2), "misha no longer follows himself");
}

#[test]
fn grouping_falls_back_to_the_nick_when_the_server_sends_no_uid() {
    // Older servers omit the UID chunk, so speaker is None. Grouping on
    // the gutter text keeps the feature working there rather than
    // silently switching itself off.
    let m = FixedMeasure::new(10);
    let mut p = params(2000);
    p.indent = true;
    let mut b = ChatBuffer::new(p);
    b.append(said(0, "misha", "one", 1000), &m);
    b.append(said(0, "misha", "two", 1001), &m);
    b.append(said(0, "alice", "hi", 1002), &m);
    b.reindex();

    assert!(!grouped(&b, 0));
    assert!(grouped(&b, 1), "same nick, no uid, still one run");
    assert!(!grouped(&b, 2));
}

/// A `[hx]` status line: system kind, no speaker, but a gutter — the
/// shape `xprintline_render_tagged` produces.
fn notice(body: &str, at: i64) -> Message {
    let mut m = Message::system(ParsedText::plain(body));
    m.gutter = Some(ParsedText::plain("[hx]"));
    m.timestamp = at;
    m
}

#[test]
fn system_rows_never_group() {
    let m = FixedMeasure::new(10);
    let mut p = params(2000);
    p.indent = true;
    let mut b = ChatBuffer::new(p);
    b.append(Message::system(ParsedText::plain("connecting")), &m);
    b.append(Message::system(ParsedText::plain("connected")), &m);
    b.reindex();
    assert!(!grouped(&b, 0));
    assert!(!grouped(&b, 1), "two system lines are not one speaker");
}

#[test]
fn tagged_notices_never_group_even_though_they_share_a_gutter() {
    // The case the test above misses, and the one that shipped broken:
    // it uses `Message::system`, which has no gutter, so it passed on
    // the "a row with no gutter never groups" rule and never exercised
    // the kind at all. A real `[hx]` line does have a gutter, and three
    // consecutive ones collapsed into a single tagged block.
    let m = FixedMeasure::new(10);
    let mut p = params(2000);
    p.indent = true;
    let mut b = ChatBuffer::new(p);
    b.append(notice("connecting...", 1000), &m);
    b.append(notice("connected", 1001), &m);
    b.append(notice("login ok", 1002), &m);
    b.reindex();
    for row in 0..3 {
        assert!(!grouped(&b, row), "row {row} grouped under the [hx] tag");
    }

    // And the rule keys on the kind, not on the missing speaker: a
    // pre-1.5 server sends real chat with no uid, and that still groups.
    let mut b = ChatBuffer::new(params(2000));
    b.append(said(0, "misha", "one", 1000), &m);
    b.append(said(0, "misha", "two", 1001), &m);
    b.reindex();
    assert!(grouped(&b, 1), "uid-less chat is still one speaker");
}

#[test]
fn a_grouped_row_hides_its_gutter_but_keeps_the_column_width() {
    // Hiding a nick must not narrow the shared gutter, or every other
    // row in the buffer shifts sideways when a run forms.
    let m = FixedMeasure::new(10);
    let mut p = params(2000);
    p.indent = true;
    let mut b = ChatBuffer::new(p);
    b.append(said(7, "misha", "one", 1000), &m);
    b.append(said(7, "misha", "two", 1001), &m);
    b.reindex();
    b.ensure_layout(0, &m);
    let width_after_head = b.indent_width();
    b.ensure_layout(1, &m);

    let head = b.layout_at(0).expect("head laid out");
    let cont = b.layout_at(1).expect("continuation laid out");
    assert!(
        head.lines.iter().any(|l| l.source == LineSource::Gutter),
        "the head draws its nick"
    );
    assert!(
        !cont.lines.iter().any(|l| l.source == LineSource::Gutter),
        "the continuation does not"
    );
    assert_eq!(
        b.indent_width(),
        width_after_head,
        "a hidden gutter still reserves its width"
    );
}

#[test]
fn grouping_can_be_switched_off() {
    let m = FixedMeasure::new(10);
    let mut p = params(2000);
    p.indent = true;
    let mut b = ChatBuffer::new(p);
    for i in 0..3 {
        b.append(said(7, "misha", "hai", 1000 + i), &m);
    }
    b.reindex();
    assert!(grouped(&b, 1));

    b.set_group_gap_secs(0, &m);
    assert!(
        !grouped(&b, 1),
        "existing rows are re-decided, not just new ones"
    );
    assert!(!grouped(&b, 2));

    b.set_group_gap_secs(crate::buffer::DEFAULT_GROUP_GAP_SECS, &m);
    assert!(grouped(&b, 1), "and back again");
}

#[test]
fn regrouping_leaves_the_height_index_agreeing_with_a_real_layout() {
    // Toggling GROUPED invalidates a row's layout, so its height entry
    // has to be re-*estimated* rather than have the old value carried
    // forward as the new estimate. Otherwise total_height drifts from
    // what a real layout produces, and the scrollbar's upper bound with
    // it.
    //
    // Today the two happen to be equal: the gutter is a left column
    // (LineBox at y=0) and row height is driven only by body lines, so
    // showing or hiding a nick changes no height. This test therefore
    // passes either way *at present* — it is here for what comes next.
    // An avatar gutter makes a head row taller than its continuations,
    // and at that point carrying a stale estimate stops being harmless.
    // Asserting the invariant now means that change gets caught by a
    // test instead of by someone noticing the scrollbar is short.
    let m = FixedMeasure::new(10);
    let mut p = params(2000);
    p.indent = true;
    let mut b = ChatBuffer::new(p);
    for i in 0..8 {
        b.append(said(7, "misha", "hai", 1000 + i), &m);
    }
    b.reindex();
    assert!(grouped(&b, 1), "precondition: rows 1.. are a run");

    b.set_group_gap_secs(0, &m);
    assert!(!grouped(&b, 1), "grouping off");
    let estimated = b.total_height();

    for r in 0..8 {
        b.ensure_layout(r, &m);
    }
    assert_eq!(
        b.total_height(),
        estimated,
        "the post-regroup estimate must match what layout actually yields"
    );

    // And back on.
    b.set_group_gap_secs(crate::buffer::DEFAULT_GROUP_GAP_SECS, &m);
    let estimated = b.total_height();
    for r in 0..8 {
        b.ensure_layout(r, &m);
    }
    assert_eq!(b.total_height(), estimated);
}

#[test]
fn direction_breaks_a_run_even_with_the_same_nick() {
    // Messaging yourself in a PM window. Every line names you as the
    // sender — including the copies the server sends back — so no
    // identity test can separate the four lines, and an earlier fix that
    // keyed on "is the sender me" did nothing at all here. Direction is
    // a property of which path produced the row, and can.
    let m = FixedMeasure::new(10);
    let mut p = params(2000);
    p.indent = true;
    let mut b = ChatBuffer::new(p);

    let mut line = |mine: bool, at: i64| {
        let mut msg = said(7, "misha", "asdfasdf", at);
        if mine {
            msg.flags = msg.flags.union(MessageFlagsNone::OUTGOING);
        }
        b.append(msg, &m);
    };
    line(true, 1000); // outgoing
    line(false, 1000); // incoming echo
    line(true, 1001); // outgoing
    line(false, 1001); // incoming echo
    b.reindex();

    for r in 0..4 {
        assert!(
            !grouped(&b, r),
            "row {r}: alternating direction means four groups, not one"
        );
    }
}

#[test]
fn same_direction_still_groups() {
    // The converse, so the fix above doesn't just disable grouping.
    let m = FixedMeasure::new(10);
    let mut p = params(2000);
    p.indent = true;
    let mut b = ChatBuffer::new(p);
    for i in 0..3 {
        let mut msg = said(7, "misha", "hai", 1000 + i);
        msg.flags = msg.flags.union(MessageFlagsNone::OUTGOING);
        b.append(msg, &m);
    }
    b.reindex();
    assert!(!grouped(&b, 0));
    assert!(
        grouped(&b, 1) && grouped(&b, 2),
        "three outgoing lines are one run"
    );
}

// ---- avatar gutter ---------------------------------------------------

#[test]
fn only_a_group_head_gets_an_avatar_box() {
    let m = FixedMeasure::new(10);
    let mut p = params(2000);
    p.indent = true;
    p.avatar_size = 24;
    let mut b = ChatBuffer::new(p);
    b.append(said(7, "misha", "one", 1000), &m);
    b.append(said(7, "misha", "two", 1001), &m);
    b.reindex();
    b.ensure_layout(0, &m);
    b.ensure_layout(1, &m);

    let head = b.layout_at(0).unwrap();
    let cont = b.layout_at(1).unwrap();
    assert!(head.avatar.is_some(), "the head shows the icon");
    assert!(cont.avatar.is_none(), "a continuation does not repeat it");
    assert_eq!(head.avatar.unwrap().key, 7);
}

#[test]
fn a_continuation_still_reserves_the_avatar_width() {
    // Same argument as the hidden nick: if a grouped row stopped
    // reserving the icon's width, the shared gutter would narrow as soon
    // as a run formed and every column in the buffer would jump left.
    let m = FixedMeasure::new(10);
    let mut p = params(2000);
    p.indent = true;
    p.avatar_size = 24;
    let mut b = ChatBuffer::new(p);
    b.append(said(7, "misha", "one", 1000), &m);
    b.reindex();
    b.ensure_layout(0, &m);
    let with_head_only = b.indent_width();

    b.append(said(7, "misha", "two", 1001), &m);
    b.reindex();
    b.ensure_layout(1, &m);
    assert_eq!(
        b.indent_width(),
        with_head_only,
        "a grouped row must not shrink the shared gutter"
    );
}

#[test]
fn an_avatar_makes_the_head_row_at_least_as_tall_as_the_icon() {
    // The case that makes the regroup re-estimate matter: with avatars
    // on, a head and its continuations genuinely differ in height, so a
    // stale height carried across a GROUPED toggle is now a real bug
    // rather than a latent one.
    let m = FixedMeasure::new(10);
    let mut p = params(2000);
    p.indent = true;
    p.avatar_size = 48; // taller than a text line
    let mut b = ChatBuffer::new(p);
    b.append(said(7, "misha", "one", 1000), &m);
    b.append(said(7, "misha", "two", 1001), &m);
    b.reindex();
    b.ensure_layout(0, &m);
    b.ensure_layout(1, &m);

    assert!(
        b.layout_at(0).unwrap().height >= 48,
        "the head must fit its icon"
    );
    assert!(
        b.layout_at(1).unwrap().height < 48,
        "a continuation has no icon and should stay text-height"
    );
}

#[test]
fn turning_avatars_off_re_estimates_and_narrows_the_gutter() {
    let m = FixedMeasure::new(10);
    let mut p = params(2000);
    p.indent = true;
    p.avatar_size = 48;
    let mut b = ChatBuffer::new(p);
    for i in 0..4 {
        b.append(said(7, "misha", "hai", 1000 + i), &m);
    }
    b.reindex();
    for r in 0..4 {
        b.ensure_layout(r, &m);
    }
    let wide = b.indent_width();
    let tall = b.total_height();

    b.set_avatar_size(0);
    for r in 0..4 {
        b.ensure_layout(r, &m);
    }
    assert!(b.indent_width() < wide, "the gutter loses the icon slot");
    assert!(b.total_height() < tall, "and the head row loses its floor");
    assert!(b.layout_at(0).unwrap().avatar.is_none());
}

#[test]
fn a_speaker_with_no_uid_gets_no_avatar_slot() {
    // uid 0 means "unknown", so there is nothing to look an icon up by.
    // Reserving space for an icon that can never resolve would indent
    // every row on a server that omits the UID chunk.
    let m = FixedMeasure::new(10);
    let mut p = params(2000);
    p.indent = true;
    p.avatar_size = 24;
    let mut b = ChatBuffer::new(p);
    b.append(said(0, "misha", "one", 1000), &m);
    b.reindex();
    b.ensure_layout(0, &m);
    assert!(b.layout_at(0).unwrap().avatar.is_none());
}

#[test]
fn a_rename_breaks_the_run() {
    // The uid survives a rename, so keying grouping on it alone would
    // hide the new name entirely — the messages would group under the
    // old one and the change, which is the thing worth noticing, would
    // never appear on screen.
    let m = FixedMeasure::new(10);
    let mut p = params(2000);
    p.indent = true;
    let mut b = ChatBuffer::new(p);
    b.append(said(7, "misha", "one", 1000), &m);
    b.append(said(7, "misha", "two", 1001), &m);
    b.append(said(7, "misha2", "three", 1002), &m); // same uid, new nick
    b.append(said(7, "misha2", "four", 1003), &m);
    b.reindex();

    assert!(!grouped(&b, 0));
    assert!(grouped(&b, 1), "same name, same person");
    assert!(!grouped(&b, 2), "the rename must show the new name");
    assert!(grouped(&b, 3), "and then group again under it");
}

#[test]
fn two_users_sharing_a_nick_do_not_group() {
    // The converse: the nick alone is not enough either. Two people can
    // present the same name, and merging their messages under one header
    // would misattribute them.
    let m = FixedMeasure::new(10);
    let mut p = params(2000);
    p.indent = true;
    let mut b = ChatBuffer::new(p);
    b.append(said(7, "misha", "one", 1000), &m);
    b.append(said(9, "misha", "two", 1001), &m); // impostor, same nick
    b.reindex();

    assert!(!grouped(&b, 0));
    assert!(!grouped(&b, 1), "different uid means a different person");
}

#[test]
fn a_one_line_fence_is_a_code_block_not_an_unterminated_one() {
    use crate::markdown::{split_blocks, RawBlock};
    // Chat boxes send on Enter, so this is how people actually type a
    // code block. Treating it as an opening fence made the rest of the
    // line the "language" and produced an empty block — a blank row.
    let b = split_blocks("```hello world```");
    assert_eq!(b.len(), 1);
    match &b[0] {
        RawBlock::Code { text, language } => {
            assert_eq!(text, "hello world");
            assert_eq!(*language, None);
        }
        other => panic!("expected code, got {other:?}"),
    }
}

#[test]
fn a_real_multi_line_fence_still_works() {
    use crate::markdown::{split_blocks, RawBlock};
    let b = split_blocks("before\n```rust\nlet x = 1;\nlet y = 2;\n```\nafter");
    assert_eq!(b.len(), 3);
    match &b[1] {
        RawBlock::Code { text, language } => {
            assert_eq!(text, "let x = 1;\nlet y = 2;");
            assert_eq!(language.as_deref(), Some("rust"));
        }
        other => panic!("expected code, got {other:?}"),
    }
}

#[test]
fn select_all_shaped_selection_covers_the_buffer() {
    // Mirrors RotulusView::select_all's caret construction exactly, to
    // find out whether "Select All does nothing" is the model or the UI.
    let m = FixedMeasure::new(10);
    let mut p = params(2000);
    p.indent = true;
    let mut b = ChatBuffer::new(p);
    b.append(said(7, "misha", "one", 1000), &m);
    b.append(said(9, "alice", "two", 2000), &m);
    b.append(said(7, "misha", "three", 3000), &m);
    b.reindex();
    for r in 0..3 {
        b.ensure_layout(r, &m);
    }

    let first = b.id_at(0).unwrap();
    let last = b.id_at(2).unwrap();
    let last_len = b
        .source_text(2, LineSource::Block(0))
        .map_or(0, |t| t.len());
    let sel = Selection::new(
        Caret {
            message: first,
            source: LineSource::Block(0),
            offset: 0,
        },
        Caret {
            message: last,
            source: LineSource::Block(0),
            offset: last_len,
        },
    );

    let rows = b.selected_rows(&sel);
    assert_eq!(rows.len(), 3, "every row should contribute: {rows:?}");
    assert!(rows[0].1.contains("one"));
    assert!(rows[1].1.contains("two"));
    assert!(rows[2].1.contains("three"));
}

#[test]
fn select_all_covers_the_gutter_and_every_block() {
    // Both ways the view's hand-rolled version got this wrong: it started
    // at Block(0), skipping the first row's nick, and ended at Block(0)
    // of the last row — which, once markdown split a body into several
    // blocks, dropped any code block or quote after the first.
    let m = FixedMeasure::new(10);
    let mut p = params(2000);
    p.indent = true;
    let mut b = ChatBuffer::new(p);
    b.append(said(7, "misha", "one", 1000), &m);
    b.append(
        Message {
            kind: crate::message::MessageKind::Live,
            timestamp: 2000,
            speaker: Some(crate::message::Speaker::new(9, "alice")),
            gutter: Some(ParsedText::plain("<alice>")),
            blocks: vec![
                Block::Text(ParsedText::plain("look:")),
                Block::Code {
                    text: "x = 1".into(),
                    language: None,
                },
            ]
            .into(),
            flags: MessageFlagsNone::NONE,
        },
        &m,
    );
    b.reindex();

    let sel = b.select_all().expect("non-empty buffer");
    assert_eq!(sel.anchor.source, LineSource::Gutter, "starts at the nick");
    assert_eq!(
        sel.focus.source,
        LineSource::Block(1),
        "ends at the last block"
    );

    let text = b.selected_text(&sel);
    assert!(text.contains("<misha>"), "the first nick: {text:?}");
    assert!(text.contains("x = 1"), "the trailing code block: {text:?}");
}

#[test]
fn select_all_on_an_empty_buffer_is_none() {
    let p = params(2000);
    let b = ChatBuffer::new(p);
    assert!(b.select_all().is_none());
}

#[test]
fn text_is_centred_against_a_taller_avatar() {
    let m = FixedMeasure::new(10);
    let mut p = params(2000);
    p.indent = true;
    p.avatar_size = 48;
    let mut b = ChatBuffer::new(p);
    b.append(said(7, "misha", "hi", 1000), &m);
    b.reindex();
    b.ensure_layout(0, &m);
    let l = b.layout_at(0).unwrap();
    let line = l
        .lines
        .iter()
        .find(|l| l.source == LineSource::Block(0))
        .unwrap();
    assert!(
        line.y > 0,
        "a single line beside a 48px icon should be pushed down, not sit on its top edge"
    );
    let centre = line.y + line.height / 2;
    assert!(
        (centre as i64 - 24).abs() <= 1,
        "line centre {centre} should be near the icon's centre (24)"
    );
}

#[test]
fn avatar_at_hits_the_painted_rect_and_returns_its_row() {
    // Clicking an icon must resolve to the same speaker as clicking the
    // name. The uid comes back with the message id because the caller
    // needs both, and looking the row up a second time meant a second
    // borrow of the buffer while the first was live.
    let m = FixedMeasure::new(10);
    let mut p = params(2000);
    p.indent = true;
    p.avatar_size = 32;
    let mut b = ChatBuffer::new(p);
    let id = b.append(said(7, "misha", "hi", 1000), &m);
    b.reindex();
    b.ensure_layout(0, &m);

    let av = b.layout_at(0).unwrap().avatar.expect("head has an avatar");
    // Dead centre of the painted rect.
    let hit = b.avatar_at((av.x + av.size / 2) as i32, (av.y + av.size / 2) as u64);
    assert_eq!(hit, Some((id, 7)));

    // Just outside it, on both axes.
    assert!(b
        .avatar_at((av.x + av.size + 4) as i32, (av.size / 2) as u64)
        .is_none());
    assert!(b
        .avatar_at((av.x + av.size / 2) as i32, (av.size + 4) as u64)
        .is_none());
}

#[test]
fn a_continuation_row_has_no_avatar_to_hit() {
    let m = FixedMeasure::new(10);
    let mut p = params(2000);
    p.indent = true;
    p.avatar_size = 32;
    let mut b = ChatBuffer::new(p);
    b.append(said(7, "misha", "one", 1000), &m);
    b.append(said(7, "misha", "two", 1001), &m);
    b.reindex();
    b.ensure_layout(0, &m);
    b.ensure_layout(1, &m);

    let top = b.index_mut().offset_of(1);
    assert!(
        b.avatar_at(4, top + 2).is_none(),
        "grouped rows show no icon"
    );
}

// ---------------------------------------------- estimate vs. real height
//
// These pin the relationship the scroll extent depends on. `total_height`
// sums the index, and the index holds an *estimate* for every row that
// has not been laid out yet — including, always, the row that was just
// appended. So while the view is following the bottom, the adjustment
// value it derives is `estimated_total - viewport`. If the estimate is
// smaller than the row's real height, "the bottom" is short by the
// difference and the newest message is clipped off the bottom edge until
// something else re-syncs.
//
// The estimator is allowed to be crude. It is not allowed to be *low*.

/// Height the row will really occupy once it is laid out.
fn real_height(msg: &Message, p: &LayoutParams, m: &FixedMeasure) -> u32 {
    layout_message(msg, p, LayoutGeneration::default(), m).height
}

#[test]
fn estimate_is_never_shorter_than_the_real_height_for_one_line() {
    let m = FixedMeasure::new(10);
    let p = params(400);
    let msg = Message::system(ParsedText::plain("a short line"));
    assert!(
        estimate_height(&msg, &p, &m) >= real_height(&msg, &p, &m),
        "a single-line row must not be under-estimated"
    );
}

#[test]
fn estimate_counts_hard_newlines() {
    // The reported bug's shape: a multi-line message.
    //
    // `estimate_height` divides the body's *byte length* by the column
    // count, which answers "how many lines would this wrap to" and not
    // "how many lines does this have". A body with hard newlines is short
    // enough to fit on one line by that measure, so a five-line message
    // is estimated at one line — and the scroll extent that follows is
    // four lines short.
    let m = FixedMeasure::new(10);
    let p = params(400);
    let msg = Message::system(ParsedText::plain("one\ntwo\nthree\nfour\nfive"));
    let est = estimate_height(&msg, &p, &m);
    let real = real_height(&msg, &p, &m);
    assert!(
        est >= real,
        "five hard-broken lines estimated at {est}px against a real {real}px"
    );
}

#[test]
fn estimate_accounts_for_the_gutter_column() {
    // The estimator has to wrap against the same column the layout
    // does. In indent mode that is the content width *less the gutter*,
    // so a line the full width would fit on one row genuinely takes two
    // — and the buffer, which is the only thing that knows the settled
    // gutter width, has to hand that width to the estimator.
    let m = FixedMeasure::new(10);
    let mut p = params(400);
    p.indent = true;
    let mut b = ChatBuffer::new(p);
    let nick = "a-fairly-long-nickname";

    // Settle the gutter on a wide nick.
    b.append(
        Message::live(Speaker::new(1, nick), ParsedText::plain("hi")),
        &m,
    );
    b.ensure_layout(0, &m);
    assert!(b.indent_width() > 0, "the gutter should have settled");

    // A body that fits the full width but not the body column.
    b.append(
        Message::live(
            Speaker::new(2, nick),
            ParsedText::plain("x".repeat(38)), // 380px of a 400px width
        ),
        &m,
    );
    let est = b.index_mut().height_at(1);
    let real = b.ensure_layout(1, &m);
    assert!(
        est >= real,
        "estimated {est}px against a real {real}px — the estimator wrapped \
         against the full width while the layout wrapped against \
         width - {}",
        b.indent_width()
    );
}

#[test]
fn following_append_leaves_the_new_row_fully_visible() {
    // The bug, in the exact order the view performs it.
    //
    //   append()                 → row enters the index at its estimate
    //   sync_adjustment()        → value = estimated_total - viewport
    //   snapshot(): scroll_offset → the same value, captured
    //   snapshot(): ensure_visible → the visible rows get real heights
    //
    // Nothing re-derives the adjustment after that last step, so the
    // frame is drawn at a scroll position computed from heights that the
    // same frame has just corrected. If the correction grew the buffer,
    // the newest row hangs below the viewport's bottom edge.
    let m = FixedMeasure::new(10);
    let mut b = ChatBuffer::new(params(400));
    let vh = 200u32;

    for i in 0..50 {
        b.append(Message::system(ParsedText::plain(format!("line {i}"))), &m);
    }
    // Draw once so everything before the new message is measured, which
    // is the state a live window is actually in.
    let settled = b.scroll_offset(vh);
    b.ensure_visible(settled, vh, &m);
    assert!(b.is_following());

    b.append(
        Message::system(ParsedText::plain("one\ntwo\nthree\nfour\nfive")),
        &m,
    );

    let scroll = b.scroll_offset(vh);
    b.ensure_visible(scroll, vh, &m);

    let last = b.len() - 1;
    let bottom = b.index_mut().offset_of(last) + u64::from(b.index_mut().height_at(last));
    assert!(
        bottom <= scroll + u64::from(vh),
        "the appended row ends at {bottom}px but the viewport ends at {} — \
         it is {}px below the bottom edge",
        scroll + u64::from(vh),
        bottom - (scroll + u64::from(vh))
    );
}

/// Every character is `char_width` wide, except bold, which is wider.
///
/// The estimator has no styles — it divides byte length by a column
/// count derived from the space width — so a bold run is the case it
/// cannot get right by construction, whatever else is fixed about it.
/// That makes this the measurer for testing the *correction*, as
/// distinct from testing the estimate.
#[derive(Clone, Copy, Debug)]
struct BoldIsWider(FixedMeasure);

impl TextMeasure for BoldIsWider {
    fn metrics(&self) -> crate::measure::FontMetrics {
        self.0.metrics()
    }

    fn run_width(&self, text: &str, style: Style) -> u32 {
        let w = self.0.run_width(text, style);
        if style.attrs.contains(Attrs::BOLD) {
            w * 3
        } else {
            w
        }
    }
}

#[test]
fn re_deriving_the_offset_after_layout_reaches_the_bottom() {
    // What the view has to do, and the reason estimating better is not
    // on its own enough.
    //
    // The offset the anchor yields while following is
    // `total_height - viewport`, and `total_height` counts estimates for
    // rows that have not been laid out. So the value read *before* the
    // layout pass is stale by exactly the correction that pass makes.
    // Reading it again afterwards is what lands on the real bottom.
    //
    // Bold text makes the estimate wrong in a way no estimator without a
    // font stack could avoid, so this holds regardless of how good
    // `estimate_height` gets.
    let m = BoldIsWider(FixedMeasure::new(10));
    let mut b = ChatBuffer::new(params(400));
    let vh = 200u32;

    for i in 0..50 {
        b.append(Message::system(ParsedText::plain(format!("line {i}"))), &m);
    }
    let settled = b.scroll_offset(vh);
    b.ensure_visible(settled, vh, &m);

    // 30 bold characters: 300px by the estimator's reckoning, 900px
    // measured, so three lines where it predicted one.
    let mut body = ParsedText::plain("x".repeat(30));
    body.spans.push(crate::span::Span {
        range: 0..30,
        style: Style::default().with_attrs(Attrs::BOLD),
    });
    b.append(Message::system(body), &m);

    let first = b.scroll_offset(vh);
    b.ensure_visible(first, vh, &m);
    let settled = b.scroll_offset(vh);
    assert!(
        settled > first,
        "the layout pass should have moved the bottom ({first} -> {settled})"
    );

    // Re-deriving, then laying out again, settles — and the newest row
    // ends exactly at the viewport's bottom edge.
    b.ensure_visible(settled, vh, &m);
    assert_eq!(
        b.scroll_offset(vh),
        settled,
        "a second correction should not be needed"
    );
    let last = b.len() - 1;
    let bottom = b.index_mut().offset_of(last) + u64::from(b.index_mut().height_at(last));
    assert_eq!(
        bottom,
        settled + u64::from(vh),
        "the newest row should end exactly at the bottom edge"
    );
}

// ---- link detection -------------------------------------------------

fn links_in(l: &crate::linkify::Linkifier, text: &str) -> Vec<String> {
    l.scan(text)
        .into_iter()
        .map(|r| text[r].to_string())
        .collect()
}

#[test]
fn scan_finds_scheme_and_bare_urls() {
    let l = crate::linkify::Linkifier::default();
    assert_eq!(
        links_in(&l, "see https://example.com/x and www.example.org now"),
        ["https://example.com/x", "www.example.org"]
    );
}

#[test]
fn scan_drops_sentence_punctuation_but_keeps_a_balanced_paren() {
    let l = crate::linkify::Linkifier::default();
    assert_eq!(
        links_in(&l, "go to https://example.com."),
        ["https://example.com"]
    );
    assert_eq!(
        links_in(&l, "(https://example.com)"),
        ["https://example.com"]
    );
    assert_eq!(
        links_in(&l, "https://en.wikipedia.org/wiki/Hotline_(software)"),
        ["https://en.wikipedia.org/wiki/Hotline_(software)"]
    );
}

#[test]
fn scan_needs_a_boundary_before_the_scheme() {
    let l = crate::linkify::Linkifier::default();
    assert!(links_in(&l, "xhttps://example.com").is_empty());
    assert_eq!(
        links_in(&l, "<https://example.com>"),
        ["https://example.com"]
    );
}

#[test]
fn scan_ignores_a_bare_scheme_with_nothing_after_it() {
    let l = crate::linkify::Linkifier::default();
    assert!(links_in(&l, "type https:// then the host").is_empty());
}

#[test]
fn scan_is_case_insensitive_and_multibyte_safe() {
    let l = crate::linkify::Linkifier::default();
    let text = "héllo → HTTPS://example.com/ø done";
    let found = l.scan(text);
    assert_eq!(found.len(), 1);
    assert!(text.is_char_boundary(found[0].start) && text.is_char_boundary(found[0].end));
    assert_eq!(&text[found[0].clone()], "HTTPS://example.com/ø");
}

#[test]
fn the_scheme_list_is_the_applications() {
    let default = crate::linkify::Linkifier::default();
    assert!(links_in(&default, "hotline://server.example").is_empty());

    let hotline = crate::linkify::Linkifier::new(
        crate::linkify::DEFAULT_SCHEMES
            .iter()
            .copied()
            .chain(["hotline://"]),
    );
    assert_eq!(
        links_in(&hotline, "hotline://server.example"),
        ["hotline://server.example"]
    );
    assert!(hotline.allows("hotline://server.example"));
    assert!(!default.allows("hotline://server.example"));
}

#[test]
fn words_classify_and_normalize_like_the_scanner() {
    let l = crate::linkify::Linkifier::default();
    assert!(l.is_url("https://example.com"));
    assert!(l.is_url("www.example.com"));
    assert!(l.is_url("someone@example.com"));
    assert!(!l.is_url("someone@example."));
    assert!(!l.is_url("plain"));
    assert!(
        !l.has_scheme("someone@example.com"),
        "an email has no scheme"
    );

    assert_eq!(l.normalize("https://example.com"), "https://example.com");
    assert_eq!(l.normalize("www.example.com"), "https://www.example.com");
    assert_eq!(l.normalize("ftp.example.com"), "ftp://ftp.example.com");
    assert_eq!(
        l.normalize("someone@example.com"),
        "mailto:someone@example.com"
    );
}

#[test]
fn markdown_links_follow_the_scheme_list() {
    let only_https = crate::linkify::Linkifier::new(["https://"]);
    let p = markdown::parse_inline_with("[a](https://x.example) [b](ftp://y.example)", &only_https);
    assert_eq!(p.links.len(), 1, "only the https link is allowed");
    assert_eq!(p.links[0].href, "https://x.example");
    assert!(
        p.text.contains("[b](ftp://y.example)"),
        "the refused link stays literal"
    );
}

// ---- single-column layout -------------------------------------------

fn nick_row(nick: &str, body: &str) -> Message {
    Message {
        kind: crate::message::MessageKind::Live,
        timestamp: 0,
        speaker: Some(Speaker::new(1, nick)),
        gutter: Some(ParsedText::plain(format!("<{nick}>"))),
        blocks: vec![Block::Text(ParsedText::plain(body))].into(),
        flags: MessageFlagsNone::NONE,
    }
}

#[test]
fn single_column_puts_the_nick_beside_the_body() {
    let m = FixedMeasure::new(10);
    let l = layout_message(
        &nick_row("al", "hi there"),
        &params(400),
        LayoutGeneration::default(),
        &m,
    );
    let gutter = l
        .lines
        .iter()
        .find(|b| b.source == crate::wrap::LineSource::Gutter)
        .expect("the gutter is drawn");
    assert_eq!((gutter.x, gutter.y), (0, 0));
    let body = l
        .lines
        .iter()
        .find(|b| b.source == crate::wrap::LineSource::Block(0))
        .unwrap();
    // "<al>" is 40 px, then one space.
    assert_eq!(
        (body.x, body.y),
        (50, 0),
        "the body starts beside the nick, on the same line"
    );
    assert_eq!(l.height, 16, "one line tall");
}

#[test]
fn single_column_wraps_later_lines_to_the_left_edge() {
    let m = FixedMeasure::new(10);
    // 100 px wide: "<al> " leaves 50 px (5 chars) on the first line.
    let l = layout_message(
        &nick_row("al", "aaaa bbbb cccc"),
        &params(100),
        LayoutGeneration::default(),
        &m,
    );
    let body: Vec<_> = l
        .lines
        .iter()
        .filter(|b| b.source == crate::wrap::LineSource::Block(0))
        .collect();
    assert_eq!(body[0].x, 50);
    assert!(body[0].width <= 50, "the first line fits beside the nick");
    assert!(
        body[1..].iter().all(|b| b.x == 0),
        "continuation lines use the full width"
    );
}

#[test]
fn single_column_starts_past_the_timestamp() {
    let m = FixedMeasure::new(10);
    let mut p = params(400);
    p.stamp_width = 30;
    let l = layout_message(&nick_row("al", "hi"), &p, LayoutGeneration::default(), &m);
    let gutter = l
        .lines
        .iter()
        .find(|b| b.source == crate::wrap::LineSource::Gutter)
        .unwrap();
    assert_eq!(gutter.x, 30, "the nick sits after the stamp");
    let body = l
        .lines
        .iter()
        .find(|b| b.source == crate::wrap::LineSource::Block(0))
        .unwrap();
    assert_eq!(body.x, 80);

    // A row with no gutter still clears the stamp.
    let sys = layout_message(
        &Message::system(ParsedText::plain("notice")),
        &p,
        LayoutGeneration::default(),
        &m,
    );
    assert_eq!(sys.lines[0].x, 30);
}

#[test]
fn single_column_puts_a_code_block_under_the_nick() {
    let m = FixedMeasure::new(10);
    let mut msg = nick_row("al", "");
    msg.blocks = vec![Block::Code {
        text: "x = 1".into(),
        language: None,
    }]
    .into();
    let l = layout_message(&msg, &params(400), LayoutGeneration::default(), &m);
    let code = l
        .lines
        .iter()
        .find(|b| b.source == crate::wrap::LineSource::Block(0))
        .unwrap();
    assert_eq!(code.x, 0);
    assert!(code.y >= 16, "the code block starts below the nick's line");
}

#[test]
fn single_column_drops_a_long_nick_onto_its_own_line() {
    let m = FixedMeasure::new(10);
    let l = layout_message(
        &nick_row(&"n".repeat(30), "hello"),
        &params(200),
        LayoutGeneration::default(),
        &m,
    );
    let body = l
        .lines
        .iter()
        .find(|b| b.source == crate::wrap::LineSource::Block(0))
        .unwrap();
    assert_eq!(
        (body.x, body.y),
        (0, 16),
        "no room beside the nick: the body goes below it"
    );
}

#[test]
fn single_column_estimates_are_never_low() {
    let m = FixedMeasure::new(10);
    let mut p = params(100);
    p.stamp_width = 20;
    for (nick, body) in [
        ("al", "aaaa bbbb cccc dddd"),
        ("someone", "x"),
        ("n", "a\nb\nc"),
    ] {
        let msg = nick_row(nick, body);
        let real = layout_message(&msg, &p, LayoutGeneration::default(), &m).height;
        let est = estimate_height(&msg, &p, &m);
        assert!(
            est >= real,
            "{nick}/{body:?}: estimated {est} below the real {real}"
        );
    }
}

#[test]
fn single_column_starts_a_block_below_a_lone_timestamp() {
    // No gutter, but a stamp: an image or code block must not start on the
    // stamp's line, where it would be painted over it.
    let m = FixedMeasure::new(10);
    let mut p = params(400);
    p.stamp_width = 30;
    let mut msg = Message::system(ParsedText::plain(""));
    msg.blocks = vec![Block::Code {
        text: "x = 1".into(),
        language: None,
    }]
    .into();
    let l = layout_message(&msg, &p, LayoutGeneration::default(), &m);
    let code = l
        .lines
        .iter()
        .find(|b| b.source == crate::wrap::LineSource::Block(0))
        .unwrap();
    assert!(
        code.y >= 16,
        "the block starts below the stamp's line, at {}",
        code.y
    );
    assert!(
        estimate_height(&msg, &p, &m) >= l.height,
        "the estimate follows the same rule"
    );
}

#[test]
fn scan_finds_bare_email_addresses() {
    let l = crate::linkify::Linkifier::default();
    assert_eq!(
        links_in(&l, "mail me at bob@example.com."),
        ["bob@example.com"]
    );
    assert_eq!(links_in(&l, "(bob@example.com)"), ["bob@example.com"]);
    assert!(
        links_in(&l, "@everyone and a@b and x@y.").is_empty(),
        "not addresses"
    );
    assert_eq!(
        links_in(&l, "see https://user@example.com/x"),
        ["https://user@example.com/x"],
        "an @ inside a URL stays part of the URL"
    );
    assert_eq!(l.normalize("bob@example.com"), "mailto:bob@example.com");
}