bigtext 0.17.0

Free editor for huge text and log files (1-50+ GB): opens them without loading them into memory, 4 GB/s search, atomic save
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
//! Application shell: tabs, menus, dialogs, status bar and background-job plumbing.

pub mod alerts;
pub mod archive;
pub mod clipboard;
pub mod column_chart;
pub mod column_editor;
pub mod columns;
pub mod commands;
#[cfg(test)]
mod compat_tests;
pub mod convert;
pub mod copy_as;
pub mod csv_tools;
pub mod derive_column;
pub mod document;
pub mod export;
pub mod extras;
pub mod fields_panel;
pub mod file_ops;
pub mod filter_panel;
pub mod find_in_files;
pub mod fold;
pub mod folder_tree;
pub mod follow_id;
pub mod fonts;
pub mod gaps_panel;
pub mod goto;
pub mod i18n;
mod i18n_de;
mod i18n_es;
mod i18n_pt;
mod i18n_texts;
mod i18n_tr;
mod i18n_zh;
pub mod join_tables;
pub mod json_crumb;
pub mod json_diff_panel;
pub mod json_fields_window;
pub mod json_panel;
pub mod json_validate;
pub mod keynav;
pub mod levels;
pub mod lines_edit;
pub mod log_report;
pub mod log_sources;
pub mod marks;
pub mod match_bracket;
pub mod match_count;
pub mod match_values;
pub mod merge_logs;
pub mod multi_cursor;
pub mod nav;
pub mod notify;
pub mod only_in;
pub mod ops;
pub mod patterns_window;
pub mod pivot;
pub mod portable;
pub mod problems_panel;
pub mod properties;
pub mod quick_open;
pub mod recovery;
pub mod remote;
pub mod run_command;
pub mod saved_searches;
pub mod search_panel;
pub mod sessions;
pub mod share;
pub mod shell;
pub mod sql_dump;
pub mod status_bar;
pub mod symbols;
pub mod table_compare;
pub mod tabs;
pub mod tasks;
pub mod text_tools;
pub mod theme;
pub mod time_link;
pub mod time_range;
pub mod timeline;
pub mod update;
pub mod welcome;

use std::collections::VecDeque;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::mpsc::{self, Receiver, Sender};
use std::sync::Arc;
use std::time::{Duration, Instant};

use egui::Key;

use bigtext::encoding::{self, Detected, Encoding};
use bigtext::file::{self, OpenMode, Source};
use bigtext::jobs::{self, human_bytes, CancelToken, Waker};
use bigtext::replace::Template;
use bigtext::search::Matcher;
use bigtext::text::Batch;

use crate::view::{hex_view, table_view, text_view};
use document::{Banner, DocState, Document, Restore};

/// What the command line asks for.
#[derive(Default)]
pub struct StartOptions {
    /// Files with the line to open them at.
    pub files: Vec<(PathBuf, Option<u64>)>,
    pub find: Option<bigtext::search::Query>,
    pub follow: bool,
    /// Temporary file that standard input is copied into.
    pub stdin: Option<PathBuf>,
}

pub struct Opened {
    pub source: Arc<Source>,
    pub detected: Detected,
    pub elapsed: Duration,
    /// Canonical path (resolved on the worker; can be slow on network drives).
    pub path: PathBuf,
    pub read_only: bool,
    /// The compressed file that `path` was unpacked from.
    pub unpacked: Option<PathBuf>,
    /// The archive's file it is, when `unpacked` is an archive.
    pub member: Option<String>,
    /// The encoding of the byte order mark the file starts with.
    pub bom: Option<Encoding>,
    /// An unpacked copy opened while the rest is still being unpacked.
    pub growing: bool,
}

/// The Replace preview: the document id, each match as (offset, text before, text after), and the
/// line number of each match.
type ReplacePreview = (u64, Vec<(u64, String, String)>, Vec<u64>);

pub enum Msg {
    Opened {
        doc: u64,
        result: Result<Opened, String>,
    },
    Copied {
        doc: u64,
        result: Result<String, String>,
        /// For a cut: the range copied and the document version then, so only that text is
        /// deleted, and only if the document did not change meanwhile.
        cut: Option<(std::ops::Range<u64>, u64)>,
    },
    Found {
        doc: u64,
        version: u64,
        found: Option<(u64, u64)>,
        wrapped: bool,
    },
    /// The number of the match `sel` among the counted ones (`match_count`).
    MatchNumber {
        doc: u64,
        version: u64,
        sel: (u64, u64),
        number: Option<u64>,
    },
    TempWritten(Box<ops::TempWritten>),
    Finalized(Box<ops::Finalized>),
    JobFailed {
        doc: u64,
        msg: Option<String>,
    },
    ReplaceBatch {
        doc: u64,
        version: u64,
        batch: Batch,
        count: usize,
    },
    ReplaceTooMany {
        doc: u64,
        version: u64,
        matcher: Arc<Matcher>,
        template: Template,
        range: std::ops::Range<u64>,
    },
    Preview {
        doc: u64,
        version: u64,
        /// Which preview it is (`BigTextApp::preview_seq`).
        seq: u64,
        items: Vec<(u64, String, String)>,
        lines: Vec<u64>,
    },
    FileChanged(Box<FileChange>),
    LowSpace(Box<LowSpace>),
    /// A document's recovery journal was written (or failed to be).
    Journaled {
        doc: u64,
        version: u64,
        add_len: u64,
        ok: bool,
    },
    LinesRemoved(Box<lines_edit::LinesRemoved>),
    /// Files another launch handed over.
    OpenRequest(Box<StartOptions>),
    LinesTooMany {
        doc: u64,
        version: u64,
        sel: Arc<lines_edit::LineSel>,
        keep: bool,
    },
    /// An archive's files, for the picker: (tab, archive, files).
    ArchiveListed(Box<(u64, PathBuf, Vec<bigtext::decompress::Member>)>),
    Update(update::Event),
    ColumnsDeleted(Box<columns::ColumnsDeleted>),
    TaskDone {
        id: u64,
        outcome: tasks::TaskOutcome,
    },
    TextOp(Box<text_tools::TextOpDone>),
    CsvRewritten(Box<csv_tools::CsvRewritten>),
    TimeFound {
        doc: u64,
        version: u64,
        result: Result<u64, bigtext::timestamp::TimeError>,
    },
    Aligned(Box<time_link::Aligned>),
    JsonCrumb(Box<json_crumb::CrumbMsg>),
    Folds(Box<fold::FoldMsg>),
    Unpacked(Box<Unpacked>),
    LevelFound(Box<levels::LevelFound>),
    CursorFound(Box<multi_cursor::CursorFound>),
    BracketJump(Box<match_bracket::BracketJump>),
    Json(Box<json_panel::JsonDone>),
    TimeRange(Box<time_range::RangeDone>),
    /// A remote file opened to be read in place (or why it could not be).
    RemoteOpened {
        doc: u64,
        src: remote::Source,
        result: Result<Box<remote::RemoteOpened>, remote::RemoteFail>,
    },
    /// Something a worker could not do, for the error dialog.
    Error(String),
    /// A click on an alert's system notification.
    AlertClicked,
}

pub struct Settings {
    pub font_size: f32,
    /// The theme shown; while `theme_system` is on, the system's dark or light one.
    pub theme: theme::Theme,
    /// Follows the system's dark or light mode (the default until a theme is chosen).
    pub theme_system: bool,
    /// Colour-blind-safe colours.
    pub cvd: bool,
    /// Interface scale in per cent (menus and dialogs; the text has its own size).
    pub scale: u16,
    pub show_perf: bool,
    pub backup_on_save: bool,
    pub syntax: bool,
    /// Highlight patterns (View → Highlights).
    pub marks: Vec<marks::Mark>,
    /// Font file of the text (None: the built-in font).
    pub font_path: Option<PathBuf>,
    /// Where unpacked copies go (`None`: the system temp folder).
    pub unpack_dir: Option<PathBuf>,
    /// The log level bar above log files.
    pub level_bar: bool,
    /// Saved searches (the ★ menu of the search bar).
    pub saved: Vec<saved_searches::SavedSearch>,
    /// View → Show whitespace and line breaks, in text and in code (off: indent guides only).
    pub show_ws: bool,
    pub show_ws_code: bool,
    /// View → Theme → Code colours.
    pub code_theme: theme::CodeTheme,
    /// Filter view: lines shown before and after each match, and whole log entries.
    pub filter_context: u32,
    pub filter_entries: bool,
    /// Keys whose values are ids (None: the defaults).
    pub id_keys: Option<Vec<String>>,
    /// The fields the status bar shows.
    pub status: status_bar::StatusFields,
    /// Zen mode: no menu, tab, level or status bar (not kept across starts).
    pub zen: bool,
    /// Line numbers in the text and table views.
    pub show_gutter: bool,
    /// View → Wrap at: rows wrap at this column (`None`: the window's width).
    pub wrap_column: Option<u16>,
    /// View → Ruler at column.
    pub ruler: Option<u16>,
    /// The JSON path at the caret in the status bar.
    pub json_crumb: bool,
    /// Edit → External tools.
    pub tools: Vec<run_command::Tool>,
}

#[derive(Clone, Copy, PartialEq, Eq)]
pub(crate) enum GotoMode {
    Line,
    Offset,
    Time,
}

struct GotoDialog {
    text: String,
    mode: GotoMode,
    error: Option<String>,
    focus: bool,
    /// A running go-to-time search.
    busy: Option<CancelToken>,
}

impl GotoDialog {
    fn new(mode: GotoMode) -> Option<GotoDialog> {
        Some(GotoDialog {
            text: String::new(),
            mode,
            error: None,
            focus: true,
            busy: None,
        })
    }
}

struct Confirm {
    title: String,
    message: String,
    action: ConfirmAction,
    checkbox: Option<(String, bool)>,
}

#[derive(Clone)]
enum ConfirmAction {
    CloseTab(u64),
    Exit,
    /// Save over a file another program changed since it was opened.
    SaveOverChanged {
        doc: u64,
    },
    CopyLarge {
        doc: u64,
        cut: bool,
    },
    ReplaceOnDisk {
        doc: u64,
    },
    DeleteColumns {
        doc: u64,
        dialect: bigtext::csv::Dialect,
        cols: Vec<usize>,
        on_disk: bool,
    },
    CsvRewrite {
        doc: u64,
        dialect: bigtext::csv::Dialect,
        rewrite: bigtext::csv::Rewrite,
        on_disk: bool,
    },
    LowSpace(Box<LowSpace>),
    LinesOnDisk {
        doc: u64,
        sel: Arc<lines_edit::LineSel>,
        keep: bool,
    },
    TextOpOnDisk {
        doc: u64,
        op: bigtext::textops::Op,
        range: std::ops::Range<u64>,
    },
    ColumnEditOnDisk {
        doc: u64,
        from: u64,
        cells: (u32, u32),
        gen: bigtext::column_edit::ColumnGen,
    },
    SortOnDisk {
        doc: u64,
        spec: bigtext::extsort::SortSpec,
        eol: Vec<u8>,
    },
    /// A file or folder of the side bar to the Recycle Bin.
    Trash(PathBuf),
}

#[derive(Default)]
pub struct FrameStats {
    times: VecDeque<f32>,
    pub last_ms: f32,
}

impl FrameStats {
    fn push(&mut self, ms: f32) {
        self.last_ms = ms;
        self.times.push_back(ms);
        if self.times.len() > 240 {
            self.times.pop_front();
        }
    }
    pub fn avg(&self) -> f32 {
        if self.times.is_empty() {
            0.0
        } else {
            self.times.iter().sum::<f32>() / self.times.len() as f32
        }
    }
    pub fn max(&self) -> f32 {
        self.times.iter().copied().fold(0.0, f32::max)
    }
}

pub struct BigTextApp {
    pub docs: Vec<Document>,
    pub active: usize,
    next_id: u64,
    untitled: usize,
    tx: Sender<Msg>,
    rx: Receiver<Msg>,
    waker: Waker,
    pub settings: Settings,
    goto: Option<GotoDialog>,
    confirm: Option<Confirm>,
    error: Option<String>,
    pub frame: FrameStats,
    pub process_start: Instant,
    pub first_frame: Option<Duration>,
    pub bench: Option<crate::bench_ui::BenchUi>,
    pub self_test: Option<crate::self_test::SelfTest>,
    exit_confirmed: bool,
    exit_after_jobs: bool,
    /// The window title last sent to the system.
    window_title: String,
    pub show_about: bool,
    pub recent: Vec<PathBuf>,
    /// Session state is saved and restored (off for benchmarks and the self-test).
    pub persist: bool,
    pub diff: Option<extras::DiffResults>,
    pub search: search_panel::SearchUi,
    pending_replace: Option<(u64, Arc<Matcher>, Template, std::ops::Range<u64>)>,
    preview: Option<ReplacePreview>,
    /// The Replace preview being found, and the number of the latest one started.
    preview_job: Option<ops::PreviewJob>,
    preview_seq: u64,
    pub update: update::UpdateUi,
    /// The page over an empty start and the note after an update.
    pub welcome: welcome::Welcome,
    pub tasks: Vec<tasks::Task>,
    next_task: u64,
    pub notice: Option<tasks::Notice>,
    pub marks: marks::MarksUi,
    pub export: export::ExportUi,
    pub csv: csv_tools::CsvUi,
    pub merge: merge_logs::MergeUi,
    /// Edit → Run command on selection.
    pub run_cmd: run_command::RunCommandUi,
    pub saved_ui: saved_searches::SavedUi,
    pairs: match_bracket::PairCache,
    /// View → JSON structure is shown.
    pub json_open: bool,
    /// Document ids, most recently used first (for Ctrl+Tab).
    mru: Vec<u64>,
    pub switcher: Option<tabs::TabSwitcher>,
    pub sessions: sessions::SessionsUi,
    pub portable: portable::PortableUi,
    pub ids: follow_id::IdUi,
    pub fields: fields_panel::FieldsUi,
    pub gaps: gaps_panel::GapsUi,
    pub range: time_range::TimeRangeUi,
    pub patterns: patterns_window::PatternsUi,
    pub log_report: log_report::ReportUi,
    pub log_sources: log_sources::SourcesUi,
    pub alerts: alerts::AlertsUi,
    pub sql_dump: sql_dump::DumpUi,
    pub share: share::ShareUi,
    pub nav: nav::NavHistory,
    pub values: Option<match_values::ValuesDialog>,
    pub problems: problems_panel::ProblemsUi,
    pub join: Option<join_tables::JoinDialog>,
    pub table_compare: Option<table_compare::CompareTablesDialog>,
    pub pivot: Option<pivot::PivotDialog>,
    pub derive: Option<derive_column::DeriveDialog>,
    pub chart: column_chart::ChartUi,
    pub json_check: json_validate::JsonCheckUi,
    pub json_fields: json_fields_window::JsonFieldsUi,
    pub json_diff: json_diff_panel::JsonDiffUi,
    /// A comparison to start once its document is ready: (document, other file).
    pub diff_pending: Option<(u64, PathBuf)>,
    pub diff_switches: extras::DiffSwitches,
    /// View → Compare side by side.
    pub side_by_side: bool,
    pub only_in_dialog: Option<only_in::OnlyInDialog>,
    pub only_in: Option<only_in::OnlyInResults>,
    pub archive_picker: Option<archive::ArchivePicker>,
    /// Help → Unpacked copies folder… is open.
    pub unpack_dir_open: bool,
    pub properties: Option<properties::PropertiesUi>,
    pub recovery: recovery::RecoveryState,
    pub text_result: Option<text_tools::TextResult>,
    pub column_editor: Option<column_editor::ColumnEditor>,
    /// Listening for other launches (dropped on exit, removing the lock).
    instance: Option<crate::instance::Server>,
    /// A later launch handed over its files: [`eframe::App::logic`] brings the window back.
    to_front: Arc<AtomicBool>,
    pub(crate) tab_bar_seen: tabs::TabBarSeen,
    pub(crate) status_seen: status_bar::StatusSeen,
    pub clips: clipboard::ClipHistory,
    pub files: find_in_files::FilesUi,
    /// File → Open folder: the side bar's tree.
    pub folder: folder_tree::FolderUi,
    /// Search → Go to file and the folder's files it chooses from.
    pub quick_open: Option<quick_open::QuickOpen>,
    pub file_index: quick_open::FileIndex,
    /// The side bar's New file, Rename and Move to the trash.
    pub file_ops: file_ops::FileOps,
    /// File → Open remote file or URL, and the remote files followed.
    pub remote: remote::RemoteUi,
    /// Search → Go to symbol.
    pub symbols: Option<symbols::SymbolsUi>,
    pub timeline: timeline::TimelineUi,
    pub keymap: commands::Keymap,
    pub palette: Option<commands::Palette>,
    pub shortcuts_ui: commands::ShortcutsUi,
    pub fonts: fonts::FontsUi,
    /// Matcher for the occurrences of the selected text, by the text it was built for.
    occurrences: Option<(String, bigtext::encoding::Codec, Option<Arc<Matcher>>)>,
    /// Document to search once it is open (command line --find).
    pending_find: Option<u64>,
    /// What was chosen for files that are not open, most recently used first.
    pub file_opts: Vec<extras::FileOpts>,
    /// The latest announcement for screen readers (a live region says it when it changes).
    pub announcement: Option<String>,
    /// Find All was running in the last frame.
    results_running: bool,
    /// The window is full screen (as the system reported it this frame).
    pub fullscreen: bool,
    /// The latest Go to this time in all tabs (older answers are dropped).
    align_seq: u64,
    /// The latest time lookup of a linked view, and the job doing it.
    link_seq: u64,
    link_job: Option<(CancelToken, Instant)>,
    /// The mode View → Link scrolling links with.
    pub link_mode: time_link::LinkMode,
}

/// The narrowest View → Wrap at column.
pub const WRAP_MIN: u16 = 4;

/// Turns I/O errors into messages a user can act on.
pub fn friendly_io(e: &std::io::Error, path: &Path) -> String {
    let p = file::display_path(path);
    match (e.kind(), e.raw_os_error()) {
        (_, Some(32)) | (_, Some(33)) => {
            i18n::trf("“{p}” is in use by another process.", &[("p", &p)])
        }
        (std::io::ErrorKind::PermissionDenied, _) => i18n::trf(
            "Access denied: “{p}”. Check permissions or the read-only attribute.",
            &[("p", &p)],
        ),
        (std::io::ErrorKind::NotFound, _) => i18n::trf("File not found: “{p}”.", &[("p", &p)]),
        _ => format!("{p}: {e}"),
    }
}

/// An unpack or a save that would not fit on its drive, waiting for the user.
#[derive(Clone)]
pub struct LowSpace {
    /// Bytes needed (estimated for unpacking) and free.
    pub need: u64,
    pub free: u64,
    pub dir: PathBuf,
    pub resume: Resume,
}

/// What to do again after a low-space warning.
#[derive(Clone)]
pub enum Resume {
    Open {
        doc: u64,
        path: PathBuf,
        member: Option<String>,
        forced: Option<Encoding>,
        size: Option<u64>,
    },
    Write {
        doc: u64,
        target: PathBuf,
        spec: ops::WriteSpec,
        backup: bool,
    },
}

/// What the watcher saw happen to a document's file.
pub struct FileChange {
    pub doc: u64,
    pub deleted: bool,
    pub grown: bool,
    pub shrunk: bool,
    /// The path names another file now (the log was rotated).
    pub rotated: bool,
    /// Where the old content most likely went.
    pub rotated_to: Option<PathBuf>,
}

/// What opening a folder returns instead of a file: it goes to the side bar.
const FOLDER: &str = "\u{1}folder";

/// The widest a side panel (folder, structure, fields) may get: 60% of the width left beside it,
/// so the text keeps room whatever the panel holds or how far it is dragged.
fn side_panel_max(ui: &egui::Ui) -> f32 {
    (ui.available_width() * 0.6).max(120.0)
}

fn open_worker(path: &Path, forced: Option<Encoding>, mode: OpenMode) -> Result<Opened, String> {
    let t = Instant::now();
    let canonical = std::fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf());
    let path = canonical.as_path();
    if std::fs::metadata(path).is_ok_and(|m| m.is_dir()) {
        return Err(FOLDER.into());
    }
    let src = Source::open(path, mode).map_err(|e| friendly_io(&e, path))?;
    let read_only = std::fs::metadata(path)
        .map(|m| m.permissions().readonly())
        .unwrap_or(false);
    let n = src.len().min(1 << 20);
    let whole = n == src.len();
    let (det, bom) = {
        let sample = src.read(0..n).map_err(|e| friendly_io(&e, path))?;
        let bom = Encoding::ALL
            .into_iter()
            .find(|e| !e.bom().is_empty() && sample.starts_with(e.bom()));
        let det = match forced {
            Some(enc) => encoding::detect_with(&sample, whole, enc, 0),
            None => encoding::detect(&sample, whole),
        };
        (det, bom)
    };
    Ok(Opened {
        source: Arc::new(src),
        detected: det,
        elapsed: t.elapsed(),
        path: canonical.clone(),
        read_only,
        unpacked: None,
        member: None,
        bom,
        growing: false,
    })
}

/// Opens `path`, unpacking it into a temporary file first when it is compressed.
/// What went wrong unpacking `path`.
fn unpack_error(path: &Path, e: std::io::Error) -> String {
    match e.kind() {
        std::io::ErrorKind::InvalidData | std::io::ErrorKind::NotFound => {
            format!("{}: {e}", file::display_path(path))
        }
        _ => i18n::trf(
            "Could not unpack into {dir}: {e}",
            &[
                ("dir", &file::display_path(&bigtext::decompress::temp_dir())),
                ("e", &e.to_string()),
            ],
        ),
    }
}

/// Unpacks the archive's file `member` (and a compressed file inside it) and opens the copy.
fn open_member(
    path: &Path,
    member: &str,
    forced: Option<Encoding>,
    cancel: &CancelToken,
    progress: &jobs::Progress,
) -> Result<Opened, String> {
    use bigtext::decompress as dc;
    let archive = dc::detect_archive(path).ok_or_else(|| {
        i18n::trf(
            "{file} is not an archive any more.",
            &[("file", &file::display_path(path))],
        )
    })?;
    let cancelled = || i18n::tr("Unpacking was cancelled.").to_string();
    let mut temp = dc::unpack_member(path, archive, member, cancel, progress)
        .map_err(|e| unpack_error(path, e))?
        .ok_or_else(cancelled)?;
    if let Some(kind) = dc::detect(&temp) {
        let inner = dc::unpack(&temp, kind, cancel, progress);
        dc::remove_temp(&temp);
        temp = inner
            .map_err(|e| unpack_error(path, e))?
            .ok_or_else(cancelled)?;
    }
    match open_worker(&temp, forced, OpenMode::Auto) {
        Ok(mut o) => {
            o.unpacked = Some(path.to_path_buf());
            o.member = Some(member.to_string());
            Ok(o)
        }
        Err(e) => {
            dc::remove_temp(&temp);
            Err(e)
        }
    }
}

/// How live unpacking ended.
pub struct Unpacked {
    pub doc: u64,
    pub temp: PathBuf,
    /// The unpacked size, `None` when cancelled.
    pub result: Result<Option<u64>, String>,
}

/// Unpacks the compressed file `path` into a temporary copy that opens as soon as its first
/// megabyte is there; the rest arrives as a followed log's does, and `Msg::Unpacked` tells how it
/// ended. A file done before that opens as usual.
#[allow(clippy::too_many_arguments)]
fn open_unpacking(
    doc: u64,
    path: &Path,
    kind: bigtext::decompress::Kind,
    forced: Option<Encoding>,
    cancel: &CancelToken,
    progress: &jobs::Progress,
    tx: &Sender<Msg>,
    waker: &Waker,
) {
    use bigtext::decompress as dc;
    let temp = dc::temp_path_for(path);
    let mut opened = false;
    let result = dc::unpack_live(path, kind, &temp, cancel, progress, || {
        let r = open_worker(&temp, forced, OpenMode::Chunked).map(|mut o| {
            o.unpacked = Some(path.to_path_buf());
            o.growing = true;
            o
        });
        opened = r.is_ok();
        if opened {
            let _ = tx.send(Msg::Opened { doc, result: r });
            waker();
        }
    });
    let failed = |e: std::io::Error| match e.kind() {
        std::io::ErrorKind::InvalidData => format!("{}: {e}", file::display_path(path)),
        _ => i18n::trf(
            "Could not unpack into {dir}: {e}",
            &[
                ("dir", &file::display_path(&dc::temp_dir())),
                ("e", &e.to_string()),
            ],
        ),
    };
    if opened {
        let result = result.map_err(failed);
        let _ = tx.send(Msg::Unpacked(Box::new(Unpacked { doc, temp, result })));
    } else {
        let r = match result {
            Ok(Some(_)) => open_worker(&temp, forced, OpenMode::Auto).map(|mut o| {
                o.unpacked = Some(path.to_path_buf());
                o
            }),
            Ok(None) => Err(i18n::tr("Unpacking was cancelled.").into()),
            Err(e) => Err(failed(e)),
        };
        if r.is_err() {
            dc::remove_temp(&temp);
        }
        let _ = tx.send(Msg::Opened { doc, result: r });
    }
    waker();
}

fn open_or_unpack(
    path: &Path,
    forced: Option<Encoding>,
    cancel: &CancelToken,
    progress: &jobs::Progress,
) -> Result<Opened, String> {
    let Some(kind) = bigtext::decompress::detect(path) else {
        return open_worker(path, forced, OpenMode::Auto);
    };
    match bigtext::decompress::unpack(path, kind, cancel, progress) {
        Ok(Some(temp)) => match open_worker(&temp, forced, OpenMode::Auto) {
            Ok(mut o) => {
                o.unpacked = Some(path.to_path_buf());
                Ok(o)
            }
            Err(e) => {
                bigtext::decompress::remove_temp(&temp);
                Err(e)
            }
        },
        Ok(None) => Err(i18n::tr("Unpacking was cancelled.").into()),
        Err(e) if e.kind() == std::io::ErrorKind::InvalidData => {
            Err(format!("{}: {e}", file::display_path(path)))
        }
        Err(e) => Err(i18n::trf(
            "Could not unpack into {dir}: {e}",
            &[
                ("dir", &file::display_path(&bigtext::decompress::temp_dir())),
                ("e", &e.to_string()),
            ],
        )),
    }
}

/// Lexical path comparison (no file-system access, so it is safe on the UI thread):
/// ignores the `\\?\` prefix, and case and separators on Windows.
pub fn same_path(a: &Path, b: &Path) -> bool {
    fn norm(p: &Path) -> String {
        let s = file::display_path(p);
        let s = std::path::absolute(&s)
            .map(|p| p.to_string_lossy().into_owned())
            .unwrap_or(s);
        if cfg!(windows) {
            s.replace('/', "\\").to_lowercase()
        } else {
            s
        }
    }
    norm(a) == norm(b)
}

/// An app without a window, saved settings or journal folder, for tests.
#[cfg(test)]
pub(crate) fn test_app() -> BigTextApp {
    let cc = eframe::CreationContext::_new_kittest(egui::Context::default());
    BigTextApp::new(&cc, StartOptions::default(), Instant::now(), false)
}

impl BigTextApp {
    pub fn new(
        cc: &eframe::CreationContext<'_>,
        start: StartOptions,
        process_start: Instant,
        persist: bool,
    ) -> Self {
        let (tx, rx) = mpsc::channel();
        let ctx = cc.egui_ctx.clone();
        let waker: Waker = Arc::new(move || ctx.request_repaint());
        cc.egui_ctx.options_mut(|o| o.zoom_with_keyboard = false);
        // The built-in fonts with the interface's fallbacks; a saved text font or Chinese below
        // applies them again.
        let _ = fonts::apply_font(&cc.egui_ctx, None);
        let mut app = BigTextApp {
            docs: Vec::new(),
            active: 0,
            next_id: 1,
            untitled: 0,
            tx,
            rx,
            waker,
            settings: Settings {
                font_size: 14.0,
                theme: theme::Theme::Dark,
                theme_system: false,
                cvd: false,
                scale: 100,
                show_perf: false,
                backup_on_save: false,
                syntax: true,
                marks: Vec::new(),
                font_path: None,
                unpack_dir: None,
                level_bar: true,
                saved: Vec::new(),
                show_ws: false,
                show_ws_code: false,
                code_theme: Default::default(),
                filter_context: 0,
                filter_entries: false,
                id_keys: None,
                status: Default::default(),
                zen: false,
                show_gutter: true,
                wrap_column: None,
                ruler: None,
                json_crumb: true,
                tools: Vec::new(),
            },
            goto: None,
            confirm: None,
            error: None,
            frame: FrameStats::default(),
            process_start,
            first_frame: None,
            bench: None,
            self_test: None,
            exit_confirmed: false,
            exit_after_jobs: false,
            window_title: String::new(),
            show_about: false,
            recent: Vec::new(),
            persist,
            diff: None,
            search: search_panel::SearchUi::default(),
            pending_replace: None,
            preview: None,
            preview_job: None,
            preview_seq: 0,
            update: update::UpdateUi::default(),
            welcome: welcome::Welcome::default(),
            tasks: Vec::new(),
            next_task: 0,
            notice: None,
            marks: marks::MarksUi::default(),
            export: export::ExportUi::default(),
            csv: csv_tools::CsvUi::default(),
            merge: merge_logs::MergeUi::default(),
            run_cmd: Default::default(),
            saved_ui: saved_searches::SavedUi::default(),
            pairs: match_bracket::PairCache::default(),
            json_open: false,
            mru: Vec::new(),
            switcher: None,
            sessions: sessions::SessionsUi::default(),
            portable: portable::PortableUi::default(),
            ids: follow_id::IdUi::default(),
            fields: fields_panel::FieldsUi::default(),
            gaps: gaps_panel::GapsUi::default(),
            range: time_range::TimeRangeUi::default(),
            patterns: patterns_window::PatternsUi::default(),
            log_report: log_report::ReportUi::default(),
            log_sources: log_sources::SourcesUi::default(),
            alerts: alerts::AlertsUi::default(),
            sql_dump: sql_dump::DumpUi::default(),
            share: share::ShareUi::default(),
            nav: nav::NavHistory::default(),
            values: None,
            problems: problems_panel::ProblemsUi::default(),
            join: None,
            table_compare: None,
            pivot: None,
            derive: None,
            chart: column_chart::ChartUi::default(),
            json_check: json_validate::JsonCheckUi::default(),
            json_fields: json_fields_window::JsonFieldsUi::default(),
            json_diff: json_diff_panel::JsonDiffUi::default(),
            diff_pending: None,
            diff_switches: extras::DiffSwitches::default(),
            side_by_side: false,
            only_in_dialog: None,
            only_in: None,
            archive_picker: None,
            unpack_dir_open: false,
            properties: None,
            recovery: recovery::RecoveryState::new(),
            text_result: None,
            column_editor: None,
            instance: None,
            to_front: Arc::new(AtomicBool::new(false)),
            tab_bar_seen: tabs::TabBarSeen::default(),
            status_seen: status_bar::StatusSeen::default(),
            clips: clipboard::ClipHistory::default(),
            files: find_in_files::FilesUi::default(),
            folder: folder_tree::FolderUi::default(),
            quick_open: None,
            file_index: Default::default(),
            file_ops: Default::default(),
            remote: Default::default(),
            symbols: None,
            timeline: timeline::TimelineUi::default(),
            keymap: commands::Keymap::default(),
            palette: None,
            shortcuts_ui: commands::ShortcutsUi::default(),
            fonts: fonts::FontsUi::default(),
            occurrences: None,
            pending_find: None,
            file_opts: Vec::new(),
            announcement: None,
            results_running: false,
            fullscreen: false,
            align_seq: 0,
            link_seq: 0,
            link_job: None,
            link_mode: Default::default(),
        };
        app.search.query.case_sensitive = true;
        if persist {
            let mut state = extras::load();
            if state.unreadable {
                // Saving the defaults now would lose every saved search, key and highlight.
                app.persist = false;
                app.error = Some(
                    i18n::tr("BigText could not read its settings file, so it starts with the default settings and does not save over the file in this session.").into(),
                );
            }
            // Until a theme is chosen, the system's dark or light mode.
            app.settings.theme_system = true;
            app.update.restore(&state);
            app.welcome.enabled = true;
            app.welcome
                .after_start(state.loaded, state.seen_version.as_deref());
            update::cleanup_in_background();
            jobs::spawn("cleanup-unpacked", bigtext::decompress::cleanup_old);
            app.settings.marks = std::mem::take(&mut state.marks);
            app.search.history = std::mem::take(&mut state.history);
            app.settings.level_bar = state.level_bar.unwrap_or(true);
            app.settings.saved = std::mem::take(&mut state.saved);
            app.file_opts = std::mem::take(&mut state.file_opts);
            app.settings.status = state.status.unwrap_or_default();
            app.settings.show_gutter = state.gutter.unwrap_or(true);
            app.settings.wrap_column = state.wrap_column.flatten();
            app.settings.ruler = state.ruler.flatten();
            app.settings.json_crumb = state.json_crumb.unwrap_or(true);
            if let Some(l) = &state.log_sources {
                app.log_sources.set_line(l);
            }
            if let Some(o) = &state.alert_options {
                app.alerts.set_options_line(o);
            }
            app.alerts.recent = state
                .alert_recent
                .iter()
                .filter_map(|l| alerts::parse_query_line(l))
                .collect();
            app.settings.tools = std::mem::take(&mut state.tools);
            app.run_cmd.history = std::mem::take(&mut state.commands);
            app.run_cmd.shell = state
                .shell
                .as_deref()
                .map(run_command::ShellChoice::from_id)
                .unwrap_or_default();
            app.settings.show_ws = state.show_ws.unwrap_or(false);
            app.settings.show_ws_code = state.show_ws_code.unwrap_or(false);
            if let Some(root) = state.folder.take() {
                app.restore_folder(
                    root,
                    state.folder_open.unwrap_or(true),
                    std::mem::take(&mut state.folder_expanded),
                );
            }
            app.recovery.enabled = state.recovery.unwrap_or(true);
            app.settings.id_keys = state.id_keys.take();
            if let Some((n, e)) = state.filter_ctx {
                app.settings.filter_context = n.min(bigtext::filter::CONTEXT_MAX);
                app.settings.filter_entries = e;
            }
            // A font that is gone or broken is forgotten; the built-in one is used.
            if let Some(p) = state.font.take() {
                if fonts::apply_font(&cc.egui_ctx, Some(&p)).is_ok() {
                    app.settings.font_path = Some(p);
                }
            }
            // A first start speaks the system's language when BigText knows it.
            if let Some(l) = state
                .lang
                .as_deref()
                .and_then(i18n::Lang::from_code)
                .or_else(|| state.lang.is_none().then(i18n::system_lang).flatten())
            {
                i18n::set_lang(l);
                if l == i18n::Lang::Zh {
                    let _ = fonts::apply_font(&cc.egui_ctx, app.settings.font_path.as_deref());
                }
            }
            for (id, k) in std::mem::take(&mut state.keys) {
                if let (Some(c), Some(k)) =
                    (commands::Cmd::from_id(&id), commands::key_from_string(&k))
                {
                    app.keymap.changed.insert(c, k);
                }
            }
            if start.files.is_empty() && start.stdin.is_none() {
                app.restore_session(state);
            } else {
                app.restore_look(&state);
                app.recent = state.recent;
                app.settings.font_size = state.font_size.unwrap_or(14.0).clamp(6.0, 72.0);
                app.settings.syntax = state.syntax.unwrap_or(true);
            }
            app.start_recovery(recovery::default_dir());
        }
        app.apply_look(&cc.egui_ctx);
        app.apply_start(start);
        if app.docs.is_empty() {
            app.new_doc();
        }
        app
    }

    /// Opens the files from the command line (at their lines, followed, searched).
    pub(crate) fn apply_start(&mut self, start: StartOptions) {
        let follow = start.follow;
        let opened = |app: &mut BigTextApp, path: PathBuf, line: Option<u64>, end: bool| {
            app.open_path_at(path, line);
            let Some(d) = app.docs.get_mut(app.active) else {
                return;
            };
            d.follow |= follow;
            match (line, d.is_ready()) {
                (None, true) if end => d.set_caret(d.buf.len(), false),
                (None, false) if end => {
                    d.restore = Some(Restore {
                        end: true,
                        ..Default::default()
                    })
                }
                _ => {}
            }
        };
        for (path, line) in start.files {
            // user@host:/path, ssh://…, https://… (with --follow: the end of a remote log, followed).
            let addr = path.to_string_lossy().into_owned();
            if !path.exists() && remote::parse(&addr).is_some() {
                let how = if follow {
                    remote::How::Tail(1)
                } else {
                    remote::How::InPlace
                };
                if let Err(e) = self.open_remote(&addr, how) {
                    self.error = Some(e);
                }
                continue;
            }
            opened(self, path, line, follow);
        }
        if let Some(path) = start.stdin {
            opened(self, path, None, true);
            if let Some(d) = self.docs.get_mut(self.active) {
                d.title = "stdin".into();
                d.temporary = true;
                d.read_only = true;
                d.follow = true;
            }
        }
        if let Some(q) = start.find {
            self.search.query = q;
            self.search.open = true;
            self.pending_find = self.docs.get(self.active).map(|d| d.id);
        }
    }

    /// Runs the command line's `--find` once its document has opened.
    fn run_pending_find(&mut self) {
        let Some(id) = self.pending_find else { return };
        match self.docs.iter().position(|d| d.id == id) {
            // After a --line go-to has its exact position (it can start as an estimate).
            Some(i) if self.docs[i].is_ready() && self.docs[i].view.pending_goto_line.is_none() => {
                self.pending_find = None;
                self.active = i;
                self.find_next(true);
            }
            Some(i) if matches!(self.docs[i].state, DocState::Failed(_)) => {
                self.pending_find = None
            }
            Some(_) => {}
            None => self.pending_find = None,
        }
    }

    fn alloc_id(&mut self) -> u64 {
        self.next_id += 1;
        self.next_id
    }

    pub fn new_doc(&mut self) {
        self.untitled += 1;
        let id = self.alloc_id();
        self.docs.push(Document::untitled(id, self.untitled));
        self.active = self.docs.len() - 1;
    }

    /// Opens `path` (or goes to its tab) at line `line` (1-based) when given.
    pub(crate) fn open_path_at(&mut self, path: PathBuf, line: Option<u64>) {
        self.open_path(path);
        let (Some(n), Some(d)) = (line, self.docs.get_mut(self.active)) else {
            return;
        };
        if d.is_ready() {
            d.goto_line(n);
        } else {
            d.restore = Some(Restore {
                line: Some(n),
                ..Default::default()
            });
        }
    }

    pub fn open_path(&mut self, path: PathBuf) {
        let canon = std::path::absolute(&path).unwrap_or(path);
        // An archive opens again for another of its files.
        let archive = bigtext::decompress::detect_archive(&canon).is_some();
        if let Some(i) = self.docs.iter().position(|d| {
            !archive
                && d.path
                    .as_deref()
                    .or(d.unpacked_from.as_deref())
                    .is_some_and(|p| same_path(p, &canon))
        }) {
            self.active = i;
            return;
        }
        // Replace a pristine untitled tab.
        if self.docs.len() == 1
            && self.docs[0].path.is_none()
            && !self.docs[0].is_modified()
            && self.docs[0].buf.is_empty()
        {
            self.docs.clear();
        }
        let id = self.alloc_id();
        let mut d = Document::loading(id, canon.clone());
        // What was chosen for the file before; a remembered encoding opens it in one pass.
        d.pending_opts = if archive { None } else { self.opts_for(&canon) };
        let forced = d.pending_opts.as_ref().and_then(|o| o.enc);
        self.docs.push(d);
        self.active = self.docs.len() - 1;
        self.spawn_open(id, canon, forced);
    }

    /// A remembered encoding gives way to the byte order mark the file now starts with (it was
    /// saved again): returns the file to open again, detecting.
    fn bom_wins(&mut self, doc: u64, result: &Result<Opened, String>) -> Option<PathBuf> {
        let o = result.as_ref().ok()?;
        let p = self.doc_mut(doc)?.pending_opts.as_mut()?;
        let enc = p.enc?;
        if o.bom.is_none_or(|b| b == enc) {
            return None;
        }
        p.enc = None;
        if o.unpacked.is_some() {
            let temp = o.path.clone();
            jobs::spawn("remove-unpacked", move || {
                bigtext::decompress::remove_temp(&temp)
            });
        }
        Some(o.unpacked.clone().unwrap_or_else(|| o.path.clone()))
    }

    /// Opens `path`, or the archive `path`'s file `member` without asking which.
    pub(crate) fn open_path_member(&mut self, path: PathBuf, member: Option<String>) {
        let Some(member) = member else {
            return self.open_path(path);
        };
        let canon = std::path::absolute(&path).unwrap_or(path);
        let same = |d: &Document| {
            d.member.as_deref() == Some(member.as_str())
                && d.unpacked_from
                    .as_deref()
                    .is_some_and(|p| same_path(p, &canon))
        };
        if let Some(i) = self.docs.iter().position(same) {
            self.active = i;
            return;
        }
        let id = self.alloc_id();
        let mut d = Document::loading(id, canon.clone());
        let archive = canon
            .file_name()
            .map(|n| n.to_string_lossy().into_owned())
            .unwrap_or_default();
        d.title = format!(
            "{archive} › {}",
            bigtext::decompress::member_file_name(&member)
        );
        d.member = Some(member.clone());
        self.docs.push(d);
        self.active = self.docs.len() - 1;
        self.spawn_open_member(id, canon, Some(member));
    }

    fn spawn_open(&mut self, id: u64, path: PathBuf, forced: Option<Encoding>) {
        self.spawn_open_job(id, path, None, forced, None, true);
    }

    /// Opens `path` (an archive's file `member` of about `size` bytes) into the loading tab `id`;
    /// with `check`, an unpack that would not fit asks first.
    pub(crate) fn spawn_open_job(
        &mut self,
        id: u64,
        path: PathBuf,
        member: Option<String>,
        forced: Option<Encoding>,
        size: Option<u64>,
        check: bool,
    ) {
        let tx = self.tx.clone();
        let waker = self.waker.clone();
        let (progress, cancel) = (jobs::Progress::default(), CancelToken::new());
        if let Some(d) = self.doc_mut(id) {
            d.unpacking = Some((progress.clone(), cancel.clone()));
        }
        jobs::spawn("open", move || {
            let (mut member, mut size) = (member, size);
            // An archive lists its files first; one file opens without asking.
            if let (None, Some(a)) = (&member, bigtext::decompress::detect_archive(&path)) {
                match bigtext::decompress::list_members(&path, a, &cancel, &progress) {
                    Ok(Some(m)) if m.len() == 1 => {
                        member = Some(m[0].name.clone());
                        size = Some(m[0].size);
                    }
                    Ok(Some(m)) if !m.is_empty() => {
                        let _ = tx.send(Msg::ArchiveListed(Box::new((id, path, m))));
                        waker();
                        return;
                    }
                    r => {
                        let result = match r {
                            Ok(Some(_)) => Err(i18n::tr("The archive has no files.").into()),
                            Ok(None) => Err(i18n::tr("Unpacking was cancelled.").into()),
                            Err(e) => Err(unpack_error(&path, e)),
                        };
                        let _ = tx.send(Msg::Opened { doc: id, result });
                        waker();
                        return;
                    }
                }
            }
            if check {
                // The size of the copy, against the free space where it goes.
                let need = match &member {
                    Some(_) => size,
                    None => bigtext::decompress::detect(&path)
                        .map(|k| bigtext::decompress::estimate_unpacked(&path, k)),
                };
                let dir = bigtext::decompress::temp_dir();
                if let (Some(need), Some(free)) =
                    (need, need.and_then(|_| bigtext::sysinfo::free_space(&dir)))
                {
                    if need > free {
                        let resume = Resume::Open {
                            doc: id,
                            path,
                            member,
                            forced,
                            size,
                        };
                        let _ = tx.send(Msg::LowSpace(Box::new(LowSpace {
                            need,
                            free,
                            dir,
                            resume,
                        })));
                        waker();
                        return;
                    }
                }
            }
            let result = match &member {
                Some(m) => open_member(&path, m, forced, &cancel, &progress),
                None => match bigtext::decompress::detect(&path) {
                    Some(kind) => {
                        return open_unpacking(
                            id, &path, kind, forced, &cancel, &progress, &tx, &waker,
                        )
                    }
                    None => open_or_unpack(&path, forced, &cancel, &progress),
                },
            };
            let _ = tx.send(Msg::Opened { doc: id, result });
            waker();
        });
    }

    /// Unpacks and opens the archive's file `member` into the loading tab `id`.
    fn spawn_open_member(&mut self, id: u64, path: PathBuf, member: Option<String>) {
        self.spawn_open_job(id, path, member, None, None, true);
    }

    fn on_low_space(&mut self, l: LowSpace) {
        let (doc, file) = match &l.resume {
            Resume::Open { doc, path, .. } => (*doc, path.clone()),
            Resume::Write { doc, target, .. } => (*doc, target.clone()),
        };
        if let Some(d) = self.doc_mut(doc) {
            d.unpacking = None;
            d.save_job = None;
        }
        let name = file
            .file_name()
            .map(|n| n.to_string_lossy().into_owned())
            .unwrap_or_default();
        let sizes = [
            ("file", name.as_str()),
            ("need", &human_bytes(l.need)),
            ("free", &human_bytes(l.free)),
            ("dir", &file::display_path(&l.dir)),
        ];
        let message = match l.resume {
            Resume::Open { .. } => i18n::trf("Unpacking {file} needs about {need} (estimated), and {dir} has {free} free. Continue anyway, or put unpacked copies in another folder?", &sizes),
            Resume::Write { .. } => i18n::trf("Writing {file} needs about {need}, and its drive has {free} free. Continue anyway?", &sizes),
        };
        self.confirm = Some(Confirm {
            title: i18n::tr("Not enough free space").into(),
            message,
            action: ConfirmAction::LowSpace(Box::new(l)),
            checkbox: None,
        });
    }

    /// Carries on after a low-space warning (checking again with `check`).
    fn resume(&mut self, r: Resume, check: bool) {
        match r {
            Resume::Open {
                doc,
                path,
                member,
                forced,
                size,
            } => self.spawn_open_job(doc, path, member, forced, size, check),
            Resume::Write {
                doc,
                target,
                spec,
                backup,
            } => self.start_write_checked(doc, target, spec, backup, check),
        }
    }

    /// Puts unpacked copies in `dir` from now on (`None`: the system temp folder).
    pub(crate) fn set_unpack_folder(&mut self, dir: Option<PathBuf>) {
        bigtext::decompress::set_unpack_dir(dir.clone());
        self.settings.unpack_dir = dir;
        self.persist_state();
    }

    pub fn active_doc(&mut self) -> Option<&mut Document> {
        self.docs.get_mut(self.active)
    }

    fn doc_mut(&mut self, id: u64) -> Option<&mut Document> {
        if let Some(i) = self.docs.iter().position(|d| d.id == id) {
            return Some(&mut self.docs[i]);
        }
        // The other file of a side-by-side comparison.
        self.diff
            .as_mut()
            .and_then(|r| r.side.as_mut())
            .map(|s| &mut *s.doc)
            .filter(|d| d.id == id)
    }

    fn poll_messages(&mut self) {
        while let Ok(msg) = self.rx.try_recv() {
            match msg {
                Msg::Opened { doc, result } => {
                    if let Some(path) = self.bom_wins(doc, &result) {
                        drop(result);
                        self.spawn_open(doc, path, None);
                        continue;
                    }
                    let waker = self.waker.clone();
                    let tx = self.tx.clone();
                    let mut folder = None;
                    if let Some(d) = self.doc_mut(doc) {
                        let unpacking = d.unpacking.take();
                        let reload = std::mem::take(&mut d.reloading);
                        match result {
                            // Edits were typed while the file was being opened again: they stay,
                            // and the banner says the file changed instead of the text being
                            // replaced by it (with no undo and no prompt on close).
                            Ok(o) if reload && d.is_modified() => {
                                d.reload_prefix = None;
                                d.banner = Some(Banner::ChangedOnDisk {
                                    deleted: false,
                                    grown: o.source.len() > d.buf.source.len(),
                                });
                            }
                            Ok(o) => {
                                d.open_elapsed = Some(o.elapsed);
                                d.read_only = d.read_only || o.read_only;
                                d.path = Some(o.path.clone());
                                if let Some(m) = &o.member {
                                    let archive = o
                                        .unpacked
                                        .as_deref()
                                        .and_then(|p| p.file_name())
                                        .map(|n| n.to_string_lossy().into_owned())
                                        .unwrap_or_default();
                                    d.title = format!(
                                        "{archive} › {}",
                                        bigtext::decompress::member_file_name(m)
                                    );
                                    d.member = Some(m.clone());
                                }
                                if let Some(orig) = o.unpacked {
                                    d.read_only = true;
                                    d.banner = Some(Banner::Info(if o.growing {
                                        d.growing = unpacking;
                                        i18n::trf("Unpacking {name}: the start is shown and the rest appears as it is unpacked (read-only).", &[("name", &d.title)])
                                    } else {
                                        i18n::trf(
                                            "Unpacked copy of {name} ({size}), read-only. To keep changes, turn off Edit → Read-only and use Save As.",
                                            &[("name", &d.title), ("size", &human_bytes(o.source.len()))],
                                        )
                                    }));
                                    d.unpacked_from = Some(orig);
                                    d.temporary = true;
                                }
                                let prefix = d.reload_prefix.take();
                                let follow_end = d.follow
                                    && (prefix.is_some() || std::mem::take(&mut d.reload_to_end));
                                if let Some(b) = d.banner_after_reload.take() {
                                    d.banner = Some(b);
                                }
                                d.file_read_only = o.read_only || d.temporary;
                                d.install(o.source, o.detected, prefix, waker.clone());
                                if let Some(opts) = d.pending_opts.take() {
                                    d.apply_opts(opts);
                                }
                                if follow_end {
                                    let len = d.buf.len();
                                    d.set_caret(len, false);
                                }
                                if let Some(mut r) = d.restore.take() {
                                    d.pending_filter = r.filter.take();
                                    let len = d.buf.len();
                                    d.view.wrap = r.wrap;
                                    d.bookmarks =
                                        r.bookmarks.into_iter().filter(|&b| b <= len).collect();
                                    match r.line {
                                        _ if r.select.is_some() => {
                                            let (s, e) = r.select.unwrap_or_default();
                                            d.select(s.min(len), e.min(len));
                                            d.view.center();
                                        }
                                        None if r.end => d.set_caret(len, false),
                                        Some(line) => d.goto_line(line),
                                        None => {
                                            d.set_caret(r.caret.min(len), false);
                                            d.view.top = r.top.min(len);
                                            d.view.scroll_to_caret = false;
                                        }
                                    }
                                }
                                watch(d, tx, waker);
                                let opened = (!reload).then(|| d.title.clone());
                                // Standard input has no file to remember.
                                if !d.temporary || d.unpacked_from.is_some() {
                                    let p = d.unpacked_from.clone().unwrap_or(o.path);
                                    self.add_recent(&p);
                                }
                                if let Some(name) = opened {
                                    self.announce(i18n::trf("Opened {name}", &[("name", &name)]));
                                }
                            }
                            Err(e) if e == FOLDER => folder = d.path.clone(),
                            Err(e) => d.state = DocState::Failed(e),
                        }
                    } else if let Ok(o) = result
                        .as_ref()
                        .map(|o| (o.unpacked.is_some(), o.path.clone()))
                    {
                        // The tab was closed while its file was being unpacked.
                        drop(result);
                        if o.0 {
                            jobs::spawn("remove-unpacked", move || {
                                bigtext::decompress::remove_temp(&o.1)
                            });
                        }
                    }
                    // A folder: its tab goes, the side bar shows it.
                    if let Some(dir) = folder {
                        self.close_tab(doc, true);
                        self.open_folder(dir);
                    }
                }
                Msg::Found {
                    doc,
                    version,
                    found,
                    wrapped,
                } => self.on_found(doc, version, found, wrapped),
                Msg::MatchNumber {
                    doc,
                    version,
                    sel,
                    number,
                } => self.on_match_number(doc, version, sel, number),
                Msg::TempWritten(tw) => self.on_temp_written(*tw),
                Msg::Finalized(f) => self.on_finalized(*f),
                Msg::JobFailed { doc, msg } => self.on_job_failed(doc, msg),
                Msg::ReplaceBatch {
                    doc,
                    version,
                    batch,
                    count,
                } => self.on_replace_batch(doc, version, batch, count),
                Msg::ReplaceTooMany {
                    doc,
                    version,
                    matcher,
                    template,
                    range,
                } => self.on_replace_too_many(doc, version, matcher, template, range),
                Msg::Preview {
                    doc,
                    version,
                    seq,
                    items,
                    lines,
                } => self.on_preview(doc, version, seq, items, lines),
                Msg::LowSpace(l) => self.on_low_space(*l),
                Msg::Journaled {
                    doc,
                    version,
                    add_len,
                    ok,
                } => self.on_journaled(doc, version, add_len, ok),
                Msg::LinesRemoved(l) => self.on_lines_removed(*l),
                // The window came to the front in `logic` (see `to_front`).
                Msg::OpenRequest(s) => self.apply_start(*s),
                Msg::LinesTooMany {
                    doc,
                    version,
                    sel,
                    keep,
                } => self.on_lines_too_many(doc, version, sel, keep),
                Msg::ArchiveListed(a) => {
                    let (doc, archive, members) = *a;
                    self.on_archive_listed(doc, archive, members);
                }
                Msg::FileChanged(c) => {
                    let (tx, waker) = (self.tx.clone(), self.waker.clone());
                    if let Some(d) = self.doc_mut(c.doc) {
                        let quiet = !d.is_modified() && d.save_job.is_none() && !d.temporary;
                        if d.follow && quiet && !c.deleted && (c.shrunk || c.rotated) {
                            // Rotated (renamed away, or copied and truncated): follow the new file.
                            d.rotations += 1;
                            d.reload_to_end = true;
                            d.banner_after_reload = Some(Banner::Rotated(c.rotated_to.clone()));
                            reload(d, &tx, &waker, false);
                        } else if (d.follow || d.growing.is_some())
                            && c.grown
                            && !c.deleted
                            && !d.is_modified()
                            && d.save_job.is_none()
                        {
                            reload(d, &tx, &waker, true);
                        } else if d.is_ready() {
                            d.banner = Some(Banner::ChangedOnDisk {
                                deleted: c.deleted,
                                grown: c.grown,
                            });
                        }
                    }
                }
                Msg::Copied { doc, result, cut } => match result {
                    Ok(text) => {
                        let ctx = self.ctx_clone();
                        if let Some(ctx) = ctx {
                            ctx.copy_text(text);
                        }
                        if let Some((range, version)) = cut {
                            let cut_done = self.doc_mut(doc).is_some_and(|d| {
                                let ok = d.version == version && d.editable();
                                if ok {
                                    d.edit(range, &[], document::EditKind::Other);
                                }
                                ok
                            });
                            if !cut_done {
                                self.notify(
                                    i18n::tr("Copied. The document changed meanwhile, so nothing was cut.").into(),
                                    None,
                                );
                            }
                        }
                    }
                    Err(e) => self.error = Some(e),
                },
                Msg::Update(e) => self.on_update_event(e),
                Msg::RemoteOpened { doc, src, result } => self.remote_opened(doc, src, result),
                Msg::Error(e) => self.error = Some(e),
                Msg::AlertClicked => self.on_alert_clicked(),
                Msg::ColumnsDeleted(c) => self.on_columns_deleted(*c),
                Msg::TaskDone { id, outcome } => self.on_task_done(id, outcome),
                Msg::TextOp(r) => self.on_text_op(*r),
                Msg::CsvRewritten(c) => self.on_csv_rewritten(*c),
                Msg::TimeFound {
                    doc,
                    version,
                    result,
                } => self.on_time_found(doc, version, result),
                Msg::Aligned(a) => self.on_aligned(*a),
                Msg::JsonCrumb(m) => self.on_json_crumb(*m),
                Msg::Folds(m) => self.on_folds(*m),
                Msg::Unpacked(u) => self.on_unpacked(*u),
                Msg::LevelFound(f) => self.on_level_found(*f),
                Msg::CursorFound(f) => self.on_cursor_found(*f),
                Msg::BracketJump(j) => self.on_bracket_jump(*j),
                Msg::Json(j) => self.on_json(*j),
                Msg::TimeRange(r) => self.on_time_range(*r),
            }
        }
    }

    fn on_time_found(
        &mut self,
        doc: u64,
        version: u64,
        result: Result<u64, bigtext::timestamp::TimeError>,
    ) {
        let Some(g) = &mut self.goto else { return };
        if g.busy.take().is_none() {
            return;
        }
        match result {
            Ok(off) => {
                self.goto = None;
                if let Some(d) = self.doc_mut(doc).filter(|d| d.version == version) {
                    d.goto_offset(off);
                }
            }
            Err(bigtext::timestamp::TimeError::NoTimestamps) => {
                g.error =
                    Some(i18n::tr("No timestamps found at the start of the file's lines.").into())
            }
            Err(bigtext::timestamp::TimeError::Cancelled) => {}
        }
    }

    /// Live unpacking ended: the copy is whole (read the rest), cancelled or broken.
    fn on_unpacked(&mut self, u: Unpacked) {
        let (tx, waker) = (self.tx.clone(), self.waker.clone());
        let Some(d) = self.doc_mut(u.doc).filter(|d| d.growing.is_some()) else {
            // The tab was closed meanwhile.
            jobs::spawn("remove-unpacked", move || {
                bigtext::decompress::remove_temp(&u.temp)
            });
            return;
        };
        d.growing = None;
        let name = d
            .unpacked_from
            .as_deref()
            .and_then(|p| p.file_name())
            .map(|n| n.to_string_lossy().into_owned())
            .unwrap_or_default();
        let banner = match u.result {
            Ok(Some(n)) => {
                if d.buf.len() != n && !d.reloading {
                    reload(d, &tx, &waker, true);
                }
                i18n::trf("Unpacked copy of {name} ({size}), read-only. To keep changes, turn off Edit → Read-only and use Save As.", &[("name", &name), ("size", &human_bytes(n))])
            }
            Ok(None) => i18n::trf(
                "Unpacking was cancelled; the first {size} of {name} are shown.",
                &[("size", &human_bytes(d.buf.len())), ("name", &name)],
            ),
            Err(e) => e,
        };
        if d.reloading {
            d.banner_after_reload = Some(Banner::Info(banner));
        } else {
            d.banner = Some(Banner::Info(banner));
        }
    }

    pub(crate) fn ctx_clone(&self) -> Option<egui::Context> {
        CTX.with(|c| c.borrow().clone())
    }

    pub(crate) fn close_tab(&mut self, id: u64, force: bool) {
        let Some(i) = self.docs.iter().position(|d| d.id == id) else {
            return;
        };
        if !force && self.docs[i].is_modified() {
            self.confirm = Some(Confirm {
                title: i18n::tr("Unsaved changes").into(),
                message: i18n::trf(
                    "“{name}” has unsaved changes. Close it anyway?",
                    &[("name", &self.docs[i].title)],
                ),
                action: ConfirmAction::CloseTab(id),
                checkbox: None,
            });
            return;
        }
        extras::remember(&mut self.file_opts, &self.docs[i]);
        let mut d = self.docs.remove(i);
        if self.diff.as_ref().is_some_and(|r| r.doc == id) {
            if let Some(r) = self.diff.take() {
                r.cancel.cancel();
            }
        }
        d.cancel_jobs();
        d.watch_cancel.cancel();
        if let Some(j) = &d.save_job {
            j.cancel.cancel();
        }
        if let (Some(temp), true) = (d.path.clone(), d.temporary) {
            drop(d);
            jobs::spawn("remove-unpacked", move || {
                bigtext::decompress::remove_temp(&temp)
            });
        }
        if self.docs.is_empty() {
            self.new_doc();
        }
        self.active = self.active.min(self.docs.len() - 1);
        self.persist_state();
    }

    fn start_copy_job(&mut self, id: u64, cut: bool) {
        let Some(d) = self.docs.iter().find(|d| d.id == id) else {
            return;
        };
        let (s, e) = d.selection();
        let cut = cut.then_some((s..e, d.version));
        let snap = d.buf.snapshot();
        let tx = self.tx.clone();
        let waker = self.waker.clone();
        jobs::spawn("copy", move || {
            let result = snap
                .read(s..e)
                .map(|b| snap.codec.decode_lossy(&b))
                .ok_or_else(|| i18n::tr("Could not read the selection").to_string());
            let _ = tx.send(Msg::Copied {
                doc: id,
                result,
                cut,
            });
            waker();
        });
    }

    fn open_dialog(&mut self) {
        if let Some(files) = rfd::FileDialog::new()
            .set_title(i18n::tr("Open"))
            .pick_files()
        {
            for f in files {
                self.open_path(f);
            }
        }
    }

    // ------------------------------------------------------------------------------------------
    // UI pieces.

    /// Opens the file again in `enc` (remembered for it), or detecting with `None`.
    fn reopen_with(&mut self, enc: Option<Encoding>) {
        let Some(d) = self.docs.get_mut(self.active) else {
            return;
        };
        let Some(path) = d.path.clone() else { return };
        if d.is_modified() {
            self.error = Some(
                i18n::tr("Save or discard your changes before reopening with another encoding.")
                    .into(),
            );
            return;
        }
        d.state = DocState::Loading;
        d.index_cancel.cancel();
        d.forced_enc = enc;
        let id = d.id;
        self.spawn_open(id, path, enc);
    }

    fn banner(&mut self, ui: &mut egui::Ui) {
        let Some(d) = self.docs.get_mut(self.active) else {
            return;
        };
        if d.hex && d.banner == Some(Banner::Binary) {
            d.banner = None;
        }
        let Some(b) = d.banner.clone() else { return };
        let mut open_rotated: Option<PathBuf> = None;
        egui::Frame::new()
            .fill(ui.visuals().faint_bg_color)
            .inner_margin(6.0)
            .show(ui, |ui| {
                ui.horizontal(|ui| {
                    match &b {
                        Banner::Binary => {
                            ui.label(i18n::tr("This file looks binary."));
                            if ui.button(i18n::tr("Switch to hex view")).clicked() {
                                d.hex = true;
                                d.banner = None;
                            }
                        }
                        Banner::ChangedOnDisk { deleted, grown } => {
                            ui.label(if *deleted {
                                i18n::tr("The file was deleted or moved on disk.")
                            } else if *grown {
                                i18n::tr("The file grew on disk.")
                            } else {
                                i18n::tr("The file changed on disk.")
                            });
                            if !*deleted
                                && ui
                                    .button(i18n::tr(if d.is_modified() {
                                        "Reload (discard edits)"
                                    } else {
                                        "Reload"
                                    }))
                                    .clicked()
                            {
                                d.banner = None;
                                reload(d, &self.tx, &self.waker, false);
                                return;
                            }
                            if *grown
                                && !*deleted
                                && !d.is_modified()
                                && ui.button(i18n::tr("Follow")).clicked()
                            {
                                d.banner = None;
                                d.follow = true;
                                reload(d, &self.tx, &self.waker, true);
                                return;
                            }
                        }
                        Banner::Rotated(to) => {
                            ui.label(i18n::tr("The log was rotated; following the new file."));
                            if let Some(p) = to {
                                let name = p
                                    .file_name()
                                    .map(|n| n.to_string_lossy().into_owned())
                                    .unwrap_or_default();
                                if ui
                                    .button(i18n::trf("Open {file}", &[("file", &name)]))
                                    .on_hover_text(i18n::tr(
                                        "The file the earlier lines most likely went to",
                                    ))
                                    .clicked()
                                {
                                    open_rotated = Some(p.clone());
                                }
                            }
                        }
                        Banner::Info(s) => {
                            ui.label(s);
                        }
                        Banner::Error(s) => {
                            ui.colored_label(ui.visuals().error_fg_color, s);
                        }
                    }
                    if ui.button(i18n::tr("Dismiss")).clicked() {
                        d.banner = None;
                    }
                });
            });
        if let Some(p) = open_rotated {
            self.open_path(p);
        }
    }

    fn dialogs(&mut self, ctx: &egui::Context) {
        if let Some(g) = &mut self.goto {
            let mut open = true;
            let mut submit = false;
            let title = match g.mode {
                GotoMode::Line => "Go to line",
                GotoMode::Offset => "Go to byte offset",
                GotoMode::Time => "Go to time",
            };
            egui::Window::new(i18n::tr(title))
                .collapsible(false)
                .resizable(false)
                .open(&mut open)
                .show(ctx, |ui| {
                    ui.horizontal(|ui| {
                        ui.radio_value(&mut g.mode, GotoMode::Line, i18n::tr("Line"));
                        ui.radio_value(&mut g.mode, GotoMode::Offset, i18n::tr("Byte offset (dec or 0x hex)"));
                        ui.radio_value(&mut g.mode, GotoMode::Time, i18n::tr("Time"));
                    });
                    let hint = match g.mode {
                        GotoMode::Time => "14:32:05 · 2024-05-01 14:32:05",
                        GotoMode::Line => "1234 · 50% · +100 · -100 · $-100",
                        GotoMode::Offset => "4096 · 0x1F00 · 50% · +0x100 · $-4096",
                    };
                    let r = ui.add(egui::TextEdit::singleline(&mut g.text).hint_text(hint));
                    if g.focus {
                        r.request_focus();
                        g.focus = false;
                    }
                    if r.lost_focus() && ui.input(|i| i.key_pressed(Key::Enter)) {
                        submit = true;
                    }
                    if g.mode == GotoMode::Time {
                        ui.weak(i18n::tr("Jumps to the first line at or after this time (the log must be in time order)."));
                    } else {
                        ui.weak(i18n::tr("+N / -N: from the caret; $-N: from the end; 50%: a share of the file."));
                    }
                    if let Some(e) = &g.error {
                        ui.colored_label(ui.visuals().error_fg_color, e);
                    }
                    ui.horizontal(|ui| {
                        if g.busy.is_some() {
                            ui.spinner();
                            ui.label(i18n::tr("Searching…"));
                        } else if ui.button(i18n::tr("Go")).clicked() {
                            submit = true;
                        }
                    });
                });
            if submit && g.busy.is_none() && g.mode == GotoMode::Time {
                match bigtext::timestamp::parse_input(g.text.trim()) {
                    Some(st) => {
                        g.error = None;
                        let cancel = CancelToken::new();
                        g.busy = Some(cancel.clone());
                        if let Some(d) = self.docs.get(self.active) {
                            let (snap, id, version) = (d.buf.snapshot(), d.id, d.version);
                            let tx = self.tx.clone();
                            let waker = self.waker.clone();
                            jobs::spawn("goto-time", move || {
                                let result = bigtext::timestamp::find_time(&snap, st, &cancel);
                                if !cancel.is_cancelled() {
                                    let _ = tx.send(Msg::TimeFound {
                                        doc: id,
                                        version,
                                        result,
                                    });
                                    waker();
                                }
                            });
                        }
                    }
                    None => {
                        g.error = Some(
                            i18n::tr("Enter a time like 14:32:05 or 2024-05-01 14:32:05").into(),
                        )
                    }
                }
            } else if submit && g.busy.is_none() {
                match goto::parse(&g.text, g.mode == GotoMode::Offset) {
                    Some(t) => {
                        if let Some(d) = self.docs.get_mut(self.active) {
                            d.goto_target(t);
                        }
                        self.goto = None;
                    }
                    None => g.error = Some(i18n::tr("Enter a number").into()),
                }
            } else if !open || ctx.input(|i| i.key_pressed(Key::Escape)) {
                if let Some(c) = &g.busy {
                    c.cancel();
                }
                self.goto = None;
            }
        }

        if self.confirm.is_some() {
            // 0 = cancel, 1 = primary, 2 = save (close-tab only)
            let mut decision = None;
            let c = self.confirm.as_mut().unwrap();
            let is_close = matches!(c.action, ConfirmAction::CloseTab(_));
            egui::Modal::new(egui::Id::new("confirm")).show(ctx, |ui| {
                ui.set_max_width(460.0);
                ui.heading(&c.title);
                ui.label(&c.message);
                if let Some((label, v)) = &mut c.checkbox {
                    ui.checkbox(v, label.as_str());
                }
                ui.add_space(6.0);
                ui.horizontal(|ui| {
                    if is_close && ui.button(i18n::tr("Save")).clicked() {
                        decision = Some(2);
                    }
                    let primary = match c.action {
                        ConfirmAction::CloseTab(_) | ConfirmAction::Exit => "Discard",
                        ConfirmAction::SaveOverChanged { .. } => "Save anyway",
                        ConfirmAction::ReplaceOnDisk { .. } => "Replace on disk",
                        ConfirmAction::CopyLarge { .. } => "Copy",
                        ConfirmAction::DeleteColumns { .. } => "Delete",
                        ConfirmAction::CsvRewrite { .. } => "Rewrite",
                        ConfirmAction::LowSpace(_) => "Continue",
                        ConfirmAction::LinesOnDisk { .. } => "Delete on disk",
                        ConfirmAction::TextOpOnDisk { .. } => "Change on disk",
                        ConfirmAction::ColumnEditOnDisk { .. } => "Fill on disk",
                        ConfirmAction::SortOnDisk { .. } => "Sort on disk",
                        ConfirmAction::Trash(_) if cfg!(windows) => "Move to the Recycle Bin",
                        ConfirmAction::Trash(_) => "Move to the Trash",
                    };
                    if ui.button(i18n::tr(primary)).clicked() {
                        decision = Some(1);
                    }
                    if matches!(&c.action, ConfirmAction::LowSpace(l) if matches!(l.resume, Resume::Open { .. })) && ui.button(i18n::tr("Choose folder…")).clicked() {
                        decision = Some(3);
                    }
                    let cancel = ui.button(i18n::tr("Cancel"));
                    // Keyboard and screen reader users land in the dialog, on its safe choice.
                    if ui.memory(|m| m.focused().is_none()) {
                        cancel.request_focus();
                    }
                    if cancel.clicked() || ui.input(|i| i.key_pressed(Key::Escape)) {
                        decision = Some(0);
                    }
                });
            });
            if let Some(dec) = decision {
                let c = self.confirm.take().unwrap();
                self.apply_confirm(ctx, dec, c);
            }
        }

        if let Some((doc, items, lines)) = &self.preview {
            let mut open = true;
            let mut jump = None;
            let same_doc = self.docs.get(self.active).map(|d| d.id) == Some(*doc);
            egui::Window::new(i18n::trf(
                "Replace preview (first {n})",
                &[("n", &items.len().to_string())],
            ))
            .open(&mut open)
            .default_size([640.0, 400.0])
            .show(ctx, |ui| {
                if items.is_empty() {
                    ui.label(i18n::tr("No matches."));
                }
                egui::ScrollArea::vertical().show(ui, |ui| {
                    egui::Grid::new("preview").striped(true).show(ui, |ui| {
                        for (i, (off, before, after)) in items.iter().enumerate() {
                            if ui
                                .link(format!("{}", lines.get(i).copied().unwrap_or(0)))
                                .clicked()
                            {
                                jump = Some(*off);
                            }
                            // ↵ and → exist in the monospace font only.
                            ui.monospace(before.replace('\n', "↵"));
                            ui.monospace("→");
                            ui.monospace(after.replace('\n', "↵"));
                            ui.end_row();
                        }
                    });
                });
            });
            if let (Some(off), true) = (jump, same_doc) {
                if let Some(d) = self.docs.get_mut(self.active) {
                    d.goto_offset(off);
                }
            }
            if !open {
                self.preview = None;
            }
        }

        if let Some(e) = self.error.clone() {
            egui::Modal::new(egui::Id::new("error")).show(ctx, |ui| {
                ui.heading(i18n::tr("Error"));
                ui.label(e);
                if ui.button(i18n::tr("OK")).clicked() {
                    self.error = None;
                }
            });
        }

        if self.show_about {
            egui::Window::new(i18n::tr("About BigText"))
                .open(&mut self.show_about)
                .collapsible(false)
                .resizable(false)
                .show(ctx, |ui| {
                    about_contents(ui);
                });
        }
    }

    /// Carries out the answer to a confirmation: 0 = cancel, 1 = primary, 2 = save.
    fn apply_confirm(&mut self, ctx: &egui::Context, dec: u8, c: Confirm) {
        let checked = c.checkbox.as_ref().map(|x| x.1).unwrap_or(false);
        match (dec, c.action) {
            (2, ConfirmAction::CloseTab(id)) => {
                if let Some(i) = self.docs.iter().position(|d| d.id == id) {
                    self.active = i;
                    self.docs[i].close_after_save = true;
                    self.save(false);
                }
            }
            (1, ConfirmAction::CloseTab(id)) => self.close_tab(id, true),
            (1, ConfirmAction::SaveOverChanged { doc }) => self.save_unchecked(doc),
            (1, ConfirmAction::Exit) => {
                // The edits are discarded: so are their journals.
                self.end_recovery();
                self.exit_confirmed = true;
                ctx.send_viewport_cmd(egui::ViewportCommand::Close);
            }
            (1, ConfirmAction::CopyLarge { doc, cut }) => self.start_copy_job(doc, cut),
            (1, ConfirmAction::Trash(path)) => self.trash_now(path),
            (1, ConfirmAction::ReplaceOnDisk { doc }) => self.replace_on_disk(doc, checked),
            (
                1,
                ConfirmAction::DeleteColumns {
                    doc,
                    dialect,
                    cols,
                    on_disk,
                },
            ) => self.delete_columns(doc, dialect, cols, on_disk, checked),
            (
                1,
                ConfirmAction::CsvRewrite {
                    doc,
                    dialect,
                    rewrite,
                    on_disk,
                },
            ) => self.rewrite_csv(doc, dialect, rewrite, on_disk, checked),
            (1, ConfirmAction::LowSpace(l)) => self.resume(l.resume, false),
            (1, ConfirmAction::LinesOnDisk { doc, sel, keep }) => {
                self.lines_on_disk(doc, sel, keep, checked)
            }
            (
                1,
                ConfirmAction::ColumnEditOnDisk {
                    doc,
                    from,
                    cells,
                    gen,
                },
            ) => self.column_edit_on_disk(doc, from, cells, gen, checked),
            (1, ConfirmAction::SortOnDisk { doc, spec, eol }) => {
                if let Some(path) = self
                    .docs
                    .iter()
                    .find(|d| d.id == doc)
                    .and_then(|d| d.path.clone())
                {
                    self.start_write(doc, path, ops::WriteSpec::Sort { spec, eol }, checked);
                }
            }
            (1, ConfirmAction::TextOpOnDisk { doc, op, range }) => {
                if let Some(path) = self
                    .docs
                    .iter()
                    .find(|d| d.id == doc)
                    .and_then(|d| d.path.clone())
                {
                    self.start_write(doc, path, ops::WriteSpec::TextOp { op, range }, checked);
                }
            }
            (3, ConfirmAction::LowSpace(l)) => match rfd::FileDialog::new()
                .set_title(i18n::tr("Folder for unpacked copies"))
                .pick_folder()
            {
                Some(dir) => {
                    self.set_unpack_folder(Some(dir));
                    self.resume(l.resume, true);
                }
                None => self.on_low_space(*l),
            },
            (_, ConfirmAction::LowSpace(l)) => {
                if let Resume::Open { doc, .. } = l.resume {
                    self.close_tab(doc, true);
                }
            }
            _ => {
                self.pending_replace = None;
                // Exit was cancelled: "Restart now" for an update no longer applies.
                self.update.restart = false;
            }
        }
    }

    fn perf_overlay(&self, ctx: &egui::Context) {
        if !self.settings.show_perf {
            return;
        }
        let d = self.docs.get(self.active);
        egui::Area::new(egui::Id::new("perf"))
            .anchor(egui::Align2::RIGHT_BOTTOM, egui::vec2(-20.0, -40.0))
            .show(ctx, |ui| {
                egui::Frame::popup(ui.style()).show(ui, |ui| {
                    ui.monospace(format!(
                        "frame {:.2} ms  avg {:.2}  max {:.2}",
                        self.frame.last_ms,
                        self.frame.avg(),
                        self.frame.max()
                    ));
                    if let Some(p) = bigtext::sysinfo::private_bytes() {
                        ui.monospace(format!("private memory {}", human_bytes(p)));
                    }
                    if let Some(d) = d {
                        ui.monospace(format!(
                            "index {} ({:.4}% of file)  pieces {}",
                            human_bytes(d.buf.index.memory_bytes() as u64),
                            d.buf.index.memory_bytes() as f64 * 100.0 / d.buf.len().max(1) as f64,
                            d.buf.piece_count()
                        ));
                        if let (Some(o), Some(fp)) = (d.open_elapsed, d.view.first_paint) {
                            ui.monospace(format!(
                                "open {:.1} ms, first paint {:.1} ms",
                                o.as_secs_f64() * 1e3,
                                fp.duration_since(d.opened_at).as_secs_f64() * 1e3
                            ));
                        }
                    }
                    if let Some(f) = self.first_frame {
                        ui.monospace(format!(
                            "startup → first frame {:.1} ms",
                            f.as_secs_f64() * 1e3
                        ));
                    }
                });
            });
    }

    fn writes_in_progress(&self) -> bool {
        self.docs
            .iter()
            .any(|d| d.save_job.is_some() || matches!(d.state, DocState::Finalizing(_)))
    }

    fn handle_close_request(&mut self, ctx: &egui::Context) {
        if self.exit_after_jobs && !self.writes_in_progress() {
            // Ask again, now through the unsaved-changes check below: a save cancelled by the
            // close leaves its document modified, and other tabs may have edits too. An exit
            // the user already confirmed has `exit_confirmed` set and goes straight through.
            self.exit_after_jobs = false;
            ctx.send_viewport_cmd(egui::ViewportCommand::Close);
            return;
        }
        if ctx.input(|i| i.viewport().close_requested()) && self.writes_in_progress() {
            // Let a running save/replace cancel cleanly (temp file removed) or finish its
            // atomic swap before the process exits.
            ctx.send_viewport_cmd(egui::ViewportCommand::CancelClose);
            for d in &self.docs {
                if let (Some(j), false) = (&d.save_job, matches!(d.state, DocState::Finalizing(_)))
                {
                    j.cancel.cancel();
                }
            }
            self.exit_after_jobs = true;
            return;
        }
        if ctx.input(|i| i.viewport().close_requested()) && !self.exit_confirmed {
            let n = self.docs.iter().filter(|d| d.is_modified()).count();
            if n > 0 {
                ctx.send_viewport_cmd(egui::ViewportCommand::CancelClose);
                self.confirm = Some(Confirm {
                    title: i18n::tr("Unsaved changes").into(),
                    message: i18n::trf(
                        "{n} document(s) have unsaved changes. Exit and discard them?",
                        &[("n", &n.to_string())],
                    ),
                    action: ConfirmAction::Exit,
                    checkbox: None,
                });
            } else {
                self.end_recovery();
                self.persist_state();
                for d in &mut self.docs {
                    d.cancel_jobs();
                    d.watch_cancel.cancel();
                    if let Some(j) = &d.save_job {
                        // Cancelling removes the temp file; the original is untouched.
                        j.cancel.cancel();
                    }
                }
            }
        }
    }
}

/// Turns the split view on (second pane starts at the same position) or off.
pub(super) fn toggle_split(d: &mut Document) {
    if d.split.take().is_none() {
        d.split = Some(document::PaneView {
            top: d.view.top,
            scroll_x: d.view.scroll_x,
            ..Default::default()
        });
    }
    d.active_pane = 0;
}

/// Starts a background watcher that reports size/mtime changes and deletion of the file.
pub(super) fn watch(d: &mut Document, tx: Sender<Msg>, waker: Waker) {
    d.watch_cancel.cancel();
    let cancel = CancelToken::new();
    d.watch_cancel = cancel.clone();
    let Some(path) = d.path.clone() else { return };
    let (len0, mtime0) = (d.buf.source.len(), d.buf.source.modified());
    let id = d.id;
    jobs::spawn("watch", move || {
        let id0 = bigtext::file::file_id(&path);
        let mut last = None;
        // A path that vanishes counts as deleted after two looks (a rotation renames it away
        // and creates it again in between); it is still watched for coming back.
        let mut missing = 0;
        while !cancel.is_cancelled() {
            for _ in 0..10 {
                std::thread::sleep(Duration::from_millis(100));
                if cancel.is_cancelled() {
                    return;
                }
            }
            let (len, mtime) = match std::fs::metadata(&path) {
                Ok(m) => {
                    missing = 0;
                    (m.len(), m.modified().ok())
                }
                Err(_) => {
                    missing += 1;
                    if missing < 2 {
                        continue;
                    }
                    (0, None)
                }
            };
            let deleted = missing >= 2;
            let file = if deleted {
                None
            } else {
                bigtext::file::file_id(&path)
            };
            let rotated = matches!((id0, file), (Some(a), Some(b)) if a != b);
            let shrunk = !deleted && len < len0;
            let changed = deleted || rotated || len != len0 || mtime != mtime0;
            let state = (deleted, rotated, len, mtime);
            if changed && last != Some(state) {
                last = Some(state);
                let rotated_to = if rotated || shrunk {
                    bigtext::file::rotated_sibling(&path, std::time::SystemTime::now())
                } else {
                    None
                };
                let c = FileChange {
                    doc: id,
                    deleted,
                    grown: !deleted && !rotated && len > len0,
                    shrunk,
                    rotated,
                    rotated_to,
                };
                let _ = tx.send(Msg::FileChanged(Box::new(c)));
                waker();
            }
        }
    });
}

/// Following reads a file in chunks rather than mapped (or, on Unix, read in blocks on the
/// calling thread): the writer can then truncate it (copytruncate rotation) on Windows, and the
/// loader keeps up with a growing file.
pub(super) fn follow_chunked(d: &mut Document, tx: &Sender<Msg>, waker: &Waker) {
    if d.follow
        && d.is_ready()
        && (d.buf.source.is_mmap() || d.buf.source.is_pread())
        && !d.reloading
        && !d.temporary
        && !d.is_modified()
        && d.save_job.is_none()
    {
        reload(d, tx, waker, true);
    }
}

/// Reopens the document from disk. With `append`, the file is assumed to have only grown, so
/// the existing line index is carried over and indexing resumes where it stopped.
pub(super) fn reload(d: &mut Document, tx: &Sender<Msg>, waker: &Waker, append: bool) {
    let Some(path) = d.path.clone() else { return };
    d.reload_prefix = if append {
        Some(d.buf.index.prefix_checkpoints(d.buf.source.len()))
    } else {
        None
    };
    let enc = d.buf.codec.enc;
    let id = d.id;
    let tx = tx.clone();
    let waker = waker.clone();
    let mode = if d.follow || d.growing.is_some() {
        OpenMode::Chunked
    } else {
        OpenMode::Auto
    };
    d.reloading = true;
    jobs::spawn("reload", move || {
        let result = open_worker(&path, Some(enc), mode);
        let _ = tx.send(Msg::Opened { doc: id, result });
        waker();
    });
}

thread_local! {
    static CTX: std::cell::RefCell<Option<egui::Context>> = const { std::cell::RefCell::new(None) };
}

/// Author and project links shown in Help > About.
pub const AUTHOR: &str = "Erkin Pardayev";
pub const AUTHOR_LINKS: &[(&str, &str, &str)] = &[
    (
        "GitHub",
        "github.com/Erkinbek",
        "https://github.com/Erkinbek",
    ),
    (
        "Repository",
        "github.com/Erkinbek/bigtext",
        "https://github.com/Erkinbek/bigtext",
    ),
    ("Telegram", "@ErkinPardayev", "https://t.me/ErkinPardayev"),
    (
        "E-mail",
        "erkin.pardayev@gmail.com",
        "mailto:erkin.pardayev@gmail.com",
    ),
];

fn about_contents(ui: &mut egui::Ui) {
    ui.vertical_centered(|ui| {
        ui.heading("BigText");
        ui.label(i18n::trf(
            "Version {v}",
            &[("v", env!("CARGO_PKG_VERSION"))],
        ));
        ui.label(i18n::tr("A fast, non-freezing large-file text editor."));
    });
    ui.separator();
    egui::Grid::new("author")
        .num_columns(2)
        .spacing([16.0, 6.0])
        .show(ui, |ui| {
            ui.strong(i18n::tr("Author"));
            ui.label(AUTHOR);
            ui.end_row();
            for (label, text, url) in AUTHOR_LINKS {
                ui.strong(i18n::tr(label));
                ui.hyperlink_to(*text, *url);
                ui.end_row();
            }
        });
    ui.separator();
    ui.small(i18n::tr(
        "Licensed under the MIT license. Built with Rust and egui.",
    ));
}

impl BigTextApp {
    pub(crate) fn test_has_confirm(&self) -> bool {
        self.confirm.is_some()
    }
    pub(crate) fn test_error(&self) -> Option<String> {
        self.error.clone()
    }
    pub(crate) fn test_force_exit(&mut self) {
        self.exit_confirmed = true;
        self.confirm = None;
    }
    /// Answers the open confirmation with its primary button.
    pub(crate) fn test_accept_confirm(&mut self) {
        if let (Some(c), Some(ctx)) = (self.confirm.take(), self.ctx_clone()) {
            self.apply_confirm(&ctx, 1, c);
        }
    }
    pub(crate) fn test_close(&mut self, id: u64) {
        self.close_tab(id, true);
    }
    /// The settings as the next start reads them back.
    pub(crate) fn test_state_round_trip(&self) -> extras::Persisted {
        extras::parse(&extras::serialize(&self.persisted()))
    }
    pub(crate) fn test_reopen_with(&mut self, enc: Option<Encoding>) {
        self.reopen_with(enc);
    }
    /// Takes the files of later launches (see `instance`).
    pub(crate) fn start_instance_server(&mut self, lock: PathBuf) {
        self.instance = crate::instance::serve_app(
            lock,
            self.tx.clone(),
            self.waker.clone(),
            self.to_front.clone(),
        );
    }

    pub(crate) fn test_ctx(&self) -> Option<egui::Context> {
        self.ctx_clone()
    }
    /// The title of the confirmation being asked, if any.
    pub(crate) fn test_confirm_title(&self) -> Option<String> {
        self.confirm.as_ref().map(|c| c.title.clone())
    }
    pub(crate) fn test_cancel_confirm(&mut self) {
        self.confirm = None;
    }

    pub(crate) fn test_properties_sha(&mut self) {
        self.start_sha();
    }
    pub(crate) fn test_dismiss(&mut self) {
        self.error = None;
        self.confirm = None;
    }
}

impl eframe::App for BigTextApp {
    /// Runs before every `ui`, and also while the window is minimized, when eframe calls no
    /// `ui` at all: messages wait for `ui`, so a file handed over by a later launch would wait
    /// until the user brought the window back. Here the window comes back by itself, and the
    /// next `ui` opens the file.
    fn logic(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) {
        if self.to_front.swap(false, Ordering::AcqRel) {
            // To the front, as far as the system lets it.
            ctx.send_viewport_cmd(egui::ViewportCommand::Minimized(false));
            ctx.send_viewport_cmd(egui::ViewportCommand::Focus);
            ctx.send_viewport_cmd(egui::ViewportCommand::RequestUserAttention(
                egui::UserAttentionType::Informational,
            ));
            ctx.request_repaint();
        }
    }

    fn raw_input_hook(&mut self, _ctx: &egui::Context, raw_input: &mut egui::RawInput) {
        if let Some(t) = &mut self.self_test {
            t.inject(raw_input);
        }
    }

    fn ui(&mut self, ui: &mut egui::Ui, _frame: &mut eframe::Frame) {
        let t0 = Instant::now();
        let ctx = ui.ctx().clone();
        CTX.with(|c| *c.borrow_mut() = Some(ctx.clone()));
        self.track_jumps();
        self.poll_messages();
        self.run_pending_diff();
        self.sync_side_doc();
        self.handle_close_request(&ctx);
        fonts::refresh(&ctx, self.settings.font_path.as_deref());

        // Dropped files.
        let dropped: Vec<PathBuf> = ctx.input(|i| {
            i.raw
                .dropped_files
                .iter()
                .map(|f| f.path().to_path_buf())
                .collect()
        });
        for p in dropped {
            self.open_path(p);
        }

        if let Some(mut b) = self.bench.take() {
            b.before_frame(self, &ctx);
            self.bench = Some(b);
        }
        if let Some(mut t) = self.self_test.take() {
            t.before_frame(self, &ctx);
            self.self_test = Some(t);
        }

        self.update_tick();
        self.welcome_tick();
        self.theme_tick(&ctx);
        let modal_open = self.run_cmd.open
            || self.goto.is_some()
            || self.clips.open.is_some()
            || self.switcher.is_some()
            || self.files.open
            || self.export.is_open()
            || self.csv.rename.is_some()
            || self.palette.is_some()
            || self.quick_open.is_some()
            || self.file_ops.dialog.is_some()
            || self.remote.open
            || self.symbols_open()
            || self.shortcuts_ui.capturing.is_some()
            || self.confirm.is_some()
            || self.error.is_some()
            || self.update.dialog_open()
            || self.welcome.whats_new.is_some();
        if !modal_open {
            self.shortcuts(&ctx);
            // The mouse's back and forward buttons.
            let (back, forward) = ctx.input(|i| {
                (
                    i.pointer.button_pressed(egui::PointerButton::Extra1),
                    i.pointer.button_pressed(egui::PointerButton::Extra2),
                )
            });
            if back {
                self.nav_back();
            }
            if forward {
                self.nav_forward();
            }
        }
        self.switcher_keys(&ctx);
        self.paste_history_keys(&ctx);
        self.track_mru();

        for d in &mut self.docs {
            d.tick();
            d.refine_goto();
            follow_chunked(d, &self.tx, &self.waker);
        }
        self.journal_tick();
        self.apply_pending_journal();
        self.preview_tick();
        if let Some(s) = self.diff.as_mut().and_then(|r| r.side.as_mut()) {
            s.doc.tick();
        }
        self.run_pending_find();
        self.run_pending_filters();
        self.announce_results();
        self.json_crumb_tick(&ctx);
        self.folder_tick(&ctx);
        self.remote_tick();
        self.alerts_tick(&ctx);
        self.records_tick();
        self.hl_tick();
        self.sync_diff_marks();

        self.fullscreen = ctx.input(|i| i.viewport().fullscreen.unwrap_or(false));
        let zen = self.settings.zen;
        if zen {
            self.zen_menu(&ctx);
        } else {
            egui::Panel::top("menu").show(ui, |ui| self.menu_bar(ui));
            // The status bar under everything, the side bar beside the tabs and the text.
            egui::Panel::bottom("status").show(ui, |ui| self.status_bar(ui));
            if self.folder.visible && self.folder.root.is_some() {
                egui::Panel::left("folder")
                    .resizable(true)
                    .default_size(240.0)
                    .min_size(120.0)
                    .max_size(side_panel_max(ui))
                    .show(ui, |ui| self.folder_panel(ui));
            }
            egui::Panel::top("tabs").show(ui, |ui| self.tab_bar(ui));
        }
        self.match_count_tick();
        if self.search.open {
            egui::Panel::top("search").show(ui, |ui| self.search_panel(ui));
        }
        if self.level_bar_visible() && !zen {
            egui::Panel::top("levels").show(ui, |ui| self.level_bar(ui));
        }
        if self.search.show_results
            && self
                .docs
                .get(self.active)
                .is_some_and(|d| d.results.is_some())
        {
            egui::Panel::bottom("results")
                .resizable(true)
                .default_size(220.0)
                .show(ui, |ui| self.results_panel(ui));
        }
        if self.search.show_filter
            && self
                .docs
                .get(self.active)
                .is_some_and(|d| d.filter.is_some())
        {
            egui::Panel::bottom("filter")
                .resizable(true)
                .default_size(260.0)
                .show(ui, |ui| self.filter_panel(ui));
        }
        if self.files.results.is_some() {
            egui::Panel::bottom("files")
                .resizable(true)
                .default_size(240.0)
                .show(ui, |ui| self.files_panel(ui));
        }
        if self.timeline.open
            && self
                .docs
                .get(self.active)
                .is_some_and(|d| d.timeline.is_some())
        {
            egui::Panel::bottom("timeline")
                .resizable(true)
                .default_size(170.0)
                .show(ui, |ui| self.timeline_panel(ui));
        }
        if self.json_diff.open
            && self
                .docs
                .get(self.active)
                .is_some_and(|d| d.json_diff.is_some())
        {
            egui::Panel::bottom("json-diff")
                .resizable(true)
                .default_size(180.0)
                .show(ui, |ui| self.json_diff_panel(ui));
        }
        if self.json_check.open
            && self
                .docs
                .get(self.active)
                .is_some_and(|d| d.json_check.is_some())
        {
            egui::Panel::bottom("json-check")
                .resizable(true)
                .default_size(160.0)
                .show(ui, |ui| self.json_check_panel(ui));
        }
        if self.chart.open
            && self
                .docs
                .get(self.active)
                .is_some_and(|d| d.chart.is_some())
        {
            egui::Panel::bottom("chart")
                .resizable(true)
                .default_size(200.0)
                .show(ui, |ui| self.chart_panel(ui));
        }
        if self.problems.open
            && self
                .docs
                .get(self.active)
                .is_some_and(|d| d.problems.is_some())
        {
            egui::Panel::bottom("problems")
                .resizable(true)
                .default_size(180.0)
                .show(ui, |ui| self.problems_panel(ui));
        }
        if self.gaps.open && self.docs.get(self.active).is_some_and(|d| d.gaps.is_some()) {
            egui::Panel::bottom("gaps")
                .resizable(true)
                .default_size(160.0)
                .show(ui, |ui| self.gaps_panel(ui));
        }
        if self.diff.is_some() {
            egui::Panel::bottom("diff")
                .resizable(true)
                .default_size(200.0)
                .show(ui, |ui| self.diff_panel(ui));
        }
        if self.only_in.is_some() {
            egui::Panel::bottom("only-in")
                .resizable(true)
                .default_size(220.0)
                .show(ui, |ui| self.only_in_panel(ui));
        }
        if self
            .docs
            .get(self.active)
            .is_some_and(|d| d.banner.is_some())
        {
            egui::Panel::top("banner")
                .show_separator_line(false)
                .show(ui, |ui| self.banner(ui));
        }

        if self.json_open
            && self
                .docs
                .get(self.active)
                .is_some_and(|d| d.is_ready() && !d.hex)
        {
            egui::Panel::left("json")
                .resizable(true)
                .default_size(320.0)
                .max_size(side_panel_max(ui))
                .show(ui, |ui| self.json_panel(ui));
        }
        if self.fields.open
            && self
                .docs
                .get(self.active)
                .is_some_and(|d| d.is_ready() && !d.hex)
        {
            egui::Panel::left("fields")
                .resizable(true)
                .default_size(300.0)
                .max_size(side_panel_max(ui))
                .show(ui, |ui| self.fields_panel(ui));
        }

        // Over the empty document of a fresh start; typing goes on to the document below.
        if self.welcome_visible() {
            let editor = ui.available_rect_before_wrap();
            self.welcome_ui(&ctx, editor);
        }
        let mut actions = Vec::new();
        let mut table_actions = Vec::new();
        let hl = self.view_highlights(ui.visuals().dark_mode);
        let link_partner = self.linked_partner();
        let font_size = &mut self.settings.font_size;
        let syntax = self.settings.syntax;
        let show_ws = text_view::ShowWs {
            text: self.settings.show_ws,
            code: self.settings.show_ws_code,
        };
        let show_gutter = self.settings.show_gutter;
        let (wrap_column, ruler) = (
            self.settings.wrap_column.map(usize::from),
            self.settings.ruler.map(usize::from),
        );
        egui::CentralPanel::no_frame().show(ui, |ui| {
            // Two linked logs side by side; the right one follows and takes no keys.
            if let Some(pi) = link_partner {
                let (a, b) = time_link::pair_mut(&mut self.docs, self.active, pi);
                let full = ui.available_rect_before_wrap();
                let mid = full.center().x.round();
                let left = egui::Rect::from_min_max(full.min, egui::pos2(mid - 2.0, full.bottom()));
                let right = egui::Rect::from_min_max(egui::pos2(mid + 2.0, full.top()), full.max);
                ui.painter().vline(
                    mid,
                    full.y_range(),
                    ui.visuals().widgets.noninteractive.bg_stroke,
                );
                for (d, rect, focus) in [(a, left, !modal_open), (b, right, false)] {
                    let lang = if syntax {
                        d.effective_lang()
                    } else {
                        crate::view::highlight::Lang::Plain
                    };
                    let mut env = text_view::ViewEnv {
                        font_size: &mut *font_size,
                        highlight: &hl,
                        actions: &mut actions,
                        focus,
                        lang,
                        pane: 0,
                        show_ws,
                        show_gutter,
                        wrap_column,
                        ruler,
                        diff: None,
                    };
                    ui.scope_builder(egui::UiBuilder::new().max_rect(rect), |ui| {
                        text_view::show(ui, d, &mut env)
                    });
                }
                return;
            }
            if let Some(d) = self.docs.get_mut(self.active) {
                if d.hex && d.is_ready() {
                    hex_view::show(ui, d, *font_size, !modal_open);
                } else if d.table && d.is_ready() {
                    let mut env = table_view::TableEnv {
                        font_size,
                        focus: !modal_open,
                        show_gutter,
                        actions: &mut table_actions,
                    };
                    table_view::show(ui, d, &mut env);
                } else {
                    let lang = if syntax {
                        d.effective_lang()
                    } else {
                        crate::view::highlight::Lang::Plain
                    };
                    let side = match &mut self.diff {
                        Some(r) if self.side_by_side && r.doc == d.id && r.side.is_some() => {
                            Some(r)
                        }
                        _ => None,
                    };
                    match (side, d.split.take()) {
                        (Some(r), split) => {
                            d.split = split;
                            let mut env = text_view::ViewEnv {
                                font_size,
                                highlight: &hl,
                                actions: &mut actions,
                                focus: !modal_open,
                                lang,
                                pane: 0,
                                show_ws,
                                show_gutter,
                                wrap_column,
                                ruler,
                                diff: None,
                            };
                            extras::show_side_by_side(ui, d, r, &mut env);
                        }
                        (None, None) => {
                            let mut env = text_view::ViewEnv {
                                font_size,
                                highlight: &hl,
                                actions: &mut actions,
                                focus: !modal_open,
                                lang,
                                pane: 0,
                                show_ws,
                                show_gutter,
                                wrap_column,
                                ruler,
                                diff: None,
                            };
                            text_view::show(ui, d, &mut env);
                        }
                        (None, Some(mut pane)) => {
                            // Two panes over the same document: independent scrolling, shared caret.
                            let full = ui.available_rect_before_wrap();
                            let mid = full.center().y;
                            let top = egui::Rect::from_min_max(
                                full.min,
                                egui::pos2(full.right(), mid - 2.0),
                            );
                            let bottom = egui::Rect::from_min_max(
                                egui::pos2(full.left(), mid + 2.0),
                                full.max,
                            );
                            ui.painter().hline(
                                full.x_range(),
                                mid,
                                ui.visuals().widgets.noninteractive.bg_stroke,
                            );
                            ui.scope_builder(egui::UiBuilder::new().max_rect(top), |ui| {
                                let mut env = text_view::ViewEnv {
                                    font_size: &mut *font_size,
                                    highlight: &hl,
                                    actions: &mut actions,
                                    focus: !modal_open,
                                    lang,
                                    pane: 0,
                                    show_ws,
                                    show_gutter,
                                    wrap_column,
                                    ruler,
                                    diff: None,
                                };
                                text_view::show(ui, d, &mut env);
                            });
                            pane.swap_with(&mut d.view);
                            ui.scope_builder(egui::UiBuilder::new().max_rect(bottom), |ui| {
                                let mut env = text_view::ViewEnv {
                                    font_size: &mut *font_size,
                                    highlight: &hl,
                                    actions: &mut actions,
                                    focus: !modal_open,
                                    lang,
                                    pane: 1,
                                    show_ws,
                                    show_gutter,
                                    wrap_column,
                                    ruler,
                                    diff: None,
                                };
                                text_view::show(ui, d, &mut env);
                            });
                            pane.swap_with(&mut d.view);
                            d.split = Some(pane);
                        }
                    }
                }
            }
        });
        for a in table_actions {
            self.on_table_action(a);
        }
        self.sync_link(&ctx);
        if self
            .docs
            .get_mut(self.active)
            .is_some_and(|d| std::mem::take(&mut d.table_state.layout_changed))
        {
            self.persist_state();
        }
        for a in actions {
            match a {
                text_view::ViewAction::Escape => {
                    if self.settings.zen {
                        self.settings.zen = false;
                    }
                }
                text_view::ViewAction::CopyLarge { cut, len } => {
                    if let Some(id) = self.docs.get(self.active).map(|d| d.id) {
                        if len > 100 * 1024 * 1024 {
                            self.confirm = Some(Confirm {
                                title: i18n::tr("Large copy").into(),
                                message: i18n::trf(
                                    "Copy {size} to the clipboard? This needs that much memory.",
                                    &[("size", &human_bytes(len))],
                                ),
                                action: ConfirmAction::CopyLarge { doc: id, cut },
                                checkbox: None,
                            });
                        } else {
                            self.start_copy_job(id, cut);
                        }
                    }
                }
            }
        }

        self.dialogs(&ctx);
        self.update_dialog(&ctx);
        self.whats_new_ui(&ctx);
        self.marks_window(&ctx);
        self.export_windows(&ctx);
        self.csv_windows(&ctx);
        self.merge_window(&ctx);
        self.run_command_window(&ctx);
        self.find_in_files_window(&ctx);
        self.switcher_window(&ctx);
        self.portable_window(&ctx);
        self.id_patterns_window(&ctx);
        self.time_range_window(&ctx);
        self.patterns_window(&ctx);
        self.log_report_window(&ctx);
        self.values_window(&ctx);
        self.join_window(&ctx);
        self.table_compare_window(&ctx);
        self.only_in_window(&ctx);
        self.archive_window(&ctx);
        self.unpack_dir_window(&ctx);
        self.properties_window(&ctx);
        self.recovery_window(&ctx);
        self.text_result_window(&ctx);
        self.column_editor_window(&ctx);
        self.paste_history_window(&ctx);
        self.pivot_window(&ctx);
        self.derive_window(&ctx);
        self.json_fields_window(&ctx);
        self.palette_window(&ctx);
        self.quick_open_window(&ctx);
        self.file_ops_window(&ctx);
        self.remote_window(&ctx);
        self.log_sources_window(&ctx);
        self.alerts_window(&ctx);
        self.sql_dump_window(&ctx);
        self.share_window(&ctx);
        self.symbols_window(&ctx);
        self.shortcuts_window(&ctx);
        self.fonts_window(&ctx);
        self.perf_overlay(&ctx);
        self.record_copies(&ctx);

        let title = match self.docs.get(self.active) {
            Some(d) => format!(
                "{}{} — BigText",
                d.title,
                if d.is_modified() { " ●" } else { "" }
            ),
            None => "BigText".into(),
        };
        // Only when it changes: every viewport command asks for another frame, so sending the
        // title each frame kept an idle window repainting as fast as it could.
        if title != self.window_title {
            ctx.send_viewport_cmd(egui::ViewportCommand::Title(title.clone()));
            self.window_title = title;
        }

        // Keep repainting while background work is visible in the UI.
        let busy = self.docs.iter().any(|d| {
            (d.is_ready() && !d.buf.index.is_done() && !d.buf.source.is_remote())
                || matches!(d.state, DocState::Loading | DocState::Finalizing(_))
                || d.save_job.is_some()
                || d.find_job.is_some()
                || d.results.as_ref().is_some_and(|r| r.is_running())
                || d.filter.as_ref().is_some_and(|r| r.is_running())
                || d.timeline.as_ref().is_some_and(|t| t.is_running())
                || d.gaps.as_ref().is_some_and(|g| g.is_running())
                || d.patterns.as_ref().is_some_and(|p| p.is_running())
                || d.log_report.as_ref().is_some_and(|r| r.is_running())
                || d.sql_dump.as_ref().is_some_and(|r| r.is_running())
                || d.problems.as_ref().is_some_and(|p| p.is_running())
                || d.chart.as_ref().is_some_and(|c| c.is_running())
                || d.json_check.as_ref().is_some_and(|j| j.is_running())
                || d.json_diff.as_ref().is_some_and(|j| j.is_running())
        }) || !self.tasks.is_empty()
            || self.files.is_running();
        if busy {
            ctx.request_repaint_after(Duration::from_millis(100));
        }

        let ms = t0.elapsed().as_secs_f32() * 1000.0;
        self.frame.push(ms);
        if self.first_frame.is_none() {
            self.first_frame = Some(self.process_start.elapsed());
        }
        if let Some(mut b) = self.bench.take() {
            b.after_frame(self, &ctx, ms);
            self.bench = Some(b);
        }
        if let Some(t) = &mut self.self_test {
            t.after_frame(&ctx, ms);
        }
    }

    fn on_exit(&mut self, _gl: Option<&eframe::glow::Context>) {
        notify::hide();
        self.apply_update_on_exit();
        // Unpacked copies are deleted once nothing maps them any more.
        let temps: Vec<PathBuf> = self
            .docs
            .iter()
            .filter(|d| d.temporary)
            .filter_map(|d| d.path.clone())
            .collect();
        if !temps.is_empty() {
            for d in &mut self.docs {
                d.cancel_jobs();
                d.watch_cancel.cancel();
            }
            self.docs.clear();
            for t in temps {
                for _ in 0..20 {
                    if std::fs::remove_file(&t).is_ok() || !t.exists() {
                        break;
                    }
                    std::thread::sleep(Duration::from_millis(50));
                }
                if let Some(dir) = t.parent() {
                    let _ = std::fs::remove_dir(dir);
                }
            }
        }
    }
}