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
//! Files the editor shows rather than edits as text: pictures and SVG, PDF pages,
//! spreadsheet and SQLite grids (their edits and saves too), archives, hex, logs and gzip,
//! SARIF, and the Markdown and notebook previews.

use super::*;

/// The most a single gzipped file may decompress to and still open as text
/// (#1469); past it the file stays a hex dump of its gzip bytes.
pub(super) const MAX_GUNZIP_BYTES: u64 = 256 * 1024 * 1024;

pub(super) const MAX_IMAGE_BYTES: u64 = 25 * 1024 * 1024;

/// Why a viewer declined a file (#2062), carried in its error so the open
/// picks the next route by the reason, never by the wording of the message.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(super) enum Refusal {
    /// The bytes are not the format the viewer reads, such as an image
    /// that does not decode: the next route may read them.
    NotItsFormat,
    /// A deliberate size cap, on the file or on what it expands to: the
    /// open says so instead of quietly taking another route around it.
    PastCap,
}

/// A viewer's refusal: its [`Refusal`] and the message the user sees.
#[derive(Debug)]
struct Refused {
    reason: Refusal,
    message: String,
}

impl std::fmt::Display for Refused {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(&self.message)
    }
}

impl std::error::Error for Refused {}

/// An error that says `message` and carries `reason` for the router.
pub(super) fn refused(reason: Refusal, message: String) -> anyhow::Error {
    anyhow::Error::new(Refused { reason, message })
}

/// Why a viewer declined, when the error is a refusal made by [`refused`].
pub(super) fn refusal(e: &anyhow::Error) -> Option<Refusal> {
    e.downcast_ref::<Refused>().map(|r| r.reason)
}

/// An image's pixel size from its header alone. Opening a tab decoded the
/// whole picture on the render thread just to read these two numbers: a
/// 48-megapixel photo meant a ~190 MB decode per open, and one past the
/// decoder's memory limit refused to open although only a downscale shows.
pub(super) fn image_dimensions_of(bytes: &[u8]) -> Option<(u32, u32)> {
    image::ImageReader::new(std::io::Cursor::new(bytes))
        .with_guessed_format()
        .ok()?
        .into_dimensions()
        .ok()
}

pub(super) const IMAGE_EXTENSIONS: &[&str] = &[
    "png", "jpg", "jpeg", "gif", "bmp", "webp", "ico", "tif", "tiff",
];

/// Read-only image preview attached to a tab. Holds the raw file bytes so
/// the OSC-1337 inline-image bake can re-fit on resize without rereading
/// from disk, plus parsed metadata for the header line that's painted in
/// the buffer (so non-image-capable terminals still see meaningful info).
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ImageView {
    pub bytes: Vec<u8>,
    pub format_label: String,
    pub pixel_w: u32,
    pub pixel_h: u32,
    /// The drawing's own size, as the header shows it, when the raster is a
    /// scaled rendering of it: an SVG's CSS-pixel width and height (#1008).
    /// Shown rather than `pixel_w`×`pixel_h`, which is croft's render
    /// quality. `None` for bitmaps, whose pixels are their size.
    pub natural_size: Option<String>,
    pub byte_size: u64,
    /// Monotonic content stamp, fresh on every (re)load of the bytes. Part
    /// of the overlay's re-emit key: a PDF rebuilt on disk reloads to the
    /// same path, rect and page, and without this stamp the baked overlay
    /// kept showing the pre-rebuild pixels until a page turn.
    pub generation: u64,
    /// Set when this preview was rasterised from a PDF page; tracks the
    /// page-navigation state so re-renders on Page Down/Up know which
    /// page to ask the rasteriser for next.
    pub pdf: Option<PdfState>,
}

/// Next value for [`ImageView::generation`]: process-wide monotonic counter,
/// bumped on every byte (re)load anywhere.
pub(super) fn next_image_generation() -> u64 {
    static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
    NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub struct PdfState {
    pub source_path: PathBuf,
    pub current_page: u32,
    pub page_count: Option<u32>,
    pub backend: crate::pdf::PdfBackend,
    pub source_byte_size: u64,
    /// Link regions of `current_page`, extracted lazily on the first click
    /// (never on render — a page flip must not pay a second subprocess).
    /// `None` = not extracted yet; cleared on every page change.
    pub links: Option<crate::pdf::PageLinks>,
}

/// A PDF's work that runs off the UI thread (#2824): poppler can take
/// seconds on a large or half-written file, and a key press, click or frame
/// must not wait for it. A page turn asks for a page and the one shown stays
/// until it lands, the page count is read after the open, and a link click
/// waits for its page's links.
#[derive(Default)]
pub struct PdfJobs {
    /// The page being rendered: one at a time, so holding a page key never
    /// piles up renderers.
    render: Option<PageJob<Vec<u8>>>,
    /// The page asked for while one renders, rendered after it: the latest
    /// one asked for is the one shown.
    next_page: Option<u32>,
    /// The page count, read after the open.
    count: Option<crate::jobs::Job<Option<u32>>>,
    /// End was pressed before the count was in: go to the last page once it
    /// is.
    last_page_wanted: bool,
    /// The page whose links are being read, and the reading.
    links: Option<PageJob<crate::pdf::PageLinks>>,
    /// Where on the page a click waits for its page's links, as fractions of
    /// the page (left, top, right, bottom).
    pub waiting_click: Option<(f64, f64, f64, f64)>,
    /// A rebuild on disk being rendered (#2827).
    reload: Option<PdfReload>,
    /// How the last reload went once it landed, for the sweep's report:
    /// [`ExternalChange::Reloaded`] or [`ExternalChange::ReloadFailed`].
    pub(super) reload_outcome: Option<ExternalChange>,
    /// The disk version whose failed reload was reported, so retrying it is
    /// quiet.
    pub(super) failed_found: Option<Option<(std::time::SystemTime, u64)>>,
}

/// What a rebuild's render hands back: the page count, the page it came up
/// on, and that page.
type Rebuilt = Result<(Option<u32>, u32, Vec<u8>), String>;

/// A rebuild of a PDF on disk, rendering on a job (#2827).
struct PdfReload {
    job: crate::jobs::Job<Rebuilt>,
    /// The page the reader was on, or asked for, when it started.
    asked: u32,
    /// The disk version the tab showed before it.
    before: Option<(std::time::SystemTime, u64)>,
    /// The disk version it renders.
    found: Option<(std::time::SystemTime, u64)>,
    /// The file's size then.
    size: u64,
}

/// A page and the job reading something from it.
type PageJob<T> = (u32, crate::jobs::Job<Result<T, String>>);

/// Render `page` of `source` on a job, stopped once the job is let go of:
/// a page the reader has left, or a tab showing another file now, does not
/// keep its renderer running (#2829 review).
fn pdf_render_job(
    source: PathBuf,
    page: u32,
    backend: crate::pdf::PdfBackend,
) -> std::io::Result<crate::jobs::Job<Result<Vec<u8>, String>>> {
    crate::jobs::Job::spawn_stoppable("pdf-page", crate::jobs::Start::Now, move |unwanted| {
        crate::pdf::rasterize_page_while_wanted(&source, page, backend, unwanted)
            .map_err(|e| e.to_string())
            .and_then(readable_page)
    })
}

/// A render that ran to its end but left nothing croft can read (an empty
/// or damaged picture) is a failed render, as the open that waited for it
/// once said, not a page that shows nothing (#2829 review).
pub(super) fn readable_page(bytes: Vec<u8>) -> Result<Vec<u8>, String> {
    match image_dimensions_of(&bytes) {
        Some(_) => Ok(bytes),
        None => Err(String::from("the rendered page could not be read")),
    }
}

impl PdfJobs {
    /// Whether any of a PDF's work is still running.
    pub fn busy(&self) -> bool {
        self.render.is_some()
            || self.count.is_some()
            || self.links.is_some()
            || self.reload.is_some()
    }

    /// Whether a rebuild on disk is being rendered.
    pub fn reloading(&self) -> bool {
        self.reload.is_some()
    }

    /// Whether a page is being rendered.
    pub fn rendering(&self) -> bool {
        self.render.is_some()
    }

    /// The page being rendered now, for a test.
    #[cfg(test)]
    pub fn rendering_page(&self) -> Option<u32> {
        self.render.as_ref().map(|(page, _)| *page)
    }
}

/// The background the image/sheet/diff canvases fill with. On iTerm2,
/// `Reset` inherits the session bg that `SetColors` re-tints per theme, so
/// the canvas matches the surrounding panes for free. Every other host
/// (Ghostty, Kitty, sixel) ignores `SetColors`, so `Reset` falls through to
/// the terminal's own background — and the frame prefill cannot save it,
/// because these fills override the prefill (ratatui applies any `Some`
/// bg, and `Some(Reset)` is `Some`). Those hosts paint the theme bg
/// explicitly instead, or a CSV/PDF/diff tab sits as a host-black island
/// inside an otherwise themed frame.
pub(super) fn canvas_bg(host_is_iterm2: bool, theme: crate::theme::Theme) -> Color {
    if host_is_iterm2 {
        Color::Reset
    } else {
        theme.editor_bg()
    }
}

/// The background the image/PDF canvas fills with — a separate choice from
/// [`canvas_bg`] because the picture is an inline image the canvas must not
/// occlude. Kitty places the preview at `KITTY_Z_BELOW_TEXT_AND_BG` and
/// draws any cell with a non-default background OVER an image that deep, so
/// the canvas has to keep the DEFAULT background there; iTerm2 keeps
/// `Reset` for the [`canvas_bg`] reason (the `SetColors` session bg).
/// Neither host shows an untinted island while a picture is up: the bake
/// letterboxes with the theme bg pixel, covering every canvas cell. Sixel
/// blits into the cell buffer over the canvas, and a no-graphics host shows
/// only the placeholder, so both keep the themed fill.
pub(super) fn image_canvas_bg(
    protocol: crate::iterm2_inline::InlineImageProtocol,
    theme: crate::theme::Theme,
) -> Color {
    use crate::iterm2_inline::InlineImageProtocol;
    match protocol {
        InlineImageProtocol::ITerm2 | InlineImageProtocol::Kitty => Color::Reset,
        InlineImageProtocol::Sixel | InlineImageProtocol::None => theme.editor_bg(),
    }
}

pub(super) fn render_image_placeholder(
    image: &ImageView,
    rendering: bool,
    path: Option<&Path>,
    inner: Rect,
    buf: &mut Buffer,
    bg: Color,
    theme: crate::theme::Theme,
) {
    // Solid bg fill so the OSC-1337 inline image (emitted post-frame on
    // capable terminals) sits on a clean canvas; on non-capable terminals
    // the metadata header below is the only content the user sees.
    let bg_style = Style::default().bg(bg);
    for y in inner.y..inner.y + inner.height {
        for x in inner.x..inner.x + inner.width {
            buf[(x, y)].set_style(bg_style);
            buf[(x, y)].set_symbol(" ");
        }
    }
    let name = path
        .and_then(|p| p.file_name())
        .map(|n| n.to_string_lossy().into_owned())
        .unwrap_or_else(|| String::from("(unnamed image)"));
    let header = if let Some(pdf) = image.pdf.as_ref() {
        let page_label = match pdf.page_count {
            Some(total) => format!("page {} / {}", pdf.current_page, total),
            None => format!("page {}", pdf.current_page),
        };
        // Nothing on screen yet (#2827): the first page renders on a job,
        // and the status line says why when it fails.
        let size = if image.bytes.is_empty() {
            String::from(if rendering {
                "rendering…"
            } else {
                "not rendered"
            })
        } else {
            format!("{}×{}", image.pixel_w, image.pixel_h)
        };
        format!(
            " {} · {} · {} · {} · PDF (← / → to flip) ",
            name,
            page_label,
            size,
            format_bytes_human(pdf.source_byte_size),
        )
    } else {
        let size = match &image.natural_size {
            Some(size) => size.clone(),
            None => format!("{}×{}", image.pixel_w, image.pixel_h),
        };
        format!(
            " {} · {} · {} · {} ",
            name,
            size,
            format_bytes_human(image.byte_size),
            image.format_label,
        )
    };
    buf.set_string(
        inner.x,
        inner.y,
        &header,
        Style::default()
            .fg(Color::White)
            .bg(theme.ui(Color::Rgb(0x09, 0x4d, 0x77)))
            .add_modifier(Modifier::BOLD),
    );
}

/// A CSS-pixel size for the image header: each length whole when it is
/// (nearly) whole, else to one decimal, so `10mm` reads `37.8` rather than
/// `37.795277`.
pub(super) fn css_px_size((w, h): (f32, f32)) -> String {
    let px = |v: f32| {
        let tenths = (v * 10.0).round();
        if tenths % 10.0 == 0.0 {
            format!("{}", tenths / 10.0)
        } else {
            format!("{:.1}", tenths / 10.0)
        }
    };
    format!("{}×{}", px(w), px(h))
}

/// Half-block cells as `(columns, rows, (upper, lower) colours)`.
pub(super) type HalfBlocks = (u16, u16, Vec<(Color, Color)>);

/// Decode `bytes` and shrink the picture to fit `cols` × `rows` cells, two
/// pixels a cell, keeping its shape (a cell is about twice as tall as it is
/// wide, so a half cell is square) and never enlarging it. Transparency is
/// blended over `bg`. `None` for bytes the decoder refuses or an empty
/// area. Returns the cells' `(columns, rows, (upper, lower) colours)`.
pub(super) fn halfblock_cells(bytes: &[u8], cols: u16, rows: u16, bg: Color) -> Option<HalfBlocks> {
    if cols == 0 || rows == 0 {
        return None;
    }
    // The header is cheap and the decode is not: a small compressed file can
    // declare a canvas that decodes to gigabytes. The same budget the
    // inline-image bake enforces (#1160), checked before the decode.
    let (dw, dh) = image_dimensions_of(bytes)?;
    if u64::from(dw) * u64::from(dh) > crate::iterm2_inline::MAX_DECODE_PIXELS {
        return None;
    }
    #[cfg(test)]
    HALFBLOCK_DECODES.with(|c| c.set(c.get() + 1));
    let img = image::load_from_memory(bytes).ok()?.to_rgba8();
    let (iw, ih) = img.dimensions();
    if iw == 0 || ih == 0 {
        return None;
    }
    let (max_w, max_h) = (u32::from(cols), u32::from(rows) * 2);
    let scale = (f64::from(max_w) / f64::from(iw))
        .min(f64::from(max_h) / f64::from(ih))
        .min(1.0);
    let w = ((f64::from(iw) * scale).round() as u32).clamp(1, max_w);
    let h = ((f64::from(ih) * scale).round() as u32).clamp(1, max_h);
    let small = if (w, h) == (iw, ih) {
        img
    } else {
        image::imageops::resize(&img, w, h, image::imageops::FilterType::Triangle)
    };
    let (br, bg_g, bb) = match bg {
        Color::Rgb(r, g, b) => (r, g, b),
        _ => (0, 0, 0),
    };
    let blend = |p: &image::Rgba<u8>| {
        let a = u16::from(p[3]);
        let mix =
            |c: u8, under: u8| ((u16::from(c) * a + u16::from(under) * (255 - a)) / 255) as u8;
        Color::Rgb(mix(p[0], br), mix(p[1], bg_g), mix(p[2], bb))
    };
    let cell_rows = h.div_ceil(2);
    let mut cells = Vec::with_capacity((w * cell_rows) as usize);
    for r in 0..cell_rows {
        for x in 0..w {
            let upper = blend(small.get_pixel(x, 2 * r));
            let lower = if 2 * r + 1 < h {
                blend(small.get_pixel(x, 2 * r + 1))
            } else {
                Color::Rgb(br, bg_g, bb)
            };
            cells.push((upper, lower));
        }
    }
    Some((w as u16, cell_rows as u16, cells))
}

/// Paint `picture` centred in `area`.
pub(super) fn paint_cell_image(picture: &CellImage, area: Rect, buf: &mut Buffer) {
    let x0 = area.x + area.width.saturating_sub(picture.cols) / 2;
    let y0 = area.y + area.height.saturating_sub(picture.rows) / 2;
    for r in 0..picture.rows.min(area.height) {
        for c in 0..picture.cols.min(area.width) {
            let (upper, lower) =
                picture.cells[usize::from(r) * usize::from(picture.cols) + usize::from(c)];
            let cell = &mut buf[(x0 + c, y0 + r)];
            cell.set_symbol("\u{2580}");
            cell.set_style(Style::default().fg(upper).bg(lower));
        }
    }
}

/// Paint a rendered ANSI log tab (#257): one buffer line per file line, with
/// SGR spans resolved through the theme palette. Mutates the view because the
/// window is refilled around the viewport — the file is never held whole.
#[allow(clippy::too_many_arguments)]
pub(super) fn render_log(
    view: &mut crate::log_view::LogView,
    path: Option<&Path>,
    inner: Rect,
    buf: &mut Buffer,
    bg: Color,
    theme: crate::theme::Theme,
    scroll: usize,
    search: Option<(&str, crate::search::SearchOpts)>,
    active: Option<(usize, usize, usize)>,
) {
    let bg_style = Style::default().bg(bg);
    for y in inner.y..inner.y + inner.height {
        for x in inner.x..inner.x + inner.width {
            buf[(x, y)].set_style(bg_style);
            buf[(x, y)].set_symbol(" ");
        }
    }
    if inner.height == 0 || inner.width == 0 {
        // Frame truth cuts both ways: a frame that paints nothing must
        // publish nothing. Returning with the previous rect still stored let
        // the mouse path accept a click in an area this frame did not paint,
        // after a resize or a layout change.
        view.last_body = Rect::default();
        return;
    }
    let name = path
        .and_then(|p| p.file_name())
        .map(|n| n.to_string_lossy().into_owned())
        .unwrap_or_else(|| String::from("log"));
    let truncated = view.truncated;
    let total = view.len();
    // While the background pass runs the count is a lower bound (#394); the
    // header says so rather than presenting a moving number as a total.
    let header = if truncated {
        format!(" {name} — rendered log, {total} lines shown (file truncated at the index cap) ")
    } else if view.indexing() {
        format!(" {name} — rendered log, {total} lines so far, indexing… ")
    } else {
        format!(" {name} — rendered log, {total} lines ")
    };
    let head_style = Style::default()
        .fg(Color::White)
        .bg(theme.ui(Color::Rgb(0x09, 0x4d, 0x77)));
    buf.set_stringn(
        inner.x,
        inner.y,
        format!("{header:width$}", width = inner.width as usize),
        inner.width as usize,
        head_style,
    );
    let body_top = inner.y + 1;
    let rows = inner.height.saturating_sub(1) as usize;
    if rows == 0 {
        view.last_body = Rect::default();
        return;
    }
    // Frame truth: the mouse path reads the body rect this frame painted,
    // rather than recomputing the header offset in a second place.
    view.last_body = Rect {
        x: inner.x,
        y: body_top,
        width: inner.width,
        height: rows as u16,
    };
    let selection = view.ordered_selection_public();
    // Refill the window around the viewport: one bounded read per scroll.
    let _ = view.ensure(scroll, rows);
    // Where each character lands, by display width: a CJK pair is four
    // cells, and the span after it starts on the fifth (#404). Advancing
    // by `chars().count()` put it on the third, over the pair's second
    // half, and the drift grew with every wide character on the line. One
    // map, refilled per row, so the redraw path allocates nothing.
    let mut cells = crate::cell_map::CellMap::default();
    let right = inner.x + inner.width;
    for r in 0..rows {
        let idx = scroll + r;
        let Some(line) = view.line(idx) else { break };
        let y = body_top + r as u16;
        cells.build_into(&line.text);
        for span in &line.spans {
            let x = inner.x.saturating_add(cells.cell_of_byte(span.start));
            if x >= right {
                break;
            }
            let text = &line.text[span.start..span.end];
            let mut style = Style::default().bg(bg);
            let (fg, sbg) = if span.style.inverse {
                // Swap against the theme's default pair, which the parser
                // deliberately does not know.
                (span.style.bg, span.style.fg)
            } else {
                (span.style.fg, span.style.bg)
            };
            if let Some(c) = fg {
                style = style.fg(ansi_color_to_tui(c, theme));
            } else if span.style.inverse {
                style = style.fg(bg);
            }
            if let Some(c) = sbg {
                style = style.bg(ansi_color_to_tui(c, theme));
            }
            if span.style.bold {
                style = style.add_modifier(Modifier::BOLD);
            }
            if span.style.dim {
                style = style.add_modifier(Modifier::DIM);
            }
            if span.style.italic {
                style = style.add_modifier(Modifier::ITALIC);
            }
            if span.style.underline {
                style = style.add_modifier(Modifier::UNDERLINED);
            }
            if span.style.strikeout {
                style = style.add_modifier(Modifier::CROSSED_OUT);
            }
            let room = right.saturating_sub(x) as usize;
            buf.set_stringn(x, y, text, room, style);
        }
        // Selection goes under the find highlight and over the log's own
        // colours: it is the coarser mark, and a match inside a selection
        // should still read as the match.
        if let Some(((sr, sc), (er, ec))) =
            selection.filter(|((sr, _), (er, _))| idx >= *sr && idx <= *er)
        {
            {
                let from = if idx == sr { sc } else { 0 };
                let to = if idx == er {
                    ec
                } else {
                    line.text.chars().count()
                };
                for c in from..to {
                    if !paint_log_cells(buf, inner.x, right, y, &cells, c, |s| {
                        s.bg(theme.selection())
                    }) {
                        break;
                    }
                }
            }
        }
        // Find highlight goes over the painted colours, keyed off the same
        // stripped text the search ran on, so the columns line up with what
        // the spans put on screen (#257).
        if let Some((needle, opts)) = search {
            let active_on_line = active.filter(|(r, _, _)| *r == idx).map(|(_, c, l)| (c, l));
            paint_search_highlight(
                buf,
                inner.x,
                y,
                inner.width,
                &line.text,
                needle,
                opts,
                &RowCells::default(),
                active_on_line,
                Some(&cells),
                None,
                theme,
            );
        }
    }
}

/// Restyle every cell character `col` occupies on a rendered log row, using
/// the same cell map the painter used so a band lands on the character it
/// names rather than on its character index. `restyle` is given the cell's
/// current style. Returns false once the row's right edge is reached, so a
/// caller walking columns can stop.
pub(super) fn paint_log_cells(
    buf: &mut Buffer,
    left: u16,
    right: u16,
    y: u16,
    cells: &crate::cell_map::CellMap,
    col: usize,
    restyle: impl Fn(Style) -> Style,
) -> bool {
    let first = left.saturating_add(cells.cell_of_char(col));
    let width = cells.width_of_char(col);
    // A character that does not fit WHOLE is one `set_stringn` dropped
    // entirely, so a band on its first half would colour a cell the painter
    // deliberately left blank: the same painter/annotator disagreement this
    // module exists to close, at the boundary.
    if first >= right || first.saturating_add(width) > right {
        return false;
    }
    for x in first..first + width {
        let cell = &mut buf[(x, y)];
        cell.set_style(restyle(cell.style()));
    }
    true
}

/// Paint a hex tab (#172): header row, `offset  hex  |ascii|` body rows,
/// and a status row with the cursor offset. Mutates the view: the window
/// is refilled around the viewport, and the chosen bytes-per-row plus the
/// frame's layout are written back for navigation and mouse hit-testing
/// (frame truth, the `last_wrap_rows` pattern).
pub(super) fn render_hex(
    view: &mut crate::hex::HexView,
    path: Option<&Path>,
    inner: Rect,
    buf: &mut Buffer,
    bg: Color,
    theme: crate::theme::Theme,
) {
    let bg_style = Style::default().bg(bg);
    for y in inner.y..inner.y + inner.height {
        for x in inner.x..inner.x + inner.width {
            buf[(x, y)].set_style(bg_style);
            buf[(x, y)].set_symbol(" ");
        }
    }
    // Zero-size guard AFTER the layout reset below would leave stale hit
    // rects; clear them first (the #103 frame-truth invariant).
    view.layout = crate::hex::HexLayout::default();
    if inner.height == 0 || inner.width == 0 {
        return;
    }
    let offw = view.offset_digits() as u16;
    // Narrowest workable layout: lead + offset + gap + 8 hex cells
    // (3/byte minus the trailing space) + gap + 8 ascii cells. Below it
    // the per-cell clip would paint offsets with no bytes — a half-drawn
    // grid — so a too-narrow split shows a deliberate empty state (the
    // clamped header only) instead.
    let need8 = 1 + offw + 2 + (8 * 3 - 1) + 2 + 8;
    let name = path
        .and_then(|p| p.file_name())
        .map(|n| n.to_string_lossy().into_owned())
        .unwrap_or_else(|| String::from("(unnamed)"));
    let header = format!(" {} · HEX · {} bytes ", name, view.file_len);
    buf.set_stringn(
        inner.x,
        inner.y,
        &header,
        inner.width as usize,
        Style::default()
            .fg(Color::White)
            .bg(theme.ui(Color::Rgb(0x09, 0x4d, 0x77)))
            .add_modifier(Modifier::BOLD),
    );
    if inner.height < 3 || inner.width < need8 {
        return;
    }

    // lead + offset + gap + hex cells (3/byte minus the trailing space)
    // + mid-group gap + gap + ascii gutter
    let need16 = 1 + offw + 2 + (16 * 3 - 1) + 1 + 2 + 16;
    let bpr: u64 = if inner.width >= need16 { 16 } else { 8 };
    view.bytes_per_row = bpr;

    let data_top = inner.y + 1;
    let data_rows = inner.height - 2; // header + status row
    // Clamp the scroll to the new geometry and make the span resident
    // (a delta of zero only clamps + refills).
    view.scroll_by(0, data_rows as usize);

    let hex_x = inner.x + 1 + offw + 2;
    let mid_gap: u16 = if bpr == 16 { 1 } else { 0 };
    let ascii_x = hex_x + (bpr as u16) * 3 - 1 + mid_gap + 2;
    view.layout = crate::hex::HexLayout {
        data_top,
        data_rows,
        hex_x,
        ascii_x,
    };

    let sel = view.selection();
    let dim = Style::default().fg(Color::DarkGray).bg(bg);
    for r in 0..data_rows {
        let row = view.top_row + r as u64;
        if row >= view.total_rows() {
            break;
        }
        let y = data_top + r;
        let base = row * bpr;
        buf.set_string(
            inner.x + 1,
            y,
            format!("{base:0w$X}", w = offw as usize),
            dim,
        );
        for i in 0..bpr {
            let off = base + i;
            if off >= view.file_len {
                break;
            }
            let x = hex_x + (i as u16) * 3 + if i >= 8 { mid_gap } else { 0 };
            let ax = ascii_x + i as u16;
            if ax >= inner.x + inner.width || x + 1 >= inner.x + inner.width {
                break;
            }
            let edited = view.edits.contains_key(&off);
            let (mut hex_s, ascii_ch, byte_dim) = match view.effective_byte(off) {
                Some(v) => (
                    format!("{v:02X}"),
                    if (0x20..0x7f).contains(&v) {
                        (v as char).to_string()
                    } else {
                        String::from("·")
                    },
                    v == 0 && !edited,
                ),
                // Not resident (an IO error mid-scroll): an honest blank,
                // never a stale byte.
                None => (String::from("··"), String::from("·"), true),
            };
            let selected = sel.map(|(a, b)| off >= a && off < b).unwrap_or(false);
            let is_cursor = off == view.cursor;
            // A half-typed byte shows its high nibble in place (#173).
            if is_cursor
                && !view.ascii_focus
                && let Some(n) = view.pending_nibble
            {
                hex_s = format!("{n:X}·");
            }
            // The focused pane's cursor is the accent block; its mirror
            // in the other pane is a dim block so the pairing stays
            // visible without stealing focus.
            let cursor_style = Style::default()
                .fg(theme.accent_contrast_fg())
                .bg(theme.accent());
            let mirror_style = Style::default().fg(Color::White).bg(Color::DarkGray);
            let edited_style = Style::default()
                .fg(theme.ui(Color::Rgb(0xe0, 0x9a, 0x4e)))
                .bg(bg)
                .add_modifier(Modifier::BOLD);
            // A high contrast theme's selection may be pale (High Contrast
            // Light, #1548): its pure foreground keeps selected bytes legible.
            let selected_fg = if theme.high_contrast() {
                theme.ui(Color::White)
            } else {
                Color::White
            };
            let base_style = if selected {
                Style::default().fg(selected_fg).bg(theme.selection())
            } else if edited {
                edited_style
            } else if byte_dim {
                dim
            } else {
                Style::default().fg(theme.ui(Color::Gray)).bg(bg)
            };
            let (hex_style, ascii_style) = if is_cursor {
                if view.ascii_focus {
                    (mirror_style, cursor_style)
                } else {
                    (cursor_style, mirror_style)
                }
            } else {
                (base_style, base_style)
            };
            buf.set_string(x, y, &hex_s, hex_style);
            buf.set_string(ax, y, &ascii_ch, ascii_style);
        }
    }
    let status = format!(" {} ", view.status_line());
    buf.set_stringn(
        inner.x,
        inner.y + inner.height - 1,
        &status,
        inner.width as usize,
        Style::default()
            .fg(theme.ui(Color::Gray))
            .bg(theme.ui(Color::Rgb(0x07, 0x33, 0x55))),
    );
}

/// Paint an archive browser tab (#179): header, member rows (selected
/// highlighted, sizes right-aligned), and a hint row. Frame truth for
/// the row band is written back for mouse hit-testing.
pub(super) fn render_archive(
    view: &mut crate::archive::ArchiveView,
    path: Option<&Path>,
    inner: Rect,
    buf: &mut Buffer,
    bg: Color,
    theme: crate::theme::Theme,
) {
    let bg_style = Style::default().bg(bg);
    for y in inner.y..inner.y + inner.height {
        for x in inner.x..inner.x + inner.width {
            buf[(x, y)].set_style(bg_style);
            buf[(x, y)].set_symbol(" ");
        }
    }
    view.rows_top = 0;
    view.rows_visible = 0;
    if inner.height < 4 || inner.width < 20 {
        return;
    }
    let name = path
        .and_then(|p| p.file_name())
        .map(|n| n.to_string_lossy().into_owned())
        .unwrap_or_else(|| String::from("(archive)"));
    let header = format!(
        " {} · {} · {} members · {} bytes ",
        name,
        view.kind.label(),
        view.entries.len(),
        view.source_byte_size
    );
    buf.set_stringn(
        inner.x,
        inner.y,
        &header,
        inner.width as usize,
        Style::default()
            .fg(Color::White)
            .bg(theme.ui(Color::Rgb(0x09, 0x4d, 0x77)))
            .add_modifier(Modifier::BOLD),
    );
    let rows_top = inner.y + 1;
    let rows = inner.height - 2;
    view.rows_top = rows_top;
    view.rows_visible = rows;
    // Keep the selection visible.
    if view.selected < view.scroll {
        view.scroll = view.selected;
    } else if view.selected >= view.scroll + rows as usize {
        view.scroll = view.selected + 1 - rows as usize;
    }
    for r in 0..rows as usize {
        let idx = view.scroll + r;
        let Some(entry) = view.entries.get(idx) else {
            break;
        };
        let y = rows_top + r as u16;
        let marker = if entry.dir { "▸ " } else { "  " };
        let size = if entry.dir {
            String::new()
        } else {
            format!("{} ", entry.size)
        };
        let style = if idx == view.selected {
            Style::default()
                .fg(theme.accent_contrast_fg())
                .bg(theme.accent())
        } else if entry.dir {
            Style::default().fg(Color::DarkGray).bg(bg)
        } else {
            Style::default().fg(theme.ui(Color::Gray)).bg(bg)
        };
        let name_w = (inner.width as usize).saturating_sub(size.len() + 3);
        let line = format!(" {marker}{:<name_w$}{size}", entry.path, name_w = name_w);
        buf.set_stringn(inner.x, y, &line, inner.width as usize, style);
    }
    let hint = " Enter: open member · E: extract member to a folder ";
    buf.set_stringn(
        inner.x,
        inner.y + inner.height - 1,
        hint,
        inner.width as usize,
        Style::default()
            .fg(theme.ui(Color::Gray))
            .bg(theme.ui(Color::Rgb(0x07, 0x33, 0x55))),
    );
}

pub(super) fn render_sheet(
    view: &mut crate::sheet::SheetView,
    path: Option<&Path>,
    inner: Rect,
    buf: &mut Buffer,
    bg: Color,
    theme: crate::theme::Theme,
) {
    // Frame truth: reset before any early return so stale geometry can
    // never serve a mouse hit-test.
    view.grid = crate::sheet::SheetGridLayout::default();
    let editing = view.editing.clone();
    let dirty = view.dirty;
    // Bg fill so the spreadsheet sits on a clean canvas regardless of
    // what the previous tab left behind (see [`canvas_bg`]).
    let bg_style = Style::default().bg(bg);
    for y in inner.y..inner.y + inner.height {
        for x in inner.x..inner.x + inner.width {
            buf[(x, y)].set_style(bg_style);
            buf[(x, y)].set_symbol(" ");
        }
    }
    if inner.height < 3 || inner.width < 8 {
        return;
    }
    let name = path
        .and_then(|p| p.file_name())
        .map(|n| n.to_string_lossy().into_owned())
        .unwrap_or_else(|| String::from("(unnamed sheet)"));
    let sheet = match view.sheets.get(view.current_sheet) {
        Some(s) => s,
        None => return,
    };
    let row_count = sheet.row_count();
    let col_count = sheet.col_count();
    let header = format!(
        " {} · {} · sheet {}/{} ({}) · {} rows × {} cols{} ",
        name,
        view.kind.label(),
        view.current_sheet + 1,
        view.sheets.len(),
        sheet.name,
        row_count,
        col_count,
        if dirty { " · edited (Cmd+S)" } else { "" },
    );
    buf.set_string(
        inner.x,
        inner.y,
        &header,
        Style::default()
            .fg(Color::White)
            .bg(theme.ui(Color::Rgb(0x09, 0x4d, 0x77)))
            .add_modifier(Modifier::BOLD),
    );

    let grid_top = inner.y + 1;
    let grid_height = inner.height.saturating_sub(2); // header + status row
    let grid_w = inner.width;
    if grid_height < 2 || col_count == 0 {
        return;
    }

    // Reserve a row-number gutter so the user can see the absolute row
    // index even after horizontal scrolling.
    let gutter_w = ((sheet.row_base + row_count).max(1).to_string().len() as u16 + 2).max(4);
    if grid_w <= gutter_w + 2 {
        return;
    }
    let body_x = inner.x + gutter_w;
    let body_w = grid_w - gutter_w;

    let header_y = grid_top;
    let data_top = grid_top + 1;
    let data_rows = grid_height.saturating_sub(1) as usize;

    // Header row backdrop.
    let head_style = Style::default()
        .fg(Color::White)
        .bg(theme.ui(Color::Rgb(0x07, 0x33, 0x55)))
        .add_modifier(Modifier::BOLD);
    for x in inner.x..inner.x + inner.width {
        buf[(x, header_y)].set_style(head_style);
        buf[(x, header_y)].set_symbol(" ");
    }

    // Lay out visible columns from `scroll_col` rightwards until we run
    // out of horizontal space: (col_idx, x_offset, drawn width).
    let visible = crate::sheet::visible_columns(&sheet.col_widths, sheet.scroll_col, body_w);

    // Header text.
    for &(c, x_off, w) in &visible {
        let label = sheet.headers.get(c).map(|s| s.as_str()).unwrap_or("");
        let cell_x = body_x + x_off;
        write_cell(buf, cell_x, header_y, w, label, head_style);
    }

    // Data rows.
    let row_end = (sheet.scroll_row + data_rows).min(row_count);
    // Base rows wear the canvas bg (see [`canvas_bg`]); alternating rows
    // keep an explicit lift for the zebra stripe.
    let row_style = Style::default().fg(Color::White).bg(bg);
    let alt_row_style = Style::default()
        .fg(Color::White)
        .bg(theme.ui(Color::Rgb(0x24, 0x29, 0x37)));
    let gutter_style = Style::default().fg(Color::DarkGray);
    for (display_row, row_idx) in (sheet.scroll_row..row_end).enumerate() {
        let y = data_top + display_row as u16;
        let style = if display_row % 2 == 0 {
            row_style
        } else {
            alt_row_style
        };
        for x in inner.x..inner.x + inner.width {
            buf[(x, y)].set_style(style);
            buf[(x, y)].set_symbol(" ");
        }
        // Numbered by place in the source (#1222): a SQLite page's rows
        // continue from the pages before it.
        let row_label = format!(
            " {:>width$} ",
            sheet.row_base + row_idx + 1,
            width = (gutter_w - 2) as usize
        );
        buf.set_string(
            inner.x,
            y,
            &row_label,
            gutter_style.bg(style.bg.unwrap_or(Color::Reset)),
        );
        let row = &sheet.rows[row_idx];
        for (c, x_off, w) in &visible {
            let w = *w;
            let cell_text = row.get(*c).map(|s| s.as_str()).unwrap_or("");
            let is_cursor = row_idx == sheet.cur_row && *c == sheet.cur_col;
            if is_cursor {
                if let Some(edit) = editing.as_ref() {
                    // In-grid editor (#177): show the tail that keeps the
                    // caret visible, caret cell reversed. The window is
                    // measured in screen columns (#1138), whole graphemes
                    // dropped from the left until what is before the caret
                    // fits with a column left for the caret itself.
                    use unicode_segmentation::UnicodeSegmentation;
                    let avail = w as usize;
                    let before = &edit.value[..edit.cursor];
                    let mut caret_cells = crate::sheet::text_width(before);
                    let mut start = 0;
                    let mut dropped = before.grapheme_indices(true);
                    while caret_cells + 1 > avail {
                        let Some((i, g)) = dropped.next() else {
                            break;
                        };
                        caret_cells -= crate::sheet::grapheme_width(g);
                        start = i + g.len();
                    }
                    let shown = &edit.value[start..];
                    let edit_style = Style::default()
                        .fg(theme.accent_contrast_fg())
                        .bg(theme.accent());
                    write_cell(buf, body_x + *x_off, y, w, shown, edit_style);
                    let caret_cells = caret_cells.min(u16::MAX as usize) as u16;
                    let cx = body_x + *x_off + caret_cells.min(w.saturating_sub(1));
                    buf[(cx, y)].set_style(
                        Style::default()
                            .fg(theme.accent())
                            .bg(Color::Black)
                            .add_modifier(Modifier::BOLD),
                    );
                } else {
                    let cursor_style = Style::default()
                        .fg(theme.accent_contrast_fg())
                        .bg(theme.accent())
                        .add_modifier(Modifier::BOLD);
                    if sheet.null_cells.contains(&(row_idx, *c)) {
                        let null_style = cursor_style.add_modifier(Modifier::ITALIC);
                        let null = crate::sqlite_view::NULL_LABEL;
                        write_cell(buf, body_x + *x_off, y, w, null, null_style);
                    } else {
                        write_cell(buf, body_x + *x_off, y, w, cell_text, cursor_style);
                    }
                }
            } else if sheet.null_cells.contains(&(row_idx, *c)) {
                // SQL NULL (#1002): dimmed, so it reads apart from `''`.
                let null_style = style.fg(Color::DarkGray).add_modifier(Modifier::ITALIC);
                let null = crate::sqlite_view::NULL_LABEL;
                write_cell(buf, body_x + *x_off, y, w, null, null_style);
            } else {
                write_cell(buf, body_x + *x_off, y, w, cell_text, style);
            }
        }
    }
    view.grid = crate::sheet::SheetGridLayout {
        data_top,
        data_rows: data_rows as u16,
        body_x,
        body_w,
    };

    // Status row at the bottom showing scroll position + nav hint.
    let status_y = inner.y + inner.height - 1;
    let visible_first = sheet.scroll_row + 1;
    let visible_last = (sheet.scroll_row + data_rows).min(row_count);
    let visible_col_first = sheet.scroll_col + 1;
    let visible_col_last = visible
        .last()
        .map(|(c, _, _)| *c + 1)
        .unwrap_or(visible_col_first);
    // A SQLite page names its rows by place in the table, with no total:
    // nobody counted the table (#1222), and the sheet name says whether
    // more rows follow.
    let rows = if view.kind == crate::sheet::SheetKind::Sqlite {
        let base = sheet.row_base;
        format!("rows {}–{}", base + visible_first, base + visible_last)
    } else {
        format!("rows {visible_first}–{visible_last} of {row_count}")
    };
    let status = format!(
        " {rows} · cols {visible_col_first}–{visible_col_last} of {col_count} · ←/→ ↑/↓ PgUp/PgDn Tab=next sheet "
    );
    buf.set_string(
        inner.x,
        status_y,
        &status,
        Style::default()
            .fg(theme.ui(Color::Gray))
            .bg(theme.ui(Color::Rgb(0x14, 0x18, 0x22))),
    );
}

pub(crate) fn format_bytes_human(n: u64) -> String {
    const KB: u64 = 1024;
    const MB: u64 = KB * 1024;
    if n >= MB {
        format!("{:.1} MB", n as f64 / MB as f64)
    } else if n >= KB {
        format!("{:.1} KB", n as f64 / KB as f64)
    } else {
        format!("{n} B")
    }
}

pub fn extension_is_image(ext: &str) -> bool {
    let lc = ext.to_ascii_lowercase();
    IMAGE_EXTENSIONS.iter().any(|e| *e == lc)
}

pub fn extension_is_pdf(ext: &str) -> bool {
    ext.eq_ignore_ascii_case("pdf")
}

pub fn image_format_label_from_ext(ext: &str) -> String {
    match ext.to_ascii_lowercase().as_str() {
        "jpg" | "jpeg" => "JPEG".to_string(),
        "tif" | "tiff" => "TIFF".to_string(),
        other => other.to_ascii_uppercase(),
    }
}

/// The delimiter a CSV or TSV grid was read and is written with.
pub(super) fn sheet_delim(kind: crate::sheet::SheetKind) -> u8 {
    match kind {
        crate::sheet::SheetKind::Tsv => b'\t',
        _ => b',',
    }
}

impl Editor {
    /// Drop every view this tab could be showing other than its text: the
    /// diff and merge views with their hunk-arrow rects, the image or PDF,
    /// the sheet, hex, log and archive views, the Markdown, document or
    /// media preview, and the PR review, fleet and SARIF views.
    ///
    /// Every file opener calls this before installing its own view, so a
    /// tab reused for another file (the preview tab) keeps nothing of what
    /// it showed before. The render and the key dispatch each pick the first
    /// view that is set, so a leftover one paints over the new file or takes
    /// its keys: a diff reopened as a preview kept its clickable hunk arrows
    /// (#187), a stale log kept painting over "Reopen as Hex", and a
    /// document preview kept the keys of the image, PDF or sheet opened after
    /// it (#2069).
    pub(super) fn clear_viewers(&mut self) {
        self.diff = None;
        self.merge = None;
        self.diff_prev_arrow = Rect::default();
        self.diff_next_arrow = Rect::default();
        self.image = None;
        self.sheet = None;
        self.hex = None;
        self.log = None;
        self.archive = None;
        self.markdown_preview = None;
        self.pr_review = None;
        self.fleet = None;
        self.sarif = None;
        // A page or links landing after the tab moved on are not its.
        self.pdf_jobs = PdfJobs::default();
    }

    /// Turn this tab into a viewer of `path`, whose text side is an empty
    /// stub: drop the text, its history, its language and the place in it,
    /// and clear every other view ([`Self::clear_viewers`]), so nothing of
    /// what the tab showed before survives into the new view. `disk_stamp`
    /// is what a later check for changes on disk compares against. The
    /// caller then fills its own view and status line.
    pub(super) fn become_viewer(
        &mut self,
        path: &Path,
        disk_stamp: Option<(std::time::SystemTime, u64)>,
    ) {
        self.path = Some(path.to_path_buf());
        self.disk_stamp = disk_stamp;
        // A viewer shows a file that exists: whatever the tab expected of a
        // file not yet created no longer applies.
        self.disk_expect_absent = false;
        self.disk_conflict = false;
        // A whole-buffer swap: whatever the previous contents could not be
        // encoded as is no longer this tab's problem.
        self.encoding_loss = false;
        self.lossy_save_armed = false;
        self.lines = vec![String::new()];
        // The map described the text this swap replaced (#349); a viewer's
        // placeholder line was written by no seat, and a save from the
        // viewer must not persist the old map against the new bytes.
        self.provenance = crate::provenance::Provenance::new();
        // Caches memoised on edit_seq (conflicts, git marks) must not
        // survive into this tab.
        self.edit_seq = self.edit_seq.wrapping_add(1);
        self.lang = None;
        self.language_by_hand = false;
        self.scroll = 0;
        self.cursor_row = 0;
        self.cursor_col = 0;
        self.dirty = false;
        self.selection = None;
        self.undo_stack.clear();
        self.redo_stack.clear();
        self.last_edit_kind = None;
        self.highlights = vec![Vec::new()];
        self.clear_viewers();
    }

    /// The view slots this tab has filled, by name: the viewers that stand
    /// in for its text and the two layers drawn over it (a merge, a Markdown
    /// preview). A tab shows one at most; two is the state #2069 was, where
    /// keys went to a document preview hidden under the image opened after
    /// it. Test builds check every tab after every key, click and paste
    /// (`App::assert_one_view_per_tab`).
    #[cfg(test)]
    pub(crate) fn views_filled(&self) -> Vec<&'static str> {
        [
            ("diff", self.diff.is_some()),
            ("merge", self.merge.is_some()),
            ("image", self.image.is_some()),
            ("sheet", self.sheet.is_some()),
            ("hex", self.hex.is_some()),
            ("log", self.log.is_some()),
            ("archive", self.archive.is_some()),
            ("markdown preview", self.markdown_preview.is_some()),
            ("PR review", self.pr_review.is_some()),
            ("fleet", self.fleet.is_some()),
            ("SARIF", self.sarif.is_some()),
        ]
        .into_iter()
        .filter_map(|(name, filled)| filled.then_some(name))
        .collect()
    }

    pub(super) fn open_image(&mut self, path: &Path) -> Result<()> {
        let meta = std::fs::metadata(path)?;
        if meta.len() > MAX_IMAGE_BYTES {
            anyhow::bail!("Image too large ({} bytes)", meta.len());
        }
        let bytes = std::fs::read(path)?;
        let (pixel_w, pixel_h) = image_dimensions_of(&bytes).ok_or_else(|| {
            refused(
                Refusal::NotItsFormat,
                String::from("Could not decode image"),
            )
        })?;
        let ext = path.extension().and_then(|e| e.to_str()).unwrap_or("");
        let format_label = image_format_label_from_ext(ext);
        self.become_viewer(path, Self::disk_stamp_of(path));
        self.image = Some(ImageView {
            bytes,
            format_label,
            pixel_w,
            pixel_h,
            natural_size: None,
            byte_size: meta.len(),
            generation: next_image_generation(),
            pdf: None,
        });
        self.status = format!("Opened image {}", path.display());
        Ok(())
    }

    pub(super) fn open_sheet(&mut self, path: &Path) -> Result<()> {
        let view = crate::sheet::open_sheet(path).map_err(|e| {
            let reason = if crate::sheet::is_size_refusal(&e) {
                Refusal::PastCap
            } else {
                Refusal::NotItsFormat
            };
            refused(reason, format!("Spreadsheet open failed: {e}"))
        })?;
        self.install_sheet_view(path, view);
        Ok(())
    }

    /// Media info view (#183): header-probed properties rendered as a
    /// markdown card, with an ffmpeg poster frame when available.
    pub(super) fn open_media_preview(&mut self, path: &Path) -> Result<()> {
        let info = crate::media::probe(path)
            .ok_or_else(|| anyhow::anyhow!("no recognisable media header"))?;
        let scratch = std::env::temp_dir().join(format!("croft-media-{}", std::process::id()));
        let md_text = crate::media::to_markdown(path, &info, &scratch);
        let (lines, images) = crate::markdown::render_markdown_with_images(
            &md_text,
            self.theme,
            &mut self.registry,
            Some(&scratch),
        );
        self.become_viewer(path, Self::disk_stamp_of(path));
        self.markdown_preview = Some(crate::markdown::MarkdownPreview {
            rows: Vec::new(),
            selection: None,
            dragging: false,
            lines,
            scroll: 0,
            built_seq: self.edit_seq,
            images,
            anchor_rows: Vec::new(),
            runnables: Vec::new(),
            run_rows: Vec::new(),
            wrap_key: (0, 0),
            last_area: Rect::default(),
            notebook: false,
            doc_path: Some(path.to_path_buf()),
            media: true,
            source_map: Vec::new(),
            row_of_line: Vec::new(),
            scroll_to_source: None,
            links: crate::markdown::MdLinks::default(),
            follows: None,
        });
        self.status = format!("Opened media info {}", path.display());
        Ok(())
    }

    /// Read-only SQLite browser (#182): tables as sheet-grid
    /// worksheets, through the standard sheet install.
    pub(super) fn open_sqlite(&mut self, path: &Path) -> Result<()> {
        let view = crate::sqlite_view::open_database(path)
            .map_err(|e| anyhow::anyhow!("SQLite open failed: {e}"))?;
        self.install_sheet_view(path, view);
        Ok(())
    }

    /// docx/odt read-only preview (#181): the document walks into
    /// markdown and renders through the preview machinery; embedded
    /// images extract to scratch and ride the inline-image overlay.
    pub(super) fn open_doc_preview(&mut self, path: &Path) -> Result<()> {
        let scratch = std::env::temp_dir().join("croft-doc-images");
        let md = crate::docx::to_markdown(path, &scratch)
            .ok_or_else(|| anyhow::anyhow!("not a recognisable document"))?;
        let (lines, images) = crate::markdown::render_markdown_with_images(
            &md,
            self.theme,
            &mut self.registry,
            Some(&scratch),
        );
        self.become_viewer(path, Self::disk_stamp_of(path));
        self.markdown_preview = Some(crate::markdown::MarkdownPreview {
            rows: Vec::new(),
            selection: None,
            dragging: false,
            lines,
            scroll: 0,
            built_seq: self.edit_seq,
            images,
            anchor_rows: Vec::new(),
            runnables: Vec::new(),
            run_rows: Vec::new(),
            wrap_key: (0, 0),
            last_area: Rect::default(),
            notebook: false,
            doc_path: Some(path.to_path_buf()),
            media: false,
            source_map: Vec::new(),
            row_of_line: Vec::new(),
            scroll_to_source: None,
            links: crate::markdown::MdLinks::default(),
            follows: None,
        });
        self.status = format!("Opened document {}", path.display());
        Ok(())
    }

    /// Archive browser (#179): list the members read-only; Enter
    /// extracts one to scratch and reopens it through the dispatch.
    pub(super) fn open_archive(
        &mut self,
        path: &Path,
        kind: crate::archive::ArchiveKind,
    ) -> Result<()> {
        let view = crate::archive::list(path, kind).map_err(|e| {
            let reason = if crate::archive::is_list_cap_error(&e) {
                Refusal::PastCap
            } else {
                Refusal::NotItsFormat
            };
            refused(reason, format!("Archive open failed: {e}"))
        })?;
        // A listing that succeeds positively disproves any refusal armed
        // for this path, so it cannot be left to explain a later view.
        self.route_note = None;
        self.become_viewer(path, Self::disk_stamp_of(path));
        self.archive = Some(view);
        self.status = format!("Opened archive {}", path.display());
        Ok(())
    }

    /// Rendered SVG preview (#175): rasterise through resvg at a fixed
    /// quality (the PDF philosophy — one raster per open, no re-render
    /// on pane resize) and hand the PNG to the standard image pipeline.
    pub(super) fn open_svg(&mut self, path: &Path) -> Result<()> {
        let meta = std::fs::metadata(path)?;
        if meta.len() > crate::svg::MAX_SVG_BYTES {
            anyhow::bail!("SVG too large ({} bytes)", meta.len());
        }
        let src = std::fs::read(path)?;
        let crate::svg::Raster {
            png,
            pixels: (pixel_w, pixel_h),
            natural,
        } = crate::svg::render(&src).map_err(|e| anyhow::anyhow!("SVG render failed: {e}"))?;
        self.become_viewer(path, Self::disk_stamp_of(path));
        self.image = Some(ImageView {
            bytes: png,
            format_label: String::from("SVG"),
            pixel_w,
            pixel_h,
            natural_size: Some(match natural {
                crate::svg::NaturalSize::Px(w, h) => css_px_size((w, h)),
                crate::svg::NaturalSize::Relative(w, h) => format!("{w}×{h}"),
            }),
            byte_size: meta.len(),
            generation: next_image_generation(),
            pdf: None,
        });
        self.status = format!("Opened SVG {}", path.display());
        Ok(())
    }

    /// The state swap half of a sheet open, shared with the content
    /// router (#174), which fetches the view by sniffed kind instead of
    /// by extension.
    pub(super) fn install_sheet_view(&mut self, path: &Path, view: crate::sheet::SheetView) {
        self.become_viewer(
            path,
            Self::disk_stamp_with_wal(path, view.kind == crate::sheet::SheetKind::Sqlite),
        );
        self.status = format!("Opened {} ({})", path.display(), view.kind.label());
        self.sheet = Some(view);
    }

    pub(super) fn open_pdf(&mut self, path: &Path) -> Result<()> {
        let backend = crate::pdf::detect_backend()
            .ok_or_else(|| anyhow::anyhow!("Install poppler (pdftoppm) to preview PDFs"))?;
        let meta = std::fs::metadata(path)?;
        let restore = self.pdf_restore_page.take();
        // A tab already showing this PDF is reloading it, after a rebuild on
        // disk; anything else opens it afresh, without waiting (#2827).
        let reload = self.path.as_deref() == Some(path)
            && self.image.as_ref().is_some_and(|i| i.pdf.is_some());
        if !reload {
            return self.start_pdf(path, backend, meta.len());
        }
        // One rebuild renders at a time: a newer one waits for it, and the
        // sweep starts it once it has landed, since the tab's version is the
        // older one then.
        if self.pdf_jobs.reloading() {
            return Ok(());
        }
        // A rebuild on disk renders on a job (#2827): the page on screen
        // stays until the new one lands, and on a failure it stays with the
        // reader's place (#72). The job comes up on the reader's page,
        // clamped to the new count, so a shrunken document lands on its new
        // last page.
        // Stopped, like a page's render, if the tab moves on before it lands.
        let source = path.to_path_buf();
        let job = crate::jobs::Job::spawn_stoppable(
            "pdf-reload",
            crate::jobs::Start::Now,
            move |unwanted| {
                let count = crate::pdf::detect_page_count(&source);
                let page = match restore {
                    Some(p) => p.clamp(1, count.unwrap_or(p).max(1)),
                    None => 1,
                };
                crate::pdf::rasterize_page_while_wanted(&source, page, backend, unwanted)
                    .map_err(|e| e.to_string())
                    .and_then(readable_page)
                    .map(|bytes| (count, page, bytes))
            },
        )
        .map_err(|e| anyhow::anyhow!("PDF render failed: {e}"))?;
        let found = Self::disk_stamp_of(path);
        self.pdf_jobs.reload = Some(PdfReload {
            job,
            asked: restore.unwrap_or(1),
            before: self.disk_stamp,
            found,
            size: meta.len(),
        });
        // Taken while it renders, so the sweep does not start it again; a
        // failure gives it back ([`Self::pdf_reload_failed`]).
        self.disk_stamp = found;
        Ok(())
    }

    /// Open `path` as a PDF without waiting for poppler (#2827): the tab
    /// comes up at once saying page 1 is rendering, page 1 renders on a job
    /// and the page count is read on another ([`Self::poll_pdf_jobs`]).
    fn start_pdf(&mut self, path: &Path, backend: crate::pdf::PdfBackend, size: u64) -> Result<()> {
        let render = pdf_render_job(path.to_path_buf(), 1, backend)
            .map_err(|e| anyhow::anyhow!("PDF render failed: {e}"))?;
        self.become_viewer(path, Self::disk_stamp_of(path));
        self.image = Some(ImageView {
            bytes: Vec::new(),
            format_label: String::from("PDF"),
            pixel_w: 0,
            pixel_h: 0,
            natural_size: None,
            byte_size: size,
            generation: next_image_generation(),
            pdf: Some(PdfState {
                source_path: path.to_path_buf(),
                current_page: 1,
                page_count: None,
                backend,
                source_byte_size: size,
                links: None,
            }),
        });
        let pdf = path.to_path_buf();
        self.pdf_jobs = PdfJobs {
            render: Some((1, render)),
            count: crate::jobs::Job::spawn("pdf-count", crate::jobs::Start::Now, move || {
                crate::pdf::detect_page_count(&pdf)
            })
            .ok(),
            ..PdfJobs::default()
        };
        self.status = format!("Opened PDF {}", path.display());
        Ok(())
    }

    /// Whether a PDF preview has a page on screen: not while its first page
    /// is still rendering, or after that render failed.
    pub fn pdf_page_shown(&self) -> bool {
        self.image
            .as_ref()
            .is_some_and(|i| i.pdf.is_some() && !i.bytes.is_empty())
    }

    /// Why this tab shows its file in the hex viewer rather than the viewer
    /// its kind gets, when that viewer declined it (#2711).
    pub fn hex_routed_because(&self) -> Option<&str> {
        self.hex.as_ref()?.routed_because.as_deref()
    }

    /// True when this tab shows any non-text view: a diff, sheet,
    /// image/PDF, or hex tab. Text-only affordances (save, LSP sync,
    /// vim, merge commands, encoding, markdown preview) refuse on it.
    /// Every preview kind the format epic (#184) adds joins HERE, so the
    /// twenty-odd guard sites never enumerate kinds again.
    pub fn has_non_text_view(&self) -> bool {
        self.diff.is_some()
            || self.sheet.is_some()
            || self.image.is_some()
            || self.hex.is_some()
            || self.archive.is_some()
            || self.pr_review.is_some()
            || self.fleet.is_some()
            || self.sarif.is_some()
            // A rendered log's text side is an empty stub, so a save would
            // write one blank line over the file — the #185 truncation class.
            || self.log.is_some()
            // A docx/odt preview's text side is a STUB (#200 review):
            // letting a save through would overwrite the document with
            // the placeholder, the exact #185 class.
            || self
                .markdown_preview
                .as_ref()
                .is_some_and(|md| md.doc_path.is_some())
    }

    /// Route a gzip-magic file: a tar inside opens the archive browser, one
    /// compressed text file opens as its text (#1469). `false` leaves the
    /// caller to fall back to hex; a size refusal on either route rides
    /// along as the route note so the viewer can say why.
    pub(super) fn route_gzip(&mut self, path: &Path) -> bool {
        match self.open_archive(path, crate::archive::ArchiveKind::TarGz) {
            Ok(()) => return true,
            Err(e) if refusal(&e) == Some(Refusal::PastCap) => {
                self.route_note = Some((path.to_path_buf(), e.to_string()));
                return false;
            }
            Err(_) => {}
        }
        // Not a tar: one compressed file, such as a rotated `app.log.1.gz`.
        // Its text opens; binary, or too large once decompressed, stays hex.
        match self.open_gunzipped(path) {
            Ok(()) => true,
            Err(e) => {
                if refusal(&e) == Some(Refusal::PastCap) {
                    self.route_note = Some((path.to_path_buf(), e.to_string()));
                }
                false
            }
        }
    }

    /// A gzip of one file (#1469), such as logrotate's `app.log.1.gz` or a
    /// `dump.sql.gz`: its text, decompressed to a scratch copy, in the
    /// read-only log view, so it reads like the file it was and a save can
    /// never write the text over the archive. It used to open as a hex dump
    /// of the gzip bytes. Fails, so the caller falls back to hex, when the
    /// file does not decompress, holds binary data, or decompresses to more
    /// than [`MAX_GUNZIP_BYTES`], a bound against a decompression bomb.
    pub(super) fn open_gunzipped(&mut self, path: &Path) -> Result<()> {
        use std::io::{Read, Write};
        let file = std::fs::File::open(path)?;
        let mut decoder = flate2::read::MultiGzDecoder::new(std::io::BufReader::new(file))
            .take(MAX_GUNZIP_BYTES + 1);
        let mut head = vec![0u8; 8192];
        let mut filled = 0;
        while filled < head.len() {
            match decoder.read(&mut head[filled..])? {
                0 => break,
                n => filled += n,
            }
        }
        head.truncate(filled);
        // The log view reads UTF-8 only, so a UTF-16 BOM would render as
        // NULs and replacement characters: such a payload stays hex.
        match encoding_rs::Encoding::for_bom(&head) {
            Some((enc, _)) if enc != encoding_rs::UTF_8 => {
                anyhow::bail!("not UTF-8 text once decompressed");
            }
            Some(_) => {}
            None if is_binary(&head) => anyhow::bail!("not text once decompressed"),
            None => {}
        }
        let inner = path
            .file_name()
            .and_then(|n| n.to_str())
            .map(|n| n.strip_suffix(".gz").unwrap_or(n).to_string())
            .unwrap_or_default();
        let key = {
            use std::hash::{Hash, Hasher};
            let mut h = std::collections::hash_map::DefaultHasher::new();
            path.hash(&mut h);
            h.finish()
        };
        let dir = gunzip_scratch_dir()?;
        // Off this thread: an archive restored at launch opens before the
        // first frame, and the sweep must not hold that frame up.
        let swept = dir.clone();
        let _ = std::thread::Builder::new()
            .name(String::from("gunzip-sweep"))
            .spawn(move || sweep_gunzip_copies(&swept, false));
        let scratch = dir.join(gunzip_copy_name(
            key,
            std::process::id(),
            next_gunzip_copy_number(key),
            &inner,
        ));
        // Never follow a link planted at the name: unlink whatever is there
        // (a link, not its target) and create the file exclusively.
        match std::fs::remove_file(&scratch) {
            Err(e) if e.kind() != std::io::ErrorKind::NotFound => return Err(e.into()),
            _ => {}
        }
        let mut out = std::fs::OpenOptions::new()
            .write(true)
            .create_new(true)
            .open(&scratch)?;
        // From here every way out deletes the copy (#2675): a gzip corrupt
        // partway, one too large, or a view that cannot open it.
        let copy = crate::log_view::OwnedCopy::new(scratch.clone());
        out.write_all(&head)?;
        let written = head.len() as u64 + std::io::copy(&mut decoder, &mut out)?;
        drop(out);
        if written > MAX_GUNZIP_BYTES {
            return Err(refused(
                Refusal::PastCap,
                format!(
                    "Decompressed file too large to show (over {} MiB)",
                    MAX_GUNZIP_BYTES / (1024 * 1024)
                ),
            ));
        }
        self.open_log(&scratch)?;
        if let Some(log) = self.log.as_mut() {
            log.own_copy(copy);
        }
        self.path = Some(path.to_path_buf());
        self.disk_stamp = Self::disk_stamp_of(path);
        self.status = format!("Opened {} decompressed, read-only", path.display());
        Ok(())
    }

    /// Open `path` as a rendered ANSI log (#257): colours paint through the
    /// theme's palette and escapes never reach the text. Windowed, so the
    /// file is not read whole. Fails (and the caller falls through to the
    /// normal text path) when the file cannot be indexed.
    pub fn open_log(&mut self, path: &Path) -> Result<()> {
        let view = crate::log_view::LogView::open(path)
            .map_err(|e| anyhow::anyhow!("Log open failed: {e}"))?;
        self.become_viewer(path, Self::disk_stamp_of(path));
        self.log = Some(view);
        self.log_reload_top = None;
        self.status = format!("Opened {} as a rendered log", path.display());
        Ok(())
    }

    /// Open `path` in the SARIF results viewer (#577). Fails with the
    /// loader's explanation (position of a JSON error, an unsupported
    /// version) so the caller can fall back to text and say why.
    pub fn open_sarif(&mut self, path: &Path) -> Result<()> {
        let meta = std::fs::metadata(path)?;
        if meta.len() > crate::sarif::view::MAX_LOG_BYTES {
            anyhow::bail!("SARIF log too large to load ({} bytes)", meta.len());
        }
        let bytes = std::fs::read(path)?;
        let text = String::from_utf8_lossy(&bytes);
        let log = crate::sarif::load::parse_log(&text).map_err(|e| anyhow::anyhow!("{e}"))?;
        let view = crate::sarif::view::SarifView::open(path, log);
        self.become_viewer(path, Self::disk_stamp_of(path));
        let n = view.entries.len();
        self.sarif = Some(view);
        self.status = format!(
            "Opened {} · {n} SARIF result{}",
            path.display(),
            if n == 1 { "" } else { "s" }
        );
        Ok(())
    }

    /// Whether `path` should open as a rendered log: a log-ish extension, or
    /// any extension at all if the first bytes carry an SGR sequence. The
    /// content sniff is what catches `foo.txt` holding pytest output; the
    /// extension list is what avoids sniffing every file on open.
    pub fn should_open_as_log(path: &Path) -> bool {
        let ext = path
            .extension()
            .and_then(|e| e.to_str())
            .unwrap_or("")
            .to_ascii_lowercase();
        if !matches!(ext.as_str(), "log" | "ansi" | "out" | "txt" | "") {
            return false;
        }
        // Sniff a bounded prefix: a colour log announces itself immediately,
        // and reading more would tax every plain .txt open.
        let Ok(mut f) = std::fs::File::open(path) else {
            return false;
        };
        use std::io::Read;
        let mut buf = [0u8; 8192];
        let Ok(n) = f.read(&mut buf) else {
            return false;
        };
        crate::ansi_text::looks_like_ansi(&String::from_utf8_lossy(&buf[..n]))
    }

    /// Open `path` in the read-only hex viewer (#172): the routing
    /// fallback for files the text heuristic rejects, and the target of
    /// the explicit "Reopen as Hex" command. `pub` for that command's
    /// dispatch; extension routing never needs to call it directly.
    pub fn open_hex(&mut self, path: &Path) -> Result<()> {
        // `open` is also the same-path reload behind the FS-sync sweep:
        // refresh the existing view in place so the reader keeps their
        // offset through an external rewrite (the PDF restore-page
        // precedent, without the second-render window).
        if self.path.as_deref() == Some(path)
            && let Some(view) = self.hex.as_mut()
        {
            // A refresh writes no status line, so a note armed by the open
            // that called us would outlive its open and go stale against a
            // file that may since have come under the cap.
            self.route_note = None;
            // Pending overwrites survive a same-path re-open (a tree
            // re-click must not silently drop them); the FS sweep never
            // reloads a dirty tab, and an explicit Revert discards via
            // `discard_edits` first, which re-arms this refresh.
            if view.has_edits() {
                return Ok(());
            }
            view.refresh_from_disk(path)
                .map_err(|e| anyhow::anyhow!("Hex reload failed: {e}"))?;
            self.disk_stamp = Self::disk_stamp_of(path);
            self.disk_conflict = false;
            return Ok(());
        }
        let mut view =
            crate::hex::HexView::open(path).map_err(|e| anyhow::anyhow!("Hex open failed: {e}"))?;
        self.become_viewer(path, Self::disk_stamp_of(path));
        // Only for the file it was set for: an open can set the note and
        // then fail before reaching a viewer, and this is also reached
        // directly by "Reopen as Hex", so a note that outlived its open
        // would explain the wrong file.
        let why = match self.route_note.take() {
            Some((noted, why)) if noted == path => Some(why),
            _ => None,
        };
        self.status = match &why {
            Some(why) => format!("Opened {} in the hex viewer: {why}", path.display()),
            None => format!("Opened {} in the hex viewer", path.display()),
        };
        view.routed_because = why;
        self.hex = Some(view);
        Ok(())
    }

    /// Write a hex tab's pending byte overwrites to disk (#173). The
    /// same disk-conflict contract as `save_to_disk`: an external change
    /// since the last sync refuses (once), and `force` overrides. Never
    /// routes through `write_buffer_to_disk` — that choke point refuses
    /// every preview kind (#185), and hex writes bytes, not lines.
    pub fn hex_save(&mut self, force: bool) -> Result<SaveOutcome> {
        let Some(path) = self.path.clone() else {
            anyhow::bail!("No file open");
        };
        if self.hex.is_none() {
            anyhow::bail!("Not a hex tab");
        }
        // Nothing pending: touch NOTHING (#191 review). Re-anchoring the
        // disk stamp here would claim sync with an external change the
        // window never read, and the FS sweep would then skip the reload.
        if self.hex.as_ref().is_some_and(|v| !v.has_edits()) {
            self.status = String::from("No pending byte edits");
            return Ok(SaveOutcome::Saved);
        }
        if !force && self.disk_changed_externally() {
            self.disk_conflict = true;
            return Ok(SaveOutcome::DiskConflict);
        }
        let Some(view) = self.hex.as_mut() else {
            unreachable!("checked above");
        };
        let written = view
            .save_edits(&path)
            .map_err(|e| anyhow::anyhow!("Hex save failed: {e}"))?;
        self.disk_stamp = Self::disk_stamp_of(&path);
        self.disk_conflict = false;
        self.dirty = false;
        self.status = format!(
            "Wrote {written} byte{} to {}",
            if written == 1 { "" } else { "s" },
            path.display()
        );
        Ok(SaveOutcome::Saved)
    }

    /// Write a CSV/TSV sheet tab's grid edits back to disk (#177),
    /// serialised with the delimiter the file was read with. Same
    /// disk-conflict contract as text saves; never the text choke point
    /// (#185).
    pub fn sheet_save(&mut self, force: bool, overwrite_formulas: bool) -> Result<SaveOutcome> {
        let Some(path) = self.path.clone() else {
            anyhow::bail!("No file open");
        };
        let Some(view) = self.sheet.as_ref() else {
            anyhow::bail!("Not a sheet tab");
        };
        let delim = match view.kind {
            crate::sheet::SheetKind::Csv => Some(b','),
            crate::sheet::SheetKind::Tsv => Some(b'\t'),
            crate::sheet::SheetKind::Xlsx => None,
            crate::sheet::SheetKind::Sqlite => {
                anyhow::bail!("SQLite databases are read-only in the browser")
            }
            _ => anyhow::bail!("This workbook format is read-only (xls/ods/xlsb)"),
        };
        if !force && self.disk_changed_externally() {
            self.disk_conflict = true;
            return Ok(SaveOutcome::DiskConflict);
        }
        let view = self.sheet.as_mut().expect("checked above");
        match delim {
            Some(delim) => {
                let data = match view.sheets.get(view.current_sheet) {
                    Some(d) => d,
                    None => anyhow::bail!("No worksheet"),
                };
                // The file's own line ending, read from its first line.
                let original = std::fs::read(&path).unwrap_or_default();
                let crlf = original
                    .iter()
                    .position(|&c| c == b'\n')
                    .is_some_and(|i| i > 0 && original[i - 1] == b'\r');
                // Unchanged rows go back as the file had them (#1375).
                let bytes = crate::sheet::serialize_delimited(data, delim, crlf, &original);
                std::fs::write(&path, &bytes)
                    .map_err(|e| anyhow::anyhow!("Sheet save failed: {e}"))?;
                view.dirty = false;
                view.cell_edits.clear();
                self.status = format!("Saved {}", path.display());
            }
            None => {
                // xlsx (#178): apply exactly the edited cells through
                // umya. `force` doubles as formula-overwrite consent, the
                // same double-press contract as disk conflicts; skipped
                // formula cells stay pending so the tab stays dirty.
                let edits = view.cell_edits.clone();
                let report =
                    crate::sheet::save_xlsx_edits(&path, &view.sheets, &edits, overwrite_formulas)
                        .map_err(|e| anyhow::anyhow!("Workbook save failed: {e}"))?;
                if report.formula_skipped.is_empty() {
                    view.cell_edits.clear();
                    view.dirty = false;
                    self.status = format!(
                        "Saved {} ({} cell{})",
                        path.display(),
                        report.written,
                        if report.written == 1 { "" } else { "s" }
                    );
                } else {
                    // Keep ONLY the skipped formula cells pending.
                    let names = &view.sheets;
                    view.cell_edits.retain(|&(si, r, c)| {
                        names.get(si).is_some_and(|d| {
                            report.formula_skipped.contains(&format!(
                                "{}!{}{}",
                                d.name,
                                crate::sheet::column_letters_pub(d.origin.1 + c as u32 + 1),
                                d.origin.0 + r as u32 + 2
                            ))
                        })
                    });
                    view.dirty = true;
                    self.status = format!(
                        "Saved {} cell{}; {} formula cell{} kept ({}) - Cmd+S again overwrites the formulas",
                        report.written,
                        if report.written == 1 { "" } else { "s" },
                        report.formula_skipped.len(),
                        if report.formula_skipped.len() == 1 {
                            ""
                        } else {
                            "s"
                        },
                        report.formula_skipped.join(", ")
                    );
                }
            }
        }
        let still_dirty = self.sheet.as_ref().is_some_and(|v| v.dirty);
        self.disk_stamp = Self::disk_stamp_of(&path);
        self.disk_conflict = false;
        self.set_dirty(still_dirty);
        Ok(SaveOutcome::Saved)
    }

    /// The cell being typed into in this tab's grid, when what is typed
    /// differs from the cell (#1593): `(sheet, row, col, value)`. It is
    /// in no cell yet, so hot exit reads it here.
    pub fn sheet_pending_cell(&self) -> Option<(usize, usize, usize, &str)> {
        let view = self.sheet.as_ref()?;
        let edit = view.editing.as_ref()?;
        let data = view.sheets.get(view.current_sheet)?;
        let (r, c) = (data.cur_row, data.cur_col);
        (data.cell(r, c) != edit.value).then_some((view.current_sheet, r, c, edit.value.as_str()))
    }

    /// What hot exit and the update relaunch keep of a grid's unsaved
    /// edits (#1593), `None` when it has none: a CSV/TSV grid as the text a
    /// save would write, an xlsx as its edited cells `(sheet, row, col,
    /// value)` by worksheet name, the cells its save applies. The cell being typed into
    /// counts as edited, as a save would commit it.
    pub fn sheet_backup(&self) -> Option<(Option<String>, Vec<SheetCellEdit>)> {
        let view = self.sheet.as_ref()?;
        let pending = self.sheet_pending_cell();
        if !view.dirty && pending.is_none() {
            return None;
        }
        match view.kind {
            crate::sheet::SheetKind::Csv | crate::sheet::SheetKind::Tsv => {
                let data = view.sheets.get(view.current_sheet)?;
                let typed;
                let data = match pending {
                    Some((_, r, c, value)) => {
                        let mut copy = data.clone();
                        copy.set_cell(r, c, value.to_string());
                        typed = copy;
                        &typed
                    }
                    None => data,
                };
                let bytes =
                    crate::sheet::serialize_delimited(data, sheet_delim(view.kind), false, &[]);
                Some((
                    Some(String::from_utf8_lossy(&bytes).into_owned()),
                    Vec::new(),
                ))
            }
            crate::sheet::SheetKind::Xlsx => {
                let mut cells: Vec<_> = view
                    .cell_edits
                    .iter()
                    .filter(|&&(s, r, c)| pending.is_none_or(|p| (p.0, p.1, p.2) != (s, r, c)))
                    .filter_map(|&(s, r, c)| {
                        let data = view.sheets.get(s)?;
                        Some((data.name.clone(), r, c, data.cell(r, c).to_string()))
                    })
                    .collect();
                if let Some((s, r, c, value)) = pending
                    && let Some(data) = view.sheets.get(s)
                {
                    cells.push((data.name.clone(), r, c, value.to_string()));
                }
                (!cells.is_empty()).then_some((None, cells))
            }
            _ => None,
        }
    }

    /// Put a grid's backed-up edits (#1593) over the file just opened in
    /// it, as unsaved edits: a CSV/TSV's text re-read into the grid, an
    /// xlsx's cells set again and queued for its save. Returns the xlsx
    /// cells it could not set (their worksheet or row is gone from the
    /// workbook), which the caller keeps rather than lose. The tab turns
    /// dirty only when something was put back.
    pub fn restore_sheet_edits(
        &mut self,
        text: Option<&str>,
        cells: &[SheetCellEdit],
    ) -> Vec<SheetCellEdit> {
        let Some(view) = self.sheet.as_mut() else {
            return cells.to_vec();
        };
        let mut unapplied = Vec::new();
        match (view.kind, text) {
            (crate::sheet::SheetKind::Csv | crate::sheet::SheetKind::Tsv, Some(text)) => {
                let name = view
                    .sheets
                    .first()
                    .map_or_else(|| String::from("Sheet1"), |d| d.name.clone());
                let Ok(data) =
                    crate::sheet::parse_delimited(text.as_bytes(), sheet_delim(view.kind), &name)
                else {
                    return Vec::new();
                };
                view.sheets = vec![data];
                view.current_sheet = 0;
            }
            (crate::sheet::SheetKind::Xlsx, _) if !cells.is_empty() => {
                for cell in cells {
                    let (name, r, c, value) = cell;
                    let Some(s) = view
                        .sheets
                        .iter()
                        .position(|d| d.name == *name && *r < d.rows.len())
                    else {
                        unapplied.push(cell.clone());
                        continue;
                    };
                    view.sheets[s].set_cell(*r, *c, value.clone());
                    if !view.cell_edits.contains(&(s, *r, *c)) {
                        view.cell_edits.push((s, *r, *c));
                    }
                }
                if unapplied.len() == cells.len() {
                    return unapplied;
                }
            }
            _ => return cells.to_vec(),
        }
        view.dirty = true;
        self.mark_dirty();
        unapplied
    }

    /// The page an open PDF preview is showing, if this tab is one.
    pub fn pdf_page(&self) -> Option<u32> {
        self.image.as_ref()?.pdf.as_ref().map(|p| p.current_page)
    }

    /// Step the active PDF preview by `delta` pages. Returns true if the page
    /// actually changed, so the caller can flag the OSC overlay for re-bake.
    /// Wraps around at the document boundaries when the page count is known;
    /// clamps at page 1 below otherwise.
    pub fn change_pdf_page(&mut self, delta: i32) -> bool {
        let Some(pdf) = self.image.as_ref().and_then(|i| i.pdf.clone()) else {
            return false;
        };
        // From the page asked for last, so two quick presses move two pages
        // while the first still renders.
        let from = self.pdf_target_page().unwrap_or(pdf.current_page);
        let new_page = if let Some(total) = pdf.page_count {
            if total == 0 {
                return false;
            }
            let cur = from as i64;
            let next = ((cur - 1 + delta as i64).rem_euclid(total as i64)) + 1;
            next as u32
        } else if delta > 0 {
            from.saturating_add(delta as u32)
        } else {
            from.saturating_sub((-delta) as u32).max(1)
        };
        self.render_pdf_page(new_page)
    }

    /// The page an open PDF preview will show: the one asked for while it
    /// renders, else the one on screen.
    pub fn pdf_target_page(&self) -> Option<u32> {
        self.pdf_jobs
            .next_page
            .or_else(|| self.pdf_jobs.render.as_ref().map(|(page, _)| *page))
            .or_else(|| self.pdf_page())
    }

    /// Jump the active PDF preview to an absolute page, clamped to the
    /// document. `u32::MAX` therefore means "last page" without the caller
    /// knowing the count - which is what Home / End need, and what stepping
    /// by a huge delta cannot express (a step wraps).
    pub fn set_pdf_page(&mut self, page: u32) -> bool {
        let Some(pdf) = self.image.as_ref().and_then(|i| i.pdf.clone()) else {
            return false;
        };
        // "Last page" is unanswerable without a page count (sips-only Macs
        // where mdls reports nothing): rendering the sentinel itself would
        // just spray "PDF page 4294967295 failed" into the status bar.
        if page == u32::MAX && pdf.page_count.is_none() {
            // Still being read: go there once it is in.
            if self.pdf_jobs.count.is_some() {
                // The newest wish: a page asked for before it is dropped.
                self.pdf_jobs.next_page = None;
                self.pdf_jobs.last_page_wanted = true;
                return false;
            }
            self.status = String::from("PDF page count unknown; cannot jump to the last page");
            return false;
        }
        let last = pdf.page_count.unwrap_or(u32::MAX).max(1);
        self.render_pdf_page(page.clamp(1, last))
    }

    /// Ask for `new_page`, rendered on a job (#2824): the page on screen
    /// stays until it lands ([`Self::poll_pdf_jobs`]). False: nothing on
    /// screen changed yet.
    pub(super) fn render_pdf_page(&mut self, new_page: u32) -> bool {
        let Some(pdf) = self.image.as_ref().and_then(|i| i.pdf.clone()) else {
            return false;
        };
        // A page asked for after End, while the count was still being read,
        // is the newer wish: End is dropped.
        self.pdf_jobs.last_page_wanted = false;
        if let Some((rendering, _)) = &self.pdf_jobs.render {
            // One render at a time: this page goes after the one running
            // ([`Self::poll_pdf_jobs`]), replacing any asked for before it;
            // asking for the page rendering drops what was asked since.
            self.pdf_jobs.next_page = (*rendering != new_page).then_some(new_page);
            return false;
        }
        if new_page == pdf.current_page && self.pdf_page_shown() {
            // Back to the page on screen, with nothing rendering. A page not
            // shown yet (its first render failed) is asked for again.
            self.pdf_jobs.next_page = None;
            return false;
        }
        match pdf_render_job(pdf.source_path.clone(), new_page, pdf.backend) {
            Ok(job) => self.pdf_jobs.render = Some((new_page, job)),
            Err(e) => self.status = format!("PDF page {new_page} failed: {e}"),
        }
        false
    }

    /// Read the links of the page on screen on a job, for a click at
    /// `frac` of the page that waits for them (#2824).
    pub fn read_pdf_links_for(&mut self, frac: (f64, f64, f64, f64)) {
        let Some(pdf) = self.image.as_ref().and_then(|i| i.pdf.clone()) else {
            return;
        };
        self.pdf_jobs.waiting_click = Some(frac);
        if self
            .pdf_jobs
            .links
            .as_ref()
            .is_some_and(|(page, _)| *page == pdf.current_page)
        {
            return;
        }
        let (source, page) = (pdf.source_path.clone(), pdf.current_page);
        match crate::jobs::Job::spawn("pdf-links", crate::jobs::Start::Now, move || {
            crate::pdf::page_links(&source, page).map_err(|e| e.to_string())
        }) {
            Ok(job) => self.pdf_jobs.links = Some((page, job)),
            Err(e) => {
                self.pdf_jobs.waiting_click = None;
                self.status = format!("PDF links unavailable: {e}");
            }
        }
    }

    /// Settle the PDF work that has finished: a page that landed is shown,
    /// the page count is kept, a page's links are kept for the click that
    /// waits on them. Whether anything on screen changed.
    pub fn poll_pdf_jobs(&mut self) -> bool {
        let mut changed = false;
        if let Some((page, job)) = &self.pdf_jobs.render {
            let page = *page;
            match job.poll() {
                crate::jobs::Poll::Pending => {}
                crate::jobs::Poll::Done(Ok(bytes)) => {
                    self.pdf_jobs.render = None;
                    match self.pdf_jobs.next_page.take() {
                        // The reader went back to the page on screen while
                        // this one rendered: it stays.
                        Some(next) if Some(next) == self.pdf_page() && self.pdf_page_shown() => {}
                        next => {
                            changed |= self.show_pdf_page(page, bytes);
                            if let Some(next) = next.filter(|&next| next != page) {
                                self.render_pdf_page(next);
                            }
                        }
                    }
                }
                crate::jobs::Poll::Done(Err(e)) => {
                    self.pdf_jobs.render = None;
                    self.status = format!("PDF page {page} failed: {e}");
                    self.pdf_first_render_failed(&e);
                    changed = true;
                    if let Some(next) = self.pdf_jobs.next_page.take() {
                        self.render_pdf_page(next);
                    }
                }
                crate::jobs::Poll::Died => {
                    self.pdf_jobs.render = None;
                    self.status = format!("PDF page {page} failed: it stopped before it finished");
                    changed = true;
                    if let Some(next) = self.pdf_jobs.next_page.take() {
                        self.render_pdf_page(next);
                    }
                }
            }
        }
        if let Some(job) = &self.pdf_jobs.count {
            match job.poll() {
                crate::jobs::Poll::Pending => {}
                answer => {
                    self.pdf_jobs.count = None;
                    let count = match answer {
                        crate::jobs::Poll::Done(count) => count,
                        _ => None,
                    };
                    if let Some(pdf) = self.image.as_mut().and_then(|i| i.pdf.as_mut()) {
                        pdf.page_count = count;
                    }
                    if std::mem::take(&mut self.pdf_jobs.last_page_wanted) && count.is_some() {
                        self.set_pdf_page(u32::MAX);
                    }
                    changed = true;
                }
            }
        }
        if let Some((page, job)) = &self.pdf_jobs.links {
            let page = *page;
            match job.poll() {
                crate::jobs::Poll::Pending => {}
                answer => {
                    self.pdf_jobs.links = None;
                    let current = self.pdf_page();
                    match answer {
                        crate::jobs::Poll::Done(Ok(links)) if current == Some(page) => {
                            if let Some(pdf) = self.image.as_mut().and_then(|i| i.pdf.as_mut()) {
                                pdf.links = Some(links);
                            }
                        }
                        // The page turned meanwhile: those links are not its.
                        crate::jobs::Poll::Done(Ok(_)) => self.pdf_jobs.waiting_click = None,
                        // Not kept: a mid-write extraction failure (pdflatex
                        // rebuilding the file) heals on the next click.
                        crate::jobs::Poll::Done(Err(e)) => {
                            self.pdf_jobs.waiting_click = None;
                            self.status = format!("PDF links unavailable: {e}");
                        }
                        _ => {
                            self.pdf_jobs.waiting_click = None;
                            self.status = String::from(
                                "PDF links unavailable: it stopped before it finished",
                            );
                        }
                    }
                    changed = true;
                }
            }
        }
        let reloaded = self
            .pdf_jobs
            .reload
            .as_ref()
            .map(|reload| reload.job.poll())
            .filter(|answer| !matches!(answer, crate::jobs::Poll::Pending));
        // Taken only once it has answered: a rebuild still rendering stays.
        if let Some(answer) = reloaded
            && let Some(reload) = self.pdf_jobs.reload.take()
        {
            match answer {
                crate::jobs::Poll::Done(Ok((count, page, bytes))) => {
                    self.land_pdf_reload(reload, count, page, bytes);
                }
                crate::jobs::Poll::Done(Err(_)) | crate::jobs::Poll::Died => {
                    self.pdf_reload_failed(reload.before, reload.found);
                }
                crate::jobs::Poll::Pending => unreachable!("filtered above"),
            }
            changed = true;
        }
        changed
    }

    /// Show a rebuild of the PDF that landed: its `page` in place of the page
    /// on screen, its page count, and the version it came from as the one the
    /// tab now shows. A page the reader turned to while it rendered is asked
    /// for again, from the new file.
    fn land_pdf_reload(
        &mut self,
        reload: PdfReload,
        count: Option<u32>,
        page: u32,
        bytes: Vec<u8>,
    ) {
        let Some((pixel_w, pixel_h)) = image_dimensions_of(&bytes) else {
            self.pdf_reload_failed(reload.before, reload.found);
            return;
        };
        let wanted = self.pdf_target_page();
        if let Some(image) = self.image.as_mut() {
            image.bytes = bytes;
            image.generation = next_image_generation();
            image.pixel_w = pixel_w;
            image.pixel_h = pixel_h;
            image.byte_size = reload.size;
            if let Some(pdf) = image.pdf.as_mut() {
                pdf.current_page = page;
                pdf.page_count = count;
                pdf.source_byte_size = reload.size;
                pdf.links = None;
            }
        }
        // What was rendering or read from the file before it was rebuilt is
        // the old file's; the reload read the count afresh.
        self.pdf_jobs.links = None;
        self.pdf_jobs.waiting_click = None;
        self.pdf_jobs.render = None;
        self.pdf_jobs.next_page = None;
        self.pdf_jobs.count = None;
        self.pdf_reload_landed();
        if std::mem::take(&mut self.pdf_jobs.last_page_wanted) && count.is_some() {
            // End pressed before the old file's count was in.
            self.set_pdf_page(u32::MAX);
        } else if let Some(wanted) = wanted.filter(|&w| w != reload.asked) {
            let last = count.unwrap_or(u32::MAX).max(1);
            self.render_pdf_page(wanted.clamp(1, last));
        }
    }

    /// A file sniffed as a PDF without the `.pdf` extension whose first page
    /// would not render goes to the hex viewer saying why, as its open did
    /// when it rendered there: it may not be a PDF at all. A `.pdf` keeps
    /// its tab, which says the page could not be rendered, and a key press
    /// or the next rebuild on disk asks again.
    fn pdf_first_render_failed(&mut self, error: &str) {
        if self.pdf_page_shown() {
            return;
        }
        let Some(path) = self.path.clone() else {
            return;
        };
        if path
            .extension()
            .and_then(|e| e.to_str())
            .is_some_and(extension_is_pdf)
        {
            return;
        }
        self.route_note = Some((
            path.clone(),
            format!("the PDF viewer could not render it ({error})"),
        ));
        if let Err(e) = self.open_hex(&path) {
            self.route_note = None;
            self.status = format!("PDF page 1 failed: {error}; {e}");
        }
    }

    /// Show `bytes`, the render of `new_page`, in place of the page on
    /// screen.
    fn show_pdf_page(&mut self, new_page: u32, bytes: Vec<u8>) -> bool {
        // A click waiting on the old page's links is not this page's.
        self.pdf_jobs.waiting_click = None;
        self.pdf_jobs.links = None;
        let Some(image) = self.image.as_mut() else {
            return false;
        };
        let Some((pixel_w, pixel_h)) = image_dimensions_of(&bytes) else {
            return false;
        };
        image.bytes = bytes;
        image.generation = next_image_generation();
        image.pixel_w = pixel_w;
        image.pixel_h = pixel_h;
        if let Some(state) = image.pdf.as_mut() {
            state.current_page = new_page;
            state.links = None;
        }
        true
    }

    /// Rebuild an open Markdown preview from the current buffer, theme and
    /// captured outputs. No-op when no preview is open.
    ///
    /// Extracted so a settled capture (#354) and a theme change share one
    /// implementation: the theme path had a hard-won detail the other would
    /// otherwise have had to rediscover.
    pub fn rebuild_markdown_preview(&mut self) {
        if self.markdown_preview.is_none() {
            return;
        }
        let text = self.lines.join("\n");
        self.rebuild_markdown_preview_from(&text, None);
    }

    /// [`Self::rebuild_markdown_preview`] from `text` instead of this tab's
    /// buffer (#1605): the source pane's text, for a preview to the side
    /// that follows it, with `follows` naming that source (`None` when
    /// `text` is the buffer's own).
    pub fn rebuild_markdown_preview_from(&mut self, text: &str, follows: Option<(u64, u64)>) {
        if self.markdown_preview.is_none() {
            return;
        }
        // The image-aware builder (#196 review): the plain one left
        // md.images pointing at anchors into the REPLACED lines, and
        // the wrap-key recompute then sliced with stale first_line
        // values - an out-of-range panic on a theme switch.
        let base = self
            .path
            .as_ref()
            .and_then(|p| p.parent().map(|d| d.to_path_buf()));
        let (lines, images, runnables, source_map, links) = crate::markdown::render_markdown_mapped(
            text,
            self.theme,
            &mut self.registry,
            base.as_deref(),
            self.md_outputs.clone(),
        );
        if let Some(md) = self.markdown_preview.as_mut() {
            md.lines = lines;
            md.source_map = source_map;
            md.images = images;
            md.runnables = runnables;
            md.links = links;
            md.built_seq = self.edit_seq;
            md.follows = follows;
            // The visual-row caches (images, play glyphs, scroll sync) are
            // keyed on `(built_seq, width)`, and a preview following another
            // pane rebuilds with its own `built_seq` unchanged (#1605
            // review): without this they kept the first build's rows, so
            // clicks and scrolling landed on stale lines. `(0, 0)` never
            // matches a drawn width.
            md.wrap_key = (0, 0);
        }
    }

    /// Whether this buffer is a plain `.log` file shown as text (#1537): no
    /// grammar, no rendered view. It gets tailspin's colours, the same ones
    /// the rendered log view paints, and reads "Log" in the status bar.
    pub fn is_plain_log(&self) -> bool {
        self.lang.is_none()
            && !self.has_non_text_view()
            && self
                .path
                .as_deref()
                .and_then(|p| p.extension())
                .is_some_and(|e| e.eq_ignore_ascii_case("log"))
    }

    /// Recolour a plain `.log` tab after "Log: Highlighting (tailspin)"
    /// flips (#1537); every other buffer is unaffected by that setting.
    pub fn refresh_log_highlight(&mut self) {
        if self.is_plain_log() {
            self.recompute_highlights();
        }
    }

    /// Spans for a grammar-less buffer: none, except on a plain `.log`
    /// (#1537), where tailspin colours levels, dates, numbers and ids while
    /// "Log: Highlighting (tailspin)" is on. A log too big to rescan on every
    /// edit stays uncoloured rather than making typing pay for it.
    pub(super) fn plain_log_highlights(&mut self) -> Vec<Vec<HiSpan>> {
        let bytes: usize = self.lines.iter().map(String::len).sum();
        if !self.is_plain_log()
            || !crate::log_view::default_highlight()
            || bytes > LOG_HIGHLIGHT_MAX_BYTES
        {
            self.log_spans.clear();
            return vec![Vec::new(); self.lines.len()];
        }
        let mut seen = std::mem::take(&mut self.log_spans);
        let mut kept = std::collections::HashMap::with_capacity(seen.len());
        let theme = self.theme;
        let out = self
            .lines
            .iter()
            .map(|line| {
                let spans: &Vec<crate::ansi_text::AnsiSpan> =
                    kept.entry(line.clone()).or_insert_with(|| {
                        seen.remove(line)
                            .unwrap_or_else(|| crate::log_view::plain_line_spans(line))
                    });
                spans
                    .iter()
                    .map(|s| HiSpan::new(s.start, s.end, log_span_style(&s.style, theme)))
                    .collect()
            })
            .collect();
        self.log_spans = kept;
        out
    }

    /// Markdown: Toggle Preview (Cmd/Ctrl+Shift+V). Returns false when the
    /// active tab is not a Markdown text buffer (the caller reports why).
    pub fn toggle_markdown_preview(&mut self) -> bool {
        if let Some(md) = self.markdown_preview.take() {
            // Back to the source where the preview was (#619).
            if let Some(line) = md.source_line_at_top() {
                self.scroll = line.min(self.lines.len().saturating_sub(1));
                self.scroll_sub = 0;
            }
            return true;
        }
        let is_notebook = self
            .path
            .as_deref()
            .is_some_and(|p| p.extension().and_then(|e| e.to_str()) == Some("ipynb"))
            && !self.has_non_text_view();
        if is_notebook {
            return self.build_notebook_preview();
        }
        let is_md_text = matches!(self.lang, Some(LangKind::Markdown))
            && self.image.is_none()
            && self.sheet.is_none()
            && self.diff.is_none();
        if !is_md_text {
            return false;
        }
        let text = self.lines.join("\n");
        let base = self
            .path
            .as_ref()
            .and_then(|p| p.parent().map(|d| d.to_path_buf()));
        let (lines, images, runnables, source_map, links) = crate::markdown::render_markdown_mapped(
            &text,
            self.theme,
            &mut self.registry,
            base.as_deref(),
            self.md_outputs.clone(),
        );
        // Open where the source is scrolled (#619).
        let scroll_to_source = Some(self.scroll);
        self.markdown_preview = Some(crate::markdown::MarkdownPreview {
            rows: Vec::new(),
            selection: None,
            dragging: false,
            lines,
            scroll: 0,
            built_seq: self.edit_seq,
            images,
            anchor_rows: Vec::new(),
            runnables,
            run_rows: Vec::new(),
            wrap_key: (0, 0),
            last_area: Rect::default(),
            notebook: false,
            doc_path: None,
            media: false,
            source_map,
            row_of_line: Vec::new(),
            scroll_to_source,
            links,
            follows: None,
        });
        true
    }

    /// Build (or rebuild) the rendered notebook view (#180) over the
    /// raw-JSON text tab. Returns false when the JSON does not parse as
    /// a notebook - the tab stays plain text.
    pub fn build_notebook_preview(&mut self) -> bool {
        let text = self.lines.join("\n");
        if !crate::notebook::looks_like_notebook(&text) {
            return false;
        }
        let base = self
            .path
            .as_ref()
            .and_then(|p| p.parent().map(|d| d.to_path_buf()));
        let scratch = std::env::temp_dir().join("croft-notebook-outputs");
        let Some((lines, images, runnables)) = crate::notebook::render(
            &text,
            self.theme,
            &mut self.registry,
            base.as_deref(),
            &scratch,
            &self.notebook_running,
        ) else {
            return false;
        };
        self.markdown_preview = Some(crate::markdown::MarkdownPreview {
            rows: Vec::new(),
            selection: None,
            dragging: false,
            lines,
            scroll: 0,
            built_seq: self.edit_seq,
            images,
            anchor_rows: Vec::new(),
            runnables,
            run_rows: Vec::new(),
            wrap_key: (0, 0),
            last_area: Rect::default(),
            notebook: true,
            doc_path: None,
            media: false,
            source_map: Vec::new(),
            row_of_line: Vec::new(),
            scroll_to_source: None,
            links: crate::markdown::MdLinks::default(),
            follows: None,
        });
        true
    }

    /// Rebuild the notebook view (#180) from the buffer, keeping its
    /// scroll. A document that no longer parses drops to the raw text
    /// (#199 review): keeping the stale render would repaint and re-fail
    /// every frame.
    pub(super) fn rebuild_notebook_preview(&mut self) {
        let scroll = self.markdown_preview.as_ref().map_or(0, |m| m.scroll);
        if self.build_notebook_preview() {
            if let Some(md) = self.markdown_preview.as_mut() {
                md.scroll = scroll;
            }
        } else {
            self.markdown_preview = None;
        }
    }

    /// Mark the notebook cells running or queued in its kernel (#355). The
    /// view redraws their `In [*]` marks at once: it otherwise rebuilds only
    /// on an edit, and a run can end without one, as when the kernel never
    /// starts (#878), which left the cells marked running for good.
    pub fn set_notebook_running(&mut self, running: Vec<usize>) {
        if self.notebook_running == running {
            return;
        }
        self.notebook_running = running;
        if self.markdown_preview.as_ref().is_some_and(|md| md.notebook) {
            self.rebuild_notebook_preview();
        }
    }

    /// Scroll the active Markdown preview; returns false when none is open
    /// so the caller falls through to normal buffer scrolling.
    pub fn scroll_markdown_preview(&mut self, delta: i32) -> bool {
        let Some(md) = self.markdown_preview.as_mut() else {
            return false;
        };
        md.scroll = md.scroll.saturating_add_signed(delta as i16);
        true
    }

    /// True when this tab is a SQLite browser, whose stamp covers the log.
    pub(super) fn is_sqlite_view(&self) -> bool {
        self.sheet
            .as_ref()
            .is_some_and(|s| s.kind == crate::sheet::SheetKind::Sqlite)
    }

    /// Where the reader is in a SQLite tab, for [`Self::reload_from_disk`]
    /// to put back on the rebuilt view.
    pub(super) fn sqlite_place(&self) -> Option<SqlitePlace> {
        let view = self.sheet.as_ref().filter(|_| self.is_sqlite_view())?;
        let data = view.sheets.get(view.current_sheet)?;
        let (table, page) = view.sqlite_pages.get(view.current_sheet)?.clone();
        Some(SqlitePlace {
            sheet: view.current_sheet,
            table,
            page,
            cell: (data.cur_row, data.cur_col),
            scroll: (data.scroll_row, data.scroll_col),
        })
    }

    /// Put a reloaded SQLite view back where [`Self::sqlite_place`] found
    /// the reader: the same table (found by name, else the same position
    /// clamped), the same page while the table still reaches it (else its
    /// last), and the cell and scroll clamped to what that page now holds.
    pub(super) fn restore_sqlite_place(&mut self, path: &Path, place: SqlitePlace) {
        if !self.is_sqlite_view() {
            return;
        }
        let Some(view) = self.sheet.as_mut() else {
            return;
        };
        let Some(last) = view.sheets.len().checked_sub(1) else {
            return;
        };
        let idx = view
            .sqlite_pages
            .iter()
            .position(|(t, _)| *t == place.table)
            .unwrap_or(place.sheet.min(last));
        view.current_sheet = idx;
        let table = view.sqlite_pages[idx].0.clone();
        let same_table = table == place.table;
        if same_table && place.page > 0 {
            // The page as it was; when the table has shrunk short of it, its
            // last page instead (counting only then, as Ctrl+End does).
            let fetch = |page| crate::sqlite_view::table_page(path, &table, page).ok();
            let found = match fetch(place.page) {
                Some(got) if !got.rows.is_empty() => Some((place.page, got)),
                _ => crate::sqlite_view::last_page(path, &table)
                    .ok()
                    .filter(|&l| l > 0 && l < place.page)
                    .and_then(|l| fetch(l).map(|got| (l, got))),
            };
            if let Some((page, got)) = found {
                view.sheets[idx] = got.into_sheet(&table, page);
                view.sqlite_pages[idx].1 = page;
            }
        }
        if !same_table {
            return;
        }
        let data = &mut view.sheets[idx];
        let rows = data.row_count().saturating_sub(1);
        let cols = data.col_count().saturating_sub(1);
        data.cur_row = place.cell.0.min(rows);
        data.cur_col = place.cell.1.min(cols);
        data.scroll_row = place.scroll.0.min(data.cur_row);
        data.scroll_col = place.scroll.1.min(data.cur_col);
    }

    /// Scroll an open spreadsheet preview by `rows` (negative scrolls up).
    /// Returns true when this tab is a spreadsheet, so the generic scroll
    /// paths can hand it off instead of moving the (empty) text buffer.
    pub fn scroll_sheet_rows(&mut self, rows: isize) -> bool {
        let Some(sheet) = self.sheet.as_mut() else {
            return false;
        };
        let Some(data) = sheet.sheets.get_mut(sheet.current_sheet) else {
            return false;
        };
        let last = data.rows.len().saturating_sub(1);
        data.scroll_row = data.scroll_row.saturating_add_signed(rows).min(last);
        true
    }

    /// Scroll a reloaded log to the place its reload kept (#1538), clamped
    /// to what is indexed so far, and keep the request while the index is
    /// still growing so the place is reached once it covers it.
    pub fn settle_log_reload(&mut self) {
        let Some(top) = self.log_reload_top.take() else {
            return;
        };
        if self.log.is_none() {
            return;
        }
        self.scroll_view_to(top);
        if self.log.as_ref().is_some_and(|log| log.indexing()) {
            self.log_reload_top = Some(top);
        }
    }

    /// Drop the place a log reload is still settling (#1538): the reader
    /// moved the view some other way, such as a find-bar jump, and the next
    /// index batch must not take it back.
    pub fn cancel_log_reload(&mut self) {
        self.log_reload_top = None;
    }
}

/// Above this many bytes a plain `.log` buffer is left uncoloured (#1537):
/// tailspin runs over every line the first time, and the rendered log view,
/// which windows the file, is the place for logs this big.
pub(super) const LOG_HIGHLIGHT_MAX_BYTES: usize = 4_000_000;

/// A tailspin span's style for the text editor (#1537). Foreground and
/// emphasis only: the highlighter never sets a background, and the editor's
/// own background, selection and find marks must show through.
pub(super) fn log_span_style(s: &crate::ansi_text::AnsiStyle, theme: crate::theme::Theme) -> Style {
    let mut style = Style::default();
    if let Some(c) = s.fg {
        style = style.fg(ansi_color_to_tui(c, theme));
    }
    if s.bold {
        style = style.add_modifier(Modifier::BOLD);
    }
    if s.dim {
        style = style.add_modifier(Modifier::DIM);
    }
    if s.italic {
        style = style.add_modifier(Modifier::ITALIC);
    }
    if s.underline {
        style = style.add_modifier(Modifier::UNDERLINED);
    }
    style
}

/// Where the private folder for decompressed gzip copies lives, whether or
/// not it exists yet: one per user.
fn gunzip_scratch_path() -> std::path::PathBuf {
    #[cfg(unix)]
    {
        // SAFETY: getuid has no preconditions and cannot fail.
        let uid = unsafe { libc::getuid() };
        std::env::temp_dir().join(format!("croft-gunzip-{uid}"))
    }
    #[cfg(not(unix))]
    {
        std::env::temp_dir().join("croft-gunzip")
    }
}

/// The private folder that holds decompressed gzip copies (#1469): one per
/// user, mode 0700 on unix, and refused unless it is a real directory this
/// user owns that no one else can enter, so another local user can neither
/// plant links in it nor read the text written there.
pub(super) fn gunzip_scratch_dir() -> std::io::Result<std::path::PathBuf> {
    #[cfg(unix)]
    {
        use std::os::unix::fs::{DirBuilderExt as _, MetadataExt as _, PermissionsExt as _};
        // SAFETY: getuid has no preconditions and cannot fail.
        let uid = unsafe { libc::getuid() };
        let dir = gunzip_scratch_path();
        match std::fs::DirBuilder::new().mode(0o700).create(&dir) {
            Err(e) if e.kind() != std::io::ErrorKind::AlreadyExists => return Err(e),
            _ => {}
        }
        let meta = std::fs::symlink_metadata(&dir)?;
        if !meta.is_dir() || meta.uid() != uid || meta.permissions().mode() & 0o077 != 0 {
            return Err(std::io::Error::other(format!(
                "{} is not a private directory",
                dir.display()
            )));
        }
        Ok(dir)
    }
    #[cfg(not(unix))]
    {
        let dir = gunzip_scratch_path();
        std::fs::create_dir_all(&dir)?;
        Ok(dir)
    }
}

/// The file name of the `n`th copy this process makes of the archive whose
/// path hashes to `key` (#2675). Every opening gets its own file, so a tab
/// closing never deletes a copy another tab still reads, and the process id
/// tells a later croft whose copy it is. The archive's own name ends it,
/// cut from the front to its last [`GUNZIP_NAME_KEEP`] bytes, so the whole
/// stays within the 255 bytes most file systems allow a name and a long
/// one still opens.
pub(super) fn gunzip_copy_name(key: u64, pid: u32, n: u64, inner: &str) -> String {
    let mut cut = inner.len().saturating_sub(GUNZIP_NAME_KEEP);
    while !inner.is_char_boundary(cut) {
        cut += 1;
    }
    format!("{key:016x}-{pid}-{n}-{}", &inner[cut..])
}

/// How much of an archive's name its copy keeps: 255 bytes less the
/// longest key, process id and count with their dashes (16, 10 and 20
/// digits, 3 dashes).
const GUNZIP_NAME_KEEP: usize = 255 - (16 + 10 + 20 + 3);

/// How many copies of the archive hashing to `key` this process has made
/// before this one.
fn next_gunzip_copy_number(key: u64) -> u64 {
    static MADE: std::sync::Mutex<std::collections::BTreeMap<u64, u64>> =
        std::sync::Mutex::new(std::collections::BTreeMap::new());
    let mut made = MADE.lock().unwrap_or_else(|e| e.into_inner());
    let n = made.entry(key).or_insert(0);
    *n += 1;
    *n - 1
}

/// The process that made the copy named `name`, for a name
/// [`gunzip_copy_name`] wrote.
fn gunzip_copy_owner(name: &str) -> Option<u32> {
    let mut parts = name.splitn(4, '-');
    let key = parts.next()?;
    let pid = parts.next()?;
    let n = parts.next()?;
    parts.next()?;
    let named = key.len() == 16
        && key.bytes().all(|b| b.is_ascii_hexdigit())
        && !n.is_empty()
        && n.bytes().all(|b| b.is_ascii_digit());
    named.then(|| pid.parse().ok()).flatten()
}

/// Delete the copies in `dir` that no running croft reads (#2675): those
/// of a process that is gone, such as one killed or cut off with its ssh
/// session, and, when `own` is set, this process's own. The way out that
/// skips the tabs' own clean-up sets it: the self-update relaunch keeps
/// this process id, so its copies would look in use forever.
pub(super) fn sweep_gunzip_copies(dir: &Path, own: bool) {
    let me = std::process::id();
    let Ok(entries) = std::fs::read_dir(dir) else {
        return;
    };
    for entry in entries.flatten() {
        let Some(pid) = entry.file_name().to_str().and_then(gunzip_copy_owner) else {
            continue;
        };
        let unused = if pid == me {
            own
        } else {
            !process_is_running(pid)
        };
        if unused {
            let _ = std::fs::remove_file(entry.path());
        }
    }
}

/// Whether a process with this id may be running. Only "no such process"
/// counts as gone: one this user may not signal, because a security policy
/// says no or another user took the id, counts as running, so a copy still
/// in use is never deleted. Where that cannot be asked, every other process
/// counts as running.
fn process_is_running(pid: u32) -> bool {
    #[cfg(unix)]
    {
        let Ok(pid) = libc::pid_t::try_from(pid) else {
            return true;
        };
        if pid <= 0 {
            return true;
        }
        // SAFETY: signal 0 only checks the process exists; nothing is sent.
        let probe = unsafe { libc::kill(pid, 0) };
        probe == 0 || std::io::Error::last_os_error().raw_os_error() != Some(libc::ESRCH)
    }
    #[cfg(not(unix))]
    {
        let _ = pid;
        true
    }
}

/// Delete this process's decompressed copies before an exit that skips the
/// tabs' own clean-up (#2675): the self-update relaunch and the drop back
/// to the local machine.
pub fn delete_own_gunzip_copies() {
    let dir = gunzip_scratch_path();
    if dir.is_dir()
        && let Ok(dir) = gunzip_scratch_dir()
    {
        sweep_gunzip_copies(&dir, true);
    }
}

impl Editor {
    /// Paint the rendered Markdown preview: the pre-built lines flow through
    /// a wrapping `Paragraph` so paragraphs reflow with the pane, scrolled by
    /// the preview's own offset, with a scrollbar over the wrapped height.
    /// Rebuilds first when the buffer moved under the preview (an edit, an
    /// external reload) so it always shows the current text. A preview to
    /// the side shows its source pane's text, which the app hands it
    /// (`App::sync_markdown_side_previews`, #1605).
    pub(super) fn render_markdown_preview(&mut self, inner: Rect, buf: &mut Buffer) {
        let stale = self
            .markdown_preview
            .as_ref()
            .is_some_and(|md| md.built_seq != self.edit_seq);
        let is_nb = self.markdown_preview.as_ref().is_some_and(|md| md.notebook);
        if stale && is_nb {
            // A JSON made invalid by the edit drops to the raw text.
            self.rebuild_notebook_preview();
        } else if stale {
            // The image-aware builder (#176): the plain one here left the
            // images list pointing at STALE anchors after a live edit.
            self.rebuild_markdown_preview();
        }
        let Some(md) = self.markdown_preview.as_mut() else {
            return;
        };
        // One-cell left margin; the right column stays free for the bar.
        let text_area = Rect {
            x: inner.x + 1,
            width: inner.width.saturating_sub(3),
            ..inner
        };
        if text_area.width == 0 {
            return;
        }
        let para = Paragraph::new(Text::from(md.lines.clone())).wrap(Wrap { trim: false });
        let total = para.line_count(text_area.width);
        let max_scroll = total.saturating_sub(inner.height as usize) as u16;
        md.scroll = md.scroll.min(max_scroll);
        // Anchor mapping (#176): each image's first reserved line as a
        // VISUAL row, through the same wrap the paragraph uses. Cached on
        // (built_seq, width) - blank lines never wrap, so the prefix
        // line_count is exact.
        if md.wrap_key != (md.built_seq, text_area.width) {
            let visual_row = |first_line: usize| {
                let prefix: Vec<Line> = md.lines[..first_line].to_vec();
                Paragraph::new(Text::from(prefix))
                    .wrap(Wrap { trim: false })
                    .line_count(text_area.width)
            };
            md.anchor_rows = md
                .images
                .iter()
                .map(|img| visual_row(img.first_line))
                .collect();
            // Same mapping for the play glyphs (#353); a glyph line can
            // wrap, but its first visual row is where the glyph paints.
            md.run_rows = md
                .runnables
                .iter()
                .map(|r| visual_row(r.first_line))
                .collect();
            // Scroll sync (#619): each built line's first visual row. A
            // paragraph wraps line by line, so per-line counts sum exactly.
            let mut row = 0usize;
            md.row_of_line = md
                .lines
                .iter()
                .map(|l| {
                    let here = row;
                    row += Paragraph::new(Text::from(vec![l.clone()]))
                        .wrap(Wrap { trim: false })
                        .line_count(text_area.width)
                        .max(1);
                    here
                })
                .collect();
            md.wrap_key = (md.built_seq, text_area.width);
        }
        if let Some(line) = md.scroll_to_source.take()
            && let Some(row) = md.row_for_source_line(line)
        {
            md.scroll = row.min(usize::from(max_scroll)) as u16;
        }
        md.last_area = text_area;
        // The link under the pointer lifts like a hovered row (#1939), so it
        // reads as clickable before the click. Asked after the frame's
        // scroll, area and wrap are settled, so the hit-test sees this frame.
        match self.pointer.and_then(|(col, row)| md.link_at(col, row)) {
            Some(i) => {
                let bg = crate::widgets::hover::hover_bg(self.theme);
                let (lines, skip) = md.view_with_hovered_link(i, bg, text_area.height);
                Paragraph::new(Text::from(lines))
                    .wrap(Wrap { trim: false })
                    .scroll((skip, 0))
                    .render(text_area, buf);
            }
            None => para.scroll((md.scroll, 0)).render(text_area, buf),
        }
        // Frame truth for selection (#215): the rendered view is a wrapped
        // Paragraph, so the only faithful record of what the user sees is
        // the cells we just painted. Read them back per row, then tint the
        // selected span.
        md.rows = (0..text_area.height)
            .map(|dy| {
                (0..text_area.width)
                    .map(|dx| {
                        buf[(text_area.x + dx, text_area.y + dy)]
                            .symbol()
                            .to_string()
                    })
                    .collect::<Vec<String>>()
            })
            .collect();
        if md.has_selection() {
            let sel_bg = self.theme.selection();
            for dy in 0..text_area.height {
                for dx in 0..text_area.width {
                    if md.cell_selected(dy, dx) {
                        buf[(text_area.x + dx, text_area.y + dy)].set_bg(sel_bg);
                    }
                }
            }
        }
        if let Some(metrics) = scrollbar::vertical_metrics(
            Rect {
                x: inner.x + inner.width.saturating_sub(1),
                y: inner.y,
                width: 1,
                height: inner.height,
            },
            total,
            inner.height as usize,
            md.scroll as usize,
        ) {
            self.last_scrollbar = metrics.area;
            scrollbar::render_vertical(buf, metrics, self.focused, self.theme);
        }
    }
}

/// A reader's place in a SQLite tab, carried across a reload (#1643).
pub(super) struct SqlitePlace {
    sheet: usize,
    table: String,
    page: usize,
    cell: (usize, usize),
    scroll: (usize, usize),
}

/// Where SQLite keeps `path`'s write-ahead log, if `path` were a database
/// in WAL mode: the same name with `-wal` after it (#1643).
///
/// SQLite keeps the log beside the real database file, so a database opened
/// through a symlink has its log beside the link's target, not the link.
pub fn sqlite_wal_path(path: &Path) -> Option<PathBuf> {
    let path = std::fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf());
    let mut name = path.file_name()?.to_os_string();
    name.push("-wal");
    Some(path.with_file_name(name))
}