croft-software 0.2.232

VSCode-style TUI written in Rust
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
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
//! Non-text viewers: images, PDF, spreadsheets, SQLite, archives, hex, docx
//! and extension viewers.

use super::*;

#[test]
fn sqlite_pages_step_at_batch_boundaries() {
    // #201 review: PageDown at the bottom of a full batch fetches the
    // next page; PageUp at the top returns.
    let tmp = tempfile::tempdir().unwrap();
    let p = tmp.path().join("big.db");
    {
        let conn = rusqlite::Connection::open(&p).unwrap();
        conn.execute_batch("CREATE TABLE t (n INTEGER);").unwrap();
        let mut ins = conn.prepare("INSERT INTO t VALUES (?1)").unwrap();
        for i in 0..700 {
            ins.execute([i]).unwrap();
        }
    }
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open(&p).unwrap();
    let view = app.editor.sheet.as_ref().unwrap();
    assert_eq!(view.sheets[0].row_count(), 500);
    assert!(view.sheets[0].name.contains("rows 1-500, more follow"));

    app.handle_sheet_key(key(KeyCode::End, KeyModifiers::SUPER));
    app.handle_sheet_key(key(KeyCode::PageDown, KeyModifiers::NONE));
    let view = app.editor.sheet.as_ref().unwrap();
    assert_eq!(view.sheets[0].row_count(), 200, "second page loaded");
    assert!(
        view.sheets[0].name.ends_with("rows 501-700"),
        "{}",
        view.sheets[0].name
    );
    assert_eq!(view.sheets[0].cell(0, 0), "500", "first value of page 2");

    app.handle_sheet_key(key(KeyCode::Home, KeyModifiers::SUPER));
    app.handle_sheet_key(key(KeyCode::PageUp, KeyModifiers::NONE));
    let view = app.editor.sheet.as_ref().unwrap();
    assert!(
        view.sheets[0].name.contains("rows 1-500"),
        "{}",
        view.sheets[0].name
    );
}

/// A database with one table `t` of `n` rows holding 1..=n.
fn sqlite_table_of(dir: &std::path::Path, n: usize) -> std::path::PathBuf {
    let p = dir.join("big.db");
    let conn = rusqlite::Connection::open(&p).unwrap();
    conn.execute_batch(&format!(
        "CREATE TABLE t (n INTEGER); WITH RECURSIVE c(x) AS (SELECT 1 UNION ALL \
         SELECT x+1 FROM c WHERE x < {n}) INSERT INTO t SELECT x FROM c;"
    ))
    .unwrap();
    p
}

/// #1222: Ctrl+End in a SQLite table goes to the table's last row, not the
/// last row of the loaded batch, and Ctrl+Home comes back to the first.
#[test]
fn ctrl_end_in_a_sqlite_table_reaches_its_last_row() {
    let tmp = tempfile::tempdir().unwrap();
    let p = sqlite_table_of(tmp.path(), 2 * crate::sqlite_view::ROW_CAP + 7);
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open(&p).unwrap();
    app.handle_sheet_key(key(KeyCode::End, KeyModifiers::CONTROL));
    let data = &app.editor.sheet.as_ref().unwrap().sheets[0];
    assert!(data.name.ends_with("rows 1001-1007"), "{}", data.name);
    assert_eq!(data.cell(data.cur_row, data.cur_col), "1007");
    app.handle_sheet_key(key(KeyCode::Home, KeyModifiers::CONTROL));
    let data = &app.editor.sheet.as_ref().unwrap().sheets[0];
    assert!(
        data.name.contains("rows 1-500, more follow"),
        "{}",
        data.name
    );
    assert_eq!(data.cell(data.cur_row, data.cur_col), "1");
    // PageUp at the top of the last page still steps back one page.
    app.handle_sheet_key(key(KeyCode::End, KeyModifiers::CONTROL));
    let view = app.editor.sheet.as_mut().unwrap();
    assert_eq!(view.sqlite_pages[0].1, 2, "the page index follows the jump");
    (view.sheets[0].cur_row, view.sheets[0].scroll_row) = (0, 0);
    app.handle_sheet_key(key(KeyCode::PageUp, KeyModifiers::NONE));
    let data = &app.editor.sheet.as_ref().unwrap().sheets[0];
    assert!(data.name.contains("rows 501-1000"), "{}", data.name);
}

/// #1222: a batch's rows are numbered by their place in the table, so
/// the grid says where in the table you are.
#[test]
fn sqlite_rows_are_numbered_by_their_place_in_the_table() {
    let tmp = tempfile::tempdir().unwrap();
    let p = sqlite_table_of(tmp.path(), 2 * crate::sqlite_view::ROW_CAP + 7);
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open(&p).unwrap();
    app.handle_sheet_key(key(KeyCode::End, KeyModifiers::CONTROL));
    let mut term = ratatui::Terminal::new(ratatui::backend::TestBackend::new(100, 30)).unwrap();
    term.draw(|f| app.render(f)).unwrap();
    let buf = term.backend().buffer();
    let dump: String = (0..buf.area.height)
        .map(|y| {
            let row: String = (0..buf.area.width).map(|x| buf[(x, y)].symbol()).collect();
            row + "\n"
        })
        .collect();
    assert!(
        dump.contains(" 1007 ") && dump.contains("rows 1001–1007"),
        "{dump}"
    );
}

/// Negative (#1222): a table that fits in one batch, and a CSV, keep
/// Ctrl+End within what is loaded, numbered from 1.
#[test]
fn ctrl_end_in_a_one_batch_table_or_a_csv_is_unchanged() {
    let tmp = tempfile::tempdir().unwrap();
    let p = sqlite_table_of(tmp.path(), 7);
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open(&p).unwrap();
    app.handle_sheet_key(key(KeyCode::End, KeyModifiers::CONTROL));
    let data = &app.editor.sheet.as_ref().unwrap().sheets[0];
    assert_eq!(data.name, "t: 7 rows");
    assert_eq!(data.cell(data.cur_row, data.cur_col), "7");
    let csv = tmp.path().join("s.csv");
    std::fs::write(&csv, "a,b\n1,2\n3,4\n").unwrap();
    app.editor.open(&csv).unwrap();
    app.handle_sheet_key(key(KeyCode::End, KeyModifiers::CONTROL));
    let data = &app.editor.sheet.as_ref().unwrap().sheets[0];
    assert_eq!((data.cur_row, data.cur_col), (1, 1));
    assert_eq!(data.row_base, 0);
}

#[test]
fn media_file_opens_as_an_info_card_and_save_refuses() {
    // #183: a WAV opens as the rendered info card (duration, rates), a
    // save refuses (#185 class), and junk with a media extension falls
    // through to the binary path instead of erroring.
    use std::io::Write as _;
    let tmp = tempfile::tempdir().unwrap();
    let p = tmp.path().join("tone.wav");
    let mut f = std::fs::File::create(&p).unwrap();
    let byte_rate = 16000u32;
    let data = vec![0u8; byte_rate as usize]; // 1 second
    let mut hdr = Vec::new();
    hdr.extend_from_slice(b"RIFF");
    hdr.extend_from_slice(&((36 + data.len()) as u32).to_le_bytes());
    hdr.extend_from_slice(b"WAVEfmt ");
    hdr.extend_from_slice(&16u32.to_le_bytes());
    hdr.extend_from_slice(&1u16.to_le_bytes());
    hdr.extend_from_slice(&1u16.to_le_bytes());
    hdr.extend_from_slice(&8000u32.to_le_bytes());
    hdr.extend_from_slice(&byte_rate.to_le_bytes());
    hdr.extend_from_slice(&2u16.to_le_bytes());
    hdr.extend_from_slice(&16u16.to_le_bytes());
    hdr.extend_from_slice(b"data");
    hdr.extend_from_slice(&(data.len() as u32).to_le_bytes());
    f.write_all(&hdr).unwrap();
    f.write_all(&data).unwrap();

    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open(&p).unwrap();
    let md = app
        .editor
        .markdown_preview
        .as_ref()
        .expect("media opens as the info card");
    assert!(md.media && md.doc_path.is_some());
    let all: String = md
        .lines
        .iter()
        .flat_map(|l| l.spans.iter())
        .map(|s| s.content.as_ref())
        .collect();
    assert!(all.contains("tone.wav"), "{all}");
    assert!(all.contains("8000 Hz"), "{all}");
    let before = std::fs::read(&p).unwrap();
    assert!(app.editor.save_to_disk().is_err(), "info card save refuses");
    assert_eq!(std::fs::read(&p).unwrap(), before);

    // Junk wearing .mp3: never a dead-end.
    let junk = tmp.path().join("noise.mp3");
    std::fs::write(&junk, b"\x00\x01 not audio").unwrap();
    let mut e = crate::widgets::editor::Editor::new();
    e.open(&junk).unwrap();
    assert!(e.hex.is_some(), "junk media falls to hex");
}

#[test]
fn docx_opens_as_a_rendered_document() {
    // #181: a docx renders headings/emphasis through the preview
    // machinery; the text side is a stub (Reopen as Text routes the zip
    // container onward, never a mojibake buffer).
    use std::io::Write as _;
    let tmp = tempfile::tempdir().unwrap();
    let p = tmp.path().join("memo.docx");
    let f = std::fs::File::create(&p).unwrap();
    let mut z = zip::ZipWriter::new(f);
    let o =
        zip::write::SimpleFileOptions::default().compression_method(zip::CompressionMethod::Stored);
    z.start_file("word/document.xml", o).unwrap();
    z.write_all(
        br#"<w:document xmlns:w="x"><w:body>
<w:p><w:pPr><w:pStyle w:val="Heading1"/></w:pPr><w:r><w:t>Memo Title</w:t></w:r></w:p>
<w:p><w:r><w:t>memo body</w:t></w:r></w:p></w:body></w:document>"#,
    )
    .unwrap();
    z.finish().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open(&p).unwrap();
    let md = app
        .editor
        .markdown_preview
        .as_ref()
        .expect("docx opens rendered");
    assert!(md.doc_path.is_some());
    let all: String = md
        .lines
        .iter()
        .flat_map(|l| l.spans.iter())
        .map(|s| s.content.as_ref())
        .collect();
    assert!(all.contains("Memo Title"), "{all}");
    assert!(all.contains("memo body"));
    // #200 review: the text side is a stub - a save must refuse at the
    // choke point (#185 class), leaving the document untouched.
    let before = std::fs::read(&p).unwrap();
    assert!(
        app.editor.save_to_disk().is_err(),
        "doc preview save refuses"
    );
    assert_eq!(std::fs::read(&p).unwrap(), before, "document intact");
}

/// #1979: a Word 97-2003 `.doc` opens in the same read-only preview as a
/// docx, not as a hex dump, and a save still refuses.
#[test]
fn a_word_97_doc_opens_as_a_rendered_document() {
    let tmp = tempfile::tempdir().unwrap();
    let p = tmp.path().join("report.doc");
    let fixture =
        std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("src/word97/testdata/report.doc");
    std::fs::copy(fixture, &p).unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open(&p).unwrap();
    assert!(app.editor.hex.is_none(), "not the hex viewer");
    let md = app
        .editor
        .markdown_preview
        .as_ref()
        .expect(".doc opens rendered");
    let all: String = md
        .lines
        .iter()
        .flat_map(|l| l.spans.iter())
        .map(|s| s.content.as_ref())
        .collect();
    for text in ["Quarterly report", "North", "1,200", "日本語"] {
        assert!(all.contains(text), "{text:?} missing from {all}");
    }
    assert!(!all.contains("HYPERLINK"), "field codes stay hidden");
    let before = std::fs::read(&p).unwrap();
    assert!(
        app.editor.save_to_disk().is_err(),
        "the preview never saves"
    );
    assert_eq!(std::fs::read(&p).unwrap(), before, "document intact");
}

/// Negative (#1979): a `.doc` that is not a Word document opens the way it
/// did before: an HTML page saved under that name as text, and a broken
/// compound file as hex.
#[test]
fn a_doc_that_is_not_a_word_document_falls_back() {
    let tmp = tempfile::tempdir().unwrap();
    let page = tmp.path().join("page.doc");
    std::fs::write(&page, "<html><body>Hello</body></html>\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open(&page).unwrap();
    assert!(app.editor.markdown_preview.is_none());
    assert!(app.editor.hex.is_none());
    assert_eq!(app.editor.lines[0], "<html><body>Hello</body></html>");

    let fixture =
        std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("src/word97/testdata/report.doc");
    let broken = tmp.path().join("broken.doc");
    std::fs::write(&broken, &std::fs::read(fixture).unwrap()[..3000]).unwrap();
    app.editor.open(&broken).unwrap();
    assert!(app.editor.markdown_preview.is_none());
    assert!(app.editor.hex.is_some(), "a broken .doc opens as bytes");
}

#[test]
fn archive_tab_lists_members_and_enter_opens_an_extracted_copy() {
    // #179 end-to-end: a zip opens as the member browser, Enter on a
    // text member extracts it to scratch and opens it through the
    // normal dispatch.
    use std::io::Write as _;
    let tmp = tempfile::tempdir().unwrap();
    let zp = tmp.path().join("bundle.zip");
    let f = std::fs::File::create(&zp).unwrap();
    let mut z = zip::ZipWriter::new(f);
    let opts =
        zip::write::SimpleFileOptions::default().compression_method(zip::CompressionMethod::Stored);
    z.start_file("notes/inner.txt", opts).unwrap();
    z.write_all(b"member text").unwrap();
    z.finish().unwrap();

    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open(&zp).unwrap();
    let view = app.editor.archive.as_ref().expect("zip opens as a browser");
    assert_eq!(view.entries.len(), 1);
    assert_eq!(view.entries[0].path, "notes/inner.txt");

    app.handle_archive_key(key(KeyCode::Enter, KeyModifiers::NONE));
    assert!(
        app.editor.archive.is_none(),
        "the member opened in the editor: {}",
        app.status
    );
    assert_eq!(app.editor.lines, vec!["member text".to_string()]);
}

#[test]
fn misnamed_zip_routes_to_the_archive_browser_by_content() {
    use std::io::Write as _;
    let tmp = tempfile::tempdir().unwrap();
    let p = tmp.path().join("data.bin");
    let f = std::fs::File::create(&p).unwrap();
    let mut z = zip::ZipWriter::new(f);
    let opts =
        zip::write::SimpleFileOptions::default().compression_method(zip::CompressionMethod::Stored);
    z.start_file("x.txt", opts).unwrap();
    z.write_all(b"in").unwrap();
    z.finish().unwrap();
    let mut e = crate::widgets::editor::Editor::new();
    e.open(&p).unwrap();
    assert!(
        e.archive.is_some(),
        "sniffed zip lands in the browser, not hex"
    );
}

#[test]
fn markdown_preview_computes_image_anchor_frame_truth() {
    // #176: the preview render must publish each image's wrapped visual
    // row and the paragraph's text area, which the overlay driver
    // consumes.
    let tmp = tempfile::tempdir().unwrap();
    image::RgbaImage::new(100, 50)
        .save(tmp.path().join("pic.png"))
        .unwrap();
    std::fs::write(
        tmp.path().join("doc.md"),
        "# Title\n\nintro text\n\n![p](pic.png)\n\ntail",
    )
    .unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open(&tmp.path().join("doc.md")).unwrap();
    assert!(app.editor.toggle_markdown_preview());
    let backend = ratatui::backend::TestBackend::new(100, 30);
    let mut term = ratatui::Terminal::new(backend).unwrap();
    term.draw(|f| app.render(f)).unwrap();
    let md = app.editor.markdown_preview.as_ref().unwrap();
    assert_eq!(md.images.len(), 1);
    assert_eq!(md.anchor_rows.len(), 1);
    assert!(
        md.anchor_rows[0] >= 3,
        "the anchor sits below the heading and intro: {}",
        md.anchor_rows[0]
    );
    assert!(md.last_area.width > 0, "frame-truth area published");
    // The reserved rows are blank in the paint: no placeholder glyph.
    let mut all = String::new();
    for y in 0..30 {
        for x in 0..100 {
            all.push_str(term.backend().buffer()[(x, y)].symbol());
        }
    }
    assert!(
        !all.contains("(pic.png)"),
        "no labelled placeholder for a local image"
    );
}

/// Whether poppler can render pages and read their links here; says why
/// not when it cannot.
fn pdf_links_readable() -> bool {
    let readable = crate::pdf::detect_backend() == Some(crate::pdf::PdfBackend::PdftoppmCli)
        && !crate::pdf::page_links(std::path::Path::new("/nonexistent"), 1)
            .err()
            .is_some_and(|e| e.to_string().contains("install poppler"));
    if !readable {
        eprintln!("skipping: poppler (pdftoppm + pdftohtml) not installed");
    }
    readable
}

/// A click that waits for its page's links acts on the preview in front
/// (#2824): one made just before the user left the tab is dropped, and never
/// turns the page behind their back or when they come back.
#[test]
fn a_pdf_link_click_is_dropped_when_its_tab_is_left_before_the_links_are_in() {
    if !pdf_links_readable() {
        return;
    }
    let tmp = tempfile::tempdir().unwrap();
    let pdf = tmp.path().join("linked.pdf");
    std::fs::write(&pdf, two_page_pdf_with_internal_link()).unwrap();
    let notes = tmp.path().join("notes.txt");
    std::fs::write(&notes, "notes\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open_pinned(&pdf).unwrap();
    settle_pdf(&mut app);
    // Over "go to two" (x 30..103 of 300, y 62..79 of 150 in pdftohtml's
    // space).
    let on_the_link = (0.2, 0.45, 0.25, 0.5);

    app.editor.read_pdf_links_for(on_the_link);
    settle_pdf(&mut app);
    assert_eq!(
        app.editor.pdf_page(),
        Some(2),
        "a click on the link in front acts once the links are in; status: {}",
        app.status
    );

    app.jump_pdf_page(1);
    settle_pdf(&mut app);
    app.editor.read_pdf_links_for(on_the_link);
    app.editor.open_pinned(&notes).unwrap();
    settle_pdf(&mut app);
    let pdf_tab = app
        .editor
        .editors
        .iter()
        .position(|ed| ed.pdf_page().is_some())
        .expect("the PDF tab stays open");
    app.editor.select(pdf_tab);
    settle_pdf(&mut app);
    assert_eq!(
        app.editor.pdf_page(),
        Some(1),
        "a click left behind on a tab must not act when the user returns"
    );
}

/// A minimal two-page PDF whose page 1 carries the text "go to two" under a
/// GoTo link annotation targeting page 2. Hand-assembled (correct xref
/// offsets included) so the test needs no pdflatex, only poppler to read it.
fn two_page_pdf_with_internal_link() -> Vec<u8> {
    let s1 = b"BT /F1 12 Tf 20 50 Td (go to two) Tj ET";
    let s2 = b"BT /F1 12 Tf 20 50 Td (second page) Tj ET";
    let objs: Vec<Vec<u8>> = vec![
        b"<< /Type /Catalog /Pages 2 0 R >>".to_vec(),
        b"<< /Type /Pages /Kids [3 0 R 5 0 R] /Count 2 >>".to_vec(),
        b"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 200 100] /Contents 4 0 R \
           /Resources << /Font << /F1 6 0 R >> >> /Annots [7 0 R] >>"
            .to_vec(),
        [
            format!("<< /Length {} >>\nstream\n", s1.len()).into_bytes(),
            s1.to_vec(),
            b"\nendstream".to_vec(),
        ]
        .concat(),
        b"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 200 100] /Contents 8 0 R \
           /Resources << /Font << /F1 6 0 R >> >> >>"
            .to_vec(),
        b"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>".to_vec(),
        b"<< /Type /Annot /Subtype /Link /Rect [18 44 92 64] /Border [0 0 0] \
           /A << /S /GoTo /D [5 0 R /Fit] >> >>"
            .to_vec(),
        [
            format!("<< /Length {} >>\nstream\n", s2.len()).into_bytes(),
            s2.to_vec(),
            b"\nendstream".to_vec(),
        ]
        .concat(),
    ];
    let mut out = b"%PDF-1.4\n".to_vec();
    let mut offsets = Vec::new();
    for (i, body) in objs.iter().enumerate() {
        offsets.push(out.len());
        out.extend_from_slice(format!("{} 0 obj\n", i + 1).as_bytes());
        out.extend_from_slice(body);
        out.extend_from_slice(b"\nendobj\n");
    }
    let xref = out.len();
    out.extend_from_slice(format!("xref\n0 {}\n", objs.len() + 1).as_bytes());
    out.extend_from_slice(b"0000000000 65535 f \n");
    for off in &offsets {
        out.extend_from_slice(format!("{off:010} 00000 n \n").as_bytes());
    }
    out.extend_from_slice(
        format!(
            "trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n",
            objs.len() + 1
        )
        .as_bytes(),
    );
    out
}

/// The user's gesture end to end: a PDF preview is on screen and a click on
/// a link flips to its target page — through the REAL mouse dispatch, the
/// real overlay geometry from a rendered frame, and real poppler extraction.
#[test]
fn clicking_an_internal_pdf_link_flips_to_its_page() {
    use crossterm::event::{MouseButton, MouseEventKind};
    if !pdf_links_readable() {
        return;
    }
    let tmp = tempfile::tempdir().unwrap();
    let pdf = tmp.path().join("linked.pdf");
    std::fs::write(&pdf, two_page_pdf_with_internal_link()).unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    // A real terminal would have reported these during startup; the overlay
    // bake (whose layout the hit-test reads) is gated on both.
    app.cell_pixel = Some((10, 20));
    app.inline_protocol = crate::iterm2_inline::InlineImageProtocol::Kitty;
    app.editor.open_pinned(&pdf).unwrap();
    settle_pdf(&mut app);
    let backend = ratatui::backend::TestBackend::new(120, 40);
    let mut term = ratatui::Terminal::new(backend).unwrap();
    term.draw(|frame| app.render(frame)).unwrap();
    let layout = app.overlays.editor[0]
        .layout()
        .expect("rendering a PDF tab bakes the image overlay")
        .clone();
    let image = app.editor.image.as_ref().unwrap();
    let (px_w, px_h) = (image.pixel_w, image.pixel_h);
    // The link's text run "go to two" sits around (0.22, 0.47) of the page
    // (measured: x 30..103 of 300, y 62..79 of 150 in pdftohtml space).
    // Find the screen cell covering that point instead of hardcoding one,
    // so the test survives font-metric drift across poppler versions.
    let (mut col, mut row) = (0u16, 0u16);
    'outer: for r in 0..layout.cell_h {
        for c in 0..layout.cell_w {
            if let Some((x0, y0, x1, y1)) = crate::iterm2_inline::cell_source_fraction(
                (c, r),
                (10, 20),
                (layout.cell_w, layout.cell_h),
                (px_w, px_h),
            ) && x0 <= 0.22
                && 0.22 < x1
                && y0 <= 0.47
                && 0.47 < y1
            {
                (col, row) = (layout.cell_x + c, layout.cell_y + r);
                break 'outer;
            }
        }
    }
    assert!(col > 0, "some cell must cover the link's page position");
    assert_eq!(app.editor.pdf_page(), Some(1));
    app.handle_mouse(mouse(MouseEventKind::Down(MouseButton::Left), col, row));
    // The page's links are read on a job (#2824): the click returns at once
    // and acts when they are in.
    assert_eq!(
        app.editor.pdf_page(),
        Some(1),
        "the click must not wait for the links"
    );
    settle_pdf(&mut app);
    assert_eq!(
        app.editor.pdf_page(),
        Some(2),
        "clicking the internal link must flip the preview to page 2; status: {}",
        app.status
    );
}

#[test]
fn cmd_w_closes_a_sheet_tab() {
    // Same swallow bug, sheet branch: handle_sheet_key returned before
    // the close-tab handler so Cmd+W never reached close_active.
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    let csv = tmp.path().join("data.csv");
    std::fs::write(&csv, "name,age\nAlice,30\n").unwrap();
    app.editor.open(&csv).unwrap();
    app.focus = Pane::Editor;
    assert!(app.editor.sheet.is_some(), "setup: sheet must be open");

    app.handle_key(key(KeyCode::Char('w'), KeyModifiers::SUPER))
        .unwrap();

    assert!(
        app.editor.sheet.is_none(),
        "Cmd+W on a sheet view must close the tab, not be swallowed by handle_sheet_key"
    );
}

#[test]
fn cmd_w_closes_an_image_tab() {
    // Same swallow bug, image branch: the read-only image guard returned
    // before the close-tab handler so Cmd+W could never close a PNG tab.
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    let png = tmp.path().join("pic.png");
    image::RgbaImage::new(2, 2).save(&png).unwrap();
    app.editor.open(&png).unwrap();
    app.focus = Pane::Editor;
    assert!(app.editor.image.is_some(), "setup: image must be open");

    app.handle_key(key(KeyCode::Char('w'), KeyModifiers::SUPER))
        .unwrap();

    assert!(
        app.editor.image.is_none(),
        "Cmd+W on an image view must close the tab, not be swallowed by the read-only image guard"
    );
}

#[test]
fn xlsx_grid_editing_saves_cells_and_holds_formulas_for_consent() {
    // #178 end-to-end: xlsx cells edit like CSV, Cmd+S applies exactly
    // the touched cells through umya, and a formula cell needs the
    // second (forced) save to be overwritten.
    let tmp = tempfile::tempdir().unwrap();
    let p = tmp.path().join("book.xlsx");
    let mut book = umya_spreadsheet::new_file();
    let ws = book.sheet_mut(0).unwrap();
    ws.cell_mut((1u32, 1u32)).set_value("name");
    ws.cell_mut((2u32, 1u32)).set_value("qty");
    ws.cell_mut((1u32, 2u32)).set_value("apples");
    ws.cell_mut((2u32, 2u32)).set_value_number(3);
    // With its cached result, as Excel saves it: calamine 0.38 reads a
    // formula whose cached value is a bare `<v/>` as empty, which would
    // leave this row out of the used range and so out of the grid.
    ws.cell_mut((2u32, 3u32))
        .set_formula("SUM(B2)")
        .set_formula_result_default("3");
    umya_spreadsheet::writer::xlsx::write(&book, &p).unwrap();

    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open(&p).unwrap();
    assert!(app.editor.sheet.is_some());

    // Edit qty (0,1) to 42.
    app.handle_sheet_key(key(KeyCode::Right, KeyModifiers::NONE));
    app.handle_sheet_key(key(KeyCode::Char('4'), KeyModifiers::NONE));
    app.handle_sheet_key(key(KeyCode::Char('2'), KeyModifiers::NONE));
    app.handle_sheet_key(key(KeyCode::Enter, KeyModifiers::NONE));
    assert!(app.editor.dirty);
    // And overwrite the formula cell (1,1).
    app.handle_sheet_key(key(KeyCode::Char('8'), KeyModifiers::NONE));
    app.handle_sheet_key(key(KeyCode::Enter, KeyModifiers::NONE));

    app.handle_key(key(KeyCode::Char('s'), KeyModifiers::SUPER))
        .unwrap();
    assert!(
        app.editor.dirty,
        "the formula cell is held back, so the tab stays dirty: {}",
        app.status
    );
    assert!(
        app.status.contains("formula"),
        "status names it: {}",
        app.status
    );
    let book2 = umya_spreadsheet::reader::xlsx::read(&p).unwrap();
    let ws2 = book2.sheet_by_name("Sheet1").unwrap();
    assert_eq!(
        ws2.cell((2u32, 2u32)).unwrap().value(),
        "42",
        "the plain cell landed on the first save"
    );
    assert!(ws2.cell((2u32, 3u32)).unwrap().is_formula());

    // Second Cmd+S consents to the formula overwrite.
    app.handle_key(key(KeyCode::Char('s'), KeyModifiers::SUPER))
        .unwrap();
    assert!(!app.editor.dirty, "everything saved: {}", app.status);
    let book3 = umya_spreadsheet::reader::xlsx::read(&p).unwrap();
    let ws3 = book3.sheet_by_name("Sheet1").unwrap();
    assert!(!ws3.cell((2u32, 3u32)).unwrap().is_formula());
    assert_eq!(ws3.cell((2u32, 3u32)).unwrap().value(), "8");
}

/// #1618: F2 is the spreadsheet "edit this cell" key, caret at the end, as
/// docs/KEYBINDINGS.md says. Rename Symbol used to swallow it, so the next
/// characters replaced the value instead of appending to it.
#[test]
fn f2_in_the_sheet_grid_edits_the_cell_with_the_caret_at_the_end() {
    let tmp = tempfile::tempdir().unwrap();
    let p = tmp.path().join("people.csv");
    std::fs::write(&p, "id,name\n1,Smith\n2,Lee\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open(&p).unwrap();
    app.handle_editor_key(key(KeyCode::Down, KeyModifiers::NONE));
    app.handle_editor_key(key(KeyCode::Right, KeyModifiers::NONE));
    app.handle_editor_key(key(KeyCode::F(2), KeyModifiers::NONE));
    let editing = app.editor.sheet.as_ref().unwrap().editing.as_ref();
    assert_eq!(
        editing.map(|e| (e.value.as_str(), e.cursor)),
        Some(("Lee", 3)),
        "F2 opens the cell editor on the value, caret at the end"
    );
    for c in "son".chars() {
        app.handle_editor_key(key(KeyCode::Char(c), KeyModifiers::NONE));
    }
    app.handle_editor_key(key(KeyCode::Enter, KeyModifiers::NONE));
    let view = app.editor.sheet.as_ref().unwrap();
    assert_eq!(
        view.sheets[0].cell(1, 1),
        "Leeson",
        "F2 appends, like Enter"
    );
    app.save();
    assert_eq!(
        std::fs::read_to_string(&p).unwrap(),
        "id,name\n1,Smith\n2,Leeson\n"
    );
}

/// #1375 end-to-end: one cell typed into a fully quoted CSV and saved
/// changes that line only, still fully quoted.
#[test]
fn saving_a_quoted_csv_from_the_grid_changes_only_the_edited_line() {
    let tmp = tempfile::tempdir().unwrap();
    let p = tmp.path().join("scores.csv");
    let src = "\"id\",\"name\",\"score\"\n\"1\",\"Ada\",\"91\"\n\"2\",\"Grace\",\"88\"\n";
    std::fs::write(&p, src).unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open(&p).unwrap();
    app.handle_sheet_key(key(KeyCode::Right, KeyModifiers::NONE));
    app.handle_sheet_key(key(KeyCode::Right, KeyModifiers::NONE));
    for c in "95".chars() {
        app.handle_sheet_key(key(KeyCode::Char(c), KeyModifiers::NONE));
    }
    app.handle_sheet_key(key(KeyCode::Enter, KeyModifiers::NONE));
    app.save();
    assert!(!app.editor.dirty);
    assert_eq!(
        std::fs::read_to_string(&p).unwrap(),
        src.replace("\"91\"", "\"95\"")
    );
}

#[test]
fn sheet_grid_editing_types_commits_and_saves_with_the_delimiter() {
    // #177 end-to-end: cell cursor, type-to-replace, commit-and-advance,
    // dirty mirroring, the serialisation save path, and a structure op.
    let tmp = tempfile::tempdir().unwrap();
    let p = tmp.path().join("data.csv");
    std::fs::write(&p, "a,b\n1,2\n3,4\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open(&p).unwrap();
    assert!(app.editor.sheet.is_some());

    app.handle_sheet_key(key(KeyCode::Right, KeyModifiers::NONE));
    app.handle_sheet_key(key(KeyCode::Char('9'), KeyModifiers::NONE));
    assert!(
        app.editor.sheet.as_ref().unwrap().editing.is_some(),
        "typing opens the in-grid editor, replacing the value"
    );
    app.handle_sheet_key(key(KeyCode::Char('!'), KeyModifiers::NONE));
    app.handle_sheet_key(key(KeyCode::Enter, KeyModifiers::NONE));
    let view = app.editor.sheet.as_ref().unwrap();
    assert_eq!(view.sheets[0].cell(0, 1), "9!", "Enter commits");
    assert_eq!(view.sheets[0].cur_row, 1, "and advances down");
    assert!(view.dirty && app.editor.dirty);

    app.save();
    assert!(!app.editor.dirty);
    assert_eq!(std::fs::read_to_string(&p).unwrap(), "a,b\n1,9!\n3,4\n");

    // Structure op on the selected row (row index 1: "3,4").
    app.sheet_structure_op(crate::widgets::command_palette::Command::SheetDeleteRow);
    assert!(app.editor.dirty);
    app.save();
    assert_eq!(std::fs::read_to_string(&p).unwrap(), "a,b\n1,9!\n");

    // Esc cancels an edit without committing.
    app.handle_sheet_key(key(KeyCode::Char('x'), KeyModifiers::NONE));
    app.handle_sheet_key(key(KeyCode::Esc, KeyModifiers::NONE));
    assert!(app.editor.sheet.as_ref().unwrap().editing.is_none());
    assert_eq!(
        app.editor.sheet.as_ref().unwrap().sheets[0].cell(0, 1),
        "9!"
    );
}

/// #963: a non-ASCII first key starts the edit instead of being dropped,
/// so `Ölberg` is saved whole and an all-CJK word is typed at all.
#[test]
fn typing_a_non_ascii_first_letter_over_a_sheet_cell_keeps_it() {
    let tmp = tempfile::tempdir().unwrap();
    let p = tmp.path().join("sales.csv");
    std::fs::write(&p, "id,name,city\n1,Frank,Oslo\n2,Bob,New York\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open(&p).unwrap();
    app.handle_sheet_key(key(KeyCode::Right, KeyModifiers::NONE));
    app.handle_sheet_key(key(KeyCode::Right, KeyModifiers::NONE));
    type_into_sheet(&mut app, "Ölberg");
    app.handle_sheet_key(key(KeyCode::Enter, KeyModifiers::NONE));
    type_into_sheet(&mut app, "東京");
    app.handle_sheet_key(key(KeyCode::Enter, KeyModifiers::NONE));
    app.save();
    assert_eq!(
        std::fs::read_to_string(&p).unwrap(),
        "id,name,city\n1,Frank,Ölberg\n2,Bob,東京\n",
        "{}",
        app.status
    );
}

/// `stock.csv` open in the grid, as #1140 repros it.
fn stock_sheet_app() -> (tempfile::TempDir, std::path::PathBuf, App) {
    let tmp = tempfile::tempdir().unwrap();
    let p = tmp.path().join("stock.csv");
    std::fs::write(&p, "item,qty\nbolt,4\nnut,9\nwasher,25\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open(&p).unwrap();
    assert!(app.editor.sheet.is_some());
    (tmp, p, app)
}

/// #1140: Cmd+S with a cell still being typed into saves that cell along
/// with the ones already committed.
#[test]
fn saving_a_sheet_saves_the_cell_still_being_typed_into() {
    let (_tmp, p, mut app) = stock_sheet_app();
    app.handle_sheet_key(key(KeyCode::Right, KeyModifiers::NONE));
    type_into_sheet(&mut app, "40");
    app.handle_sheet_key(key(KeyCode::Enter, KeyModifiers::NONE));
    type_into_sheet(&mut app, "90");
    app.save();
    assert_eq!(
        std::fs::read_to_string(&p).unwrap(),
        "item,qty\nbolt,40\nnut,90\nwasher,25\n"
    );
    assert!(!app.editor.dirty, "{}", app.status);
    assert!(app.editor.sheet.as_ref().unwrap().editing.is_none());
}

/// #1140: with the typed cell the only change, Cmd+S saves it instead of
/// calling the editable grid a read-only preview.
#[test]
fn saving_a_sheet_whose_only_change_is_being_typed_saves_it() {
    let (_tmp, p, mut app) = stock_sheet_app();
    app.handle_sheet_key(key(KeyCode::Right, KeyModifiers::NONE));
    type_into_sheet(&mut app, "40");
    app.save();
    assert_eq!(
        std::fs::read_to_string(&p).unwrap(),
        "item,qty\nbolt,40\nnut,9\nwasher,25\n",
        "{}",
        app.status
    );
    assert!(app.status.starts_with("Saved"), "{}", app.status);
}

/// An unedited sheet writes nothing, and says there's nothing to save
/// rather than that the grid is read-only.
#[test]
fn saving_an_unedited_sheet_writes_nothing_and_says_so() {
    let (_tmp, p, mut app) = stock_sheet_app();
    let before = std::fs::metadata(&p).unwrap().modified().unwrap();
    app.save();
    assert_eq!(app.status, "No changes to save");
    assert_eq!(std::fs::metadata(&p).unwrap().modified().unwrap(), before);
}

/// Esc still throws a typed value away: the save that follows has nothing
/// to write.
#[test]
fn a_cell_edit_cancelled_with_esc_is_not_saved() {
    let (_tmp, p, mut app) = stock_sheet_app();
    app.handle_sheet_key(key(KeyCode::Right, KeyModifiers::NONE));
    type_into_sheet(&mut app, "40");
    app.handle_sheet_key(key(KeyCode::Esc, KeyModifiers::NONE));
    app.save();
    assert_eq!(
        std::fs::read_to_string(&p).unwrap(),
        "item,qty\nbolt,4\nnut,9\nwasher,25\n"
    );
}

/// #1141: an xlsx cell committed by clicking another cell is saved.
#[test]
fn an_xlsx_cell_committed_by_a_click_is_saved() {
    let (_tmp, p, mut app) = prices_xlsx_app();
    app.handle_sheet_key(key(KeyCode::Right, KeyModifiers::NONE));
    type_into_sheet(&mut app, "5");
    let (x, y) = sheet_cell_on_screen(&app, 2, 0);
    left_click(&mut app, x, y);
    assert!(app.editor.dirty, "the click commits the edit");
    app.save();
    assert_eq!(xlsx_value(&p, 2, 2), "5", "{}", app.status);
    assert!(app.status.ends_with("(1 cell)"), "{}", app.status);
    assert!(!app.editor.dirty);
}

/// #1140 (hex comment): half a byte typed is not a read-only preview.
#[test]
fn a_hex_tab_with_half_a_byte_typed_is_not_called_read_only() {
    let tmp = tempfile::tempdir().unwrap();
    let p = tmp.path().join("blob.bin");
    std::fs::write(&p, vec![0u8; 16]).unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open(&p).unwrap();
    app.handle_hex_key(key(KeyCode::Char('f'), KeyModifiers::NONE));
    app.save();
    assert!(!app.status.contains("read-only"), "{}", app.status);
    assert_eq!(std::fs::read(&p).unwrap(), vec![0u8; 16]);
}

/// stock.csv from #1137: the widget row's unquoted `1,200` gives it the
/// only third field, so deleting it shrinks the sheet to two columns.
fn sheet_app_on_stock_csv() -> (tempfile::TempDir, App) {
    let tmp = tempfile::tempdir().unwrap();
    let p = tmp.path().join("stock.csv");
    std::fs::write(&p, "item,qty\nbolt,4\nwidget,1,200\nnut,9\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open(&p).unwrap();
    (tmp, app)
}

#[test]
fn deleting_the_only_row_reaching_the_last_column_keeps_the_caret_in_the_sheet() {
    let (_tmp, mut app) = sheet_app_on_stock_csv();
    app.handle_sheet_key(key(KeyCode::Down, KeyModifiers::NONE));
    app.handle_sheet_key(key(KeyCode::Right, KeyModifiers::NONE));
    app.handle_sheet_key(key(KeyCode::Right, KeyModifiers::NONE));
    let data = &app.editor.sheet.as_ref().unwrap().sheets[0];
    assert_eq!((data.cur_row, data.cur_col, data.col_count()), (1, 2, 3));

    // Panicked with "range end index 2 out of range for slice of length 2".
    app.sheet_structure_op(crate::widgets::command_palette::Command::SheetDeleteRow);
    let data = &app.editor.sheet.as_ref().unwrap().sheets[0];
    assert_eq!(data.col_count(), 2);
    assert_eq!(data.cur_col, 1, "the caret moves onto the last column left");
    assert!(data.scroll_col <= data.cur_col);
    assert_eq!(data.cell(1, 0), "nut");
    // The grid still moves and renders from there.
    app.handle_sheet_key(key(KeyCode::Right, KeyModifiers::NONE));
    app.handle_sheet_key(key(KeyCode::Left, KeyModifiers::NONE));
    let mut term = ratatui::Terminal::new(ratatui::backend::TestBackend::new(100, 30)).unwrap();
    term.draw(|f| app.render(f)).unwrap();
}

#[test]
fn deleting_a_row_that_leaves_the_column_count_alone_keeps_the_caret_column() {
    // Negative: bolt is not the widest row, so the sheet keeps its three
    // columns and the caret stays where it was.
    let (_tmp, mut app) = sheet_app_on_stock_csv();
    app.handle_sheet_key(key(KeyCode::Right, KeyModifiers::NONE));
    app.sheet_structure_op(crate::widgets::command_palette::Command::SheetDeleteRow);
    let data = &app.editor.sheet.as_ref().unwrap().sheets[0];
    assert_eq!(data.col_count(), 3);
    assert_eq!((data.cur_row, data.cur_col), (0, 1));
    assert_eq!(data.cell(0, 0), "widget");
}

#[test]
fn hex_typing_edits_bytes_and_cmd_s_writes_them_in_place() {
    // #173 end-to-end: hex-pane nibble typing, Tab to the ASCII pane,
    // dirty tracking, undo, and the byte save path (never the text
    // choke point, which #185 makes refuse preview tabs).
    let tmp = tempfile::tempdir().unwrap();
    let p = tmp.path().join("blob.bin");
    std::fs::write(&p, vec![0u8; 16]).unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open(&p).unwrap();
    assert!(app.editor.hex.is_some());

    // "4" then "1" completes 0x41 at offset 0 and advances the cursor.
    app.handle_hex_key(key(KeyCode::Char('4'), KeyModifiers::NONE));
    assert_eq!(
        app.editor.hex.as_ref().unwrap().pending_nibble,
        Some(4),
        "first nibble latches"
    );
    app.handle_hex_key(key(KeyCode::Char('1'), KeyModifiers::NONE));
    let v = app.editor.hex.as_ref().unwrap();
    assert_eq!(v.effective_byte(0), Some(0x41));
    assert_eq!(v.cursor, 1, "completed byte advances");
    assert!(app.editor.dirty, "pending edits mark the tab dirty");

    // Tab switches panes; a typed character lands as its byte.
    app.handle_hex_key(key(KeyCode::Tab, KeyModifiers::NONE));
    app.handle_hex_key(key(KeyCode::Char('Z'), KeyModifiers::NONE));
    let v = app.editor.hex.as_ref().unwrap();
    assert_eq!(v.effective_byte(1), Some(b'Z'));
    assert_eq!(v.cursor, 2);

    // Undo removes the last byte; redo restores it.
    app.handle_hex_key(key(KeyCode::Char('z'), KeyModifiers::SUPER));
    assert_eq!(
        app.editor.hex.as_ref().unwrap().effective_byte(1),
        Some(0),
        "undo reverts to the disk byte"
    );
    app.handle_hex_key(key(
        KeyCode::Char('z'),
        KeyModifiers::SUPER | KeyModifiers::SHIFT,
    ));
    assert_eq!(
        app.editor.hex.as_ref().unwrap().effective_byte(1),
        Some(b'Z')
    );

    // Cmd+S through the REAL key dispatch writes the bytes in place
    // and cleans the tab (#191 review: app.save() directly would keep
    // passing if the chord routing broke).
    app.handle_key(key(KeyCode::Char('s'), KeyModifiers::SUPER))
        .unwrap();
    assert!(!app.editor.dirty);
    let disk = std::fs::read(&p).unwrap();
    assert_eq!(disk[0], 0x41);
    assert_eq!(disk[1], b'Z');
    assert_eq!(disk.len(), 16, "in-place write, length untouched");
    assert!(
        app.status.starts_with("Wrote 2 bytes"),
        "status reports the write: {}",
        app.status
    );
}

#[test]
fn a_half_typed_hex_byte_does_not_follow_the_cursor() {
    // #1142: f, Right, 2 over 41 42 saved F2 into byte 1, a byte the user
    // never typed on. Leaving byte 0 drops its half-typed digit.
    let tmp = tempfile::tempdir().unwrap();
    let p = tmp.path().join("h.bin");
    std::fs::write(&p, b"ABCDEFGH\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open_hex(&p).unwrap();
    assert!(app.editor.hex.is_some());
    app.handle_hex_key(key(KeyCode::Char('f'), KeyModifiers::NONE));
    app.handle_hex_key(key(KeyCode::Right, KeyModifiers::NONE));
    app.handle_hex_key(key(KeyCode::Char('2'), KeyModifiers::NONE));
    let v = app.editor.hex.as_ref().unwrap();
    assert_eq!(v.effective_byte(0), Some(b'A'));
    assert_eq!(v.effective_byte(1), Some(b'B'));
    assert_eq!(v.pending_nibble, Some(2), "the 2 starts byte 1 afresh");
    assert!(!app.editor.dirty, "no byte has changed");
}

/// The firmware image from #1644: the text "1234" at 0x115 and 0x137, and
/// the bytes 12 34 at 0x11A.
fn app_with_firmware_in_hex(tmp: &std::path::Path) -> App {
    let f = tmp.join("fw.bin");
    // 256 bytes of non-ASCII lead-in, so no digits come before the text.
    let mut bytes: Vec<u8> = (0x80..=0xff).chain(0x80..=0xff).collect();
    bytes.extend_from_slice(b"version 2024.1 build 1234\x00\x12\x34");
    bytes.extend_from_slice(&[0; 20]);
    bytes.extend_from_slice(b"serial 1234\x00");
    std::fs::write(&f, bytes).unwrap();
    let mut app = App::new(tmp.to_path_buf()).unwrap();
    app.editor.open_hex(&f).unwrap();
    app
}

fn hex_find(app: &mut App, query: &str) {
    app.open_hex_find_prompt();
    app.input_prompt.as_mut().unwrap().value = query.to_string();
    app.submit_input_prompt();
}

/// #1644: `"1234"` in quotes finds the text, then the next one on F3, and
/// the status line says it searched for text.
#[test]
fn hex_find_of_quoted_digits_finds_the_text() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = app_with_firmware_in_hex(tmp.path());
    hex_find(&mut app, "\"1234\"");
    assert_eq!(app.editor.hex.as_ref().unwrap().cursor, 0x115);
    assert_eq!(app.status, "Found text \"1234\" at 0x115");
    app.hex_find_next();
    assert_eq!(app.editor.hex.as_ref().unwrap().cursor, 0x137);
}

/// #1644: from the text column (Tab), a hex-shaped query is text, and the
/// prompt's title says so.
#[test]
fn hex_find_from_the_text_column_reads_digits_as_text() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = app_with_firmware_in_hex(tmp.path());
    app.editor.hex.as_mut().unwrap().ascii_focus = true;
    app.open_hex_find_prompt();
    assert_eq!(
        app.input_prompt.as_ref().unwrap().title,
        "Find in Hex (text)"
    );
    app.input_prompt.as_mut().unwrap().value = String::from("2024");
    app.submit_input_prompt();
    assert_eq!(app.editor.hex.as_ref().unwrap().cursor, 0x108);
    assert_eq!(app.status, "Found text \"2024\" at 0x108");
}

/// Negative (#1644): in the hex grid a hex-shaped query is still bytes,
/// now named in the status line, and a query that is not hex-shaped is
/// found the same from either column.
#[test]
fn hex_find_in_the_grid_still_reads_hex_pairs_as_bytes() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = app_with_firmware_in_hex(tmp.path());
    hex_find(&mut app, "12 34");
    assert_eq!(app.editor.hex.as_ref().unwrap().cursor, 0x11A);
    assert_eq!(app.status, "Found bytes 12 34 at 0x11A");
    for text_side in [false, true] {
        let mut app = app_with_firmware_in_hex(tmp.path());
        app.editor.hex.as_mut().unwrap().ascii_focus = text_side;
        hex_find(&mut app, "serial");
        assert_eq!(
            app.editor.hex.as_ref().unwrap().cursor,
            0x130,
            "{text_side}"
        );
    }
    hex_find(&mut app, "\"no such text\"");
    assert_eq!(app.status, "Not found: text \"no such text\"");
}

/// #1438: a spreadsheet cell still being typed into is an unsaved edit:
/// Commit asks first, and Save All & Commit writes the typed value.
#[test]
fn a_sheet_cell_being_typed_into_holds_the_commit() {
    let (tmp, mut app) = scm_ready_to_commit();
    let csv = tmp.path().join("stock.csv");
    std::fs::write(&csv, "item,qty\nbolt,4\n").unwrap();
    app.editor.open(&csv).unwrap();
    assert!(app.editor.sheet.is_some());
    app.handle_sheet_key(key(KeyCode::Right, KeyModifiers::NONE));
    type_into_sheet(&mut app, "40");
    assert!(!app.editor.dirty, "the typed cell is not committed yet");
    app.source_control.message = "bump seed".to_string();
    app.source_control.message_cursor = app.source_control.message.chars().count();
    app.handle_source_control_key(key(KeyCode::Enter, KeyModifiers::NONE));
    let pending = app.pending_unsaved_scm.as_ref().expect("the prompt opens");
    assert_eq!(pending.files, vec![csv.clone()]);
    app.handle_key(key(KeyCode::Char('s'), KeyModifiers::NONE))
        .unwrap();
    wait_for_git_net(&mut app);
    assert!(app.pending_unsaved_scm.is_none());
    assert_eq!(
        std::fs::read_to_string(&csv).unwrap(),
        "item,qty\nbolt,40\n",
        "{}",
        app.status
    );
}

/// A swap into a viewer drops the map (#349 review): the hex view's single
/// placeholder line was written by no seat, and a save from the viewer must
/// not persist the text tab's map against bytes it never described. The swap
/// back to text is an ordinary reopen and gets the persisted map again.
#[test]
fn a_viewer_swap_drops_the_map_and_the_text_reopen_gets_it_back() {
    use crate::provenance::Seat;
    let tmp = tempfile::tempdir().unwrap();
    let hist = tempfile::tempdir().unwrap();
    let f = tmp.path().join("note.txt");
    std::fs::write(&f, "one\n").unwrap();
    let mut seats = crate::provenance::Provenance::new();
    seats.record(0..1, Seat::Navigator);
    crate::history::record_with_seats_in(
        hist.path(),
        &f,
        &std::fs::read(&f).unwrap(),
        1_000,
        &seats,
    )
    .unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.history_root = hist.path().to_path_buf();
    app.editor.open(&f).unwrap();
    app.sync_provenance();
    assert_eq!(
        app.editor.provenance, seats,
        "staging: the text tab is synced"
    );
    app.editor.open_hex(&f).unwrap();
    assert!(app.editor.hex.is_some(), "staging: the tab is a hex view");
    assert_eq!(
        app.editor.provenance.attributed(),
        0,
        "the swap into the viewer dropped the map"
    );
    app.sync_provenance();
    assert_eq!(
        app.editor.provenance.attributed(),
        0,
        "and a sync does not credit the viewer's placeholder line"
    );
    assert_eq!(
        app.editor.provenance_to_record().attributed(),
        0,
        "a save from the viewer would record no map"
    );
    app.editor.open(&f).unwrap();
    app.sync_provenance();
    assert_eq!(
        app.editor.provenance, seats,
        "the reopen as text gets the persisted map back"
    );
}

/// A markdown preview is not a viewer (#349 review): `lines` still holds the
/// file's own text and the tab is saveable, so a save taken while the
/// preview is up records the map rather than dropping it (and, inside the
/// merge window, deleting the previous snapshot's sidecar with nothing to
/// replace it).
#[test]
fn a_markdown_preview_save_keeps_the_map() {
    use crate::provenance::Seat;
    let tmp = tempfile::tempdir().unwrap();
    let hist = tempfile::tempdir().unwrap();
    let f = tmp.path().join("note.md");
    std::fs::write(&f, "# one\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.history_root = hist.path().to_path_buf();
    app.editor.open(&f).unwrap();
    app.focus_pane(Pane::Editor);
    app.editor.provenance.record(0..1, Seat::Navigator);
    assert!(
        app.editor.toggle_markdown_preview(),
        "staging: the preview is up"
    );
    assert!(
        !app.editor.has_non_text_view(),
        "staging: a markdown preview tab is still saveable text"
    );
    assert_eq!(
        app.editor.provenance_to_record().seat(0),
        Some(&Seat::Navigator),
        "the buffer's own text is in `lines`; its map still describes it"
    );
    app.editor.dirty = true;
    app.save();
    let snaps = wait_for_snapshots(&app.history_root, &f);
    assert_eq!(snaps.len(), 1, "staging: the save recorded a snapshot");
    wait_for_seats(&app.history_root, &f, snaps[0].millis);
}

/// #465: a viewer runs the declared program on the file in a pane of its own,
/// with `{file}` replaced by the file's path, and the pane takes focus. The
/// program here is `sh`, so nothing has to be installed for the test.
#[test]
fn opening_a_file_in_a_viewer_runs_the_tool_on_it_in_a_new_terminal_pane() {
    let tmp = tempfile::tempdir().unwrap();
    let data = tmp.path().join("data.csv");
    std::fs::write(&data, "a,b\n1,2\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.consented_extensions.insert("csvlens".into());
    let before = app.terminals.len();
    let viewer = crate::mcp::registry::ContributedViewer {
        ext_id: "csvlens".into(),
        id: "csvlens".into(),
        label: "Open in csvlens".into(),
        command: "/bin/sh".into(),
        args: vec![
            "-c".into(),
            "echo VIEWING \"$1\"; sleep 30".into(),
            "sh".into(),
            "{file}".into(),
        ],
        extensions: vec!["csv".into()],
        provision: None,
    };
    app.open_in_viewer(&viewer, &data);
    assert_eq!(
        app.terminals.len(),
        before + 1,
        "the viewer gets a pane of its own"
    );
    assert!(app.show_terminal, "the panel is shown");
    assert!(
        matches!(app.focus, Pane::Terminal),
        "and the pane takes focus"
    );
    let want = format!("VIEWING {}", data.display());
    crate::test_budget::await_spawned(
        std::time::Duration::from_millis(500),
        "the viewer to print the file it was handed",
        || app.terminal().visible_text().contains(&want),
    );
}

/// A file name that is not valid UTF-8 must not be handed to the viewer
/// mangled (#485 review): the tool would open a different path and fail.
/// Until the pane spawn can carry OS-native arguments, such a file is
/// refused with a status line rather than opened wrong.
#[cfg(unix)]
#[test]
fn a_viewer_refuses_a_path_it_cannot_pass_faithfully() {
    use std::os::unix::ffi::OsStrExt;
    let tmp = tempfile::tempdir().unwrap();
    // The file is deliberately not created: APFS refuses such a name, and
    // the guard fires before the viewer path touches the disk anyway.
    let odd = tmp
        .path()
        .join(std::ffi::OsStr::from_bytes(b"d\xffata.csv"));
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    let viewer = crate::mcp::registry::ContributedViewer {
        ext_id: "csvlens".into(),
        id: "csvlens".into(),
        label: "Open in csvlens".into(),
        command: "/bin/sh".into(),
        args: vec!["-c".into(), "sleep 30".into(), "sh".into(), "{file}".into()],
        extensions: vec!["csv".into()],
        provision: None,
    };
    let before = app.terminals.len();
    app.open_in_viewer(&viewer, &odd);
    assert_eq!(
        app.terminals.len(),
        before,
        "no pane is spawned for a path that cannot be passed"
    );
    assert!(
        app.status.contains("not valid UTF-8"),
        "the status says why: {:?}",
        app.status
    );
}

/// A viewer spawns a program from a manifest, so it passes the same
/// first-run consent gate a sidecar does (#485 review): the first use of an
/// extension's viewer shows the exact command line and spawns nothing until
/// the user allows it; a consented extension runs straight away.
#[test]
fn a_viewer_asks_for_consent_before_its_first_run() {
    let tmp = tempfile::tempdir().unwrap();
    let data = tmp.path().join("data.csv");
    std::fs::write(&data, "a,b\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    let viewer = crate::mcp::registry::ContributedViewer {
        ext_id: format!("consent-test-{}", std::process::id()),
        id: "csvlens".into(),
        label: "Open in csvlens".into(),
        command: "/bin/sh".into(),
        args: vec!["-c".into(), "sleep 30".into(), "sh".into(), "{file}".into()],
        extensions: vec!["csv".into()],
        provision: None,
    };
    let before = app.terminals.len();
    app.open_in_viewer(&viewer, &data);
    assert_eq!(app.terminals.len(), before, "nothing spawns before consent");
    let prompt = app
        .input_prompt
        .as_ref()
        .expect("the consent prompt is open");
    assert!(
        prompt.title.contains(&viewer.ext_id) && prompt.title.contains("/bin/sh"),
        "the prompt names the extension and the exact command: {:?}",
        prompt.title
    );
}

/// Allowing a viewer records the consent and resumes the open that asked;
/// a prefs write that fails is said in the status rather than swallowed.
#[test]
fn allowing_a_viewer_records_consent_and_resumes_the_open() {
    const EXT: &str = r#"
id = "tviewer"
name = "tviewer"
api_version = 1
[[viewers]]
id = "sh"
label = "Open in sh"
command = "/bin/sh"
args = ["-c", "sleep 30", "sh", "{file}"]
extensions = ["csv"]
"#;
    let (_scratch, croft) = scratch_config(&[("tviewer", EXT)]);
    let tmp = tempfile::tempdir().unwrap();
    let data = tmp.path().join("data.csv");
    std::fs::write(&data, "a,b\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.config_dir = croft.clone();
    app.consented_extensions = consent_on_disk(&croft);
    let viewer =
        crate::mcp::registry::viewer_by_id_in_dir(&croft, &app.disabled_extensions, "tviewer/sh")
            .expect("the scratch viewer");
    let before = app.terminals.len();
    app.open_in_viewer(&viewer, &data);
    assert!(
        app.input_prompt.is_some(),
        "fixture: consent is asked first"
    );
    app.submit_input_prompt();
    assert_eq!(app.terminals.len(), before + 1, "allowing resumes the open");
    assert!(
        app.consented_extensions.contains("tviewer"),
        "and records the consent"
    );
    let saved = consent_on_disk(&croft);
    assert!(saved.contains("tviewer"), "on disk too: {saved:?}");
    assert!(
        !app.status.contains("could not be saved"),
        "a successful save is not reported as a failure: {:?}",
        app.status
    );
    // Now with the prefs file made unwritable (a directory in its place):
    // the consent still holds for the session and the status says the save
    // failed, instead of the failure vanishing.
    app.consented_extensions.remove("tviewer");
    let _ = std::fs::remove_file(croft.join("config.json"));
    std::fs::create_dir_all(croft.join("config.json")).unwrap();
    app.open_in_viewer(&viewer, &data);
    app.submit_input_prompt();
    assert!(
        app.status.contains("could not be saved"),
        "a failed prefs write is reported: {:?}",
        app.status
    );
    assert!(
        app.consented_extensions.contains("tviewer"),
        "the session grant still holds"
    );
}

/// The Explorer row and the palette row for a viewer are built from the
/// same config dir the click resolves them through: a viewer installed only
/// under the app's dir gets its row, and the row opens.
#[test]
fn a_viewer_row_is_built_and_resolved_through_the_same_config_dir() {
    const EXT: &str = r#"
id = "tviewer"
name = "tviewer"
api_version = 1
[[viewers]]
id = "sh"
label = "Open in sh"
command = "/bin/sh"
args = ["-c", "sleep 30", "sh", "{file}"]
extensions = ["csv"]
"#;
    let (_scratch, croft) = scratch_config(&[("tviewer", EXT)]);
    let tmp = tempfile::tempdir().unwrap();
    let csv = tmp.path().join("data.csv");
    std::fs::write(&csv, "a,b\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.config_dir = croft.clone();
    app.consented_extensions = consent_on_disk(&croft);
    app.consented_extensions.insert("tviewer".into());
    let n = file_node(&csv);
    let items = app.tree_context_menu_items(Some(&n), std::slice::from_ref(&csv), tmp.path());
    let row = items
        .iter()
        .find_map(|(label, a)| match a {
            MenuAction::OpenInViewer(id, p) if p == &csv => Some((label.clone(), id.clone())),
            _ => None,
        })
        .expect("the viewer under the app's config dir gets a row");
    assert_eq!(row, ("Open in sh".to_string(), "tviewer/sh".to_string()));
    let before = app.terminals.len();
    app.dispatch_menu_action(
        MenuAction::OpenInViewer(row.1.clone(), csv.clone()),
        tmp.path().to_path_buf(),
    );
    assert_eq!(
        app.terminals.len(),
        before + 1,
        "and the row resolves and opens"
    );
    let palette_ids: Vec<String> =
        crate::mcp::registry::contributed_viewer_commands_in_dir(&croft, &app.disabled_extensions)
            .into_iter()
            .map(|c| c.id)
            .collect();
    assert!(
        palette_ids.iter().any(|id| id == "viewer:tviewer/sh"),
        "the palette row comes from the same dir: {palette_ids:?}"
    );
}

/// A viewer that is gone by the time its menu row is clicked, or by the time
/// its consent prompt is allowed (the extension was removed in between),
/// must say so rather than do nothing: a silent click reads as a broken
/// menu. Neither path spawns anything or records consent for a viewer it
/// could not find.
#[test]
fn a_vanished_viewer_is_reported_from_the_menu_and_the_consent_prompt() {
    use crate::widgets::input_prompt::{InputPrompt, InputPurpose};
    let tmp = tempfile::tempdir().unwrap();
    let data = tmp.path().join("data.csv");
    std::fs::write(&data, "a,b\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    let before = app.terminals.len();
    let key = format!("vanished-ext-{}/csvlens", std::process::id());
    app.status.clear();
    app.dispatch_menu_action(
        MenuAction::OpenInViewer(key.clone(), data.clone()),
        tmp.path().to_path_buf(),
    );
    assert_eq!(app.terminals.len(), before, "the menu click spawns nothing");
    assert!(
        app.status.contains("no longer"),
        "the click says the viewer is gone: {:?}",
        app.status
    );
    app.status.clear();
    app.open_input_prompt(
        InputPrompt::new(
            InputPurpose::ViewerConsent {
                key: key.clone(),
                path: data,
            },
            "Allow",
            "",
        )
        .with_value("allow"),
    );
    app.submit_input_prompt();
    assert!(app.input_prompt.is_none(), "the prompt closes");
    assert_eq!(app.terminals.len(), before, "allowing spawns nothing");
    assert!(
        app.status.contains("no longer"),
        "allowing says the viewer is gone: {:?}",
        app.status
    );
    assert!(
        !app.consented_extensions
            .iter()
            .any(|e| key.starts_with(e.as_str())),
        "no consent is recorded for a viewer that could not be found"
    );
}

/// #465: the palette row reaches the viewer route (not the MCP command path)
/// and guards on the active file before anything is spawned.
#[test]
fn a_viewer_palette_row_guards_on_the_active_file() {
    let tmp = tempfile::tempdir().unwrap();
    let notes = tmp.path().join("notes.md");
    let data = tmp.path().join("data.csv");
    std::fs::write(&notes, "# hi\n").unwrap();
    std::fs::write(&data, "a,b\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.consented_extensions.insert("csvlens".into());
    // The `viewer:` prefix is routed before the MCP lookup: an unknown viewer
    // is reported as a viewer, not as an extension command.
    app.run_extension_command("viewer:nope");
    assert_eq!(app.status, "Viewer 'nope' is unavailable");

    let viewer = crate::mcp::registry::ContributedViewer {
        ext_id: "csvlens".into(),
        id: "csvlens".into(),
        label: "Open in csvlens".into(),
        command: "/bin/sh".into(),
        args: vec!["-c".into(), "sleep 30".into()],
        extensions: vec!["csv".into(), "tsv".into()],
        provision: None,
    };
    let before = app.terminals.len();
    app.editor.path = None;
    app.open_active_file_in_viewer(&viewer);
    assert_eq!(app.status, "Open in csvlens: open a file first");
    app.editor.open(&notes).unwrap();
    app.open_active_file_in_viewer(&viewer);
    assert_eq!(
        app.status,
        "Open in csvlens: the active file is not one of .csv / .tsv"
    );
    assert_eq!(app.terminals.len(), before, "a guard spawns nothing");
    app.editor.open(&data).unwrap();
    app.open_active_file_in_viewer(&viewer);
    assert_eq!(
        app.terminals.len(),
        before + 1,
        "a matching file opens in a pane"
    );
}

#[test]
fn iterm2_image_drag_artefact_does_not_paste_its_path_into_the_editor() {
    // Root cause of the user's "Pasted 67 chars" surprise: when iTerm2
    // hijacks a click-drag on an OSC-1337 activity-bar icon, it writes
    // the decoded PNG to $TMPDIR/iTerm2.<rand>.png and re-injects the
    // path as a bracketed paste. parse_dropped_paths filters those
    // paths out of the IMPORT list, but without an early-return in
    // handle_paste the fallthrough would still insert the raw path
    // text into the focused editor.
    let mut app = editor_app_with_lines(&[""]);
    app.focus_pane(Pane::Editor);
    let tmp = tempfile::tempdir().unwrap();
    let temp_dir = tmp.path().join("T").join("com.googlecode.iterm2");
    std::fs::create_dir_all(&temp_dir).unwrap();
    let fake = temp_dir.join("iTerm2.5AO7K5.png");
    std::fs::write(&fake, b"\x89PNG\r\n\x1a\n").unwrap();
    let payload = format!("{}\n", fake.display());
    app.handle_paste(&payload);
    assert_eq!(
        app.editor.lines,
        vec![""],
        "iTerm2 inline-image drag artefact must be silently dropped at every level — the path string must NOT be pasted as text into the editor body (the user reported a CLAUDE.local.md tab opening with 'Pasted 67 chars' after trying to resize the sidebar near the Explorer icon)"
    );
}

#[test]
fn parse_dropped_paths_drops_iterm2_inline_image_drag_artefact() {
    // iTerm2 lets the user drag any OSC-1337 inline image (which is
    // how croft paints activity-bar icons / welcome wordmark / SSH
    // hero) out of the terminal. On mouse-up iTerm2 writes the bytes
    // to $TMPDIR/iTerm2.<rand>.png and re-injects the path as a
    // bracketed paste, which croft would otherwise see as "the user
    // dragged a file into the editor" and open as an image preview.
    // That has happened to the user accidentally when they tried to
    // click a sidebar icon and the click drifted into a drag — the
    // file `iTerm2.5AO7K5.png` opened as a tab showing the Explorer
    // glyph. The drop must be silently filtered.
    let tmp = tempfile::tempdir().unwrap();
    let temp_dir = tmp.path().join("T").join("com.googlecode.iterm2");
    std::fs::create_dir_all(&temp_dir).unwrap();
    let fake = temp_dir.join("iTerm2.5AO7K5.png");
    std::fs::write(&fake, b"\x89PNG\r\n\x1a\n").unwrap();
    let parsed = parse_dropped_paths(&format!("{}\n", fake.display()));
    assert!(
        parsed.is_empty(),
        "iTerm2's inline-image drag temp file must be filtered out so a stray click-drag on an activity-bar icon does not open a phantom PNG tab — got {parsed:?}"
    );
}

#[test]
fn closing_image_tab_requests_overlay_clear_on_next_render() {
    // Repro for: opening a PNG/PDF then closing the tab leaves the
    // OSC-1337 pixels bleeding through the welcome screen. The render
    // path that swaps to welcome must mark the editor image overlay
    // for clearing so the main loop wipes the screen.
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.overlays.editor[0].set_test_state(
        Some(String::from("dummy-osc")),
        Some(EditorImageLayout {
            cell_x: 0,
            cell_y: 0,
            cell_w: 10,
            cell_h: 10,
            path: tmp.path().join("doomed.png"),
            page: 1,
            generation: 0,
        }),
        true,
    );
    // Editor is blank-initial right after construction, so calling
    // disable_editor_image directly mimics what render() does on
    // the welcome branch.
    app.disable_editor_image(0);
    assert!(app.overlays.editor[0].image_is_none());
    assert!(app.overlays.editor[0].layout_is_none());
    assert!(
        app.consume_editor_image_clear(),
        "first call must report a pending clear"
    );
    assert!(
        !app.consume_editor_image_clear(),
        "second call must be a no-op"
    );
}

#[cfg(target_os = "macos")]
#[test]
fn iterm2_and_terminal_scripts_shell_quote_paths_with_spaces() {
    let exe = std::path::Path::new("/usr/local/bin/croft");
    let root = std::path::Path::new("/home/me/My Project");
    let file = std::path::Path::new("/home/me/My Project/a b.rs");

    let iterm = iterm2_new_window_script(exe, root, file);
    assert!(
        iterm
            .contains(r#"tell application "iTerm" to create window with default profile command "#),
        "{iterm}"
    );
    // Each path single-quoted so the space survives the shell.
    assert!(iterm.contains("'/home/me/My Project'"), "{iterm}");
    assert!(iterm.contains("'/home/me/My Project/a b.rs'"), "{iterm}");

    // The window opens focused on the file: --zen is part of the invocation.
    assert!(iterm.contains("--zen"), "{iterm}");

    let term = apple_terminal_new_window_script(exe, root, file);
    assert!(
        term.contains(r#"tell application "Terminal" to do script "#),
        "{term}"
    );
    assert!(
        term.contains("--open-file '/home/me/My Project/a b.rs' --zen"),
        "{term}"
    );
}

/// There are physically two image-overlay slots (left/right column); any
/// layout other than the two-column split bakes the active group into slot 0.
/// The focused side must therefore never index past the array: clicking a PDF
/// in the lower-right group of a three-way split panicked with
/// index-out-of-bounds before this was clamped.
#[test]
fn focused_image_side_stays_within_the_two_overlay_slots() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = app_with_open_file(tmp.path(), "a.txt", "hello");
    app.split_editor_dir(editor_layout::SplitDir::Horizontal, true);
    app.split_editor_dir(editor_layout::SplitDir::Vertical, true);
    assert_eq!(app.editor_layout.active_dfs_index(), 2);
    assert!(
        app.focused_image_side() < 2,
        "focused_image_side must stay within overlays.editor"
    );
}

#[test]
fn editor_image_overlay_is_dual_slot_and_clear_ors_both_columns() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    let layout = |name: &str| EditorImageLayout {
        cell_x: 0,
        cell_y: 0,
        cell_w: 10,
        cell_h: 10,
        path: tmp.path().join(name),
        page: 1,
        generation: 0,
    };
    // Both physical columns can hold an inline image at once.
    app.overlays.editor[0].set_test_state(Some("left-osc".into()), Some(layout("l.png")), true);
    app.overlays.editor[1].set_test_state(Some("right-osc".into()), Some(layout("r.png")), true);
    assert_eq!(
        app.editor_image_payload(0).map(|(o, _)| o),
        Some("left-osc")
    );
    assert_eq!(
        app.editor_image_payload(1).map(|(o, _)| o),
        Some("right-osc")
    );

    // Disabling the right slot arms a clear; `consume_editor_image_clear`
    // must report it even though the left slot is quiet.
    app.disable_editor_image(1);
    assert!(
        app.consume_editor_image_clear(),
        "a clear armed on either column must surface from the ORed consume"
    );
    assert!(
        !app.consume_editor_image_clear(),
        "the latch is one-shot and both slots were consumed"
    );
}

/// #2859 review: a selection begun in the rendered Markdown view whose release
/// was lost must not take the next press's drag. Here the next press lands on
/// the status bar's problem counts, which take it before the preview could
/// end its own selection; the drag after it left the preview selection
/// following the pointer.
#[test]
fn a_press_after_a_lost_release_ends_a_markdown_preview_selection() {
    use crossterm::event::{MouseButton, MouseEventKind};
    let tmp = tempfile::tempdir().unwrap();
    let md = tmp.path().join("doc.md");
    std::fs::write(&md, "# Heading\n\nSome rendered body text here.\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open_pinned(&md).unwrap();
    app.focus_pane(Pane::Editor);
    app.handle_key(key(
        KeyCode::Char('v'),
        KeyModifiers::SUPER | KeyModifiers::SHIFT,
    ))
    .unwrap();
    let backend = ratatui::backend::TestBackend::new(100, 30);
    let mut term = ratatui::Terminal::new(backend).unwrap();
    term.draw(|frame| app.render(frame)).unwrap();
    let (area, row_idx, text) = {
        let md = app.editor.markdown_preview.as_ref().unwrap();
        let (i, t) = md
            .rows
            .iter()
            .enumerate()
            .map(|(i, cells)| (i as u16, cells.concat()))
            .find(|(_, r)| r.contains("rendered body"))
            .expect("the body text must be rendered");
        (md.last_area, i, t)
    };
    let start_col = text.find("rendered").unwrap() as u16;
    let y = area.y + row_idx;
    app.handle_mouse(mouse(
        MouseEventKind::Down(MouseButton::Left),
        area.x + start_col,
        y,
    ));
    let begun = app.editor.markdown_preview.as_ref().unwrap().selection;
    assert!(begun.is_some(), "the press starts a preview selection");
    // That press's release never arrives. The next press is on the status
    // bar's problem counts.
    let diag = app.status_hits.diagnostics;
    assert!(!diag.is_empty(), "the status bar shows the problem counts");
    app.handle_mouse(mouse(
        MouseEventKind::Down(MouseButton::Left),
        diag.x,
        diag.y,
    ));
    app.handle_mouse(mouse(
        MouseEventKind::Drag(MouseButton::Left),
        area.x + start_col + 6,
        y,
    ));
    let md = app.editor.markdown_preview.as_ref().unwrap();
    assert!(!md.dragging, "the new press ended the lost selection drag");
    assert_eq!(md.selection, begun, "the later drag did not extend it");
}

/// Issue #215: text in the rendered Markdown view must be selectable.
/// A drag over the preview selects what is on screen, Cmd+C copies the
/// RENDERED text (not the source), and Esc clears the selection.
#[test]
fn dragging_in_the_markdown_preview_selects_and_copies_rendered_text() {
    use crossterm::event::{MouseButton, MouseEventKind};
    let tmp = tempfile::tempdir().unwrap();
    let md = tmp.path().join("doc.md");
    std::fs::write(&md, "# Heading\n\nSome rendered body text here.\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open_pinned(&md).unwrap();
    app.focus_pane(Pane::Editor);
    // Cmd+Shift+V flips to the rendered preview.
    app.handle_key(key(
        KeyCode::Char('v'),
        KeyModifiers::SUPER | KeyModifiers::SHIFT,
    ))
    .unwrap();
    assert!(
        app.editor.markdown_preview.is_some(),
        "the preview must be up"
    );
    let backend = ratatui::backend::TestBackend::new(100, 30);
    let mut term = ratatui::Terminal::new(backend).unwrap();
    term.draw(|frame| app.render(frame)).unwrap();

    // Find the rendered row carrying the body text and drag across it.
    let (area, row_idx, text) = {
        let md = app.editor.markdown_preview.as_ref().unwrap();
        let (i, t) = md
            .rows
            .iter()
            .enumerate()
            .map(|(i, cells)| (i as u16, cells.concat()))
            .find(|(_, r)| r.contains("rendered body"))
            .expect("the body text must be rendered");
        (md.last_area, i, t)
    };
    let start_col = text.find("rendered").unwrap() as u16;
    let end_col = start_col + "rendered".len() as u16 - 1;
    let y = area.y + row_idx;
    app.handle_mouse(mouse(
        MouseEventKind::Down(MouseButton::Left),
        area.x + start_col,
        y,
    ));
    app.handle_mouse(mouse(
        MouseEventKind::Drag(MouseButton::Left),
        area.x + end_col,
        y,
    ));
    app.handle_mouse(mouse(
        MouseEventKind::Up(MouseButton::Left),
        area.x + end_col,
        y,
    ));
    assert_eq!(
        app.editor
            .markdown_preview
            .as_ref()
            .map(|md| md.selection_text())
            .unwrap_or_default(),
        "rendered",
        "the drag must select the rendered word under the pointer"
    );
    // The selection paints: re-render and check the tinted cell.
    term.draw(|frame| app.render(frame)).unwrap();
    let sel_bg = app.theme.selection();
    assert_eq!(
        term.backend().buffer()[(area.x + start_col, y)].bg,
        sel_bg,
        "the selected cell must wear the selection background"
    );
    // Esc clears it.
    app.handle_key(key(KeyCode::Esc, KeyModifiers::NONE))
        .unwrap();
    assert!(
        !app.editor
            .markdown_preview
            .as_ref()
            .map(|md| md.has_selection())
            .unwrap_or(false),
        "Esc clears the preview selection"
    );
}

/// #931 / #1848: preview links follow as in VS Code's preview. Pointing at
/// one names its target; a click on a relative `.md` opens it rendered, a
/// Ctrl+click on `file#L3` opens the file at the line, a click on
/// `#heading` scrolls to it, and a `?query` is no part of the file's name.
#[test]
fn preview_links_follow_on_click_and_ctrl_click() {
    use crossterm::event::{MouseButton, MouseEvent, MouseEventKind};
    let tmp = tempfile::tempdir().unwrap();
    std::fs::create_dir_all(tmp.path().join("docs")).unwrap();
    std::fs::create_dir_all(tmp.path().join("src")).unwrap();
    std::fs::write(tmp.path().join("docs/SETUP.md"), "# Setup\n").unwrap();
    std::fs::write(tmp.path().join("src/main.py"), "a\nb\nc\nd\n").unwrap();
    let readme = tmp.path().join("README.md");
    let filler: String = (0..40).map(|i| format!("Line {i}.\n\n")).collect();
    let text = "See the [setup guide](docs/SETUP.md), jump to [Usage](#usage-notes), \
                or open [the code](src/main.py#L3).";
    let raw = "Or read [its source](docs/SETUP.md?plain=1).";
    std::fs::write(
        &readme,
        format!("{text}\n\n{raw}\n\n{filler}## Usage notes\n"),
    )
    .unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    let rendered = |app: &mut App| {
        draw(app, 160, 40);
        let md = app.editor.markdown_preview.as_ref();
        md.map(|md| md.rows.concat().concat()).unwrap_or_default()
    };
    // Open the README's preview and send `kinds` over the link `text`.
    let on_link = |app: &mut App, text: &str, kinds: &[MouseEventKind], modifiers| {
        app.editor.open_pinned(&readme).unwrap();
        app.focus_pane(Pane::Editor);
        if app.editor.markdown_preview.is_none() {
            app.toggle_markdown_preview();
        }
        rendered(app);
        let md = app.editor.markdown_preview.as_ref().unwrap();
        let (x, y) = (md.rows.iter().enumerate())
            .find_map(|(y, cells)| Some((cells.concat().find(text)?, y)))
            .expect("the link is on screen");
        let (column, row) = (md.last_area.x + x as u16, md.last_area.y + y as u16);
        for &kind in kinds {
            app.handle_mouse(MouseEvent {
                kind,
                column,
                row,
                modifiers,
            });
        }
    };
    let click = [
        MouseEventKind::Down(MouseButton::Left),
        MouseEventKind::Up(MouseButton::Left),
    ];
    let none = KeyModifiers::NONE;

    on_link(&mut app, "setup", &[MouseEventKind::Moved], none);
    assert_eq!(app.status, "docs/SETUP.md (click to follow)");
    on_link(&mut app, "setup", &click, none);
    assert_eq!(app.editor.path, Some(tmp.path().join("docs/SETUP.md")));
    assert!(
        rendered(&mut app).contains("Setup"),
        "a Markdown file opens rendered"
    );

    on_link(&mut app, "the code", &click, KeyModifiers::CONTROL);
    assert_eq!(app.editor.path, Some(tmp.path().join("src/main.py")));
    assert_eq!(app.editor.cursor_row, 2, "#L3 is the third line");

    on_link(&mut app, "its source", &click, none);
    assert_eq!(app.editor.path, Some(tmp.path().join("docs/SETUP.md")));

    on_link(&mut app, "Usage", &click, none);
    assert_eq!(app.status, "Went to #usage-notes");
    let shown = rendered(&mut app);
    assert!(
        shown.contains("Usage notes") && !shown.contains("See the"),
        "{shown}"
    );
}

/// #1939: the preview link under the pointer lifts to the hover background,
/// the whole link and nothing else, and drops it once the pointer moves off.
/// The view is scrolled to start partway through a wrapped paragraph, where
/// the hovered frame paints only the lines on screen, so its text must match
/// the plain frame's cell for cell.
#[test]
fn preview_link_under_the_pointer_lifts_to_the_hover_background() {
    use crossterm::event::{MouseEvent, MouseEventKind};
    let tmp = tempfile::tempdir().unwrap();
    let readme = tmp.path().join("README.md");
    let long: String = (0..80).map(|i| format!("word{i} ")).collect();
    let filler: String = (0..60).map(|i| format!("Line {i}.\n\n")).collect();
    std::fs::write(
        &readme,
        format!("{long}\n\nRead the [setup guide](docs/SETUP.md) first.\n\n{filler}"),
    )
    .unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open_pinned(&readme).unwrap();
    app.focus_pane(Pane::Editor);
    app.toggle_markdown_preview();
    draw_buffer(&mut app, 140, 50);
    app.handle_key(key(KeyCode::Down, KeyModifiers::NONE))
        .unwrap();
    draw_buffer(&mut app, 140, 50);
    let md = app
        .editor
        .markdown_preview
        .as_ref()
        .expect("the preview is open");
    let top = md.rows[0].concat();
    assert!(
        md.scroll == 1 && !top.contains("word0 ") && top.contains("word"),
        "the view starts inside the wrapped paragraph: {top}"
    );
    let (x, y) = (md.rows.iter().enumerate())
        .find_map(|(y, cells)| Some((cells.concat().find("setup guide")?, y)))
        .expect("the link is on screen");
    let (left, row) = (md.last_area.x + x as u16, md.last_area.y + y as u16);
    let link = left..left + "setup guide".len() as u16;
    let lift = crate::widgets::hover::hover_bg(app.theme);
    let move_to = |app: &mut App, column: u16| {
        app.handle_mouse(MouseEvent {
            kind: MouseEventKind::Moved,
            column,
            row,
            modifiers: KeyModifiers::NONE,
        });
        let buf = draw_buffer(app, 140, 50);
        let rows = app.editor.markdown_preview.as_ref().unwrap().rows.clone();
        (buf, rows)
    };
    let lifted = |buf: &ratatui::buffer::Buffer, cols: std::ops::Range<u16>| {
        cols.filter(|&c| buf[(c, row)].bg == lift).count()
    };

    let (plain, plain_rows) = move_to(&mut app, link.end + 2);
    assert_eq!(
        lifted(&plain, link.clone()),
        0,
        "off the link, nothing lifts"
    );

    let (buf, rows) = move_to(&mut app, left + 3);
    assert_eq!(
        lifted(&buf, link.clone()),
        link.len(),
        "every cell of the link lifts"
    );
    assert_eq!(lifted(&buf, 0..left), 0, "text before the link stays flat");
    assert_eq!(
        lifted(&buf, link.end..buf.area.width),
        0,
        "text after the link stays flat"
    );
    assert_eq!(rows, plain_rows, "the hovered frame shows the same text");

    let (buf, _) = move_to(&mut app, link.end + 2);
    assert_eq!(
        lifted(&buf, link),
        0,
        "the lift drops once the pointer leaves the link"
    );
}

#[test]
fn image_eviction_wipes_the_screen_only_on_cell_buffer_protocols() {
    // The `terminal.clear()` the main loop fires when an image-clear latch is
    // armed exists to evict CACHED IMAGE CELLS: iTerm2 OSC-1337 and sixel
    // graphics live in the normal cell buffer, so only a `2J` removes them.
    // Kitty graphics live on their own layer and are deleted by
    // `evict_inline_images_on_clear` (delete-all-by-escape) without touching a
    // single text cell - wiping the screen there blanks the whole app for a
    // full SSH round trip on every latch (the "croft blinks while I type" bug).
    use crate::iterm2_inline::InlineImageProtocol;
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.inline_protocol = InlineImageProtocol::Kitty;
    assert!(
        !app.image_eviction_needs_screen_wipe(),
        "Kitty images are deleted on their own layer; the text buffer must stay intact"
    );
    app.inline_protocol = InlineImageProtocol::ITerm2;
    assert!(app.image_eviction_needs_screen_wipe());
    app.inline_protocol = InlineImageProtocol::Sixel;
    assert!(app.image_eviction_needs_screen_wipe());
    app.inline_protocol = InlineImageProtocol::None;
    assert!(app.image_eviction_needs_screen_wipe());
}

/// #1591: with no inline-image protocol (tmux, plain SSH) an image tab
/// draws its picture in half blocks; a terminal that shows inline images
/// gets the empty canvas it paints over, as before.
#[test]
fn an_image_tab_draws_half_blocks_without_an_inline_image_protocol() {
    let tmp = tempfile::tempdir().unwrap();
    let path = tmp.path().join("shot.png");
    let mut png = Vec::new();
    image::RgbaImage::from_pixel(6, 6, image::Rgba([10, 200, 30, 255]))
        .write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png)
        .expect("encode test png");
    std::fs::write(&path, &png).unwrap();
    let half_blocks = |protocol| {
        let mut app = App::new(tmp.path().to_path_buf()).unwrap();
        app.inline_protocol = protocol;
        app.editor.open(&path).unwrap();
        let backend = ratatui::backend::TestBackend::new(100, 30);
        let mut term = ratatui::Terminal::new(backend).unwrap();
        term.draw(|f| app.render(f)).unwrap();
        let buf = term.backend().buffer().clone();
        buf.content()
            .iter()
            .filter(|c| c.symbol() == "\u{2580}" && c.fg == Color::Rgb(10, 200, 30))
            .count()
    };
    use crate::iterm2_inline::InlineImageProtocol;
    assert_eq!(
        half_blocks(InlineImageProtocol::None),
        18,
        "6×6 pixels, 6×3 cells"
    );
    assert_eq!(half_blocks(InlineImageProtocol::Kitty), 0);
    assert_eq!(half_blocks(InlineImageProtocol::ITerm2), 0);
}

/// A right-click menu opened over an image tab was painted *under* the
/// picture: on Kitty the editor preview was placed at the default z=0, which
/// the spec puts above text. Placing it below text AND below non-default
/// background cells (the same trick the sidebar illustrations use) lets any
/// opaque popup box paint fully on top, while the preview still shows through
/// the pane's default-bg canvas.
#[test]
fn editor_image_preview_sits_below_text_so_popups_paint_over_it() {
    let tmp = tempfile::tempdir().unwrap();
    let path = tmp.path().join("shot.png");
    let mut png = Vec::new();
    image::RgbaImage::from_pixel(4, 4, image::Rgba([10, 200, 30, 255]))
        .write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png)
        .expect("encode test png");
    std::fs::write(&path, &png).unwrap();

    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.inline_protocol = crate::iterm2_inline::InlineImageProtocol::Kitty;
    app.cell_pixel = Some((8, 16));
    app.editor.open(&path).unwrap();
    app.update_editor_image_overlay(
        0,
        ratatui::layout::Rect {
            x: 0,
            y: 0,
            width: 60,
            height: 30,
        },
    );

    let (osc, _) = app.editor_image_payload(0).expect("preview must bake");
    assert!(
        osc.contains(&format!(
            "z={}",
            crate::iterm2_inline::KITTY_Z_BELOW_TEXT_AND_BG
        )),
        "the preview must be placed below text so menus draw on top: {:?}",
        &osc[..osc.len().min(120)]
    );
}

/// The page the focused PDF preview shows once its work has landed.
fn current_pdf_page(app: &mut App) -> u32 {
    settle_pdf(app);
    app.editor
        .image
        .as_ref()
        .and_then(|i| i.pdf.as_ref())
        .expect("a PDF tab must carry page state")
        .current_page
}

fn sheet_cursor(app: &App) -> (usize, usize) {
    let sheet = app.editor.sheet.as_ref().expect("a spreadsheet tab");
    let data = &sheet.sheets[sheet.current_sheet];
    (data.cur_row, data.cur_col)
}

fn sheet_scroll(app: &App) -> (usize, usize) {
    let sheet = app.editor.sheet.as_ref().expect("a spreadsheet tab");
    let data = &sheet.sheets[sheet.current_sheet];
    (data.scroll_row, data.scroll_col)
}

#[test]
fn arrow_keys_page_through_an_open_pdf() {
    require_pdf_backend();
    let tmp = tempfile::tempdir().unwrap();
    let path = tmp.path().join("doc.pdf");
    write_three_page_pdf(&path);

    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open(&path).unwrap();
    app.focus_pane(Pane::Editor);
    assert_eq!(current_pdf_page(&mut app), 1);

    app.handle_key(key(KeyCode::Right, KeyModifiers::NONE))
        .unwrap();
    assert_eq!(
        current_pdf_page(&mut app),
        2,
        "Right must go to the next page"
    );

    app.handle_key(key(KeyCode::Left, KeyModifiers::NONE))
        .unwrap();
    assert_eq!(current_pdf_page(&mut app), 1, "Left must go back a page");

    app.handle_key(key(KeyCode::PageDown, KeyModifiers::NONE))
        .unwrap();
    assert_eq!(current_pdf_page(&mut app), 2, "PageDown pages forward");

    app.handle_key(key(KeyCode::End, KeyModifiers::NONE))
        .unwrap();
    assert_eq!(current_pdf_page(&mut app), 3, "End jumps to the last page");

    app.handle_key(key(KeyCode::Home, KeyModifiers::NONE))
        .unwrap();
    assert_eq!(current_pdf_page(&mut app), 1, "Home jumps back to page 1");
}

/// A page turn returns at once (#2824): the page renders on a job, the one
/// on screen stays until it lands, and a second press while the first
/// renders moves on from the page asked for.
#[test]
fn a_pdf_page_turn_does_not_wait_for_the_render() {
    require_pdf_backend();
    let tmp = tempfile::tempdir().unwrap();
    let path = tmp.path().join("doc.pdf");
    write_three_page_pdf(&path);
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open(&path).unwrap();
    app.focus_pane(Pane::Editor);
    settle_pdf(&mut app);
    let page_one = app.editor.image.as_ref().unwrap().bytes.clone();

    app.handle_key(key(KeyCode::Right, KeyModifiers::NONE))
        .unwrap();
    assert_eq!(
        app.editor.pdf_page(),
        Some(1),
        "the key press must not wait for page 2 to render"
    );
    assert!(
        app.editor.image.as_ref().unwrap().bytes == page_one,
        "page 1 stays on screen until page 2 lands"
    );
    assert_eq!(app.editor.pdf_target_page(), Some(2));
    app.handle_key(key(KeyCode::Right, KeyModifiers::NONE))
        .unwrap();
    assert_eq!(
        app.editor.pdf_target_page(),
        Some(3),
        "a second press moves on from the page asked for"
    );
    assert_eq!(current_pdf_page(&mut app), 3);
}

/// Holding a page key renders one page at a time (#2824 review): the page
/// asked for last waits for the one rendering, instead of a renderer per key
/// repeat piling up.
#[test]
fn holding_a_pdf_page_key_renders_one_page_at_a_time() {
    require_pdf_backend();
    let tmp = tempfile::tempdir().unwrap();
    let path = tmp.path().join("doc.pdf");
    write_three_page_pdf(&path);
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open(&path).unwrap();
    app.focus_pane(Pane::Editor);
    settle_pdf(&mut app);
    for _ in 0..2 {
        app.handle_key(key(KeyCode::Right, KeyModifiers::NONE))
            .unwrap();
    }
    assert_eq!(
        app.editor.pdf_jobs.rendering_page(),
        Some(2),
        "the first press's page is the only one rendering"
    );
    assert_eq!(app.editor.pdf_target_page(), Some(3));
    assert_eq!(
        current_pdf_page(&mut app),
        3,
        "the last page asked for lands"
    );
}

/// End pressed before the page count is in, then Home: Home is the newer
/// wish and wins (#2824 review).
#[test]
fn home_after_an_early_end_stays_on_the_first_pdf_page() {
    require_pdf_backend();
    let tmp = tempfile::tempdir().unwrap();
    let path = tmp.path().join("doc.pdf");
    write_three_page_pdf(&path);
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open(&path).unwrap();
    app.focus_pane(Pane::Editor);
    app.handle_key(key(KeyCode::End, KeyModifiers::NONE))
        .unwrap();
    app.handle_key(key(KeyCode::Home, KeyModifiers::NONE))
        .unwrap();
    assert_eq!(current_pdf_page(&mut app), 1, "Home came after End");
}

/// Opening a PDF from the Explorer returns at once (#2827): the tab comes
/// up saying page 1 is rendering, and the page shows when it lands.
#[test]
fn opening_a_pdf_does_not_wait_for_its_first_page() {
    require_pdf_backend();
    let tmp = tempfile::tempdir().unwrap();
    write_three_page_pdf(&tmp.path().join("doc.pdf"));
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    open_from_explorer(&mut app, "doc.pdf");
    assert!(
        app.editor.image.as_ref().is_some_and(|i| i.pdf.is_some()),
        "the PDF tab is open at once"
    );
    assert!(
        !app.editor.pdf_page_shown(),
        "the open must not wait for page 1 to render"
    );
    assert!(app.editor.pdf_jobs.rendering());
    settle_pdf(&mut app);
    assert!(app.editor.pdf_page_shown(), "page 1 shows once it lands");
    assert_eq!(app.editor.pdf_page(), Some(1));
}

/// A PDF whose first page fails in the background says so in the status
/// line, as the open that waited for it did: a `.pdf` names the failure, and
/// a file only sniffed as a PDF says why it went to the hex viewer (#2829
/// review). The open had said "Opened …" long before.
#[test]
fn a_pdf_whose_first_page_fails_says_why_once_it_lands() {
    require_pdf_backend();
    let tmp = tempfile::tempdir().unwrap();
    std::fs::write(tmp.path().join("half.pdf"), b"%PDF-1.4\nnot really a pdf\n").unwrap();
    std::fs::write(tmp.path().join("broken"), b"%PDF-1.4\nnot really a pdf\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    open_from_explorer(&mut app, "half.pdf");
    settle_pdf(&mut app);
    assert!(
        app.status.contains("PDF page 1 failed"),
        "the failure is said: {}",
        app.status
    );
    open_from_explorer(&mut app, "broken");
    settle_pdf(&mut app);
    assert!(app.editor.hex.is_some(), "status: {}", app.status);
    assert!(
        app.status.contains("in the hex viewer") && app.status.contains("could not render"),
        "why it went to hex is said: {}",
        app.status
    );
}

/// A PDF rebuilt on disk reloads without the sweep waiting for the render,
/// and the status says so once it lands (#2827).
#[test]
fn a_pdf_rebuilt_on_disk_reloads_without_waiting_and_says_so() {
    require_pdf_backend();
    let tmp = tempfile::tempdir().unwrap();
    let path = tmp.path().join("doc.pdf");
    write_three_page_pdf(&path);
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open(&path).unwrap();
    settle_pdf(&mut app);
    write_three_page_pdf(&path);
    let newer = std::time::SystemTime::now() + std::time::Duration::from_secs(2);
    std::fs::OpenOptions::new()
        .write(true)
        .open(&path)
        .unwrap()
        .set_modified(newer)
        .unwrap();
    app.status.clear();
    app.reload_open_file_after_external_change();
    assert!(
        app.editor.pdf_jobs.reloading(),
        "the rebuild renders on a job, not in the sweep"
    );
    assert!(!app.status.contains("Reloaded"), "{}", app.status);
    settle_pdf(&mut app);
    assert!(
        app.status.contains("Reloaded") && app.status.contains("doc.pdf"),
        "the reload is said once it lands: {}",
        app.status
    );
}

/// Push `path`'s modified time `secs` into the future, so the next look at
/// it sees a new version whatever the clock's resolution.
fn bump_mtime(path: &std::path::Path, secs: u64) {
    std::fs::OpenOptions::new()
        .write(true)
        .open(path)
        .unwrap()
        .set_modified(std::time::SystemTime::now() + std::time::Duration::from_secs(secs))
        .unwrap();
}

/// A PDF written again while its rebuild renders shows the newer file once
/// that rebuild lands, with nothing else changing on disk: the sweeps
/// meanwhile leave it alone, one rebuild at a time, so the landing has to
/// look again (#2830 review). The first rebuild is made to fail, so it
/// cannot happen to read the newer file itself.
#[test]
fn a_pdf_written_again_while_its_rebuild_renders_shows_the_newer_file() {
    require_pdf_backend();
    let one_page = concat!(
        "%PDF-1.4\n",
        "1 0 obj<</Type/Catalog/Pages 2 0 R>>endobj\n",
        "2 0 obj<</Type/Pages/Kids[3 0 R]/Count 1>>endobj\n",
        "3 0 obj<</Type/Page/Parent 2 0 R/MediaBox[0 0 200 200]/Contents 4 0 R>>endobj\n",
        "4 0 obj<</Length 27>>stream\n0 0 1 rg 10 10 100 100 re f\nendstream endobj\n",
        "trailer<</Root 1 0 R/Size 5>>\n%%EOF\n",
    );
    let tmp = tempfile::tempdir().unwrap();
    let path = tmp.path().join("doc.pdf");
    write_three_page_pdf(&path);
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open(&path).unwrap();
    settle_pdf(&mut app);
    write_three_page_pdf(&path);
    bump_mtime(&path, 2);
    *crate::pdf::FAIL_RASTERIZE_ONCE_FOR_TEST.lock().unwrap() = Some((path.clone(), 1));
    app.reload_open_file_after_external_change();
    assert!(app.editor.pdf_jobs.reloading());
    std::fs::write(&path, one_page).unwrap();
    bump_mtime(&path, 4);
    // The watcher's sweep meanwhile: it leaves the rebuild rendering alone.
    app.reload_open_file_after_external_change();
    settle_pdf(&mut app);
    let count = app
        .editor
        .image
        .as_ref()
        .and_then(|i| i.pdf.as_ref())
        .and_then(|pdf| pdf.page_count);
    assert_eq!(count, Some(1), "the newer file is shown: {}", app.status);
}

/// A file in another tab written while a PDF rebuild renders reloads when
/// the rebuild lands (#2830 review): the landing took in every open file's
/// new version without looking at any of them, so that write was never
/// noticed.
#[test]
fn a_file_written_while_a_pdf_rebuild_renders_still_reloads() {
    require_pdf_backend();
    let tmp = tempfile::tempdir().unwrap();
    let notes = tmp.path().join("notes.txt");
    std::fs::write(&notes, "old\n").unwrap();
    let pdf = tmp.path().join("doc.pdf");
    write_three_page_pdf(&pdf);
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open_pinned(&notes).unwrap();
    app.editor.open_pinned(&pdf).unwrap();
    settle_pdf(&mut app);
    write_three_page_pdf(&pdf);
    bump_mtime(&pdf, 2);
    app.reload_open_file_after_external_change();
    assert!(app.editor.pdf_jobs.reloading());
    std::fs::write(&notes, "new\n").unwrap();
    bump_mtime(&notes, 2);
    settle_pdf(&mut app);
    let tab = app
        .editor
        .iter_tabs()
        .find(|t| t.path.as_deref() == Some(notes.as_path()))
        .expect("the notes tab");
    assert_eq!(
        tab.lines.first().map(String::as_str),
        Some("new"),
        "{}",
        app.status
    );
}

/// End pressed right after the open, before the page count is in, goes to
/// the last page once it is: the count is read on a job (#2824).
#[test]
fn end_before_the_pdf_page_count_is_in_goes_to_the_last_page() {
    require_pdf_backend();
    let tmp = tempfile::tempdir().unwrap();
    let path = tmp.path().join("doc.pdf");
    write_three_page_pdf(&path);
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open(&path).unwrap();
    app.focus_pane(Pane::Editor);
    let count = |app: &App| {
        app.editor
            .image
            .as_ref()
            .and_then(|i| i.pdf.as_ref())
            .and_then(|pdf| pdf.page_count)
    };
    assert_eq!(count(&app), None, "the open must not wait for the count");

    app.handle_key(key(KeyCode::End, KeyModifiers::NONE))
        .unwrap();
    assert_eq!(current_pdf_page(&mut app), 3, "End lands on the last page");
    assert_eq!(count(&app), Some(3));
}

#[test]
fn a_pdf_opened_from_the_explorer_pages_with_the_arrow_keys() {
    require_pdf_backend();
    let tmp = tempfile::tempdir().unwrap();
    write_three_page_pdf(&tmp.path().join("doc.pdf"));

    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    open_from_explorer(&mut app, "doc.pdf");
    assert!(
        matches!(app.focus, Pane::Editor),
        "opening a file must hand the keyboard to the editor, or its navigation keys are dead"
    );

    app.handle_key(key(KeyCode::Right, KeyModifiers::NONE))
        .unwrap();
    assert_eq!(
        current_pdf_page(&mut app),
        2,
        "a PDF opened from the Explorer must page with Right"
    );
}

#[test]
fn the_wheel_pages_a_pdf_under_the_pointer() {
    require_pdf_backend();
    let tmp = tempfile::tempdir().unwrap();
    let path = tmp.path().join("doc.pdf");
    write_three_page_pdf(&path);

    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open(&path).unwrap();
    let (col, row) = place_editor_pane(&mut app);

    wheel(&mut app, MouseEventKind::ScrollDown, col, row);
    assert_eq!(current_pdf_page(&mut app), 2, "wheel down pages forward");
    wheel(&mut app, MouseEventKind::ScrollUp, col, row);
    assert_eq!(current_pdf_page(&mut app), 1, "wheel up pages back");
}

/// A momentum flick delivers a burst of same-direction wheel events: the
/// burst must coalesce (rate-limited per direction) into one page step
/// instead of racing through a page per event. A reversal is deliberate and
/// passes through immediately (the paging test above depends on that).
#[test]
fn a_wheel_flick_over_a_pdf_coalesces_to_one_page_step() {
    require_pdf_backend();
    let tmp = tempfile::tempdir().unwrap();
    let path = tmp.path().join("doc.pdf");
    write_three_page_pdf(&path);
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open(&path).unwrap();
    let (col, row) = place_editor_pane(&mut app);
    wheel(&mut app, MouseEventKind::ScrollDown, col, row);
    wheel(&mut app, MouseEventKind::ScrollDown, col, row);
    wheel(&mut app, MouseEventKind::ScrollDown, col, row);
    assert_eq!(
        current_pdf_page(&mut app),
        2,
        "a same-direction burst steps one page, not one per event"
    );
}

/// The wheel never wraps the document: page 1 stays put on wheel up and the
/// last page stays put on wheel down. (The arrow keys wrap deliberately;
/// no PDF viewer wraps on scroll.)
#[test]
fn the_wheel_does_not_wrap_a_pdf_at_its_ends() {
    require_pdf_backend();
    let tmp = tempfile::tempdir().unwrap();
    let path = tmp.path().join("doc.pdf");
    write_three_page_pdf(&path);
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open(&path).unwrap();
    let (col, row) = place_editor_pane(&mut app);
    wheel(&mut app, MouseEventKind::ScrollUp, col, row);
    assert_eq!(
        current_pdf_page(&mut app),
        1,
        "wheel up on page 1 must not wrap"
    );
    app.jump_pdf_page(3);
    wheel(&mut app, MouseEventKind::ScrollDown, col, row);
    assert_eq!(
        current_pdf_page(&mut app),
        3,
        "wheel down on the last page must not wrap"
    );
}

/// The wheel cooldown is per document: scrolling one PDF and immediately
/// wheeling in a second, freshly focused PDF is that document's FIRST
/// gesture, not a repeat - an app-global cooldown swallowed it.
#[test]
fn the_wheel_cooldown_does_not_leak_across_pdf_documents() {
    require_pdf_backend();
    let tmp = tempfile::tempdir().unwrap();
    let a = tmp.path().join("a.pdf");
    let b = tmp.path().join("b.pdf");
    write_three_page_pdf(&a);
    write_three_page_pdf(&b);
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open(&a).unwrap();
    let (col, row) = place_editor_pane(&mut app);
    wheel(&mut app, MouseEventKind::ScrollDown, col, row);
    assert_eq!(current_pdf_page(&mut app), 2);
    app.editor.open(&b).unwrap();
    let (col, row) = place_editor_pane(&mut app);
    // Pin the cooldown stamp to "just now, same direction, other document"
    // so the window is deterministically open regardless of how long the
    // rasteriser took: only the document identity may let this tick through.
    app.last_pdf_wheel = Some((std::time::Instant::now(), 1, Some(a.clone())));
    wheel(&mut app, MouseEventKind::ScrollDown, col, row);
    assert_eq!(
        current_pdf_page(&mut app),
        2,
        "the second document's first wheel tick must not be dropped"
    );
}

#[test]
fn a_spreadsheet_opened_from_the_explorer_scrolls_with_the_arrow_keys() {
    let tmp = tempfile::tempdir().unwrap();
    std::fs::write(tmp.path().join("data.csv"), csv_body(40)).unwrap();

    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    open_from_explorer(&mut app, "data.csv");
    assert!(app.editor.sheet.is_some(), "a .csv opens as a spreadsheet");
    assert!(matches!(app.focus, Pane::Editor));

    app.handle_key(key(KeyCode::Down, KeyModifiers::NONE))
        .unwrap();
    assert_eq!(
        sheet_cursor(&app).0,
        1,
        "Down moves the cell cursor down a row (#177)"
    );
    app.handle_key(key(KeyCode::Right, KeyModifiers::NONE))
        .unwrap();
    assert_eq!(
        sheet_cursor(&app).1,
        1,
        "Right moves the cell cursor a column"
    );
}

#[test]
fn the_wheel_scrolls_a_spreadsheet_under_the_pointer() {
    let tmp = tempfile::tempdir().unwrap();
    let path = tmp.path().join("data.csv");
    std::fs::write(&path, csv_body(40)).unwrap();

    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open(&path).unwrap();
    let (col, row) = place_editor_pane(&mut app);

    wheel(&mut app, MouseEventKind::ScrollDown, col, row);
    assert_eq!(sheet_scroll(&app).0, 3, "wheel down scrolls the sheet rows");
    wheel(&mut app, MouseEventKind::ScrollUp, col, row);
    assert_eq!(sheet_scroll(&app).0, 0, "wheel up scrolls back");
}

#[test]
fn a_tsv_preview_scrolls_the_same_way_as_a_csv() {
    let tmp = tempfile::tempdir().unwrap();
    let path = tmp.path().join("data.tsv");
    std::fs::write(&path, "a\tb\n1\t2\n3\t4\n5\t6\n7\t8\n").unwrap();

    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open(&path).unwrap();
    let (col, row) = place_editor_pane(&mut app);
    assert!(app.editor.sheet.is_some(), "a .tsv opens as a spreadsheet");

    wheel(&mut app, MouseEventKind::ScrollDown, col, row);
    assert_eq!(sheet_scroll(&app).0, 3, "wheel down scrolls a TSV too");
}

#[test]
fn the_wheel_scrolls_a_markdown_preview_under_the_pointer() {
    let tmp = tempfile::tempdir().unwrap();
    let path = tmp.path().join("notes.md");
    let body: String = (0..200).map(|i| format!("line {i}\n")).collect();
    std::fs::write(&path, body).unwrap();

    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open(&path).unwrap();
    let (col, row) = place_editor_pane(&mut app);
    app.toggle_markdown_preview();

    wheel(&mut app, MouseEventKind::ScrollDown, col, row);
    let scrolled = app
        .editor
        .markdown_preview
        .as_ref()
        .map(|p| p.scroll)
        .unwrap();
    assert!(scrolled > 0, "the wheel must scroll the rendered Markdown");
}

#[test]
fn an_image_preview_swallows_navigation_without_disturbing_the_buffer() {
    let tmp = tempfile::tempdir().unwrap();
    write_test_png(&tmp.path().join("shot.png"));

    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    open_from_explorer(&mut app, "shot.png");
    assert!(app.editor.image.is_some());
    let (col, row) = place_editor_pane(&mut app);

    for code in [
        KeyCode::Right,
        KeyCode::Left,
        KeyCode::Up,
        KeyCode::Down,
        KeyCode::PageDown,
        KeyCode::Home,
        KeyCode::End,
        KeyCode::Char('x'),
    ] {
        app.handle_key(key(code, KeyModifiers::NONE)).unwrap();
    }
    wheel(&mut app, MouseEventKind::ScrollDown, col, row);
    wheel(&mut app, MouseEventKind::ScrollUp, col, row);
    assert_eq!(
        app.editor.lines,
        vec![String::new()],
        "an image tab is read-only: no key may reach the buffer"
    );
}

/// Root cause of the frozen preview: the overlay's re-emit key held the path
/// and the rect but not the page, so a page turn looked like "same layout" and
/// the picture on screen never changed. Baking twice across a page turn must
/// produce two different payloads.
#[test]
fn turning_a_pdf_page_rebakes_the_inline_image_overlay() {
    require_pdf_backend();
    let tmp = tempfile::tempdir().unwrap();
    let path = tmp.path().join("doc.pdf");
    write_three_page_pdf(&path);

    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.inline_protocol = crate::iterm2_inline::InlineImageProtocol::Kitty;
    app.cell_pixel = Some((8, 16));
    app.editor.open(&path).unwrap();
    settle_pdf(&mut app);
    let area = Rect {
        x: 0,
        y: 0,
        width: 60,
        height: 30,
    };
    app.update_editor_image_overlay(0, area);
    let page1 = app
        .editor_image_payload(0)
        .map(|(osc, _)| osc.to_string())
        .expect("page 1 must bake");

    app.editor.change_pdf_page(1);
    settle_pdf(&mut app);
    app.update_editor_image_overlay(0, area);
    let page2 = app
        .editor_image_payload(0)
        .map(|(osc, _)| osc.to_string())
        .expect("page 2 must bake");

    assert_ne!(
        page1, page2,
        "the overlay must re-bake on a page turn, or the reader stares at a frozen page"
    );
}

/// The gesture the bug report actually used: one click on the PDF in the
/// Explorer, then the arrow keys. A single click opened the file but left the
/// keyboard on the tree, so every page-turn key walked the file list instead.
#[test]
fn a_pdf_opened_with_one_click_in_the_explorer_pages_with_the_arrow_keys() {
    require_pdf_backend();
    let tmp = tempfile::tempdir().unwrap();
    write_three_page_pdf(&tmp.path().join("doc.pdf"));

    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    click_open_in_explorer(&mut app, "doc.pdf");
    assert_eq!(current_pdf_page(&mut app), 1, "the click must open the PDF");
    assert!(
        matches!(app.focus, Pane::Editor),
        "one click on a file must hand the keyboard to the editor, as VS Code does"
    );

    app.handle_key(key(KeyCode::Right, KeyModifiers::NONE))
        .unwrap();
    assert_eq!(current_pdf_page(&mut app), 2, "Right must turn the page");
    app.handle_key(key(KeyCode::Char(' '), KeyModifiers::NONE))
        .unwrap();
    assert_eq!(current_pdf_page(&mut app), 3, "Space must turn the page");
}

/// A click on a spreadsheet must leave the arrow keys scrolling the grid, not
/// the file list - the same defect as the PDF, one tab type over.
#[test]
fn a_spreadsheet_opened_with_one_click_scrolls_with_the_arrow_keys() {
    let tmp = tempfile::tempdir().unwrap();
    std::fs::write(tmp.path().join("data.csv"), csv_body(40)).unwrap();

    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    click_open_in_explorer(&mut app, "data.csv");
    app.handle_key(key(KeyCode::Down, KeyModifiers::NONE))
        .unwrap();
    assert_eq!(
        sheet_cursor(&app).0,
        1,
        "Down must act on the grid (cell cursor), not the file list"
    );
}

/// One click on a Markdown file, Cmd+Shift+V for its rendered preview, then
/// one click on `next`: the preview tab now shows `next`, and its keys must
/// reach it. The rendered preview used to survive the swap hidden under the
/// new view, so it took every key and Cmd+W did nothing (#2069).
fn markdown_preview_then_one_click(
    next: &str,
    write_next: impl FnOnce(&std::path::Path),
) -> (tempfile::TempDir, App) {
    let tmp = tempfile::tempdir().unwrap();
    std::fs::write(tmp.path().join("notes.md"), "# Notes\n\nSome text.\n").unwrap();
    write_next(&tmp.path().join(next));

    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    click_open_in_explorer(&mut app, "notes.md");
    app.toggle_markdown_preview();
    assert!(
        app.editor.markdown_preview.is_some(),
        "setup: the rendered Markdown must be showing"
    );
    click_open_in_explorer(&mut app, next);
    assert_eq!(
        app.editor.tab_count(),
        1,
        "setup: {next} must reuse the preview tab"
    );
    assert!(
        app.editor.markdown_preview.is_none(),
        "opening {next} in the preview tab must drop the rendered Markdown it showed"
    );
    (tmp, app)
}

#[test]
fn a_spreadsheet_opened_over_a_markdown_preview_takes_the_keys() {
    let (_tmp, mut app) =
        markdown_preview_then_one_click("data.csv", |p| std::fs::write(p, csv_body(40)).unwrap());

    app.handle_key(key(KeyCode::Down, KeyModifiers::NONE))
        .unwrap();
    assert_eq!(
        sheet_cursor(&app).0,
        1,
        "Down must move the grid's cell cursor"
    );
    app.handle_key(key(KeyCode::Char('w'), KeyModifiers::SUPER))
        .unwrap();
    assert!(app.editor.sheet.is_none(), "Cmd+W must close the sheet tab");
}

#[test]
fn a_pdf_opened_over_a_markdown_preview_pages_with_the_keys() {
    require_pdf_backend();
    let (_tmp, mut app) = markdown_preview_then_one_click("doc.pdf", write_three_page_pdf);

    app.handle_key(key(KeyCode::PageDown, KeyModifiers::NONE))
        .unwrap();
    assert_eq!(current_pdf_page(&mut app), 2, "PageDown must turn the page");
    app.handle_key(key(KeyCode::Char('w'), KeyModifiers::SUPER))
        .unwrap();
    assert!(app.editor.image.is_none(), "Cmd+W must close the PDF tab");
}

#[test]
fn an_image_opened_over_a_markdown_preview_closes_with_cmd_w() {
    let (_tmp, mut app) = markdown_preview_then_one_click("pic.png", write_test_png);

    assert!(app.editor.image.is_some(), "the image must be showing");
    app.handle_key(key(KeyCode::Char('w'), KeyModifiers::SUPER))
        .unwrap();
    assert!(app.editor.image.is_none(), "Cmd+W must close the image tab");
}

/// Cmd+W on a tab showing rendered Markdown closes it. The rendered view
/// takes every key and returned before the close-tab check, so the tab could
/// not be closed from the keyboard (#2069).
#[test]
fn cmd_w_closes_a_rendered_markdown_tab() {
    let tmp = tempfile::tempdir().unwrap();
    let md = tmp.path().join("notes.md");
    std::fs::write(&md, "# Notes\n\nSome text.\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open(&md).unwrap();
    app.focus = Pane::Editor;
    app.toggle_markdown_preview();
    assert!(
        app.editor.markdown_preview.is_some(),
        "setup: the rendered Markdown must be showing"
    );

    app.handle_key(key(KeyCode::Char('w'), KeyModifiers::SUPER))
        .unwrap();

    assert_ne!(
        app.editor.path.as_deref(),
        Some(md.as_path()),
        "Cmd+W on rendered Markdown must close the tab"
    );
    assert!(app.editor.markdown_preview.is_none());
}

/// A cell typed into a spreadsheet opened with one click pins its tab, as an
/// edit in a text tab does: the next one-click open goes beside it, and the
/// unsaved cell stays (#2073).
#[test]
fn a_cell_edited_in_a_preview_sheet_pins_the_tab() {
    let tmp = tempfile::tempdir().unwrap();
    std::fs::write(tmp.path().join("data.csv"), csv_body(5)).unwrap();
    std::fs::write(tmp.path().join("notes.txt"), "notes\n").unwrap();

    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    click_open_in_explorer(&mut app, "data.csv");
    assert_eq!(app.editor.preview_index(), Some(0), "setup: a preview tab");
    app.handle_key(key(KeyCode::Char('9'), KeyModifiers::NONE))
        .unwrap();
    app.handle_key(key(KeyCode::Enter, KeyModifiers::NONE))
        .unwrap();
    assert!(app.editor.dirty, "setup: Enter commits the cell");
    assert!(
        !app.editor.editors[0].preview,
        "a committed cell must pin the tab"
    );

    click_open_in_explorer(&mut app, "notes.txt");
    assert_eq!(
        app.editor.tab_count(),
        2,
        "the next one-click open must not replace the edited sheet"
    );
    assert!(app.editor.editors[0].dirty, "the unsaved cell must stay");
}

/// A cell still being typed into, not yet committed with Enter, is unsaved
/// work too: a one-click open of another file pins the sheet's tab instead
/// of replacing it, and the half-typed value stays (#2073 review).
#[test]
fn a_cell_being_typed_in_a_preview_sheet_survives_a_one_click_open() {
    let tmp = tempfile::tempdir().unwrap();
    std::fs::write(tmp.path().join("data.csv"), csv_body(5)).unwrap();
    std::fs::write(tmp.path().join("notes.txt"), "notes\n").unwrap();

    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    click_open_in_explorer(&mut app, "data.csv");
    assert_eq!(app.editor.preview_index(), Some(0), "setup: a preview tab");
    app.handle_key(key(KeyCode::Char('9'), KeyModifiers::NONE))
        .unwrap();
    assert!(
        app.editor.sheet_pending_cell().is_some(),
        "setup: the cell is being typed into"
    );

    click_open_in_explorer(&mut app, "notes.txt");
    assert_eq!(
        app.editor.tab_count(),
        2,
        "the one-click open must not replace the sheet being typed into"
    );
    let sheet = &app.editor.editors[0];
    assert!(!sheet.preview, "the sheet's tab is pinned");
    assert!(
        sheet.sheet_pending_cell().is_some() || sheet.dirty,
        "the typed value must stay"
    );
}

/// Output scrolling under an on-screen inline image moves only the
/// placement row; re-running the full decode + Lanczos resize + PNG encode
/// per scrolled row froze the render thread for the whole pane height on
/// any real photo.
#[test]
fn a_scrolled_inline_image_reuses_its_baked_payload() {
    let (_tmp, mut app) =
        app_with_baked_terminal_image(crate::iterm2_inline::InlineImageProtocol::Kitty);
    let y0 = app.overlays.terminal_image.layout().unwrap().cell_y;
    let bakes = crate::iterm2_inline::FIT_IMAGE_BAKES.with(|c| c.get());
    app.terminals[0].feed_bytes_for_test(b"\r\n\r\n");
    app.update_terminal_image_overlay();
    let l = app.overlays.terminal_image.layout().unwrap();
    assert_eq!(l.cell_y, y0 - 2, "the placement follows the anchor");
    assert_eq!(
        crate::iterm2_inline::FIT_IMAGE_BAKES.with(|c| c.get()),
        bakes,
        "a pure row move must not re-decode the image"
    );
}

/// A 300-line rendered log (an escape on line 1 makes it one), open in a
/// drawn 100x30 app with the editor focused (#1189).
fn open_rendered_log(tmp: &tempfile::TempDir) -> App {
    let p = tmp.path().join("build.log");
    let mut body = String::from("\u{1b}[32mINFO\u{1b}[0m line 1\n");
    for i in 2..=300 {
        body.push_str(&format!("line {i}\n"));
    }
    std::fs::write(&p, &body).unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.focus_pane(Pane::Editor);
    app.editor.open(&p).unwrap();
    assert!(app.editor.log.is_some(), "the fixture is a rendered log");
    draw(&mut app, 100, 30);
    app
}

/// #1189: the arrows, PageUp/PageDown, Home/End and Ctrl+Home/End move a
/// rendered log, which they used to leave on line 1.
#[test]
fn the_keyboard_scrolls_a_rendered_log() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = open_rendered_log(&tmp);
    let press = |app: &mut App, code, mods| app.handle_key(key(code, mods)).unwrap();
    press(&mut app, KeyCode::PageDown, KeyModifiers::NONE);
    let page = app.editor.scroll;
    assert!(page > 10, "PageDown moves a screen: {page}");
    press(&mut app, KeyCode::Down, KeyModifiers::NONE);
    assert_eq!(app.editor.scroll, page + 1);
    press(&mut app, KeyCode::Up, KeyModifiers::NONE);
    press(&mut app, KeyCode::PageUp, KeyModifiers::NONE);
    assert_eq!(app.editor.scroll, 0);
    press(&mut app, KeyCode::End, KeyModifiers::CONTROL);
    let tail = app.editor.scroll;
    assert!(tail > 250, "Ctrl+End reaches the tail: {tail}");
    press(&mut app, KeyCode::Home, KeyModifiers::CONTROL);
    assert_eq!(app.editor.scroll, 0);
    press(&mut app, KeyCode::End, KeyModifiers::NONE);
    assert_eq!(app.editor.scroll, tail, "End is the tail too");
    press(&mut app, KeyCode::Down, KeyModifiers::NONE);
    assert_eq!(app.editor.scroll, tail, "and the tail is where it stops");
}

/// #1189: a key after a wheel scroll carries on from there instead of
/// throwing the view back to line 1.
#[test]
fn a_key_keeps_a_wheel_scrolled_log_where_it_was() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = open_rendered_log(&tmp);
    app.editor.scroll_down(25);
    assert_eq!(app.editor.scroll, 25);
    app.handle_key(key(KeyCode::Down, KeyModifiers::NONE))
        .unwrap();
    assert_eq!(app.editor.scroll, 26);
    app.handle_key(key(KeyCode::Char('j'), KeyModifiers::NONE))
        .unwrap();
    assert_eq!(
        app.editor.scroll, 26,
        "an unbound key leaves the view alone"
    );
}

/// Negative (#1189): typing into a rendered log changes nothing and never
/// marks it modified, while a plain `.log` with no colour is still an
/// ordinary editable file.
#[test]
fn typing_into_a_rendered_log_changes_nothing() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = open_rendered_log(&tmp);
    for code in [
        KeyCode::Char('z'),
        KeyCode::Enter,
        KeyCode::Backspace,
        KeyCode::Tab,
    ] {
        app.handle_key(key(code, KeyModifiers::NONE)).unwrap();
    }
    app.clipboard_reader = || Some(String::from("pasted"));
    app.handle_key(key(KeyCode::Char('v'), KeyModifiers::SUPER))
        .unwrap();
    assert!(!app.editor.dirty, "the read-only log is never modified");
    assert_eq!(app.editor.lines, vec![String::new()]);

    let plain = tmp.path().join("plain.log");
    std::fs::write(&plain, "line 1\nline 2\n").unwrap();
    app.editor.open(&plain).unwrap();
    assert!(app.editor.log.is_none());
    app.handle_key(key(KeyCode::Char('z'), KeyModifiers::NONE))
        .unwrap();
    assert!(app.editor.dirty, "a plain log is edited as before");
    assert_eq!(app.editor.lines[0], "zline 1");
}

/// #257: Enter and Shift+Enter step through a log's matches. The log has no
/// caret to carry the position, so the walk is anchored on the active match
/// alone; without that anchor every Enter would re-find the same line.
#[test]
fn enter_steps_through_matches_in_a_rendered_log() {
    let tmp = tempfile::tempdir().unwrap();
    let p = tmp.path().join("run.log");
    std::fs::write(
        &p,
        "\u{1b}[31mFAIL\u{1b}[0m one\nok\n\u{1b}[31mFAIL\u{1b}[0m two\nok\n",
    )
    .unwrap();

    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.focus_pane(Pane::Editor);
    app.editor.open(&p).unwrap();
    assert!(app.editor.log.is_some());

    app.handle_key(key(KeyCode::Char('f'), KeyModifiers::SUPER))
        .unwrap();
    for ch in "FAIL".chars() {
        app.handle_key(key(KeyCode::Char(ch), KeyModifiers::NONE))
            .unwrap();
    }
    assert_eq!(
        app.editor_find.as_ref().map(|s| s.match_count),
        Some(2),
        "both FAIL lines are counted through the stripped text"
    );
    assert_eq!(
        app.editor.active_search_match.map(|(r, _, _)| r),
        Some(0),
        "typing lands on the first match"
    );

    app.handle_key(key(KeyCode::Enter, KeyModifiers::NONE))
        .unwrap();
    assert_eq!(
        app.editor.active_search_match.map(|(r, _, _)| r),
        Some(2),
        "Enter steps to the second match rather than re-finding the first"
    );
    app.handle_key(key(KeyCode::Enter, KeyModifiers::NONE))
        .unwrap();
    assert_eq!(
        app.editor.active_search_match.map(|(r, _, _)| r),
        Some(0),
        "past the last match, Enter wraps to the top"
    );
    app.handle_key(key(KeyCode::Enter, KeyModifiers::SHIFT))
        .unwrap();
    assert_eq!(
        app.editor.active_search_match.map(|(r, _, _)| r),
        Some(2),
        "Shift+Enter walks back, wrapping to the last match"
    );
}

/// #257: dragging over a rendered ANSI log selects it, and Cmd+C copies what
/// the reader SEES rather than the escape bytes behind it.
///
/// Driven through the real gestures and a real render, so the body rect the
/// mouse path reads is the one a frame actually painted: a test that set
/// `last_body` by hand would pass with the renderer never having agreed.
#[test]
fn dragging_over_a_rendered_log_selects_and_copies_the_visible_text() {
    let tmp = tempfile::tempdir().unwrap();
    let p = tmp.path().join("run.log");
    std::fs::write(
        &p,
        "\u{1b}[32mINFO\u{1b}[0m starting up\n\u{1b}[31mERROR\u{1b}[0m disk full\nbye\n",
    )
    .unwrap();

    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.focus_pane(Pane::Editor);
    app.editor.open(&p).unwrap();
    assert!(app.editor.log.is_some(), "the fixture opens rendered");

    let backend = ratatui::backend::TestBackend::new(100, 30);
    let mut term = ratatui::Terminal::new(backend).unwrap();
    term.draw(|frame| app.render(frame)).unwrap();

    let body = app.editor.log.as_ref().unwrap().last_body;
    assert!(
        body.width > 0 && body.height > 0,
        "the render must have published a body rect for the mouse to hit"
    );

    // Press on the first body row, drag to the second, release.
    use crossterm::event::{MouseButton, MouseEventKind};
    app.handle_mouse(mouse(
        MouseEventKind::Down(MouseButton::Left),
        body.x,
        body.y,
    ));
    app.handle_mouse(mouse(
        MouseEventKind::Drag(MouseButton::Left),
        body.x + 10,
        body.y + 1,
    ));
    app.handle_mouse(mouse(
        MouseEventKind::Up(MouseButton::Left),
        body.x + 10,
        body.y + 1,
    ));

    let log = app.editor.log.as_ref().unwrap();
    assert!(log.has_selection(), "the drag must leave a selection");
    assert!(!log.dragging, "and the release must end the drag");
    let (text, clamped) = log.selection_text();
    assert!(!clamped);
    assert_eq!(
        text, "INFO starting up\nERROR disk",
        "the copy is the stripped text, not the escapes behind it"
    );

    // What is PAINTED must match what is copied, row for row. Nothing
    // asserted this before: deleting the entire selection-painting block from
    // the renderer left the suite green, so the visible half of the feature
    // had no coverage at all.
    let mut buf = ratatui::buffer::Buffer::empty(ratatui::layout::Rect {
        x: 0,
        y: 0,
        width: 100,
        height: 30,
    });
    term.draw(|frame| app.render(frame)).unwrap();
    {
        use ratatui::widgets::Widget;
        let area = app.editor.last_area;
        (&mut app.editor).render(area, &mut buf);
    }
    // Frame truth: the rect the render that filled THIS buffer published.
    let body = app.editor.log.as_ref().unwrap().last_body;
    let selected_bg = crate::theme::Theme::BLACK.selection();
    let copied_per_row: Vec<usize> = text.split('\n').map(|l| l.chars().count()).collect();
    for (r, expected) in copied_per_row.iter().enumerate() {
        let y = body.y + r as u16;
        let painted = (body.x..body.x + body.width)
            .filter(|x| buf[(*x, y)].style().bg == Some(selected_bg))
            .count();
        assert_eq!(
            painted, *expected,
            "row {r}: {painted} cells painted as selected, {expected} characters copied"
        );
    }

    // Cmd+C puts exactly that on the clipboard.
    app.handle_key(key(KeyCode::Char('c'), KeyModifiers::SUPER))
        .unwrap();
    assert!(
        app.status.starts_with("Copied"),
        "the copy must report itself, got {:?}",
        app.status
    );
}

/// #257: dragging past the end of a SHORT line must paint what it copies.
///
/// The renderer painted to the endpoint it was handed while the copy read
/// `min(len)`, and `log_cell_at` clamped the line but not the column, so a
/// drag off the right of a short line painted to the pointer and copied to
/// the line's end. Clamping at the source means both readers see one value
/// instead of each clamping its own way.
#[test]
fn dragging_past_a_short_lines_end_paints_what_it_copies() {
    let tmp = tempfile::tempdir().unwrap();
    let p = tmp.path().join("short.log");
    // A coloured line so the view renders, and a very short one to drag off.
    std::fs::write(&p, "\u{1b}[31mabc\u{1b}[0m\nlonger second line here\n").unwrap();

    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.focus_pane(Pane::Editor);
    app.editor.open(&p).unwrap();
    assert!(app.editor.log.is_some());

    let backend = ratatui::backend::TestBackend::new(100, 30);
    let mut term = ratatui::Terminal::new(backend).unwrap();
    term.draw(|frame| app.render(frame)).unwrap();
    let body = app.editor.log.as_ref().unwrap().last_body;

    use crossterm::event::{MouseButton, MouseEventKind};
    app.handle_mouse(mouse(
        MouseEventKind::Down(MouseButton::Left),
        body.x,
        body.y,
    ));
    // Drag far past the end of a three-character line.
    app.handle_mouse(mouse(
        MouseEventKind::Drag(MouseButton::Left),
        body.x + 60,
        body.y,
    ));
    app.handle_mouse(mouse(
        MouseEventKind::Up(MouseButton::Left),
        body.x + 60,
        body.y,
    ));

    let (text, _) = app.editor.log.as_ref().unwrap().selection_text();
    assert_eq!(text, "abc", "the copy stops at the end of the line");

    let mut buf = ratatui::buffer::Buffer::empty(ratatui::layout::Rect {
        x: 0,
        y: 0,
        width: 100,
        height: 30,
    });
    term.draw(|frame| app.render(frame)).unwrap();
    {
        use ratatui::widgets::Widget;
        let area = app.editor.last_area;
        (&mut app.editor).render(area, &mut buf);
    }
    // Frame truth: the rect to read is the one the render that filled THIS
    // buffer published, not one captured from an earlier frame. Reading the
    // stale rect pointed at the header row and reported nothing painted.
    let body = app.editor.log.as_ref().unwrap().last_body;
    let selected_bg = crate::theme::Theme::BLACK.selection();
    let painted = (body.x..body.x + body.width)
        .filter(|x| buf[(*x, body.y)].style().bg == Some(selected_bg))
        .count();
    assert_eq!(
        painted,
        text.chars().count(),
        "the paint must stop where the copy does, not follow the pointer"
    );
}

/// #404: a double-width character occupies two cells, so every span after
/// it must be painted, and every click after it hit-tested, by display
/// width rather than by character count.
///
/// The painter advanced `x` by `chars().count()`, so after a CJK pair the
/// next span landed two cells to the left of where the terminal had put
/// the pair, overpainting its second half, and `log_cell_at` matched the
/// drift by design. Fixed together so the two never disagree.
#[test]
fn double_width_characters_keep_log_columns_aligned() {
    use crossterm::event::{MouseButton, MouseEventKind};
    use ratatui::widgets::Widget;

    let tmp = tempfile::tempdir().unwrap();
    let p = tmp.path().join("wide.log");
    // "\u{4e2d}\u{6587}" is two characters and four cells; then a space and
    // a coloured X, which must land on cell 5 (character column 3).
    std::fs::write(
        &p,
        "\u{1b}[31m\u{4e2d}\u{6587}\u{1b}[0m \u{1b}[32mX\u{1b}[0m\n",
    )
    .unwrap();

    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.focus_pane(Pane::Editor);
    app.editor.open(&p).unwrap();
    assert!(app.editor.log.is_some());

    let backend = ratatui::backend::TestBackend::new(100, 30);
    let mut term = ratatui::Terminal::new(backend).unwrap();
    term.draw(|frame| app.render(frame)).unwrap();
    let body = app.editor.log.as_ref().unwrap().last_body;

    // Click the X and release on it: a one-character selection.
    app.handle_mouse(mouse(
        MouseEventKind::Down(MouseButton::Left),
        body.x + 5,
        body.y,
    ));
    app.handle_mouse(mouse(
        MouseEventKind::Drag(MouseButton::Left),
        body.x + 6,
        body.y,
    ));
    app.handle_mouse(mouse(
        MouseEventKind::Up(MouseButton::Left),
        body.x + 6,
        body.y,
    ));
    let (text, _) = app.editor.log.as_ref().unwrap().selection_text();
    assert_eq!(text, "X", "cell 5 is the X, two cells past the wide pair");

    let mut buf = ratatui::buffer::Buffer::empty(ratatui::layout::Rect {
        x: 0,
        y: 0,
        width: 100,
        height: 30,
    });
    term.draw(|frame| app.render(frame)).unwrap();
    {
        let area = app.editor.last_area;
        (&mut app.editor).render(area, &mut buf);
    }
    let body = app.editor.log.as_ref().unwrap().last_body;
    let row: Vec<&str> = (body.x..body.x + 7)
        .map(|x| buf[(x, body.y)].symbol())
        .collect();
    assert_eq!(
        buf[(body.x + 2, body.y)].symbol(),
        "\u{6587}",
        "the second wide character keeps its cells: {row:?}"
    );
    assert_eq!(
        buf[(body.x + 5, body.y)].symbol(),
        "X",
        "the span after the pair starts where the terminal put it: {row:?}"
    );
    let selected_bg = crate::theme::Theme::BLACK.selection();
    let painted: Vec<u16> = (body.x..body.x + body.width)
        .filter(|x| buf[(*x, body.y)].style().bg == Some(selected_bg))
        .collect();
    assert_eq!(
        painted,
        vec![body.x + 5],
        "the selection band sits on the X's cell, not on character column 3"
    );
}

/// #257: a frame that paints no log body must publish no body rect.
///
/// `render_log` returned early for a zero-sized area WITHOUT clearing
/// `last_body`, so after a resize the mouse path could accept a click inside
/// a rectangle this frame had not painted. Frame truth cuts both ways: the
/// rect is a claim about what was drawn, and drawing nothing is a claim too.
#[test]
fn a_log_that_paints_nothing_publishes_no_body_rect() {
    use ratatui::layout::Rect;
    use ratatui::widgets::Widget;

    let tmp = tempfile::tempdir().unwrap();
    let p = tmp.path().join("run.log");
    std::fs::write(&p, "\u{1b}[31mERROR\u{1b}[0m boom\nsecond\n").unwrap();
    let mut e = crate::widgets::editor::Editor::new();
    e.open(&p).unwrap();

    // A real frame publishes a real rect.
    let mut buf = ratatui::buffer::Buffer::empty(Rect {
        x: 0,
        y: 0,
        width: 40,
        height: 8,
    });
    (&mut e).render(
        Rect {
            x: 0,
            y: 0,
            width: 40,
            height: 8,
        },
        &mut buf,
    );
    assert!(
        e.log.as_ref().unwrap().last_body.height > 0,
        "a painted frame publishes its body"
    );

    // A frame with no room paints nothing, so it must claim nothing.
    let mut narrow = ratatui::buffer::Buffer::empty(Rect {
        x: 0,
        y: 0,
        width: 40,
        height: 8,
    });
    (&mut e).render(
        Rect {
            x: 0,
            y: 0,
            width: 0,
            height: 0,
        },
        &mut narrow,
    );
    assert_eq!(
        e.log.as_ref().unwrap().last_body,
        Rect::default(),
        "a frame that painted nothing must not leave a stale rect for the \
         mouse path to hit-test against"
    );
}

/// #394: a log past the head budget opens on a partial index, the header
/// says so, and the main loop's `poll_log_index` grows it to the total and
/// re-runs an open find's count once the pass is done.
#[test]
fn a_large_log_opens_before_its_index_is_complete_and_the_loop_finishes_it() {
    let tmp = tempfile::tempdir().unwrap();
    use ratatui::widgets::Widget as _;
    let p = tmp.path().join("huge.log");
    let mut body = Vec::new();
    body.extend_from_slice(b"\x1b[32mINFO\x1b[0m head\n");
    let mut lines = 1usize;
    while (body.len() as u64) < crate::log_view::HEAD_INDEX_BYTES + 1024 * 1024 {
        body.extend_from_slice(format!("line{lines} some padding text\n").as_bytes());
        lines += 1;
    }
    body.extend_from_slice(b"\x1b[31mERROR\x1b[0m disk full\n");
    let total = lines + 1;
    std::fs::write(&p, &body).unwrap();

    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.focus_pane(Pane::Editor);
    app.editor.open(&p).unwrap();
    let log = app.editor.log.as_ref().expect("opens as a rendered log");
    assert!(log.indexing(), "the tail is still being indexed after open");
    assert!(log.len() < total, "the count is a lower bound for now");

    let area = Rect::new(0, 0, 80, 12);
    let mut buf = ratatui::buffer::Buffer::empty(area);
    (&mut *app.editor).render(area, &mut buf);
    // The header sits on the row above the body the frame published; the
    // editor's own border occupies row 0.
    let body = app.editor.log.as_ref().unwrap().last_body;
    let header: String = (body.x..body.x + body.width)
        .map(|x| buf[(x, body.y - 1)].symbol().to_string())
        .collect();
    assert!(
        header.contains("so far, indexing"),
        "the header must not present a moving count as a total: {header:?}"
    );

    // A find typed while the pass runs: the ERROR line is past the index.
    app.handle_key(key(KeyCode::Char('f'), KeyModifiers::SUPER))
        .unwrap();
    for ch in "disk".chars() {
        app.handle_key(key(KeyCode::Char(ch), KeyModifiers::NONE))
            .unwrap();
    }
    let state = app.editor_find.as_ref().unwrap();
    assert!(
        state.count_truncated(),
        "a count taken against a partial index is flagged partial"
    );

    crate::test_budget::await_spawned(
        std::time::Duration::from_secs(10),
        "the background log index",
        || {
            app.poll_log_index();
            !app.editor.log.as_ref().unwrap().indexing()
        },
    );
    assert_eq!(app.editor.log.as_ref().unwrap().len(), total);
    (&mut *app.editor).render(area, &mut buf);
    // The header sits on the row above the body the frame published; the
    // editor's own border occupies row 0.
    let body = app.editor.log.as_ref().unwrap().last_body;
    let header: String = (body.x..body.x + body.width)
        .map(|x| buf[(x, body.y - 1)].symbol().to_string())
        .collect();
    assert!(
        header.contains(&format!("{total} lines ")) && !header.contains("indexing"),
        "the finished header carries the total: {header:?}"
    );
    assert!(
        !app.poll_log_index(),
        "a finished index asks for no more repaints"
    );
}

/// #1538: a large log viewed at its end and reloaded after an append
/// reopens on a partial index; the main loop's `poll_log_index` settles the
/// view on the new end as the index reaches it, instead of leaving it
/// clamped to the head the open indexed.
#[test]
fn the_loop_brings_a_reloaded_large_log_to_its_new_end() {
    use ratatui::widgets::Widget as _;
    let tmp = tempfile::tempdir().unwrap();
    let p = tmp.path().join("huge.log");
    let mut body = Vec::new();
    body.extend_from_slice(b"\x1b[32mINFO\x1b[0m head\n");
    let mut lines = 1usize;
    while (body.len() as u64) < crate::log_view::HEAD_INDEX_BYTES + 1024 * 1024 {
        body.extend_from_slice(format!("line{lines} some padding text\n").as_bytes());
        lines += 1;
    }
    std::fs::write(&p, &body).unwrap();

    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.focus_pane(Pane::Editor);
    app.editor.open(&p).unwrap();
    let area = Rect::new(0, 0, 80, 12);
    let mut buf = ratatui::buffer::Buffer::empty(area);
    (&mut *app.editor).render(area, &mut buf);
    app.editor.log.as_mut().unwrap().finish_index();
    app.editor.scroll_down(usize::MAX / 2);
    let rows = (app.editor.last_inner.height as usize).saturating_sub(1);
    assert_eq!(
        app.editor.scroll + rows,
        lines,
        "the view is on the last line"
    );

    {
        use std::io::Write as _;
        let mut f = std::fs::OpenOptions::new().append(true).open(&p).unwrap();
        writeln!(f, "\x1b[31mERROR\x1b[0m disk full").unwrap();
    }
    app.editor.reload_or_flag_conflict();
    assert!(app.editor.log.as_ref().unwrap().indexing());
    crate::test_budget::await_spawned(
        std::time::Duration::from_secs(10),
        "the background log index",
        || {
            app.poll_log_index();
            !app.editor.log.as_ref().unwrap().indexing()
        },
    );
    assert_eq!(
        app.editor.scroll + rows,
        lines + 1,
        "the view follows the log to its new last line"
    );
}
/// #370: a `.http` file runs the request under the caret. The variables
/// substitute from `.http.env.json` on the WIRE only: the status line,
/// history entry, and response tab all carry the raw `{{name}}` form, so
/// the token never leaves the env file. A JSON response opens pretty-printed
/// as `.jsonc`; a PNG response opens through the image path.
#[test]
fn an_http_file_runs_requests_and_keeps_secrets_out_of_history_and_the_tab() {
    use std::io::{Read as _, Write as _};
    let tmp = tempfile::tempdir().unwrap();
    // The cache-dir override is a process-wide global shared with the relay
    // family: hold their lock and restore via RAII, exactly as
    // `with_relay_home` does, so a panic cannot leak the redirect into
    // later tests (#428 review).
    let _cache_lock = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
    let _restore = override_cache_dir(tmp.path().join("cache"));

    // A 1x1 PNG via the image crate, so the decode on open genuinely works.
    let png_bytes = {
        let img: image::RgbaImage = image::ImageBuffer::from_pixel(1, 1, image::Rgba([0, 0, 0, 0]));
        let mut buf: Vec<u8> = Vec::new();
        image::DynamicImage::ImageRgba8(img)
            .write_to(&mut std::io::Cursor::new(&mut buf), image::ImageFormat::Png)
            .unwrap();
        buf
    };

    let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
    let port = listener.local_addr().unwrap().port();
    let seen = std::sync::Arc::new(std::sync::Mutex::new(Vec::<String>::new()));
    let seen2 = seen.clone();
    let png_served = png_bytes.clone();
    std::thread::spawn(move || {
        for stream in listener.incoming() {
            let Ok(mut s) = stream else { break };
            let mut buf = vec![0u8; 8192];
            let n = s.read(&mut buf).unwrap_or(0);
            let req = String::from_utf8_lossy(&buf[..n]).to_string();
            let (body, ct): (Vec<u8>, &str) = if req.starts_with("GET /users") {
                (
                    b"{\"users\":[{\"id\":1,\"name\":\"ada\"}]}".to_vec(),
                    "application/json",
                )
            } else {
                (png_served.clone(), "image/png")
            };
            seen2.lock().unwrap().push(req);
            let head = format!(
                "HTTP/1.1 200 OK\r\ncontent-type: {ct}\r\ncontent-length: {}\r\nconnection: close\r\n\r\n",
                body.len()
            );
            let _ = s.write_all(head.as_bytes());
            let _ = s.write_all(&body);
            let _ = s.shutdown(std::net::Shutdown::Both);
        }
    });

    let http = tmp.path().join("api.http");
    std::fs::write(
        &http,
        "GET {{host}}/users\nAuthorization: Bearer {{token}}\n\n###\nGET {{host}}/logo.png\n",
    )
    .unwrap();
    std::fs::write(
        tmp.path().join(crate::http_file::ENV_FILE),
        format!("{{\"host\": \"http://127.0.0.1:{port}\", \"token\": \"super-secret-token\"}}"),
    )
    .unwrap();

    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open_pinned(&http).unwrap();
    app.editor.cursor_row = 1;
    app.send_http_request_under_caret();
    assert!(
        app.status.starts_with("Sending GET {{host}}/users"),
        "the status carries the RAW line: {}",
        app.status
    );
    crate::test_budget::await_spawned(
        std::time::Duration::from_secs(10),
        "the HTTP response",
        || {
            app.drain_http_responses();
            app.http_run.is_none()
        },
    );
    let opened = app.editor.path.clone().expect("a response tab opened");
    assert_eq!(opened.extension().and_then(|e| e.to_str()), Some("jsonc"));
    let doc = app.editor.lines.join("\n");
    assert!(
        doc.contains("// GET {{host}}/users \u{2192} HTTP/1.1 200 OK"),
        "{doc}"
    );
    assert!(doc.contains("\"users\": ["), "pretty-printed: {doc}");
    assert!(
        !doc.contains("super-secret-token"),
        "the token never reaches the tab"
    );
    assert!(
        seen.lock().unwrap()[0].contains("Bearer super-secret-token"),
        "but the wire DID carry the substituted value"
    );
    let hits = app.command_history.search(
        "http GET",
        crate::command_history::HistoryScope::All,
        "",
        "",
    );
    assert_eq!(
        hits[0].cmd, "http GET {{host}}/users",
        "history keeps the raw line"
    );
    assert_eq!(hits[0].exit, Some(200));
    assert!(!hits[0].cmd.contains("super-secret-token"));

    // The PNG block renders through the image path.
    app.editor.open_pinned(&http).unwrap();
    app.editor.cursor_row = 4;
    app.send_http_request_under_caret();
    crate::test_budget::await_spawned(
        std::time::Duration::from_secs(10),
        "the PNG response",
        || {
            app.drain_http_responses();
            app.http_run.is_none()
        },
    );
    assert!(
        app.editor.image.is_some(),
        "a PNG response opens as an image, not bytes in a text tab: {:?}",
        app.editor.path
    );

    // A second send while one is in flight is refused and clobbers
    // nothing; a worker that died reports itself on the next drain.
    let (dummy_tx, dummy_rx) = std::sync::mpsc::channel();
    app.http_run = Some(dummy_rx);
    app.editor.open_pinned(&http).unwrap();
    app.editor.cursor_row = 0;
    app.send_http_request_under_caret();
    assert_eq!(app.status, "An HTTP request is already in flight");
    drop(dummy_tx);
    assert!(app.drain_http_responses());
    assert!(app.status.contains("worker died"), "{}", app.status);
    assert!(app.http_run.is_none());

    // A transport failure must NOT leak a substituted secret into the
    // status line: ureq's error Display opens with the resolved URL, so
    // only its kind may be shown (#428 review). The port is bound then
    // dropped, so the connection is refused at once.
    let dead_port = {
        let l = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
        l.local_addr().unwrap().port()
    };
    std::fs::write(
        tmp.path().join(crate::http_file::ENV_FILE),
        format!(
            "{{\"host\": \"http://127.0.0.1:{dead_port}\", \"token\": \"super-secret-token\"}}"
        ),
    )
    .unwrap();
    let secret_url = tmp.path().join("leak.http");
    std::fs::write(&secret_url, "GET {{host}}/x?api_key={{token}}\n").unwrap();
    app.editor.open_pinned(&secret_url).unwrap();
    app.editor.cursor_row = 0;
    app.send_http_request_under_caret();
    crate::test_budget::await_spawned(
        std::time::Duration::from_secs(10),
        "the refused connection",
        || {
            app.drain_http_responses();
            app.http_run.is_none()
        },
    );
    assert!(
        app.status.contains("failed"),
        "a transport failure is reported: {}",
        app.status
    );
    assert!(
        !app.status.contains("super-secret-token"),
        "the substituted URL never reaches the status line: {}",
        app.status
    );
    let hits =
        app.command_history
            .search("api_key", crate::command_history::HistoryScope::All, "", "");
    assert_eq!(hits[0].exit, None, "a failed run records no status code");
    assert!(!hits[0].cmd.contains("super-secret-token"));
    app.editor.open_pinned(&http).unwrap();

    // A hole with no value refuses to send rather than leaking the hole.
    app.editor.open_pinned(&http).unwrap();
    std::fs::remove_file(tmp.path().join(crate::http_file::ENV_FILE)).unwrap();
    app.editor.cursor_row = 0;
    app.send_http_request_under_caret();
    assert!(
        app.status.contains("no value for {{host}}, {{token}}"),
        "{}",
        app.status
    );
    assert!(app.http_run.is_none(), "nothing was sent");
}
/// #1186: a `.http` file's own `@base = …` line fills `{{base}}`, and
/// Ctrl+Enter on the `@base` line sends nothing.
#[test]
fn an_http_file_variable_fills_the_request_and_is_not_sent() {
    let tmp = tempfile::tempdir().unwrap();
    let http = tmp.path().join("api.http");
    std::fs::write(
        &http,
        "@base = http://127.0.0.1:8765\n\n### Fetch the hello document\nGET {{base}}/hello.json\nAccept: application/json\n",
    )
    .unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open_pinned(&http).unwrap();
    app.editor.cursor_row = 3;
    let (_, resolved, _) = app.http_request_under_caret().expect("resolves");
    assert_eq!(resolved.url, "http://127.0.0.1:8765/hello.json");

    app.editor.cursor_row = 0;
    app.send_http_request_under_caret();
    assert_eq!(app.status, "No request under the caret");
    assert!(app.http_run.is_none(), "the @base line is not sent");
}

/// Negative (#1186): a hole neither the file nor `.http.env.json` defines
/// still refuses to send, and the status says where a value can go.
#[test]
fn an_http_hole_no_file_variable_defines_still_refuses() {
    let tmp = tempfile::tempdir().unwrap();
    let http = tmp.path().join("api.http");
    std::fs::write(
        &http,
        "@base = http://127.0.0.1:8765\nGET {{base}}/{{path}}\n",
    )
    .unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open_pinned(&http).unwrap();
    app.editor.cursor_row = 1;
    app.send_http_request_under_caret();
    assert!(
        app.status.contains("no value for {{path}}"),
        "{}",
        app.status
    );
    assert!(!app.status.contains("{{base}}"), "{}", app.status);
    assert!(app.status.contains("@name"), "{}", app.status);
    assert!(app.http_run.is_none(), "nothing was sent");
}

/// #924: an env file in REST Client's shape (`$shared` plus named
/// environments) is read, not skipped. With none active, a hole only an
/// environment fills refuses and names them; HTTP: Switch Environment
/// lists them, and the one picked fills the request over `$shared`.
#[test]
fn an_http_named_environment_is_picked_from_the_palette() {
    use crate::widgets::command_palette::Command;
    let tmp = tempfile::tempdir().unwrap();
    let http = tmp.path().join("api.http");
    std::fs::write(&http, "GET {{host}}/items?v={{version}}\n").unwrap();
    std::fs::write(
        tmp.path().join(crate::http_file::ENV_FILE),
        r#"{"$shared": {"version": "1"}, "dev": {"host": "http://dev.test"}, "prod": {"host": "http://prod.test"}}"#,
    )
    .unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open_pinned(&http).unwrap();
    app.send_http_request_under_caret();
    assert!(
        app.status.contains("no value for {{host}};")
            && app.status.contains("(dev, prod)")
            && app.status.contains("HTTP: Switch Environment"),
        "{}",
        app.status
    );
    assert!(app.http_run.is_none(), "nothing was sent");

    app.run_command(Command::SwitchHttpEnvironment);
    let picker = app.list_picker.as_ref().expect("the environment picker");
    let labels: Vec<&str> = picker.rows.iter().map(|r| r.label.as_str()).collect();
    assert_eq!(
        labels,
        ["No Environment ($shared only)  (current)", "dev", "prod"]
    );
    app.list_picker.as_mut().unwrap().selected = 2;
    app.confirm_list_picker();
    assert_eq!(app.status, "HTTP: environment prod");
    let (_, resolved, _) = app.http_request_under_caret().expect("resolves");
    assert_eq!(resolved.url, "http://prod.test/items?v=1");

    // The picker reopens on the current one; No Environment goes back.
    app.run_command(Command::SwitchHttpEnvironment);
    let picker = app.list_picker.as_ref().unwrap();
    assert_eq!(picker.selected_row().unwrap().label, "prod  (current)");
    app.list_picker.as_mut().unwrap().selected = 0;
    app.confirm_list_picker();
    assert!(app.http_request_under_caret().is_none());
    assert!(app.status.contains("pick an environment"), "{}", app.status);
}

/// Negative (#924): with only flat values beside the file there is no
/// environment to switch to, and the picker says so instead of opening;
/// JetBrains' `http-client.env.json` environments are offered too.
#[test]
fn an_http_environment_picker_needs_named_environments() {
    use crate::widgets::command_palette::Command;
    let tmp = tempfile::tempdir().unwrap();
    let http = tmp.path().join("api.http");
    std::fs::write(&http, "GET {{host}}/a\n").unwrap();
    std::fs::write(
        tmp.path().join(crate::http_file::ENV_FILE),
        r#"{"host": "http://flat.test"}"#,
    )
    .unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open_pinned(&http).unwrap();
    app.run_command(Command::SwitchHttpEnvironment);
    assert!(app.list_picker.is_none());
    assert!(
        app.status.starts_with("No named environments"),
        "{}",
        app.status
    );
    let (_, resolved, _) = app.http_request_under_caret().expect("flat still works");
    assert_eq!(resolved.url, "http://flat.test/a");

    std::fs::write(
        tmp.path().join("http-client.env.json"),
        r#"{"local": {"host": "http://local.test"}}"#,
    )
    .unwrap();
    app.run_command(Command::SwitchHttpEnvironment);
    let picker = app.list_picker.as_ref().expect("JetBrains' file is read");
    assert_eq!(picker.rows[1].id, "local");
    app.list_picker.as_mut().unwrap().selected = 1;
    app.confirm_list_picker();
    let (_, resolved, _) = app.http_request_under_caret().expect("resolves");
    assert_eq!(resolved.url, "http://local.test/a");
}

/// #1537: "File: Reopen as Preview" on a plain text capture opens the
/// rendered log view instead of refusing, keeps it through a reload, and
/// "Reopen as Text" goes back to the editable buffer.
#[test]
fn reopen_as_preview_shows_plain_text_as_a_rendered_log() {
    use crate::widgets::command_palette::Command;
    let tmp = tempfile::tempdir().unwrap();
    let out = tmp.path().join("run.out");
    std::fs::write(&out, "2026-10-08 ERROR boom\nINFO ok\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open_pinned(&out).unwrap();
    assert!(app.editor.log.is_none(), "plain text opens as text");

    app.run_command(Command::ReopenAsPreview);
    assert!(
        app.editor.log.is_some(),
        "the capture is shown as a rendered log; status {:?}",
        app.status
    );
    assert!(!app.status.contains("No preview"), "{:?}", app.status);

    std::fs::write(&out, "2026-10-08 ERROR boom\nINFO ok\nWARN late\n").unwrap();
    assert!(app.editor.reload_if_clean().is_some_and(|r| r.is_ok()));
    assert!(app.editor.log.is_some(), "a reload keeps the preview");

    app.run_command(Command::ReopenAsText);
    assert!(app.editor.log.is_none(), "back to the text");
    assert_eq!(app.editor.lines[2], "WARN late");

    let other = tmp.path().join("other.out");
    std::fs::write(&other, "plain\n").unwrap();
    app.editor.open_pinned(&out).unwrap();
    app.run_command(Command::ReopenAsPreview);
    app.editor.open(&other).unwrap();
    assert!(
        app.editor.log.is_none(),
        "the choice belonged to run.out, not to the next file"
    );
}

/// #1537 negative: the log view reads raw bytes as UTF-8, so a UTF-16
/// capture stays in the decoded text buffer instead of turning to NULs.
#[test]
fn reopen_as_preview_keeps_a_utf16_capture_as_text() {
    use crate::widgets::command_palette::Command;
    let tmp = tempfile::tempdir().unwrap();
    let out = tmp.path().join("run.out");
    let mut bytes = vec![0xFF, 0xFE];
    for u in "ERROR boom\nINFO ok\n".encode_utf16() {
        bytes.extend_from_slice(&u.to_le_bytes());
    }
    std::fs::write(&out, bytes).unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open_pinned(&out).unwrap();
    assert_eq!(app.editor.encoding, encoding_rs::UTF_16LE);
    app.run_command(Command::ReopenAsPreview);
    assert!(app.editor.log.is_none(), "no byte-level log view of UTF-16");
    assert_eq!(app.editor.lines[0], "ERROR boom");
    assert_eq!(
        app.status,
        "No preview for this file type; showing the text"
    );
}

/// #1363: Markdown is previewed by a toggle, so Reopen as Preview turns the
/// preview on instead of reopening the source and saying there is none. The
/// tab keeps its caret and unsaved edits.
#[test]
fn reopen_as_preview_shows_the_markdown_preview() {
    use crate::widgets::command_palette::Command;
    let tmp = tempfile::tempdir().unwrap();
    let md = tmp.path().join("t.md");
    std::fs::write(&md, "# Title\n\nSome *text*.\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open_pinned(&md).unwrap();
    app.editor.cursor_row = 2;
    app.editor.cursor_col = 5;
    app.editor.insert_char('!');
    assert!(app.editor.dirty);
    app.run_command(Command::ReopenAsPreview);
    assert!(app.editor.markdown_preview.is_some(), "the preview is on");
    assert_eq!(app.status, "Markdown Preview");
    assert!(app.editor.dirty, "the unsaved edit is kept, not reloaded");
    assert_eq!(app.editor.lines[2], "Some !*text*.");
    // Asked again, it stays on rather than flipping back to the source.
    app.run_command(Command::ReopenAsPreview);
    assert!(app.editor.markdown_preview.is_some());
    // Reopen as Text still lands in the source, though the same-path reload
    // it does now keeps a Markdown preview (#1605).
    app.editor.save_to_disk().unwrap();
    app.run_command(Command::ReopenAsText);
    assert!(app.editor.markdown_preview.is_none(), "{}", app.status);
}

/// #1537 negative: source code has a grammar and no preview, so Reopen as
/// Preview still says so rather than turning it into a log.
#[test]
fn reopen_as_preview_leaves_source_code_as_text() {
    use crate::widgets::command_palette::Command;
    let tmp = tempfile::tempdir().unwrap();
    let src = tmp.path().join("main.rs");
    std::fs::write(&src, "fn main() {}\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open_pinned(&src).unwrap();
    app.run_command(Command::ReopenAsPreview);
    assert!(app.editor.log.is_none());
    assert_eq!(
        app.status,
        "No preview for this file type; showing the text"
    );
}

/// #1537: the "Log: Highlighting (tailspin)" switch reaches a plain `.log`
/// already open as text, not only rendered log views.
#[test]
fn the_log_highlight_switch_recolours_an_open_plain_log() {
    let _exclusive = crate::log_view::DEFAULT_HIGHLIGHT_TEST_LOCK
        .lock()
        .unwrap_or_else(|e| e.into_inner());
    let before = crate::log_view::default_highlight();
    let tmp = tempfile::tempdir().unwrap();
    let log = tmp.path().join("app.log");
    std::fs::write(&log, "ERROR boom\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.set_log_highlight(true);
    app.editor.open_pinned(&log).unwrap();
    assert!(app.editor.log.is_none(), "a plain log is a text tab");
    let coloured = |app: &App| !app.editor.highlights_for_test()[0].is_empty();
    assert!(coloured(&app), "ERROR is coloured");
    app.set_log_highlight(false);
    assert!(!coloured(&app), "switched off, the open tab goes plain");
    app.set_log_highlight(true);
    assert!(coloured(&app), "and back on, coloured again");
    crate::log_view::set_default_highlight(before);
}

#[test]
fn toggling_log_highlighting_flips_open_views_and_the_default() {
    // #466: the palette / Settings toggle reaches the view that is already
    // open AND steers views opened afterwards, so the user sees the change
    // at once and does not get it undone by the next log they open.
    let _exclusive = crate::log_view::DEFAULT_HIGHLIGHT_TEST_LOCK
        .lock()
        .unwrap_or_else(|e| e.into_inner());
    let tmp = tempfile::tempdir().unwrap();
    let log = tmp.path().join("build.log");
    std::fs::write(&log, b"\x1b[32mok\x1b[0m 2024-01-02 step 1\nplain step 2\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open_pinned(&log).unwrap();
    assert!(
        app.editor.log.is_some(),
        "a coloured .log opens as a rendered log"
    );
    let before = app.log_highlight;
    let view_before = app.editor.log.as_ref().unwrap().highlight();
    assert_eq!(
        view_before, before,
        "the open view starts at the app's setting"
    );

    app.toggle_log_highlight();
    assert_eq!(app.log_highlight, !before);
    assert_eq!(
        app.editor.log.as_ref().unwrap().highlight(),
        !before,
        "the open view followed the toggle"
    );
    assert_eq!(
        crate::log_view::default_highlight(),
        !before,
        "and so will the next log opened"
    );
    assert!(app.status.starts_with("Log highlighting (tailspin):"));

    // Back to where it was, so the process-wide default is left as found.
    app.toggle_log_highlight();
    assert_eq!(app.log_highlight, before);
    assert_eq!(crate::log_view::default_highlight(), before);
}

#[test]
fn startup_seeds_the_log_view_default_from_the_saved_preference() {
    // #466: `App::new` seeds the log view's opening default from the saved
    // preference. Under test that seed is recorded per thread instead of
    // written (hundreds of apps on parallel threads would race the tests
    // reading the process-wide default), which keeps the CALL SITE
    // observable: this asserts what `App::new` decided, pinned by a
    // workspace layer so it does not move with the developer's own config.
    let tmp = tempfile::tempdir().unwrap();
    let layer = crate::config_layers::workspace_config_path(tmp.path());
    std::fs::create_dir_all(layer.parent().unwrap()).unwrap();
    std::fs::write(&layer, r#"{"disable_log_highlight": true}"#).unwrap();
    STARTUP_LOG_HIGHLIGHT_SEED.with(|c| c.set(None));
    let app = App::new(tmp.path().to_path_buf()).unwrap();
    assert!(
        !app.log_highlight,
        "the workspace layer's opt-out reached the field"
    );
    assert_eq!(
        STARTUP_LOG_HIGHLIGHT_SEED.with(|c| c.get()),
        Some(false),
        "and App::new seeded the log view's opening default with the same value"
    );
    std::fs::write(&layer, r#"{"disable_log_highlight": false}"#).unwrap();
    STARTUP_LOG_HIGHLIGHT_SEED.with(|c| c.set(None));
    let app = App::new(tmp.path().to_path_buf()).unwrap();
    assert!(app.log_highlight);
    assert_eq!(STARTUP_LOG_HIGHLIGHT_SEED.with(|c| c.get()), Some(true));
}

/// #682: the fingerprint under an image changes with any write ratatui
/// makes inside it, and ignores writes outside it.
#[test]
fn the_cells_under_an_image_fingerprint_writes_inside_it_only() {
    use ratatui::buffer::Buffer;
    use ratatui::layout::Rect;
    let mut buf = Buffer::empty(Rect::new(0, 0, 20, 10));
    let before = super::cells_fingerprint(&buf, 2, 2, 5, 3);
    buf[(15, 8)].set_symbol("x");
    assert_eq!(super::cells_fingerprint(&buf, 2, 2, 5, 3), before);
    buf[(3, 3)].set_symbol("x");
    assert_ne!(super::cells_fingerprint(&buf, 2, 2, 5, 3), before);
    // A rectangle past the edge is clamped, not a panic.
    let _ = super::cells_fingerprint(&buf, 18, 8, 10, 10);
}

/// On Kitty an image lives on its own layer, so text redrawn beneath it
/// never makes croft resend it; on iTerm2 it does.
#[test]
fn only_cell_buffer_protocols_resend_an_image_when_text_beneath_changes() {
    use crate::iterm2_inline::InlineImageProtocol;
    use ratatui::buffer::Buffer;
    use ratatui::layout::Rect;
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.overlays.terminal_image.set(
        String::from("img"),
        super::TerminalImageLayout {
            cell_x: 1,
            cell_y: 1,
            cell_w: 4,
            cell_h: 2,
            seq: 0,
            pane: 0,
        },
    );
    let quiet = Buffer::empty(Rect::new(0, 0, 10, 5));
    let mut busy = quiet.clone();
    busy[(2, 1)].set_symbol("x");
    app.inline_protocol = InlineImageProtocol::ITerm2;
    assert_ne!(
        app.image_underlays(&quiet).terminal,
        app.image_underlays(&busy).terminal
    );
    app.inline_protocol = InlineImageProtocol::Kitty;
    assert_eq!(
        app.image_underlays(&quiet).terminal,
        app.image_underlays(&busy).terminal
    );
}

/// #682: only iTerm2 needs the idle icon keepalive.
#[test]
fn only_iterm2_keeps_the_activity_icons_alive() {
    use crate::iterm2_inline::InlineImageProtocol;
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    for (p, want) in [
        (InlineImageProtocol::ITerm2, true),
        (InlineImageProtocol::Kitty, false),
        (InlineImageProtocol::Sixel, false),
    ] {
        app.inline_protocol = p;
        assert_eq!(app.activity_keepalive_allowed(), want, "{p:?}");
    }
}

#[test]
fn a_csv_sheet_sorts_by_the_cursors_column_from_the_palette() {
    // #578: raw results as a sortable table. Any CSV sheet sorts.
    use crate::widgets::command_palette::Command;
    let tmp = tempfile::tempdir().unwrap();
    let csv = tmp.path().join("results.csv");
    std::fs::write(&csv, "name,count\nb,10\nA,9\nc,100\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.run_command(Command::SheetSortByColumn);
    assert_eq!(app.status, "Open a CSV or TSV file to sort it");
    app.editor.open(&csv).unwrap();
    let sheet = app.editor.sheet.as_mut().expect("a CSV opens as a sheet");
    sheet.sheets[0].cur_col = 1;
    app.run_command(Command::SheetSortByColumn);
    assert_eq!(app.status, "Sorted by count, ascending");
    let rows = |app: &App| -> Vec<String> {
        app.editor.sheet.as_ref().unwrap().sheets[0]
            .rows
            .iter()
            .map(|r| r[1].clone())
            .collect()
    };
    assert_eq!(rows(&app), ["9", "10", "100"]);
    assert!(app.editor.dirty, "a reorder is an edit");
    app.run_command(Command::SheetSortByColumn);
    assert_eq!(app.status, "Sorted by count, descending");
    assert_eq!(rows(&app), ["100", "10", "9"]);
}

/// A WAL-mode database with one row, and the connection that wrote it,
/// kept open like a running app's so nothing checkpoints into the file.
fn wal_database(dir: &std::path::Path) -> (std::path::PathBuf, rusqlite::Connection) {
    let db = dir.join("app.db");
    let writer = rusqlite::Connection::open(&db).unwrap();
    writer
        .execute_batch(
            "PRAGMA journal_mode=WAL; PRAGMA wal_autocheckpoint=0; \
             CREATE TABLE kv (k TEXT); INSERT INTO kv VALUES ('a');",
        )
        .unwrap();
    (db, writer)
}

fn sqlite_keys(app: &App) -> Vec<String> {
    let data = &app.editor.sheet.as_ref().expect("a SQLite tab").sheets[0];
    data.rows.iter().map(|r| r[0].clone()).collect()
}

/// #1643: a commit from an app holding its WAL-mode connection open lands
/// in `app.db-wal` and leaves `app.db` alone; the open database tab still
/// picks it up on the next sweep.
#[test]
fn a_wal_commit_by_a_running_app_reloads_the_database_tab() {
    let tmp = tempfile::tempdir().unwrap();
    let (db, writer) = wal_database(tmp.path());
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open(&db).unwrap();
    assert_eq!(sqlite_keys(&app), ["a"]);
    let stamp = |p: &std::path::Path| {
        let m = std::fs::metadata(p).unwrap();
        (m.modified().unwrap(), m.len())
    };
    let before = stamp(&db);
    writer.execute("INSERT INTO kv VALUES ('b')", []).unwrap();
    assert_eq!(stamp(&db), before, "setup: the commit left app.db alone");
    assert!(app.reload_open_file_after_external_change());
    assert_eq!(sqlite_keys(&app), ["a", "b"]);
    drop(writer);
}

/// #1643: the poll stats a SQLite tab's write-ahead log as well as the
/// database, even before the log exists, and no log for any other tab.
#[test]
fn the_poll_watches_a_sqlite_tabs_log_and_no_other_tabs() {
    let tmp = tempfile::tempdir().unwrap();
    let db = sqlite_table_of(tmp.path(), 3);
    let txt = tmp.path().join("notes.txt");
    std::fs::write(&txt, "x\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open(&txt).unwrap();
    app.editor.open_in_new_tab(&db).unwrap();
    let polled = app.polled_open_file_paths();
    let real_dir = std::fs::canonicalize(tmp.path()).unwrap();
    assert!(polled.contains(&real_dir.join("big.db-wal")), "{polled:?}");
    assert!(
        !polled.contains(&tmp.path().join("notes.txt-wal"))
            && !polled.contains(&real_dir.join("notes.txt-wal")),
        "{polled:?}"
    );
    assert!(polled.contains(&db) && polled.contains(&txt));
}

/// Negative (#1643): with no commit, the sweep leaves the database tab
/// alone, cell cursor included, even while a writer holds it open.
#[test]
fn a_wal_database_with_no_new_commit_is_not_reloaded() {
    let tmp = tempfile::tempdir().unwrap();
    let (db, writer) = wal_database(tmp.path());
    writer.execute("INSERT INTO kv VALUES ('b')", []).unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open(&db).unwrap();
    app.editor.sheet.as_mut().unwrap().sheets[0].cur_row = 1;
    assert!(!app.reload_open_file_after_external_change());
    assert_eq!(app.editor.sheet.as_ref().unwrap().sheets[0].cur_row, 1);
    assert_eq!(sqlite_keys(&app), ["a", "b"]);
    drop(writer);
}

/// #1643: a database opened through a symlink has its write-ahead log
/// beside the real file, and a commit there still reloads the tab.
#[cfg(unix)]
#[test]
fn a_wal_commit_reloads_a_database_opened_through_a_symlink() {
    let tmp = tempfile::tempdir().unwrap();
    let real = tmp.path().join("real");
    std::fs::create_dir(&real).unwrap();
    let (db, writer) = wal_database(&real);
    let link = tmp.path().join("link.db");
    std::os::unix::fs::symlink(&db, &link).unwrap();
    assert_eq!(
        crate::widgets::editor::sqlite_wal_path(&link),
        Some(std::fs::canonicalize(&real).unwrap().join("app.db-wal"))
    );
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open(&link).unwrap();
    assert_eq!(sqlite_keys(&app), ["a"]);
    writer.execute("INSERT INTO kv VALUES ('b')", []).unwrap();
    assert!(app.reload_open_file_after_external_change());
    assert_eq!(sqlite_keys(&app), ["a", "b"]);
    drop(writer);
}

/// #1643: a WAL commit's reload keeps the reader's table, page, cell and
/// scroll, and clamps them when the page no longer exists.
#[test]
fn a_wal_reload_keeps_the_sqlite_table_page_and_cell() {
    let tmp = tempfile::tempdir().unwrap();
    let db = tmp.path().join("app.db");
    let writer = rusqlite::Connection::open(&db).unwrap();
    writer
        .execute_batch(&format!(
            "PRAGMA journal_mode=WAL; PRAGMA wal_autocheckpoint=0; \
             CREATE TABLE a_small (k TEXT); INSERT INTO a_small VALUES ('a'); \
             CREATE TABLE z_big (n INTEGER, m INTEGER); WITH RECURSIVE c(x) AS \
             (SELECT 1 UNION ALL SELECT x+1 FROM c WHERE x < {}) \
             INSERT INTO z_big SELECT x, x FROM c;",
            crate::sqlite_view::ROW_CAP + 40
        ))
        .unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open(&db).unwrap();
    app.editor.sheet.as_mut().unwrap().current_sheet = 1;
    app.sqlite_load_page(1, false);
    {
        let data = &mut app.editor.sheet.as_mut().unwrap().sheets[1];
        (data.cur_row, data.cur_col) = (30, 1);
        (data.scroll_row, data.scroll_col) = (20, 1);
    }
    writer
        .execute("INSERT INTO a_small VALUES ('b')", [])
        .unwrap();
    assert!(app.reload_open_file_after_external_change());
    let view = app.editor.sheet.as_ref().unwrap();
    assert_eq!(view.current_sheet, 1);
    assert_eq!(view.sqlite_pages[1], (String::from("z_big"), 1));
    let data = &view.sheets[1];
    assert_eq!(data.row_base, crate::sqlite_view::ROW_CAP);
    assert_eq!((data.cur_row, data.cur_col), (30, 1));
    assert_eq!((data.scroll_row, data.scroll_col), (20, 1));
    assert_eq!(view.sheets[0].rows.len(), 2, "the reload saw the commit");

    // The table shrinks below that page: back to its first, cell clamped.
    writer.execute("DELETE FROM z_big WHERE n > 5", []).unwrap();
    assert!(app.reload_open_file_after_external_change());
    let view = app.editor.sheet.as_ref().unwrap();
    assert_eq!(view.current_sheet, 1);
    assert_eq!(view.sqlite_pages[1].1, 0);
    let data = &view.sheets[1];
    assert_eq!((data.cur_row, data.cur_col), (4, 1));
    assert!(data.scroll_row <= data.cur_row);
    drop(writer);
}

/// #2076: with a profile active, an extension is on or off as the
/// Extensions panel shows it, which is the app's own set, saved to the
/// profile's settings. The Explorer's viewer row, opening a viewer, the
/// palette's rows and running a command all follow that set. They read the
/// Default profile's config.json instead, so a viewer turned off in a
/// profile was still offered, and a command the palette listed would not run.
#[test]
fn an_extension_is_on_or_off_as_the_app_s_own_set_says_everywhere() {
    const VIEWER: &str = r#"
id = "tviewer"
name = "tviewer"
api_version = 1
[[viewers]]
id = "sh"
label = "Open in sh"
command = "/bin/sh"
args = ["-c", "sleep 30", "sh", "{file}"]
extensions = ["csv"]
"#;
    const COMMAND: &str = r#"
id = "tcmd"
name = "tcmd"
api_version = 1
[[mcp_servers]]
id = "srv"
command = "/bin/true"
[[commands]]
id = "tcmd.now"
title = "TCmd: Now"
server = "srv"
tool = "now"
"#;
    let (_scratch, croft) = scratch_config(&[("tviewer", VIEWER), ("tcmd", COMMAND)]);
    // The Default profile's file: tcmd off, tviewer on.
    std::fs::write(
        croft.join("config.json"),
        r#"{"disabled_extensions": ["tcmd"]}"#,
    )
    .unwrap();
    let tmp = tempfile::tempdir().unwrap();
    let csv = tmp.path().join("data.csv");
    std::fs::write(&csv, "a,b\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.config_dir = croft.clone();
    // The active profile's set, as the Extensions panel holds it: the other
    // way round, tviewer off and tcmd on.
    app.disabled_extensions = std::collections::BTreeSet::from([String::from("tviewer")]);

    let n = file_node(&csv);
    let items = app.tree_context_menu_items(Some(&n), std::slice::from_ref(&csv), tmp.path());
    assert!(
        !items
            .iter()
            .any(|(_, a)| matches!(a, MenuAction::OpenInViewer(..))),
        "the turned-off viewer gets no Explorer row: {items:?}"
    );

    app.open_command_palette();
    let listed: Vec<String> = app
        .command_palette
        .as_ref()
        .expect("the palette opens")
        .extensions
        .iter()
        .map(|c| c.id.clone())
        .collect();
    app.command_palette = None;
    assert!(
        listed.iter().any(|id| id == "tcmd.now"),
        "the turned-on command is listed: {listed:?}"
    );
    assert!(
        !listed.iter().any(|id| id.contains("tviewer")),
        "the turned-off viewer is not: {listed:?}"
    );

    let before = app.terminals.len();
    app.dispatch_menu_action(
        MenuAction::OpenInViewer(String::from("tviewer/sh"), csv.clone()),
        tmp.path().to_path_buf(),
    );
    assert_eq!(
        app.terminals.len(),
        before,
        "the turned-off viewer never opens"
    );

    app.status.clear();
    app.run_extension_command("tcmd.now");
    assert!(
        !app.status.contains("unavailable"),
        "the listed command runs (here, asks for consent first): {}",
        app.status
    );
}

/// #2062: every inline picture sent on its own goes out through one writer,
/// which sends exactly the bytes each of the nine copies it replaced sent: the
/// caret hidden and its place saved, a move to the picture's cell (row then
/// column, each counted from 1), the picture, the caret put back where it
/// was, and the caret shown again only when it should be visible.
#[test]
fn an_inline_picture_goes_out_inside_the_caret_guard() {
    let mut shown = Vec::new();
    write_inline_image(&mut shown, 4, 2, b"PICTURE", true);
    assert_eq!(
        shown,
        b"\x1b[?25l\x1b[s\x1b[3;5HPICTURE\x1b[u\x1b[?25h".to_vec()
    );
    let mut hidden = Vec::new();
    write_inline_image(&mut hidden, 0, 0, b"PICTURE", false);
    assert_eq!(hidden, b"\x1b[?25l\x1b[s\x1b[1;1HPICTURE\x1b[u".to_vec());
    let mut far = Vec::new();
    write_inline_image(&mut far, 239, 66, b"", true);
    assert_eq!(far, b"\x1b[?25l\x1b[s\x1b[67;240H\x1b[u\x1b[?25h".to_vec());
}

/// #2062: the activity bar's icons and badges go out through the same
/// writer, together inside one caret guard (one hide-and-save before the
/// first, one restore after the last), exactly as its own copy sent them; a
/// batch with nothing on screen still sends the guard, as that copy did; and
/// one picture on its own is the same bytes as a batch of one.
#[test]
fn the_activity_bar_pictures_share_one_caret_guard() {
    let mut icons = Vec::new();
    write_inline_images(
        &mut icons,
        [
            (0, 1, &b"FILES"[..]),
            (0, 3, &b"SEARCH"[..]),
            (2, 3, &b"7"[..]),
        ],
        false,
    );
    assert_eq!(
        icons,
        b"\x1b[?25l\x1b[s\x1b[2;1HFILES\x1b[4;1HSEARCH\x1b[4;3H7\x1b[u".to_vec()
    );
    let mut none = Vec::new();
    write_inline_images(&mut none, [], true);
    assert_eq!(none, b"\x1b[?25l\x1b[s\x1b[u\x1b[?25h".to_vec());
    let mut one = Vec::new();
    write_inline_image(&mut one, 5, 9, b"PICTURE", true);
    let mut batch_of_one = Vec::new();
    write_inline_images(&mut batch_of_one, [(5, 9, &b"PICTURE"[..])], true);
    assert_eq!(one, batch_of_one);
}

/// #2062: every activity-bar icon's pictures come out of the icon table
/// exactly as the per-icon code baked them: its own picture and Kitty id,
/// the view icons centered, the gear and the heart lower, the heart in its
/// own ink and with no selected picture.
#[test]
fn every_activity_icon_bakes_as_it_did_before_the_table() {
    use crate::iterm2_inline as ki;
    let input = ChromeBakeInput {
        protocol: ki::InlineImageProtocol::Kitty,
        cell: (8, 16),
        is_tmux: false,
        icon_bg: ::image::Rgba([30, 30, 30, 255]),
        icon_ink: ki::IconInk::default(),
        sponsor_ink: ki::IconInk::new((200, 60, 120), (230, 90, 150), (0, 0, 0)),
    };
    let images = App::bake_chrome_images(&input)
        .activity
        .expect("the activity icons bake");
    let (w, h) = (ACTIVITY_BAR_WIDTH, ACTIVITY_ICON_HEIGHT);
    let canvas = (8 * u32::from(w), 16 * u32::from(h));
    let lower = i64::from(canvas.1);
    let picture = |src: &[u8], state: ki::IconState, ink: ki::IconInk, bias: i64, id: u32| {
        let png =
            ki::compose_icon_svg(src, canvas.0, canvas.1, state, ink, input.icon_bg, bias).unwrap();
        let raw = ki::build_inline_image(input.protocol, &png, w, h, false, id).unwrap();
        ki::maybe_tmux_wrap(input.protocol, false, raw)
    };
    // The recipe each icon had before the table: picture, offset, Kitty id.
    let before = [
        (ki::EXPLORER_SRC_SVG, 0, ki::KITTY_ID_EXPLORER),
        (ki::SEARCH_SRC_SVG, 0, ki::KITTY_ID_SEARCH),
        (ki::SOURCE_CONTROL_SRC_SVG, 0, ki::KITTY_ID_SOURCE_CONTROL),
        (ki::REMOTE_SRC_SVG, 0, ki::KITTY_ID_REMOTE),
        (ki::RUN_DEBUG_SRC_SVG, 0, ki::KITTY_ID_RUN_DEBUG_BAR),
        (ki::EXTENSIONS_SRC_SVG, 0, ki::KITTY_ID_EXTENSIONS),
        (ki::TESTING_SRC_SVG, 0, ki::KITTY_ID_TESTING),
        (ki::CODEQL_SRC_SVG, 0, ki::KITTY_ID_CODEQL),
        (ki::SPONSOR_HEART_SRC_SVG, lower, ki::KITTY_ID_SPONSOR),
        (ki::SETTINGS_GEAR_SRC_SVG, lower, ki::KITTY_ID_SETTINGS),
    ];
    for (icon, (src, bias, id)) in ActivityIcon::ALL.into_iter().zip(before) {
        let ink = if icon == ActivityIcon::Sponsor {
            input.sponsor_ink
        } else {
            input.icon_ink
        };
        let baked = &images.icons[icon as usize];
        let active = (icon != ActivityIcon::Sponsor)
            .then(|| picture(src, ki::IconState::Active, ink, bias, id));
        assert_eq!(baked.active, active, "{icon:?} selected");
        assert_eq!(
            baked.inactive,
            picture(src, ki::IconState::Inactive, ink, bias, id),
            "{icon:?} at rest"
        );
        assert_eq!(
            baked.hovered,
            picture(src, ki::IconState::Hovered, ink, bias, id),
            "{icon:?} hovered"
        );
    }
}

/// A tab with two views filled fails the test-only check (#2062), even in a
/// group without focus, and the check runs on every key: the hex view and
/// the rendered log here sit on one tab of the group the split left behind.
#[test]
#[should_panic(expected = "shows 2 views at once: hex, log")]
fn two_views_on_one_tab_fail_the_check_in_any_group() {
    let tmp = tempfile::tempdir().unwrap();
    let f = tmp.path().join("notes.txt");
    std::fs::write(&f, "one\ntwo\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open(&f).unwrap();
    app.focus_pane(Pane::Editor);
    app.split_editor();
    let left = app
        .editor_layout
        .inactive_groups_mut()
        .next()
        .expect("staging: the split leaves one group without focus");
    left.hex = Some(crate::hex::HexView::open(&f).unwrap());
    left.log = Some(crate::log_view::LogView::open(&f).unwrap());

    let _ = app.handle_key(key(KeyCode::Down, KeyModifiers::NONE));
}

/// A zip past the listing cap opens as hex, and the status says why (#2711),
/// whichever way it was opened: Quick Open and `croft <file>` from croft's
/// terminal wrote their own "Opened big.zip" over the reason the Explorer
/// shows.
#[test]
fn every_open_route_says_why_a_file_landed_in_hex() {
    let tmp = tempfile::tempdir().unwrap();
    let big = tmp.path().join("big.zip");
    std::fs::write(&big, b"").unwrap();
    std::fs::OpenOptions::new()
        .write(true)
        .open(&big)
        .unwrap()
        .set_len(crate::archive::ZIP_LIST_CAP + 1)
        .unwrap();
    let why = "in the hex viewer: Archive open failed: zip too large to list";

    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    let _ = app.apply_view_request(&big);
    assert!(app.editor.hex.is_some(), "staging: the zip opens as hex");
    assert!(app.status.contains(why), "croft <file>: {:?}", app.status);
    // Asking again only switches to the tab, whose status line has moved on
    // since (a hex save or undo writes there): the reason still comes back.
    app.editor.status = String::from("No pending byte edits");
    let _ = app.apply_view_request(&big);
    assert!(
        app.status.contains(why),
        "croft <file> again: {:?}",
        app.status
    );

    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.handle_key(key(KeyCode::Char('p'), KeyModifiers::SUPER))
        .unwrap();
    type_keys(&mut app, "big.zip");
    app.handle_key(key(KeyCode::Enter, KeyModifiers::NONE))
        .unwrap();
    assert!(app.editor.hex.is_some(), "staging: the zip opens as hex");
    assert!(app.status.contains(why), "Quick Open: {:?}", app.status);

    // A line hint is for text: the reason wins over it too.
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.handle_key(key(KeyCode::Char('p'), KeyModifiers::SUPER))
        .unwrap();
    type_keys(&mut app, "big.zip:1");
    app.handle_key(key(KeyCode::Enter, KeyModifiers::NONE))
        .unwrap();
    assert!(app.editor.hex.is_some(), "staging: the zip opens as hex");
    assert!(
        app.status.contains(why),
        "Quick Open big.zip:1: {:?}",
        app.status
    );
}