fm84 0.26.2

A synthwave dual-pane TUI file manager
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
use crate::background::{Latest, Watch, WatchEvent};
use crate::fs_ops::{Clash, Description, Mount, Progress, Reply, Step, Transfer, copy_path, count_entries, delete_path, disk_usage, get_current_dir, load_directory_rows, measure, move_path, nearest_existing_dir, path_exists, rename_in_place};
use crate::options::{OPTION_ROWS, OptionRow, Options};
use crate::strip::{Strip, StripHit};
use crate::viewer::Preview;
use crate::viewer::{ViewMode, ViewerState};
use image::DynamicImage;
use ratatui::layout::{Position, Rect};
use ratatui::style::Style;
use ratatui::text::Span;
use ratatui::widgets::TableState;
use std::collections::{HashMap, HashSet};
use std::ffi::OsString;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::mpsc::{self, Receiver, Sender, TryRecvError};
use std::time::{Duration, Instant, SystemTime};

/// Reusable single-line text input with cursor.
pub struct TextInput {
    pub text: String,
    pub cursor: usize,
}

impl TextInput {
    pub fn new() -> Self {
        Self { text: String::new(), cursor: 0 }
    }

    pub fn set(&mut self, value: String) {
        self.cursor = value.chars().count();
        self.text = value;
    }

    fn byte_index(&self) -> usize {
        self.text.char_indices().nth(self.cursor).map(|(i, _)| i).unwrap_or(self.text.len())
    }

    pub fn move_left(&mut self) {
        self.cursor = self.cursor.saturating_sub(1);
    }

    pub fn move_right(&mut self) {
        let len = self.text.chars().count();
        if self.cursor < len {
            self.cursor += 1;
        }
    }

    pub fn move_home(&mut self) {
        self.cursor = 0;
    }

    pub fn move_end(&mut self) {
        self.cursor = self.text.chars().count();
    }

    pub fn insert(&mut self, c: char) {
        let idx = self.byte_index();
        self.text.insert(idx, c);
        self.cursor += 1;
    }

    pub fn backspace(&mut self) {
        if self.cursor > 0 {
            let byte_start = self.text.char_indices().nth(self.cursor - 1).map(|(i, _)| i).unwrap_or(0);
            let byte_end = self.byte_index();
            self.text.replace_range(byte_start..byte_end, "");
            self.cursor -= 1;
        }
    }

    pub fn delete_forward(&mut self) {
        let len = self.text.chars().count();
        if self.cursor < len {
            let byte_start = self.byte_index();
            let byte_end = self.text.char_indices().nth(self.cursor + 1).map(|(i, _)| i).unwrap_or(self.text.len());
            self.text.replace_range(byte_start..byte_end, "");
        }
    }

    /// Styled spans with a block cursor, windowed to `width` columns so the
    /// cursor stays in view. A name longer than the field it is typed into
    /// would otherwise run past the edge and be clipped there, taking the
    /// cursor with it: you would be typing somewhere you could not see.
    pub fn cursor_spans_within(&self, width: usize, text_style: Style, cursor_style: Style) -> Vec<Span<'static>> {
        if width == 0 {
            return Vec::new();
        }

        let cell = |character: char| crate::utils::display_width(&character.to_string()).max(1);
        let characters: Vec<char> = self.text.chars().collect();
        let cursor = self.cursor.min(characters.len());
        let at_cursor = characters.get(cursor).copied().unwrap_or(' ');

        // A cursor past the end still needs a cell of its own to sit in.
        let whole: usize = characters.iter().map(|&c| cell(c)).sum::<usize>() + 1;

        // Everything fits: start at the beginning. Otherwise scroll so the
        // cursor is at the right-hand edge, which is where typing keeps it.
        let mut first = 0;
        if whole > width {
            let mut used = cell(at_cursor);
            first = cursor;
            while first > 0 && used + cell(characters[first - 1]) <= width {
                first -= 1;
                used += cell(characters[first]);
            }
        }

        let before: String = characters[first..cursor].iter().collect();
        let mut used = crate::utils::display_width(&before) + cell(at_cursor);
        let mut after = String::new();
        for &character in characters.iter().skip(cursor + 1) {
            let this = cell(character);
            if used + this > width {
                break;
            }
            used += this;
            after.push(character);
        }

        // A rename field is opened on the name that is there, and a name can
        // hold anything; the width is unchanged, a control character standing
        // in one column as the '.' that replaces it does.
        vec![
            Span::styled(crate::utils::printable_name(&before), text_style),
            Span::styled(crate::utils::printable_name(&at_cursor.to_string()), cursor_style),
            Span::styled(crate::utils::printable_name(&after), text_style),
        ]
    }

    /// Styled spans with a block cursor at the cursor position, for a field
    /// wide enough to hold whatever is typed into it.
    pub fn cursor_spans(&self, text_style: Style, cursor_style: Style) -> Vec<Span<'static>> {
        let byte_idx = self.byte_index();
        let before = self.text[..byte_idx].to_string();
        let rest = &self.text[byte_idx..];
        let mut chars = rest.chars();
        let cursor_char = chars.next().unwrap_or(' ');
        let after: String = chars.collect();

        vec![
            Span::styled(crate::utils::printable_name(&before), text_style),
            Span::styled(crate::utils::printable_name(&cursor_char.to_string()), cursor_style),
            Span::styled(crate::utils::printable_name(&after), text_style),
        ]
    }
}

/// What the prompt in the status bar is asking for: in the viewer or the
/// editor, something to find or a line to go to; in a panel, a pattern to
/// select or deselect by.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum PromptKind {
    Find,
    GoToLine,
    Select,
    Deselect,
    /// What to replace, in the editor.
    Replace,
    /// What to replace it with.
    ReplaceWith,
}

/// What fills the space between the top bar and the bottom one: the two
/// panels, or a file open in the viewer or the editor. One at a time, by
/// construction - the file being looked at lives here and nowhere else.
pub enum Screen {
    Panels,
    Viewer(ViewerState),
    Editor(EditorState),
}

/// The one dialog open over the screen, if any, carrying what it is asking
/// about. Only one can be open at a time, and each answers its own keys, so
/// nothing behind it can act on a key meant for it.
pub enum Dialog {
    /// F1.
    Help,
    /// F11. `editing` holds a text option while it is being typed into.
    Options { editing: Option<TextInput> },
    /// F2, typed into in place of the name in the panel.
    Rename(TextInput),
    /// F7 makes a directory, Shift+F4 an empty file.
    Create { is_dir: bool, input: TextInput },
    /// F8: what to delete, as paths - the name alone could not be joined
    /// back to the file it came from when it is not valid UTF-8 - and whether
    /// it goes to the trash or for good.
    Delete { items: Vec<(PathBuf, bool)>, to_trash: bool },
    /// F5 or F6, waiting to be confirmed, with where to put what is chosen
    /// typed into `input`. It opens on the other panel's directory - with the
    /// file's name on the end, when it is a single file - `default` as the
    /// filesystem holds it, and `opened_with` as it was written into
    /// the field: a path that is not valid UTF-8 can only be shown near
    /// enough, so while the field is as it opened, `default` is what is used.
    Transfer {
        sources: Vec<(PathBuf, bool)>,
        is_copy: bool,
        input: TextInput,
        opened_with: String,
        default: PathBuf,
    },
    /// A file big enough to be worth asking about before it is opened.
    LargeFile(LargeFile),
    /// Unsaved edits, on the way out of the editor. `then_quit` when it was
    /// F10 that asked, so that answering Save or Discard also leaves.
    SaveChanges { then_quit: bool },
    /// Something else has changed the file in the editor since it was opened,
    /// and saving would write over that: asked about before it does. `then` is
    /// what the save was on its way to, done once it is answered with a save.
    DiskChanged { then: AfterSave, opened: Option<DiskStamp>, now: Option<DiskStamp> },
    /// Alt+F1 or Alt+F2: which panel is choosing, and the mount highlighted.
    DrivePicker { is_left: bool, index: usize },
    /// The line at the foot of the screen, asking for something to find, a
    /// line to go to or a pattern to select by.
    Prompt(PromptKind, TextInput),
    /// Alt+F7: what to look for, and then what was found.
    FindFiles(Box<FindFiles>),
    /// Replacing in the editor, a match at a time: the one selected is the
    /// one asked about. `stop_at` is where it started, which it stops at once
    /// it has gone round the end of the file and back; `wrapped` says it has.
    Replacing { stop_at: (usize, usize), wrapped: bool, replaced: usize },
}

/// What a save in the editor goes on to do once the file is written.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum AfterSave {
    /// Back to editing.
    Stay,
    /// Close the editor.
    Close,
    /// Close the editor, and fm84 with it: the save was F10's.
    Quit,
}

/// A file as it stood on disk: when it was last modified, and its size.
/// Together they tell a file something else has written apart from the one
/// the editor read, even on a filesystem that keeps time only to the second.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub struct DiskStamp {
    pub modified: Option<SystemTime>,
    pub size: u64,
}

impl DiskStamp {
    /// The file at `path` as it stands now, through a link to what it names
    /// - which is what a save writes. None when there is nothing there.
    pub fn of(path: &Path) -> Option<Self> {
        let metadata = std::fs::metadata(path).ok()?;
        Some(DiskStamp {
            modified: metadata.modified().ok(),
            size: metadata.len(),
        })
    }
}

/// How a save from the editor came out, when it did not fail.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Saved {
    Done,
    /// Not written: something else changed the file since the editor read
    /// it, and writing would throw that away. The stamps are the file as it
    /// was read, and as it is now.
    ChangedOnDisk {
        opened: Option<DiskStamp>,
        now: Option<DiskStamp>,
    },
}

/// Find files, from the form to the results.
pub enum FindFiles {
    /// What to look for: a name pattern, and text the file has to hold.
    /// `on_containing` says which field the keys go to.
    Asking { name: TextInput, containing: TextInput, on_containing: bool },
    /// The search, running or over, and what it has found.
    Found(Search),
}

/// A Find files walk on a thread of its own, and what it has sent so far.
/// Dropped - the dialog closed - it is told to stop.
pub struct Search {
    /// Where it started, which the results are shown from.
    pub start: PathBuf,
    /// What was looked for, for the title.
    pub label: String,
    /// Each match, and whether it is a directory, in the order found.
    pub results: Vec<(PathBuf, bool)>,
    pub cursor: usize,
    /// The first result showing, kept so the list scrolls only when the
    /// cursor reaches an edge of it.
    pub scroll: usize,
    /// The directory being looked through, while the walk goes on.
    pub looking_in: Option<PathBuf>,
    pub done: bool,
    /// Directories that could not be read, counted rather than stopping it.
    pub unreadable: usize,
    cancel: Arc<AtomicBool>,
    updates: Receiver<crate::search::Update>,
}

impl Drop for Search {
    fn drop(&mut self) {
        self.cancel.store(true, Ordering::Relaxed);
    }
}

impl Dialog {
    /// True for the dialogs drawn as a popup over the screen, which nothing
    /// behind may answer for - not even the mouse. The rename field sits in
    /// the panel, where a click cancels it; the prompt at the foot and the
    /// drive strip leave the panels to be clicked.
    fn is_popup(&self) -> bool {
        !matches!(self, Dialog::Rename(_) | Dialog::Prompt(..) | Dialog::DrivePicker { .. })
    }
}

pub struct AppState {
    pub screen: Screen,
    pub dialog: Option<Dialog>,
    /// An error to show, over the screen and over any dialog.
    pub error: Option<String>,
    /// What F11 sets, as loaded from the config file at startup.
    pub options: Options,
    /// The row the options popup has highlighted.
    pub options_cursor: usize,
    /// A file F4 is handing to an external editor. The main loop runs it,
    /// since only that can give the terminal up and take it back.
    pub external_edit: Option<PathBuf>,
    /// F12: the opposite panel shows what the cursor is on.
    pub show_preview: bool,
    pub preview: Option<PreviewState>,
    /// Editor clipboard. Internal, so it works in a bare TTY too.
    pub clipboard: String,
    /// Mounts offered in the drive strips, kept current by a watcher thread.
    pub mounts: Vec<Mount>,
    pub is_left_active: bool,
    pub dir_left: PathBuf,
    pub dir_right: PathBuf,
    pub page_size: u16,
    pub state_left: TableState,
    pub state_right: TableState,
    pub children_left: Vec<Item>,
    pub children_right: Vec<Item>,
    pub search_input: String,
    pub cached_clock: String,
    pub cached_separator_height: u16,
    pub cached_separator: String,
    pub viewer_viewport_height: usize,
    pub viewer_viewport_width: usize,
    pub editor_viewport_height: usize,
    /// What + or - last selected by, offered again the next time.
    pub select_pattern: String,
    /// What Find files last looked for - the name pattern and the text -
    /// offered again the next time.
    pub find_files_last: (String, String),
    /// How many results the Find files list showed when it was last drawn,
    /// which is how far PageUp and PageDown go.
    pub find_files_page: usize,
    /// What Ctrl+R last replaced with, offered again the next time.
    pub replace_with: String,
    /// Whether W last left the viewer wrapping lines, which the next file
    /// opened takes up.
    pub viewer_wrap: bool,
    /// What Ctrl+F last looked for. Kept when the prompt closes, for F3 and
    /// Shift+F3, and offered again the next time it opens.
    pub find_term: String,
    /// Whether the matches of find_term are marked on screen. On from the
    /// first search until the viewer or editor closes.
    pub find_shown: bool,
    /// What the last search came to - "Not found", or that it went round the
    /// end - shown in the status bar until the next key.
    pub find_note: Option<String>,
    // Keyed by file name, not row index: a reload can re-sort the rows, and an
    // index would then point at a different file than the one the user picked.
    // The name the filesystem holds, not the one shown: two names that are not
    // valid UTF-8 can read the same, and picking one would pick both.
    pub selected_left: HashSet<OsString>,
    pub selected_right: HashSet<OsString>,
    pub dir_sizes: HashMap<PathBuf, u64>,
    pub last_click_time: Option<Instant>,
    pub last_click_pos: (u16, u16),
    // Where the last frame actually drew things. Mouse handling reads these
    // instead of recomputing the layout from hardcoded row numbers.
    pub table_area_left: Rect,
    pub table_area_right: Rect,
    pub viewport_start_left: usize,
    pub viewport_start_right: usize,
    pub editor_content_area: Rect,
    pub viewer_content_area: Rect,
    // The drive strips as drawn, and which of the drives each one shows.
    pub drive_strip_left: Strip,
    pub drive_strip_right: Strip,
    // Each panel's tabs, and its tab strip as drawn.
    pub tabs_left: Tabs,
    pub tabs_right: Tabs,
    // A panel's directory still being read, past the moment the UI waits for
    // it. The panel goes on showing what it did until it lands.
    pub listing_left: Option<PendingListing>,
    pub listing_right: Option<PendingListing>,
    /// How long the UI waits on a listing before going on without it.
    /// Without limit under test, which wants each answer in hand before it
    /// looks; the same goes for `detail_wait`.
    pub listing_wait: Duration,
    /// How long the UI waits on the detail lines and the preview.
    pub detail_wait: Duration,
    // Watching each panel's directory for changes and its filesystem for free
    // space, and the mounts for drives coming and going. Dropping one stops it.
    watch_left: Option<Watch>,
    watch_right: Option<Watch>,
    _watch_mounts: Watch,
    /// Handed to each watcher as it starts; what they report arrives on
    /// `watch_events`.
    watch_sender: Sender<WatchEvent>,
    watch_events: Receiver<WatchEvent>,
    /// How often a watcher looks. Shortened under test, so a change is seen
    /// inside it.
    pub watch_interval: Duration,
    // Changed on disk since it was read, to be read again once nothing is
    // open over it.
    stale_left: bool,
    stale_right: bool,
    /// Where the detail lines are gathered.
    detail_worker: Latest<(PathBuf, bool), Option<Description>>,
    /// Where the preview is gathered.
    preview_worker: Latest<(PathBuf, bool), Preview>,
    // (used, total) bytes for each panel's filesystem.
    pub disk_left: Option<(u64, u64)>,
    pub disk_right: Option<(u64, u64)>,
    /// Set while a copy, move or delete is running on its own thread.
    pub job: Option<TransferJob>,
    /// Directories Space is working out the size of, each on its own thread.
    pub dir_sizing: Vec<DirSizing>,
    /// Pictures read around the one on screen, while F11 leaves it on.
    pub image_cache: ImageCache,
    /// The entry under the cursor, spelled out under the panels.
    pub cursor_detail: Option<CursorDetail>,
    /// F10 was pressed during a job. The job carries on; a second press is
    /// what leaves. Cleared when the job ends, so it only ever covers one.
    pub quit_armed: bool,
}

/// A copy, move or delete running on a worker thread, and what it has told us
/// so far.
/// The work is off the UI thread because a single write to a stalled network
/// mount can block for seconds, and that is exactly when a progress bar and a
/// way out of it are wanted.
pub struct TransferJob {
    pub kind: TransferKind,
    /// None until the counting pass has something to report. Counted in bytes
    /// for a copy or move, in entries removed for a delete, and in items for a
    /// move to the trash.
    pub total: Option<u64>,
    pub done: u64,
    pub current: PathBuf,
    pub started: Instant,
    /// Set by Esc, read by the worker between entries.
    cancel: Arc<AtomicBool>,
    updates: Receiver<JobUpdate>,
    /// An entry the worker could not deal with, waiting on Retry, Skip, Skip
    /// all or Abort - or Delete, for what the trash would not take. The worker
    /// sits still until it hears which.
    pub problem: Option<JobProblem>,
    /// A file in the way of one being copied or moved, waiting on whether to
    /// write over it. The worker sits still until it hears.
    pub clash: Option<JobClash>,
    answers: Sender<Answer>,
    /// Entries left where they were, by Skip or Skip all, to say so at the end.
    pub skipped: u64,
}

/// Which of the long jobs is running. They share a popup, a worker and a
/// way out, and differ only in what they count and what they are called.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum TransferKind {
    Copy,
    Move,
    Delete,
    Trash,
}

impl TransferKind {
    /// The word the popup and the cancelled message use.
    pub fn title(self) -> &'static str {
        match self {
            TransferKind::Copy => "Copy",
            TransferKind::Move => "Move",
            TransferKind::Delete => "Delete",
            TransferKind::Trash => "Move to trash",
        }
    }
}

impl TransferJob {
    /// How far along, once there is a total to measure against. None while the
    /// counting pass is still running, or when there is nothing to count.
    pub fn fraction(&self) -> Option<f64> {
        match self.total {
            Some(total) if total > 0 => Some((self.done as f64 / total as f64).min(1.0)),
            _ => None,
        }
    }

    pub fn is_cancelling(&self) -> bool {
        self.cancel.load(Ordering::Relaxed)
    }

    /// Answer the question on screen, letting the worker go on.
    pub fn answer(&mut self, answer: Answer) {
        if self.problem.take().is_some() || self.clash.take().is_some() {
            let _ = self.answers.send(answer);
        }
    }
}

/// What the popup shows while the worker waits on whether to write over a
/// file: both of them, so the sizes and dates can be weighed against each
/// other.
pub struct JobClash {
    pub source: PathBuf,
    pub dest: PathBuf,
    pub source_size: Option<u64>,
    pub source_modified: Option<SystemTime>,
    pub dest_size: Option<u64>,
    pub dest_modified: Option<SystemTime>,
}

/// How a copy or move deals with files already there. Starts as F11's "When
/// destination exists" says, and the answers to Ask can change it partway.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Clashes {
    /// Stop and ask about each.
    Ask,
    ReplaceAll,
    KeepAll,
    /// Write over a file only when it is older than the one replacing it.
    ReplaceOlder,
}

/// What the popup shows while the worker waits for an answer.
pub struct JobProblem {
    pub path: PathBuf,
    pub message: String,
}

/// The answer to a JobProblem or a JobClash, sent back to the worker.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Answer {
    Retry,
    /// Leave this one where it is: the entry that failed, or the file that
    /// would have been written over, along with the one that would have.
    Skip,
    /// Skip this one and every other like it after it without asking.
    SkipAll,
    Abort,
    /// Delete it for good, when the trash would not take it.
    Delete,
    /// Write over the file in the way.
    Overwrite,
    /// Write over this one and every other in the way without asking.
    OverwriteAll,
    /// Write over this one and every other in the way when it is older than
    /// the one replacing it, and leave the rest - without asking again.
    OverwriteOlder,
}

/// What the worker sends back. Bytes are per chunk rather than a running total,
/// so a message that arrives late still counts once.
enum JobUpdate {
    Total(u64),
    Starting(PathBuf),
    Advanced(u64),
    /// Stuck on this entry until an Answer comes back.
    Problem(JobProblem),
    /// Stuck on a file in the way until an Answer comes back.
    Clash(JobClash),
    /// One more entry left where it was.
    Skipped,
    Finished(Result<Transfer, String>),
}

/// The worker's side of a job: passes progress to the UI, and when an entry
/// fails, asks there what to do and waits for the answer.
struct JobProgress<'a> {
    updates: &'a Sender<JobUpdate>,
    cancel: &'a AtomicBool,
    answers: &'a Receiver<Answer>,
    skip_all: bool,
    clashes: Clashes,
    /// Set once the answer was Abort, so the error it ends the job with is
    /// reported as the cancel it was rather than as a failure all over again.
    aborted: bool,
}

impl<'a> JobProgress<'a> {
    fn new(updates: &'a Sender<JobUpdate>, cancel: &'a AtomicBool, answers: &'a Receiver<Answer>, clashes: Clashes) -> Self {
        JobProgress {
            updates,
            cancel,
            answers,
            skip_all: false,
            clashes,
            aborted: false,
        }
    }

    /// The message that ends the job, given how its last item came out.
    fn finish(&self, outcome: Result<Transfer, std::io::Error>) {
        let outcome = match outcome {
            Err(_) if self.aborted => Ok(Transfer::Cancelled),
            outcome => outcome.map_err(|e| e.to_string()),
        };
        let _ = self.updates.send(JobUpdate::Finished(outcome));
    }
}

impl Progress for JobProgress<'_> {
    fn step(&mut self, step: Step<'_>) -> bool {
        let update = match step {
            Step::Starting(path) => JobUpdate::Starting(path.to_path_buf()),
            Step::Advanced(amount) => JobUpdate::Advanced(amount),
        };
        // A closed channel means the UI has gone, which is its own reason to stop.
        self.updates.send(update).is_ok() && !self.cancel.load(Ordering::Relaxed)
    }

    fn failed(&mut self, path: &Path, error: &std::io::Error) -> Reply {
        // Esc pressed before this came up already said to stop.
        if self.cancel.load(Ordering::Relaxed) {
            self.aborted = true;
            return Reply::Abort;
        }
        let answer = if self.skip_all {
            Answer::Skip
        } else {
            let problem = JobProblem {
                path: path.to_path_buf(),
                message: error.to_string(),
            };
            // Nobody left to ask, or nobody answering, is an Abort.
            if self.updates.send(JobUpdate::Problem(problem)).is_err() { Answer::Abort } else { self.answers.recv().unwrap_or(Answer::Abort) }
        };
        match answer {
            Answer::Retry => Reply::Retry,
            Answer::Skip | Answer::SkipAll => {
                self.skip_all |= answer == Answer::SkipAll;
                let _ = self.updates.send(JobUpdate::Skipped);
                Reply::Skip
            }
            Answer::Abort => {
                self.aborted = true;
                Reply::Abort
            }
            Answer::Delete => Reply::Delete,
            // Answers to a clash, which a failure is never asked.
            Answer::Overwrite | Answer::OverwriteAll | Answer::OverwriteOlder => Reply::Skip,
        }
    }

    fn exists(&mut self, source: &Path, dest: &Path) -> Clash {
        if self.cancel.load(Ordering::Relaxed) {
            return Clash::Abort;
        }
        let modified = |path: &Path| std::fs::metadata(path).or_else(|_| path.symlink_metadata()).ok().and_then(|metadata| metadata.modified().ok());
        let clash = match self.clashes {
            Clashes::Ask => {
                let size = |path: &Path| std::fs::metadata(path).or_else(|_| path.symlink_metadata()).ok().map(|metadata| metadata.len());
                let question = JobClash {
                    source: source.to_path_buf(),
                    dest: dest.to_path_buf(),
                    source_size: size(source),
                    source_modified: modified(source),
                    dest_size: size(dest),
                    dest_modified: modified(dest),
                };
                // Nobody left to ask, or nobody answering, is an Abort.
                let answer = if self.updates.send(JobUpdate::Clash(question)).is_err() { Answer::Abort } else { self.answers.recv().unwrap_or(Answer::Abort) };
                match answer {
                    Answer::Overwrite => Clash::Replace,
                    Answer::Skip => Clash::Keep,
                    Answer::OverwriteAll => {
                        self.clashes = Clashes::ReplaceAll;
                        Clash::Replace
                    }
                    Answer::SkipAll => {
                        self.clashes = Clashes::KeepAll;
                        Clash::Keep
                    }
                    Answer::OverwriteOlder => {
                        self.clashes = Clashes::ReplaceOlder;
                        replace_if_older(modified(source), modified(dest))
                    }
                    Answer::Abort | Answer::Retry | Answer::Delete => Clash::Abort,
                }
            }
            Clashes::ReplaceAll => Clash::Replace,
            Clashes::KeepAll => Clash::Keep,
            Clashes::ReplaceOlder => replace_if_older(modified(source), modified(dest)),
        };
        if clash == Clash::Keep {
            let _ = self.updates.send(JobUpdate::Skipped);
        }
        clash
    }
}

/// Overwrite older: write over what is there only when it is older than what
/// would replace it. When either time cannot be read, it is left alone - it
/// cannot be shown to be older, and what is left can still be copied again.
fn replace_if_older(source: Option<SystemTime>, dest: Option<SystemTime>) -> Clash {
    match (source, dest) {
        (Some(source), Some(dest)) if dest < source => Clash::Replace,
        _ => Clash::Keep,
    }
}

/// A tab in a panel: somewhere it was left, to go back to - the directory,
/// the entry the cursor was on and what was selected there.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Tab {
    pub dir: PathBuf,
    pub cursor: Option<OsString>,
    pub selected: HashSet<OsString>,
}

impl Tab {
    pub fn new(dir: PathBuf) -> Self {
        Tab { dir, cursor: None, selected: HashSet::new() }
    }
}

/// One panel's tabs. The panel's own fields - its directory, cursor and
/// selection - are the tab it shows, so everything else goes on working
/// without knowing tabs exist. That tab's entry here is brought up to date
/// only as the panel leaves it; the rest wait here as they were left.
pub struct Tabs {
    pub list: Vec<Tab>,
    pub active: usize,
    pub strip: Strip,
}

impl Tabs {
    pub fn new(dirs: Vec<PathBuf>, active: usize) -> Self {
        let mut list: Vec<Tab> = dirs.into_iter().map(Tab::new).collect();
        if list.is_empty() {
            list.push(Tab::new(PathBuf::from(".")));
        }
        let active = active.min(list.len() - 1);
        Tabs { list, active, strip: Strip::default() }
    }
}

/// A panel's directory being read on a thread, with what to do once it is.
pub struct PendingListing {
    /// The directory asked for.
    pub dir: PathBuf,
    /// Going there, rather than reading again where the panel already is.
    navigate: bool,
    /// The entry to land on.
    select: Option<OsString>,
    /// Set when it is a tab being switched to.
    tab: Option<TabSwitch>,
    answer: Receiver<Listed>,
}

#[cfg(test)]
impl PendingListing {
    /// A panel on its way to `dir`, held there for a test: nothing is coming.
    pub fn going_to(dir: PathBuf) -> Self {
        let (_, answer) = mpsc::channel();
        PendingListing {
            dir,
            navigate: true,
            select: None,
            tab: None,
            answer,
        }
    }
}

/// A tab being switched to: what was selected in it, and how to put the tabs
/// back if its directory turns out not to be readable.
struct TabSwitch {
    selected: HashSet<OsString>,
    undo: TabUndo,
}

enum TabUndo {
    /// The tab that was active before.
    Active(usize),
    /// The tab closed, and where it was.
    Reopen(usize, Tab),
}

/// What a listing thread comes back with.
struct Listed {
    /// Where it read: the directory asked for, or the nearest parent of it
    /// still there. None if not even the root could be reached.
    dir: Option<PathBuf>,
    items: std::io::Result<Vec<Item>>,
    /// The directory's modified time, taken before it was read, so a change
    /// made during the read is still seen as one.
    stamp: Option<SystemTime>,
    disk: Option<(u64, u64)>,
}

/// Everything a panel needs from the disk, read on the listing thread.
fn read_listing(dir: &Path, options: &Options) -> Listed {
    let Some(found) = nearest_existing_dir(dir) else {
        return Listed {
            dir: None,
            items: Err(std::io::ErrorKind::NotFound.into()),
            stamp: None,
            disk: None,
        };
    };
    let stamp = std::fs::metadata(&found).and_then(|metadata| metadata.modified()).ok();
    let items = load_directory_rows(&found, options);
    let disk = disk_usage(&found);
    Listed { dir: Some(found), items, stamp, disk }
}

/// What the preview shows of an entry, read on the preview thread: the head
/// of a file, or how many entries a directory holds.
fn read_preview(path: &Path, is_dir: bool) -> Preview {
    if !is_dir {
        return crate::viewer::load_preview(path, crate::constants::PREVIEW_MAX_BYTES, crate::constants::PREVIEW_MAX_LINES);
    }
    Preview::Lines(vec![match std::fs::read_dir(path) {
        Ok(entries) => format!("{} items", entries.count()),
        Err(e) => e.to_string(),
    }])
}

/// A directory whose size Space asked for, being walked on its own thread.
/// Not a TransferJob: nothing waits on it, so it has no popup and holds up
/// nothing. The panels go on working while it counts, and the Size column
/// shows how far it has got.
///
/// Off the UI thread because walking / or a large tree takes seconds, and
/// on an unresponsive mount a single read_dir can take forever.
pub struct DirSizing {
    pub path: PathBuf,
    /// Bytes found so far, for the Size column to show while it counts.
    pub found: u64,
    cancel: Arc<AtomicBool>,
    updates: Receiver<SizeUpdate>,
}

enum SizeUpdate {
    Found(u64),
    /// None when cancelled.
    Finished(Result<Option<u64>, String>),
}

/// What a read-ahead delivers: the picture and the label the status bar shows
/// for it, or nothing if the file turned out not to be one after all.
type Decoded = Option<(DynamicImage, String)>;

/// Pictures decoded around the one being looked at, so stepping through a
/// folder does not stop to decode each one.
///
/// Only the decoded picture is held, never the file's bytes: decoding is the
/// slow part, and a decoded picture is capped at IMAGE_MAX_SIDE, so two of
/// them come to a few megabytes however large the files were. The one just
/// left costs nothing to keep - it is already decoded - and the one ahead is
/// read on a thread, so a slow disk never shows up as a pause.
#[derive(Default)]
pub struct ImageCache {
    ready: Vec<(PathBuf, DynamicImage, String)>,
    /// The read that is running, and where it will arrive.
    pending: Option<(PathBuf, Receiver<Decoded>)>,
    /// Which way the last step went, so the right side is read ahead.
    forward: bool,
}

impl ImageCache {
    /// Both neighbours at most: one behind, one ahead.
    const KEEP: usize = 2;

    fn take(&mut self, path: &Path) -> Option<(DynamicImage, String)> {
        let at = self.ready.iter().position(|(held, _, _)| held == path)?;
        let (_, image, label) = self.ready.remove(at);
        Some((image, label))
    }

    fn keep(&mut self, path: PathBuf, image: DynamicImage, label: String) {
        self.ready.retain(|(held, _, _)| *held != path);
        self.ready.push((path, image, label));
        while self.ready.len() > Self::KEEP {
            self.ready.remove(0);
        }
    }

    fn holds(&self, path: &Path) -> bool {
        self.ready.iter().any(|(held, _, _)| held == path) || self.pending.as_ref().is_some_and(|(wanted, _)| wanted == path)
    }

    /// Start reading one, unless it is already here or on its way.
    fn request(&mut self, path: PathBuf) {
        if self.holds(&path) {
            return;
        }
        let (sender, receiver) = mpsc::channel();
        let wanted = path.clone();
        std::thread::spawn(move || {
            let _ = sender.send(crate::viewer::decode_image(&wanted));
        });
        self.pending = Some((path, receiver));
    }

    /// Take delivery of anything that has finished. Called once a frame.
    pub fn collect(&mut self) {
        let Some((path, receiver)) = &self.pending else {
            return;
        };
        match receiver.try_recv() {
            Ok(Some((image, label))) => {
                let path = path.clone();
                self.pending = None;
                self.keep(path, image, label);
            }
            // Not a picture after all, or the thread is gone: stop waiting.
            Ok(None) | Err(TryRecvError::Disconnected) => self.pending = None,
            Err(TryRecvError::Empty) => {}
        }
    }

    fn clear(&mut self) {
        self.ready.clear();
        self.pending = None;
    }
}

/// What the two lines under the panels say about the entry the cursor is on.
/// Held rather than worked out while drawing, because gathering it stats the
/// file, and a stat on an unresponsive mount would take the whole frame with it.
pub struct CursorDetail {
    /// What it describes, so it is only gathered again when the cursor moves.
    pub path: Option<PathBuf>,
    pub name: String,
    pub size: String,
    pub modified: String,
    pub owner: String,
    pub attributes: String,
    pub link: Option<String>,
    /// Asked for and not yet in: only the name is known so far.
    awaiting: bool,
}

/// A file big enough to be worth asking about before it is opened.
pub struct LargeFile {
    pub path: PathBuf,
    pub is_edit: bool,
    /// Memory it will take once open.
    pub size: u64,
    /// Set for a picture, whose `size` is what it unpacks to rather than what it
    /// occupies on disk - a small file can hold an enormous number of pixels.
    pub dimensions: Option<(u32, u32)>,
}

#[derive(Clone)]
pub struct EditorState {
    pub file_path: PathBuf,
    pub lines: Vec<String>,
    pub highlighted_lines: Vec<Vec<Span<'static>>>,
    pub cursor_line: usize,
    pub cursor_col: usize,
    pub scroll_offset: usize,
    pub horizontal_offset: usize,
    pub modified: bool,
    pub auto_scroll: bool,
    /// Where a selection began. The selection runs from here to the cursor.
    pub selection_anchor: Option<(usize, usize)>,
    /// Edits that can be undone, oldest first.
    pub undo_stack: Vec<EditStep>,
    /// Undone edits, ready to be put back. Cleared by any fresh edit.
    pub redo_stack: Vec<EditStep>,
    /// Parser state entering each line, so an edit re-parses from that line
    /// instead of the whole file. Empty when highlighting is off.
    pub line_states: Vec<crate::viewer::LineState>,
    /// The terminator this file was written with, so saving doesn't rewrite
    /// every line of a CRLF file just because one character changed.
    pub line_ending: &'static str,
    /// The file as it stood when it was last read or written here, so a save
    /// can tell when something else has written it since.
    pub disk_stamp: Option<DiskStamp>,
}

/// One undoable edit: the lines it replaced, and where the cursor was. The
/// number of lines that took their place is worked out at undo time from how
/// the buffer's length changed, so nothing has to be recorded afterwards.
#[derive(Clone)]
pub struct EditStep {
    first_line: usize,
    before: Vec<String>,
    total_lines_before: usize,
    cursor: (usize, usize),
}

/// What the opposite panel is showing while preview mode is on.
pub struct PreviewState {
    /// None for the parent entry, which has nothing to show but still holds
    /// the pane so it doesn't flicker back to a table as the cursor passes.
    pub path: Option<PathBuf>,
    pub label: String,
    pub lines: Vec<String>,
    /// The head of a binary file, laid out as a hexdump by whatever draws it.
    /// Empty for everything else, which comes as lines.
    pub bytes: Vec<u8>,
    /// Asked for and not yet in: only the name is shown so far.
    awaiting: bool,
}

#[derive(Debug, Clone)]
pub struct Item {
    /// The name the filesystem holds. On Unix that is bytes, which need not be
    /// valid UTF-8 - a file from an old archive or a foreign disk often is not.
    /// Every path an operation works on is built from this, never from the
    /// strings beside it: those come from `to_string_lossy`, which puts a
    /// replacement character where it could not read one, and a path joined
    /// from that names a file that does not exist.
    pub name_os: OsString,
    /// The whole name as it is shown and sorted, searched and selected by.
    pub name_full: String,
    pub name: String,
    pub extension: String,
    pub is_dir: bool,
    pub size: String,
    pub size_bytes: u64,
    pub modified_at: Option<SystemTime>,
    pub attributes: String,
}

impl Item {
    /// Where this entry is, inside the directory it was listed from.
    pub fn path_in(&self, dir: &Path) -> PathBuf {
        dir.join(&self.name_os)
    }
}

impl AppState {
    pub fn new() -> Self {
        let mut state_left = TableState::default();
        state_left.select(Some(1));
        let mut state_right = TableState::default();
        state_right.select(Some(1));

        let (watch_sender, watch_events) = mpsc::channel();
        let (error, dir_root) = match get_current_dir() {
            Ok(root) => (None, root),
            Err(e) => (Some(e.to_string()), PathBuf::new()),
        };

        Self {
            screen: Screen::Panels,
            dialog: None,
            error,
            // A test starts from the defaults, never from whatever the config
            // of the machine running it says.
            options: if cfg!(test) { Options::default() } else { Options::load() },
            options_cursor: 0,
            external_edit: None,
            show_preview: false,
            preview: None,
            clipboard: String::new(),
            mounts: Vec::new(),
            is_left_active: true,
            dir_left: dir_root.clone(),
            dir_right: dir_root.clone(),
            page_size: 0,
            state_left,
            state_right,
            children_left: Vec::new(),
            children_right: Vec::new(),
            search_input: String::new(),
            cached_clock: String::new(),
            cached_separator_height: 0,
            cached_separator: String::new(),
            viewer_viewport_height: 0,
            viewer_viewport_width: 0,
            editor_viewport_height: 0,
            select_pattern: "*".to_string(),
            find_files_last: ("*".to_string(), String::new()),
            find_files_page: 10,
            find_term: String::new(),
            replace_with: String::new(),
            viewer_wrap: false,
            find_shown: false,
            find_note: None,
            selected_left: HashSet::new(),
            selected_right: HashSet::new(),
            dir_sizes: HashMap::new(),
            last_click_time: None,
            last_click_pos: (0, 0),
            table_area_left: Rect::default(),
            table_area_right: Rect::default(),
            viewport_start_left: 0,
            viewport_start_right: 0,
            editor_content_area: Rect::default(),
            viewer_content_area: Rect::default(),
            listing_left: None,
            listing_right: None,
            listing_wait: if cfg!(test) { Duration::MAX } else { crate::constants::LISTING_WAIT },
            detail_wait: if cfg!(test) { Duration::MAX } else { crate::constants::DETAIL_WAIT },
            watch_left: None,
            watch_right: None,
            _watch_mounts: crate::background::watch_mounts(crate::constants::REFRESH_INTERVAL, watch_sender.clone()),
            watch_sender,
            watch_events,
            watch_interval: crate::constants::REFRESH_INTERVAL,
            stale_left: false,
            stale_right: false,
            detail_worker: Latest::new(|(path, is_dir): &(PathBuf, bool)| crate::fs_ops::describe(path, *is_dir)),
            preview_worker: Latest::new(|(path, is_dir): &(PathBuf, bool)| read_preview(path, *is_dir)),
            disk_left: None,
            disk_right: None,
            job: None,
            dir_sizing: Vec::new(),
            image_cache: ImageCache::default(),
            cursor_detail: None,
            quit_armed: false,
            drive_strip_left: Strip::default(),
            drive_strip_right: Strip::default(),
            tabs_left: Tabs::new(vec![dir_root.clone()], 0),
            tabs_right: Tabs::new(vec![dir_root], 0),
        }
    }

    pub fn display_error(&mut self, message: String) {
        self.error = Some(message);
    }

    pub fn reset_error(&mut self) {
        self.error = None;
    }

    /// The file open in the viewer, if that is what is on screen.
    pub fn viewer(&self) -> Option<&ViewerState> {
        match &self.screen {
            Screen::Viewer(state) => Some(state),
            _ => None,
        }
    }

    pub fn viewer_mut(&mut self) -> Option<&mut ViewerState> {
        match &mut self.screen {
            Screen::Viewer(state) => Some(state),
            _ => None,
        }
    }

    /// The file open in the editor, if that is what is on screen.
    pub fn editor(&self) -> Option<&EditorState> {
        match &self.screen {
            Screen::Editor(state) => Some(state),
            _ => None,
        }
    }

    pub fn editor_mut(&mut self) -> Option<&mut EditorState> {
        match &mut self.screen {
            Screen::Editor(state) => Some(state),
            _ => None,
        }
    }

    pub fn is_viewing(&self) -> bool {
        matches!(self.screen, Screen::Viewer(_))
    }

    pub fn is_editing(&self) -> bool {
        matches!(self.screen, Screen::Editor(_))
    }

    /// The text field of the dialog that is open, when it has one being
    /// typed into: a name, a pattern, something to find, a text option.
    pub fn dialog_input(&mut self) -> Option<&mut TextInput> {
        match self.dialog.as_mut()? {
            Dialog::Rename(input) | Dialog::Create { input, .. } | Dialog::Transfer { input, .. } | Dialog::Prompt(_, input) => Some(input),
            Dialog::Options { editing } => editing.as_mut(),
            Dialog::FindFiles(find) => match find.as_mut() {
                FindFiles::Asking { name, containing, on_containing } => Some(if *on_containing { containing } else { name }),
                FindFiles::Found(_) => None,
            },
            _ => None,
        }
    }

    fn options_row(&self) -> OptionRow {
        OPTION_ROWS[self.options_cursor.min(OPTION_ROWS.len() - 1)]
    }

    /// Move the highlight a row, stopping at the first and the last.
    pub fn options_move(&mut self, down: bool) {
        self.options_cursor = if down { (self.options_cursor + 1).min(OPTION_ROWS.len() - 1) } else { self.options_cursor.saturating_sub(1) };
    }

    /// Step the highlighted option, or start typing into it if it is text.
    pub fn options_change(&mut self, forward: bool) {
        let row = self.options_row();
        if row.is_text() {
            let mut input = TextInput::new();
            input.set(self.options.text(row).to_string());
            self.dialog = Some(Dialog::Options { editing: Some(input) });
            return;
        }
        self.options.cycle(row, forward);
        self.options_changed(row);
    }

    pub fn options_commit_edit(&mut self) {
        let Some(Dialog::Options { editing }) = &mut self.dialog else {
            return;
        };
        let Some(input) = editing.take() else {
            return;
        };
        let row = self.options_row();
        self.options.set_text(row, input.text.trim().to_string());
        self.options_changed(row);
    }

    pub fn options_cancel_edit(&mut self) {
        if let Some(Dialog::Options { editing }) = &mut self.dialog {
            *editing = None;
        }
    }

    /// Keep a change: write it out, and reread the panels if it changes what
    /// they list. A failed write still leaves the change in place for this run.
    fn options_changed(&mut self, row: OptionRow) {
        crate::display::apply(&self.options);
        // The detail lines are held until the cursor moves, and the date
        // format is one of the things they are written in.
        self.cursor_detail = None;
        if row.affects_listing() {
            self.reload_panel(true, None);
            self.reload_panel(false, None);
        }
        if let Err(e) = self.options.save() {
            self.display_error(format!("Cannot save options: {}", e));
        }
    }

    // Quick search methods
    pub fn search_add_char(&mut self, c: char) {
        self.search_input.push(c);
        self.jump_to_first_match();
    }

    pub fn search_backspace(&mut self) {
        self.search_input.pop();
        if !self.search_input.is_empty() {
            self.jump_to_first_match();
        }
    }

    pub fn search_clear(&mut self) {
        self.search_input.clear();
    }

    pub fn jump_to_first_match(&mut self) {
        if self.search_input.is_empty() {
            return;
        }
        let search_lower = self.search_input.to_lowercase();
        let (children, state) = self.active_panel_mut();
        if let Some(index) = children.iter().position(|item| item.name_full.to_lowercase().starts_with(&search_lower)) {
            state.select(Some(index));
        }
    }

    pub fn jump_to_next_match(&mut self) {
        if self.search_input.is_empty() {
            return;
        }
        let search_lower = self.search_input.to_lowercase();
        let (children, state) = self.active_panel_mut();
        let current = state.selected().unwrap_or(0);
        let len = children.len();

        // Search forward from current+1, wrapping around
        for offset in 1..=len {
            let i = (current + offset) % len;
            if children[i].name_full.to_lowercase().starts_with(&search_lower) {
                state.select(Some(i));
                return;
            }
        }
    }

    pub fn jump_to_prev_match(&mut self) {
        if self.search_input.is_empty() {
            return;
        }
        let search_lower = self.search_input.to_lowercase();
        let (children, state) = self.active_panel_mut();
        let current = state.selected().unwrap_or(0);
        let len = children.len();

        // Search backward from current-1, wrapping around
        for offset in 1..=len {
            let i = (current + len - offset) % len;
            if children[i].name_full.to_lowercase().starts_with(&search_lower) {
                state.select(Some(i));
                return;
            }
        }
    }

    /// Returns (&children, &mut state) for the active panel.
    fn active_panel_mut(&mut self) -> (&[Item], &mut TableState) {
        if self.is_left_active { (&self.children_left, &mut self.state_left) } else { (&self.children_right, &mut self.state_right) }
    }

    /// Open a file for viewing or editing, asking first when it is large enough
    /// that loading it will stall for a noticeable while.
    pub fn request_open(&mut self, file_path: PathBuf, is_edit: bool) {
        let size = match std::fs::metadata(&file_path) {
            // A pipe, socket or device: opening one to read can block for good,
            // and /dev/zero would pass the size check below and never end.
            Ok(metadata) if !metadata.is_file() => {
                self.display_error(format!("Not a regular file: {}", file_path.display()));
                return;
            }
            Ok(metadata) => metadata.len(),
            Err(e) => {
                self.display_error(e.to_string());
                return;
            }
        };

        if size > self.options.large_file_bytes() {
            self.dialog = Some(Dialog::LargeFile(LargeFile {
                path: file_path,
                is_edit,
                size,
                dimensions: None,
            }));
            return;
        }

        // What a picture costs is its pixel count, and the two part company
        // completely: a few hundred KB of PNG can unpack to hundreds of MB, and
        // the size checked above never sees it coming. Reading the header to
        // find out costs a fraction of a millisecond. The editor refuses
        // binaries outright, so nothing is decoded on that path.
        if !is_edit
            && let Some((dimensions, decoded)) = crate::viewer::image_cost(&file_path)
            && decoded > crate::constants::IMAGE_MAX_DECODED
        {
            self.dialog = Some(Dialog::LargeFile(LargeFile {
                path: file_path,
                is_edit,
                size: decoded,
                dimensions: Some(dimensions),
            }));
            return;
        }

        self.open_file(file_path, is_edit);
    }

    /// Answer to the large-file prompt: load it after all.
    pub fn confirm_large_file(&mut self) {
        if let Some(Dialog::LargeFile(large)) = self.dialog.take() {
            self.open_file(large.path, large.is_edit);
        }
    }

    fn open_file(&mut self, file_path: PathBuf, is_edit: bool) {
        let result = if is_edit { self.open_editor(file_path) } else { self.open_viewer(file_path) };
        if let Err(e) = result {
            self.display_error(e);
        }
    }

    pub fn open_viewer(&mut self, file_path: PathBuf) -> Result<(), String> {
        let decoded = if self.options.image_prefetch { self.image_cache.take(&file_path) } else { None };
        let mut state = crate::viewer::load_file_content(&file_path, decoded).map_err(|e| e.to_string())?;
        state.image_fill = self.options.image_fill;
        state.wrap = self.viewer_wrap;

        // Only once the new one is in hand: a load that failed used to leave
        // what was open alone, and should go on doing so. The picture being
        // replaced is already decoded, so keeping it costs nothing and makes
        // stepping back as quick as stepping on.
        if self.options.image_prefetch
            && let Screen::Viewer(previous) = std::mem::replace(&mut self.screen, Screen::Panels)
            && let Some(image) = previous.image
        {
            self.image_cache.keep(previous.file_path, image, previous.syntax_name);
        }

        self.screen = Screen::Viewer(state);
        self.read_ahead();
        Ok(())
    }

    /// Redraw an image as ASCII whenever the viewer size or the fit/fill choice
    /// asks for a different width than it was drawn at. Returns true if it did,
    /// so the caller can draw again.
    pub fn fit_viewer_image(&mut self) -> bool {
        let (width, height) = (self.viewer_viewport_width, self.viewer_viewport_height);
        let backgrounds = self.options.image_backgrounds;
        let Screen::Viewer(state) = &mut self.screen else {
            return false;
        };
        let Some(image) = &state.image else {
            return false;
        };
        if state.mode != ViewMode::Image || width == 0 || height == 0 {
            return false;
        }
        let (columns, rows) = crate::viewer::image_size_for(image, width, height, state.image_fill, state.image_zoom);
        // Rows as well as columns: a picture squashed to fit is one column wide
        // whatever the viewer's height, so only the row count shows the change.
        // The backgrounds too, since turning them on or off redraws the same
        // size - whether they are filled is the record of which way it was made.
        let drawn_with_backgrounds = !state.image_backgrounds.is_empty();
        if columns == state.image_columns && rows == state.image_lines.len() && backgrounds == drawn_with_backgrounds {
            return false;
        }

        let (was_columns, was_rows) = (state.image_columns, state.image_lines.len());
        (state.image_lines, state.image_colors, state.image_backgrounds) = crate::viewer::image_to_ascii(image, columns, rows, backgrounds);
        state.total_lines = state.line_count();
        state.image_columns = columns;
        // Hold whatever was in the middle of the pane in the middle of it. A
        // zoom step that threw the view back to the top-left would be no use
        // for looking closely at a detail, which is what zooming in is for.
        state.horizontal_offset = recentre(state.horizontal_offset, width, was_columns, columns);
        state.scroll_offset = recentre(state.scroll_offset, height, was_rows, rows);
        // Positions into the old drawing mean nothing in the new one.
        state.selection = None;
        state.pan_from = None;
        true
    }

    /// Break the viewer's lines onto rows whenever it is wrapping and has not
    /// yet been, or the width has changed since; go back to a row a line when
    /// it has stopped - X to a hexdump, or W. True if it did either, so the
    /// caller can draw again.
    pub fn fit_viewer_wrap(&mut self) -> bool {
        let width = self.viewer_viewport_width;
        let Screen::Viewer(state) = &mut self.screen else {
            return false;
        };
        if state.wrapping() {
            if width > 0 && state.rows_width != width {
                state.rewrap(width);
                return true;
            }
        } else if !state.rows.is_empty() {
            state.unwrap_rows();
            return true;
        }
        false
    }

    /// W in the viewer: wrap long lines, or stop. Only for text; the next
    /// file opened wraps or not as this one was left.
    pub fn viewer_toggle_wrap(&mut self) {
        let width = self.viewer_viewport_width;
        let Screen::Viewer(state) = &mut self.screen else {
            return;
        };
        if state.mode != ViewMode::Text || state.from_edit {
            return;
        }
        state.wrap = !state.wrap;
        self.viewer_wrap = state.wrap;
        if state.wrap && width > 0 {
            state.rewrap(width);
        } else {
            state.unwrap_rows();
        }
    }

    /// Switch an image between fitting inside the viewer and filling it. The
    /// redraw itself happens in fit_viewer_image before the next frame.
    pub fn viewer_toggle_fill(&mut self) {
        if let Screen::Viewer(state) = &mut self.screen
            && state.mode == ViewMode::Image
        {
            state.image_fill = !state.image_fill;
            // F is also the way back to an unzoomed picture from any zoom.
            state.image_zoom = crate::constants::IMAGE_ZOOM_NORMAL;
            state.scroll_offset = 0;
        }
    }

    /// Step an image up or down the zoom ladder. The zoom scales whichever of
    /// Fit and Fill is showing, so F still decides what 100% means. The drawing
    /// itself is rebuilt by fit_viewer_image before the next frame.
    pub fn viewer_zoom(&mut self, closer: bool) {
        if let Screen::Viewer(state) = &mut self.screen
            && state.mode == ViewMode::Image
        {
            let steps = crate::constants::IMAGE_ZOOM_STEPS;
            // Where the current zoom sits on the ladder, whichever rung it is on.
            let at = steps.iter().position(|&percent| percent >= state.image_zoom).unwrap_or(steps.len() - 1);
            let next = if closer { (at + 1).min(steps.len() - 1) } else { at.saturating_sub(1) };
            state.image_zoom = steps[next];
        }
    }

    pub fn close_viewer(&mut self) {
        self.screen = Screen::Panels;
        self.close_find();
        // Nothing is going to be stepped to now, and these are the only thing
        // in the app holding decoded pictures.
        self.image_cache.clear();
    }

    pub fn viewer_scroll_down(&mut self) {
        if let Screen::Viewer(state) = &mut self.screen {
            let max = state.total_lines.saturating_sub(self.viewer_viewport_height);
            state.scroll_offset = (state.scroll_offset + 1).min(max);
        }
    }

    pub fn viewer_scroll_up(&mut self) {
        if let Screen::Viewer(state) = &mut self.screen {
            state.scroll_offset = state.scroll_offset.saturating_sub(1);
        }
    }

    pub fn viewer_page_down(&mut self) {
        if let Screen::Viewer(state) = &mut self.screen {
            let max = state.total_lines.saturating_sub(self.viewer_viewport_height);
            state.scroll_offset = (state.scroll_offset + self.viewer_viewport_height).min(max);
        }
    }

    pub fn viewer_page_up(&mut self) {
        if let Screen::Viewer(state) = &mut self.screen {
            state.scroll_offset = state.scroll_offset.saturating_sub(self.viewer_viewport_height);
        }
    }

    pub fn viewer_home(&mut self) {
        if let Screen::Viewer(state) = &mut self.screen {
            state.scroll_offset = 0;
            state.horizontal_offset = 0;
        }
    }

    pub fn viewer_scroll_left(&mut self) {
        if let Screen::Viewer(state) = &mut self.screen {
            state.horizontal_offset = state.horizontal_offset.saturating_sub(1);
        }
    }

    pub fn viewer_copy(&mut self) {
        if let Some(text) = self.viewer().and_then(|state| state.selected_text()) {
            crate::utils::set_system_clipboard(&text);
            self.clipboard = text;
        }
    }

    /// Step the viewer to its next mode: text and a hexdump, and the picture for
    /// an image. Reads the raw bytes the first time they are needed, so a text
    /// file only pays for them on demand.
    pub fn viewer_next_mode(&mut self) {
        // Nothing to toggle on the refusal notice F4 puts up.
        if self.viewer().is_some_and(|state| state.from_edit) {
            return;
        }

        let mut error = None;

        if let Screen::Viewer(state) = &mut self.screen {
            let next = state.next_mode();
            if next == ViewMode::Hex && state.bytes.is_empty() && state.file_size > 0 {
                match std::fs::read(&state.file_path) {
                    Ok(bytes) => state.bytes = bytes,
                    Err(e) => error = Some(e.to_string()),
                }
            }

            if error.is_none() {
                // Text of a file that was never decoded - a binary or an image:
                // build it lossily rather than leave the pane blank.
                if next == ViewMode::Text && state.content_lines.is_empty() {
                    state.content_lines = String::from_utf8_lossy(&state.bytes).lines().map(str::to_string).collect();
                    if state.content_lines.is_empty() {
                        state.content_lines.push(String::new());
                    }
                    state.max_line_width = state.content_lines.iter().map(|line| crate::utils::line_display_width(line)).max().unwrap_or(0);
                }

                // Rows broken from the lines of one mode mean nothing in
                // another's; the next frame breaks them again if it wraps.
                state.unwrap_rows();
                state.mode = next;
                state.total_lines = state.line_count();
                // Positions in one mode's lines mean nothing in another's.
                state.selection = None;
                state.scroll_offset = state.scroll_offset.min(state.total_lines.saturating_sub(1));
                state.horizontal_offset = 0;
            }
        }

        if let Some(e) = error {
            self.display_error(e);
        }
    }

    /// Step to the next picture in the panel this one was opened from, or to
    /// the one before it. Anything that is not a picture is stepped over and
    /// the walk wraps round, so a folder of photographs can be gone through
    /// without leaving the viewer.
    pub fn viewer_step_image(&mut self, forward: bool) {
        let Some(showing) = self.viewer().map(|state| state.file_path.clone()) else {
            return;
        };
        let Some(going_to) = self.image_neighbour(&showing, forward) else {
            return;
        };

        // Carry across how it is being looked at, so a folder can be stepped
        // through at one zoom rather than starting over on every picture.
        let carried = self.viewer().map(|state| (state.image_fill, state.image_zoom));
        self.image_cache.forward = forward;
        self.request_open(going_to, false);
        if let Screen::Viewer(state) = &mut self.screen
            && let Some((fill, zoom)) = carried
        {
            state.image_fill = fill;
            state.image_zoom = zoom;
        }
    }

    /// The picture before or after `showing` in the panel it came from, wrapping
    /// round. Which files are pictures is settled by reading each header, not by
    /// the name: that is how the viewer decides everywhere else, and it costs a
    /// fraction of a millisecond a file.
    fn image_neighbour(&self, showing: &Path, forward: bool) -> Option<PathBuf> {
        let (children, dir) = if self.is_left_active { (&self.children_left, &self.dir_left) } else { (&self.children_right, &self.dir_right) };
        let files: Vec<PathBuf> = children.iter().filter(|item| !item.is_dir).map(|item| item.path_in(dir)).collect();
        let at = files.iter().position(|path| path == showing)?;

        let total = files.len();
        (1..=total)
            .find_map(|step| {
                let index = if forward { (at + step) % total } else { (at + total - step) % total };
                crate::viewer::image_cost(&files[index]).map(|_| index)
            })
            .map(|index| files[index].clone())
            .filter(|path| path != showing)
    }

    /// Start reading the picture on the far side of this one, in whichever
    /// direction the last step went. Nothing happens if F11 has it off, or if
    /// what is open is not a picture.
    fn read_ahead(&mut self) {
        if !self.options.image_prefetch || !self.viewer_shows_image() {
            return;
        }
        let Some(showing) = self.viewer().map(|state| state.file_path.clone()) else {
            return;
        };
        if let Some(next) = self.image_neighbour(&showing, self.image_cache.forward) {
            self.image_cache.request(next);
        }
    }

    /// True while the viewer is showing a picture, where dragging moves the
    /// picture rather than selecting the characters it is drawn from.
    pub fn viewer_shows_image(&self) -> bool {
        self.viewer().is_some_and(|state| state.mode == ViewMode::Image && !state.from_edit)
    }

    /// Take hold of a picture at the pointer, ready to drag it about.
    pub fn viewer_pan_start(&mut self, column: u16, row: u16) {
        let content = self.viewer_content_area;
        if let Screen::Viewer(state) = &mut self.screen
            && content.contains(Position::new(column, row))
        {
            state.pan_from = Some(((column, row), (state.horizontal_offset, state.scroll_offset)));
        }
    }

    /// Move the picture taken hold of above. It follows the pointer the way a
    /// sheet of paper follows a finger on it: moving right brings what was off
    /// to the left into view, so the offset goes the other way. Both offsets
    /// move at once, which is the whole point of doing this with the mouse.
    pub fn viewer_pan_to(&mut self, column: u16, row: u16) {
        let (width, height) = (self.viewer_viewport_width, self.viewer_viewport_height);
        if let Screen::Viewer(state) = &mut self.screen
            && let Some(((from_column, from_row), (from_horizontal, from_vertical))) = state.pan_from
        {
            let moved_x = i64::from(column) - i64::from(from_column);
            let moved_y = i64::from(row) - i64::from(from_row);
            let furthest_x = state.image_columns.saturating_sub(width) as i64;
            let furthest_y = state.total_lines.saturating_sub(height) as i64;
            state.horizontal_offset = (from_horizontal as i64 - moved_x).clamp(0, furthest_x) as usize;
            state.scroll_offset = (from_vertical as i64 - moved_y).clamp(0, furthest_y) as usize;
        }
    }

    pub fn viewer_scroll_right(&mut self) {
        if let Screen::Viewer(state) = &mut self.screen
            && !state.wrapping()
        {
            // Stop once the longest line's end reaches the right edge.
            let longest = match state.mode {
                ViewMode::Hex => crate::constants::HEX_LINE_WIDTH,
                ViewMode::Image => state.image_columns,
                ViewMode::Text => state.max_line_width,
            };
            let max = longest.saturating_sub(self.viewer_viewport_width);
            state.horizontal_offset = (state.horizontal_offset + 1).min(max);
        }
    }

    pub fn viewer_end(&mut self) {
        if let Screen::Viewer(state) = &mut self.screen {
            state.scroll_offset = state.total_lines.saturating_sub(self.viewer_viewport_height);
        }
    }

    pub fn open_editor(&mut self, file_path: PathBuf) -> Result<(), String> {
        use crate::viewer::{highlight_all, is_binary_file};

        let file_size = std::fs::metadata(&file_path).map_err(|e| e.to_string())?.len();
        // Taken before the file is read: a write between the two then makes
        // the save ask needlessly, rather than go over it without a word.
        let disk_stamp = DiskStamp::of(&file_path);

        if is_binary_file(&file_path).unwrap_or(false) {
            self.open_viewer(file_path)?;
            if let Screen::Viewer(state) = &mut self.screen {
                // Editing is refused outright; F3 is where a binary gets read.
                state.from_edit = true;
                state.mode = ViewMode::Text;
                state.bytes = Vec::new();
                state.image = None;
                state.image_lines = Vec::new();
                state.image_colors = Vec::new();
                state.content_lines = Vec::new();
                state.total_lines = 1;
            }
            return Ok(());
        }

        // The binary check reads only the head of the file, so a byte that is
        // not UTF-8 can still be waiting further in. Opened lossily, saving
        // would write a replacement character over every one of them, so the
        // file is refused - with a reason, rather than the decoder's own.
        let content = String::from_utf8(std::fs::read(&file_path).map_err(|e| e.to_string())?).map_err(|_| format!("Cannot edit {}: it is not UTF-8 text. F3 shows it as it is.", file_path.display()))?;
        let line_ending = detect_line_ending(&content);
        let mut lines: Vec<String> = content.lines().map(|s| s.to_string()).collect();
        if content.ends_with('\n') {
            lines.push(String::new());
        }
        if lines.is_empty() {
            lines.push(String::new());
        }
        let extension = file_path.extension().and_then(|e| e.to_str()).unwrap_or("");
        // The initial parse measures about 0.9s per megabyte, which is what the
        // limit in F11 caps; editing stays fast afterwards regardless of length.
        let limit = self.options.highlight_limit_bytes();
        let (highlighted_lines, line_states) = if limit > 0 && file_size <= limit {
            highlight_all(&lines, extension)
        } else {
            // Rendering already falls back to plain text when these are empty.
            (Vec::new(), Vec::new())
        };

        self.screen = Screen::Editor(EditorState {
            file_path,
            lines,
            highlighted_lines,
            cursor_line: 0,
            cursor_col: 0,
            scroll_offset: 0,
            horizontal_offset: 0,
            modified: false,
            auto_scroll: true,
            selection_anchor: None,
            line_ending,
            line_states,
            undo_stack: Vec::new(),
            redo_stack: Vec::new(),
            disk_stamp,
        });
        Ok(())
    }

    /// R on the changed-on-disk question: read the file again as it now is,
    /// dropping the edits, and keep the cursor on the line it was on, as far
    /// as the file still reaches.
    pub fn editor_reload(&mut self) -> Result<(), String> {
        let Some((path, line)) = self.editor().map(|state| (state.file_path.clone(), state.cursor_line)) else {
            return Ok(());
        };
        self.open_editor(path)?;
        if let Some(state) = self.editor_mut() {
            state.cursor_line = line.min(state.lines.len().saturating_sub(1));
        }
        Ok(())
    }

    pub fn close_editor(&mut self) {
        self.screen = Screen::Panels;
        self.close_find();
    }

    /// The prompt and the marks go with the file they were for. The term is
    /// kept, to be offered again.
    fn close_find(&mut self) {
        if matches!(self.dialog, Some(Dialog::Prompt(..))) {
            self.dialog = None;
        }
        self.find_shown = false;
        self.find_note = None;
    }

    /// Ask for something to find, or a line to go to. Find opens on the last
    /// term, so Enter alone looks for it again.
    pub fn open_prompt(&mut self, kind: PromptKind) {
        if !self.can_find() {
            return;
        }
        let mut input = TextInput::new();
        if kind == PromptKind::Find {
            input.set(self.find_term.clone());
        }
        self.dialog = Some(Dialog::Prompt(kind, input));
    }

    /// Only text can be searched or numbered: not a picture, and not the notice
    /// F4 raises on a binary file.
    fn can_find(&self) -> bool {
        match &self.screen {
            Screen::Editor(_) => true,
            Screen::Viewer(state) => !state.from_edit && state.mode != ViewMode::Image,
            Screen::Panels => false,
        }
    }

    /// Enter on the prompt: look for what was typed, or go to the line.
    pub fn confirm_prompt(&mut self) {
        let Some(Dialog::Prompt(kind, input)) = self.dialog.take() else {
            return;
        };
        match kind {
            PromptKind::Find => {
                if input.text.is_empty() {
                    // Nothing to look for, so nothing to mark either.
                    self.find_shown = false;
                    return;
                }
                self.find_term = input.text;
                self.find(true, true);
            }
            PromptKind::GoToLine => match input.text.trim().parse::<usize>() {
                Ok(number) => self.go_to_line(number),
                Err(_) if input.text.trim().is_empty() => {}
                Err(_) => self.find_note = Some(format!("Not a line number: {}", input.text.trim())),
            },
            PromptKind::Select | PromptKind::Deselect => {
                let Some(glob) = crate::glob::Glob::new(&input.text) else {
                    return;
                };
                self.select_pattern = input.text;
                self.select_by(&glob, kind == PromptKind::Select);
            }
            // What to replace, and then what with. Nothing to replace is a
            // cancel; nothing to replace it with deletes it.
            PromptKind::Replace => {
                if input.text.is_empty() {
                    return;
                }
                self.find_term = input.text;
                let mut with = TextInput::new();
                with.set(self.replace_with.clone());
                self.dialog = Some(Dialog::Prompt(PromptKind::ReplaceWith, with));
            }
            PromptKind::ReplaceWith => {
                self.replace_with = input.text;
                self.start_replace();
            }
        }
    }

    /// Ctrl+R or F4 in the editor: ask what to replace, offering the text
    /// selected when it is all on one line, or else what Ctrl+F last looked
    /// for.
    pub fn open_replace(&mut self) {
        let Some(state) = self.editor() else {
            return;
        };
        let offered = state.selected_text().filter(|text| !text.contains('\n')).unwrap_or_else(|| self.find_term.clone());
        let mut input = TextInput::new();
        input.set(offered);
        self.dialog = Some(Dialog::Prompt(PromptKind::Replace, input));
    }

    /// Go to the first match from the cursor and ask about it.
    fn start_replace(&mut self) {
        let Some(needle) = crate::find::Needle::new(&self.find_term) else {
            return;
        };
        let Some(state) = self.editor() else {
            return;
        };
        let stop_at = state.selection().map_or((state.cursor_line, state.cursor_col), |(start, _)| start);
        self.find_shown = true;
        match self.editor_find(&needle, true, true) {
            Some(wrapped) => self.dialog = Some(Dialog::Replacing { stop_at, wrapped, replaced: 0 }),
            None => self.find_note = Some(format!("Not found: {}", self.find_term)),
        }
    }

    /// Y or N on the match asked about: replace it, or leave it, and go on to
    /// the next - or, back where it started, stop. True while there is
    /// another to ask about.
    pub fn replace_step(&mut self, replace: bool) -> bool {
        let Some(Dialog::Replacing { mut stop_at, mut wrapped, mut replaced }) = self.dialog.take() else {
            return false;
        };
        let Some(needle) = crate::find::Needle::new(&self.find_term) else {
            return false;
        };
        if replace && let Some(((line, start), (_, end))) = self.editor().and_then(EditorState::selection) {
            let with = self.replace_with.clone();
            self.replace_selection(&with);
            replaced += 1;
            // Gone round and back on the line it started on, text before the
            // starting point moves the starting point along with it.
            if wrapped && line == stop_at.0 && start < stop_at.1 {
                stop_at.1 = (stop_at.1 + with.chars().count()).saturating_sub(end - start);
            }
        }
        // On from the cursor, which is past the match: never into the text
        // just put in, so replacing "a" with "aa" cannot go on for ever.
        let next = self.editor_find(&needle, true, false);
        let at = self.editor().and_then(EditorState::selection).map(|(start, _)| start);
        // Done once round the end and back to where it started - or round the
        // end a second time, which is how it gets there when the last match
        // before the start was replaced and none is left after it: a search
        // that went on would find the text it put in, and never end.
        let finished = |went_round: bool, at: (usize, usize)| (wrapped && went_round) || ((wrapped || went_round) && at >= stop_at);
        match (next, at) {
            (Some(went_round), Some(at)) if !finished(went_round, at) => {
                wrapped |= went_round;
                self.dialog = Some(Dialog::Replacing { stop_at, wrapped, replaced });
                true
            }
            _ => {
                self.finish_replace(replaced);
                false
            }
        }
    }

    /// A on the match asked about: replace it and every one after it, round
    /// to where it started, as a single step for Ctrl+Z to take back.
    pub fn replace_all(&mut self) {
        let Some(state) = self.editor_mut() else {
            return;
        };
        let before = state.lines.clone();
        let cursor = (state.cursor_line, state.cursor_col);
        // Each replacement records its own step; those are put aside, and
        // one for the lot recorded in their place.
        let history = std::mem::take(&mut state.undo_stack);
        // Highlighting is held off while it replaces - redone after each, a
        // line with three matches was parsed three times over, and 60,000
        // replacements took over a second - and done once at the end, over
        // the lines that changed.
        let line_states = std::mem::take(&mut state.line_states);
        while self.replace_step(true) {}
        if let Some(state) = self.editor_mut() {
            state.line_states = line_states;
            let changed = state.lines != before;
            if changed && !state.line_states.is_empty() {
                // A replacement holds no line break, so the lines stay where
                // they were; should they not have, it is the whole file.
                let differs = |index: &usize| state.lines.get(*index) != before.get(*index);
                let (first, last) = if state.lines.len() == before.len() {
                    let last_index = state.lines.len().saturating_sub(1);
                    ((0..state.lines.len()).find(differs).unwrap_or(0), (0..state.lines.len()).rev().find(differs).unwrap_or(last_index))
                } else {
                    (0, state.lines.len().saturating_sub(1))
                };
                let extension = state.file_path.extension().and_then(|e| e.to_str()).unwrap_or("").to_string();
                crate::viewer::highlight_through(&state.lines, &extension, first, last, &mut state.highlighted_lines, &mut state.line_states);
            }
            state.undo_stack = history;
            if changed {
                state.undo_stack.push(EditStep {
                    first_line: 0,
                    total_lines_before: before.len(),
                    before,
                    cursor,
                });
                if state.undo_stack.len() > crate::constants::UNDO_LIMIT {
                    state.undo_stack.remove(0);
                }
            }
        }
    }

    /// Esc on the match asked about, or no more to ask about: say how many
    /// were replaced.
    pub fn finish_replace(&mut self, replaced: usize) {
        if let Some(Dialog::Replacing { .. }) = self.dialog {
            self.dialog = None;
        }
        self.find_note = Some(match replaced {
            0 => "Nothing replaced".to_string(),
            1 => "Replaced 1".to_string(),
            many => format!("Replaced {many}"),
        });
    }

    /// Put `text` in place of the selection, as one step to undo. Typed or
    /// pasted text does this already; nothing at all, which deletes the
    /// selection, is the case they leave out.
    fn replace_selection(&mut self, text: &str) {
        if !text.is_empty() {
            self.editor_insert_text(text);
            return;
        }
        let line = self.editor().map_or(0, |state| state.cursor_line);
        self.push_undo(self.edit_range(line..=line));
        if let Some(from) = self.delete_selection() {
            self.editor_rehighlight_from(from);
        }
        self.finish_edit();
    }

    /// Alt+F7: ask what to look for, offering the last search again.
    pub fn open_find_files(&mut self) {
        let (mut name, mut containing) = (TextInput::new(), TextInput::new());
        name.set(self.find_files_last.0.clone());
        containing.set(self.find_files_last.1.clone());
        self.dialog = Some(Dialog::FindFiles(Box::new(FindFiles::Asking { name, containing, on_containing: false })));
    }

    /// Tab in the Find files form: the other field.
    pub fn find_files_switch_field(&mut self) {
        if let Some(Dialog::FindFiles(find)) = &mut self.dialog
            && let FindFiles::Asking { on_containing, .. } = find.as_mut()
        {
            *on_containing = !*on_containing;
        }
    }

    /// Enter on the Find files form: start the walk, down from the active
    /// panel's directory, on a thread of its own. An empty name looks at
    /// every file, and empty text asks for none.
    pub fn start_find_files(&mut self) {
        let Some(Dialog::FindFiles(find)) = &self.dialog else {
            return;
        };
        let FindFiles::Asking { name, containing, .. } = find.as_ref() else {
            return;
        };
        let (name, containing) = (name.text.clone(), containing.text.clone());
        self.find_files_last = (name.clone(), containing.clone());

        let pattern = if name.trim().is_empty() { "*" } else { name.as_str() };
        let label = match containing.is_empty() {
            true => pattern.to_string(),
            false => format!("{pattern} containing \"{containing}\""),
        };
        let start = self.panel_dir(self.is_left_active);
        let query = crate::search::Query {
            start: start.clone(),
            name: crate::glob::Glob::new(pattern).unwrap_or_else(|| crate::glob::Glob::new("*").expect("* is a pattern")),
            containing: crate::find::Needle::new(&containing),
            show_hidden: self.options.show_hidden,
            case_sensitive: self.options.case_sensitive,
        };
        let cancel = Arc::new(AtomicBool::new(false));
        let (sender, updates) = mpsc::channel();
        let worker_cancel = Arc::clone(&cancel);
        std::thread::spawn(move || {
            crate::search::search(&query, &worker_cancel, &mut |update| sender.send(update).is_ok());
        });
        self.dialog = Some(Dialog::FindFiles(Box::new(FindFiles::Found(Search {
            looking_in: Some(start.clone()),
            start,
            label,
            results: Vec::new(),
            cursor: 0,
            scroll: 0,
            done: false,
            unreadable: 0,
            cancel,
            updates,
        }))));
    }

    /// Take in what the Find files walk has sent since the last frame.
    pub fn poll_find_files(&mut self) {
        let Some(Dialog::FindFiles(find)) = &mut self.dialog else {
            return;
        };
        let FindFiles::Found(search) = find.as_mut() else {
            return;
        };
        loop {
            match search.updates.try_recv() {
                Ok(crate::search::Update::Looking(dir)) => search.looking_in = Some(dir),
                Ok(crate::search::Update::Found(path, is_dir)) => search.results.push((path, is_dir)),
                Ok(crate::search::Update::Finished { unreadable }) => {
                    search.unreadable = unreadable;
                    search.looking_in = None;
                    search.done = true;
                }
                Err(TryRecvError::Empty) => break,
                // Gone without a word, which only happens if it panicked.
                Err(TryRecvError::Disconnected) => {
                    search.looking_in = None;
                    search.done = true;
                    break;
                }
            }
        }
    }

    /// Move the Find files cursor `by` results, stopping at either end, and
    /// scroll the list only as far as it takes to keep it showing.
    pub fn find_files_move(&mut self, by: isize) {
        let page = self.find_files_page.max(1);
        if let Some(Dialog::FindFiles(find)) = &mut self.dialog
            && let FindFiles::Found(search) = find.as_mut()
        {
            let last = search.results.len().saturating_sub(1);
            search.cursor = search.cursor.saturating_add_signed(by).min(last);
            if search.cursor < search.scroll {
                search.scroll = search.cursor;
            } else if search.cursor >= search.scroll + page {
                search.scroll = search.cursor + 1 - page;
            }
        }
    }

    /// Enter on a result: the active panel goes to the directory it is in,
    /// with the cursor on it, and the search is put away.
    pub fn find_files_go(&mut self) {
        let Some(Dialog::FindFiles(find)) = &self.dialog else {
            return;
        };
        let FindFiles::Found(search) = find.as_ref() else {
            return;
        };
        let Some((path, _)) = search.results.get(search.cursor) else {
            return;
        };
        let (Some(dir), Some(name)) = (path.parent().map(Path::to_path_buf), path.file_name().map(OsString::from)) else {
            return;
        };
        self.dialog = None;
        self.open_dir(self.is_left_active, dir, Some(&name));
    }

    /// + and - in a panel: ask for a pattern, starting from the last one.
    pub fn open_select_prompt(&mut self, select: bool) {
        let mut input = TextInput::new();
        input.set(self.select_pattern.clone());
        self.dialog = Some(Dialog::Prompt(if select { PromptKind::Select } else { PromptKind::Deselect }, input));
    }

    /// Select, or deselect, every entry in the active panel the pattern
    /// matches. No directory is sized: a pattern can take dozens at once, and
    /// Space is there for the one that is wanted.
    pub fn select_by(&mut self, glob: &crate::glob::Glob, select: bool) {
        let (children, selected) = if self.is_left_active {
            (&self.children_left, &mut self.selected_left)
        } else {
            (&self.children_right, &mut self.selected_right)
        };
        for item in children.iter().filter(|item| item.name != ".." && glob.matches(&item.name_full, item.is_dir)) {
            if select {
                selected.insert(item.name_os.clone());
            } else {
                selected.remove(&item.name_os);
            }
        }
    }

    /// The * key in a panel: every file selected is deselected and every other
    /// one selected. Directories stay as they are, as + leaves them unless
    /// asked: inverting a few picked files should not sweep every tree beside
    /// them into the next delete. Alt+* asks, and inverts them too.
    pub fn invert_selection(&mut self, with_dirs: bool) {
        let (children, selected) = if self.is_left_active {
            (&self.children_left, &mut self.selected_left)
        } else {
            (&self.children_right, &mut self.selected_right)
        };
        for item in children.iter().filter(|item| (with_dirs || !item.is_dir) && item.name != "..") {
            if !selected.remove(&item.name_os) {
                selected.insert(item.name_os.clone());
            }
        }
    }

    /// Move to the next match of find_term, or the previous one, selecting it.
    /// `fresh` is a new search from the prompt, which may find the match the
    /// cursor is already on; F3 and Shift+F3 go on past it.
    pub fn find(&mut self, forward: bool, fresh: bool) {
        let Some(needle) = crate::find::Needle::new(&self.find_term) else {
            // F3 with nothing looked for yet asks what to look for.
            self.open_prompt(PromptKind::Find);
            return;
        };
        if !self.can_find() {
            return;
        }
        self.find_shown = true;

        let found = if self.is_editing() { self.editor_find(&needle, forward, fresh) } else { self.viewer_find(&needle, forward, fresh) };
        self.find_note = match found {
            None => Some(format!("Not found: {}", self.find_term)),
            Some(true) => Some(if forward { "Wrapped to the top" } else { "Wrapped to the bottom" }.to_string()),
            Some(false) => None,
        };
    }

    /// Some(wrapped) when a match was found and selected.
    fn editor_find(&mut self, needle: &crate::find::Needle, forward: bool, fresh: bool) -> Option<bool> {
        let height = self.editor_viewport_height.max(1);
        let state = self.editor_mut()?;
        let cursor = (state.cursor_line, state.cursor_col);
        let start = state.selection().map_or(cursor, |(start, _)| start);
        // A match is selected from its start to the cursor at its end, so on
        // from the cursor is past it and back from its start is before it.
        let from = if forward && !fresh { cursor } else { start };

        let lines = &state.lines;
        let found = crate::find::search(needle, lines.len(), |index| lines[index].clone(), from, forward)?;
        state.selection_anchor = Some((found.line, found.start));
        state.cursor_line = found.line;
        state.cursor_col = found.end;
        state.auto_scroll = true;
        if found.line < state.scroll_offset || found.line >= state.scroll_offset + height {
            state.scroll_offset = found.line.saturating_sub(height / 3);
        }
        Some(found.wrapped)
    }

    fn viewer_find(&mut self, needle: &crate::find::Needle, forward: bool, fresh: bool) -> Option<bool> {
        let (height, width) = (self.viewer_viewport_height.max(1), self.viewer_viewport_width.max(1));
        let state = self.viewer_mut()?;
        // From the match on screen when there is one, and otherwise from the
        // top of what is showing.
        let from = match state.selected_range() {
            Some((_, end)) if forward && !fresh => end,
            Some((start, _)) => start,
            None => {
                let (line, from, _) = state.row(state.scroll_offset);
                (line, from)
            }
        };

        let found = crate::find::search(needle, state.line_count(), |index| state.line_text(index), from, forward)?;
        state.selection = Some(((found.line, found.start), (found.line, found.end)));
        // Scrolled by rows, which are the lines themselves unless wrapping.
        let row = state.row_of(found.line, found.start);
        if row < state.scroll_offset || row >= state.scroll_offset + height {
            let max = state.total_lines.saturating_sub(height);
            state.scroll_offset = row.saturating_sub(height / 3).min(max);
        }
        if !state.wrapping() && (found.start < state.horizontal_offset || found.end > state.horizontal_offset + width) {
            state.horizontal_offset = found.start.saturating_sub(width / 4);
        }
        Some(found.wrapped)
    }

    /// Ctrl+G: put the cursor on the start of a line, counted from 1. A number
    /// past the end goes to the last line. In the viewer the line goes to the
    /// top, as far as the end of the file allows.
    pub fn go_to_line(&mut self, number: usize) {
        if self.is_editing() {
            let height = self.editor_viewport_height.max(1);
            if let Screen::Editor(state) = &mut self.screen {
                let line = number.clamp(1, state.lines.len().max(1)) - 1;
                state.selection_anchor = None;
                state.cursor_line = line;
                state.cursor_col = 0;
                state.auto_scroll = true;
                if line < state.scroll_offset || line >= state.scroll_offset + height {
                    state.scroll_offset = line.saturating_sub(height / 3);
                }
            }
        } else if let Screen::Viewer(state) = &mut self.screen {
            let line = number.clamp(1, state.line_count().max(1)) - 1;
            state.scroll_offset = state.row_of(line, 0).min(state.total_lines.saturating_sub(self.viewer_viewport_height));
        }
    }

    /// Re-highlight the file from `from` downward. Cheap: the cached state lets
    /// it resume mid-file and stop again as soon as the parse converges.
    pub fn editor_rehighlight_from(&mut self, from: usize) {
        if let Screen::Editor(state) = &mut self.screen {
            if state.line_states.is_empty() {
                return; // highlighting disabled for this file
            }
            let extension = state.file_path.extension().and_then(|e| e.to_str()).unwrap_or("");
            crate::viewer::highlight_from(&state.lines, extension, from, &mut state.highlighted_lines, &mut state.line_states);
        }
    }

    pub fn editor_scroll_up(&mut self) {
        if let Screen::Editor(state) = &mut self.screen
            && state.scroll_offset > 0
        {
            state.scroll_offset -= 1;
            state.auto_scroll = false;
        }
    }

    pub fn editor_scroll_down(&mut self) {
        if let Screen::Editor(state) = &mut self.screen {
            let max = state.lines.len().saturating_sub(self.editor_viewport_height);
            if state.scroll_offset < max {
                state.scroll_offset += 1;
                state.auto_scroll = false;
            }
        }
    }

    pub fn editor_scroll_left(&mut self) {
        if let Screen::Editor(state) = &mut self.screen {
            state.horizontal_offset = state.horizontal_offset.saturating_sub(1);
            state.auto_scroll = false;
        }
    }

    pub fn editor_scroll_right(&mut self) {
        if let Screen::Editor(state) = &mut self.screen {
            state.horizontal_offset += 1;
            state.auto_scroll = false;
        }
    }

    /// Remember the lines `range` covers before they are replaced. Called once
    /// per user action, with a range spanning everything that action touches.
    fn push_undo(&mut self, range: std::ops::RangeInclusive<usize>) {
        if let Screen::Editor(state) = &mut self.screen {
            let last = (*range.end()).min(state.lines.len().saturating_sub(1));
            let first = (*range.start()).min(last);

            state.undo_stack.push(EditStep {
                first_line: first,
                before: state.lines[first..=last].to_vec(),
                total_lines_before: state.lines.len(),
                cursor: (state.cursor_line, state.cursor_col),
            });
        }
    }

    /// Settle the step push_undo recorded, once the action has run. One that
    /// changed nothing - Backspace at the very start, Delete at the very end,
    /// Ctrl+X with nothing selected - is dropped, so it neither costs an undo
    /// that does nothing nor throws away the redo history. One that did change
    /// something forks the history: editing after undoing loses the old branch.
    fn finish_edit(&mut self) {
        if let Screen::Editor(state) = &mut self.screen {
            let Some(step) = state.undo_stack.last() else {
                return;
            };
            let unchanged = state.lines.len() == step.total_lines_before && state.lines[step.first_line..step.first_line + step.before.len()] == step.before[..];
            if unchanged {
                state.undo_stack.pop();
                return;
            }
            state.redo_stack.clear();
            if state.undo_stack.len() > crate::constants::UNDO_LIMIT {
                state.undo_stack.remove(0);
            }
        }
    }

    /// The range a user action is about to touch: the selection when there is
    /// one, otherwise the given fallback.
    fn edit_range(&self, fallback: std::ops::RangeInclusive<usize>) -> std::ops::RangeInclusive<usize> {
        match self.editor().and_then(|state| state.selection()) {
            Some(((first, _), (last, _))) => first..=last,
            None => fallback,
        }
    }

    pub fn editor_undo(&mut self) {
        self.step_history(true);
    }

    pub fn editor_redo(&mut self) {
        self.step_history(false);
    }

    /// Move one step through the edit history. Undo and redo are the same
    /// operation in opposite directions: apply a step, and push the step that
    /// would put things back onto the other stack.
    fn step_history(&mut self, undoing: bool) {
        let mut from = None;

        if let Screen::Editor(state) = &mut self.screen {
            let stack = if undoing { &mut state.undo_stack } else { &mut state.redo_stack };
            if let Some(step) = stack.pop() {
                // However many lines replaced the originals, the buffer's change
                // in length tells us how many to take back out.
                let removed = step.total_lines_before - step.before.len();
                let replaced = state.lines.len().saturating_sub(removed);
                let end = (step.first_line + replaced).min(state.lines.len());

                let inverse = EditStep {
                    first_line: step.first_line,
                    before: state.lines[step.first_line..end].to_vec(),
                    total_lines_before: state.lines.len(),
                    cursor: (state.cursor_line, state.cursor_col),
                };

                state.lines.splice(step.first_line..end, step.before);
                state.cursor_line = step.cursor.0.min(state.lines.len().saturating_sub(1));
                state.cursor_col = step.cursor.1.min(state.lines[state.cursor_line].chars().count());
                state.selection_anchor = None;
                state.modified = true;

                if state.cursor_line < state.scroll_offset {
                    state.scroll_offset = state.cursor_line;
                }

                let other = if undoing { &mut state.redo_stack } else { &mut state.undo_stack };
                other.push(inverse);
                if other.len() > crate::constants::UNDO_LIMIT {
                    other.remove(0);
                }

                from = Some(step.first_line);
            }
        }

        if let Some(from) = from {
            self.editor_rehighlight_from(from);
        }
    }

    /// Remove the selected range, leaving the cursor where the selection began.
    /// Returns the line to re-highlight from, or None if nothing was selected.
    /// Shared by cut, paste, typing, Backspace and Delete.
    fn delete_selection(&mut self) -> Option<usize> {
        let state = self.editor_mut()?;
        let ((first_line, first_col), (last_line, last_col)) = state.selection()?;

        let head = char_slice(&state.lines[first_line], 0, first_col);
        let last = &state.lines[last_line];
        let tail = char_slice(last, last_col, last.chars().count());

        state.lines.splice(first_line..=last_line, [format!("{head}{tail}")]);
        state.cursor_line = first_line;
        state.cursor_col = first_col;
        state.selection_anchor = None;
        state.modified = true;
        Some(first_line)
    }

    pub fn editor_select_all(&mut self) {
        let height = self.editor_viewport_height;
        if let Screen::Editor(state) = &mut self.screen {
            let last_line = state.lines.len().saturating_sub(1);
            state.selection_anchor = Some((0, 0));
            state.cursor_line = last_line;
            state.cursor_col = state.lines[last_line].chars().count();
            state.scroll_offset = last_line.saturating_sub(height.saturating_sub(1));
        }
    }

    pub fn editor_copy(&mut self) {
        if let Some(text) = self.editor().and_then(|state| state.selected_text()) {
            // Offer it to the terminal as well, so it reaches the system
            // clipboard where OSC 52 is supported.
            crate::utils::set_system_clipboard(&text);
            self.clipboard = text;
        }
    }

    pub fn editor_cut(&mut self) {
        let line = self.editor().map_or(0, |state| state.cursor_line);
        self.push_undo(self.edit_range(line..=line));
        self.editor_copy();
        if let Some(from) = self.delete_selection() {
            self.editor_rehighlight_from(from);
        }
        self.finish_edit();
    }

    pub fn editor_paste(&mut self) {
        let text = self.clipboard.clone();
        self.editor_insert_text(&text);
    }

    /// Insert text at the cursor, replacing any selection. Serves both the
    /// internal clipboard and a bracketed paste arriving from the terminal.
    pub fn editor_insert_text(&mut self, text: &str) {
        if text.is_empty() {
            return;
        }
        let line = self.editor().map_or(0, |state| state.cursor_line);
        self.push_undo(self.edit_range(line..=line));

        // A pasted Windows clipboard arrives with CRLF; the buffer holds lines.
        let text = text.replace("\r\n", "\n");

        // A selection is replaced by what is pasted over it.
        let mut rehighlight = self.delete_selection();

        if let Screen::Editor(state) = &mut self.screen {
            let line = state.lines[state.cursor_line].clone();
            let head = char_slice(&line, 0, state.cursor_col);
            let tail = char_slice(&line, state.cursor_col, line.chars().count());
            let pieces: Vec<&str> = text.split('\n').collect();
            let start_line = state.cursor_line;

            if let [only] = pieces[..] {
                state.lines[start_line] = format!("{head}{only}{tail}");
                state.cursor_col += only.chars().count();
            } else {
                let last = pieces.len() - 1;
                let mut replacement = Vec::with_capacity(pieces.len());
                replacement.push(format!("{head}{}", pieces[0]));
                replacement.extend(pieces[1..last].iter().map(|piece| (*piece).to_string()));
                replacement.push(format!("{}{tail}", pieces[last]));

                state.lines.splice(start_line..=start_line, replacement);
                state.cursor_line = start_line + last;
                state.cursor_col = pieces[last].chars().count();
            }

            state.modified = true;
            state.selection_anchor = None;
            rehighlight = Some(rehighlight.unwrap_or(start_line).min(start_line));
        }

        if let Some(from) = rehighlight {
            self.editor_rehighlight_from(from);
        }
        self.finish_edit();
    }

    /// Called before a cursor move: Shift extends the selection from where the
    /// cursor was, anything else drops it.
    pub fn editor_prepare_move(&mut self, extend: bool) {
        if let Screen::Editor(state) = &mut self.screen {
            if extend {
                if state.selection_anchor.is_none() {
                    state.selection_anchor = Some((state.cursor_line, state.cursor_col));
                }
            } else {
                state.selection_anchor = None;
            }
        }
    }

    pub fn editor_cursor_up(&mut self) {
        if let Screen::Editor(state) = &mut self.screen
            && state.cursor_line > 0
        {
            state.cursor_line -= 1;
            state.clamp_col();
            if state.cursor_line < state.scroll_offset {
                state.scroll_offset = state.cursor_line;
            }
        }
    }

    pub fn editor_cursor_down(&mut self) {
        if let Screen::Editor(state) = &mut self.screen
            && state.cursor_line < state.lines.len().saturating_sub(1)
        {
            state.cursor_line += 1;
            state.clamp_col();
            if state.cursor_line >= state.scroll_offset + self.editor_viewport_height {
                state.scroll_offset = state.cursor_line - self.editor_viewport_height + 1;
            }
        }
    }

    pub fn editor_cursor_left(&mut self) {
        if let Screen::Editor(state) = &mut self.screen {
            if state.cursor_col > 0 {
                state.cursor_col -= 1;
            } else if state.cursor_line > 0 {
                state.cursor_line -= 1;
                state.cursor_col = state.lines[state.cursor_line].chars().count();
                if state.cursor_line < state.scroll_offset {
                    state.scroll_offset = state.cursor_line;
                }
            }
        }
    }

    pub fn editor_cursor_right(&mut self) {
        if let Screen::Editor(state) = &mut self.screen {
            let line_len = state.lines[state.cursor_line].chars().count();
            if state.cursor_col < line_len {
                state.cursor_col += 1;
            } else if state.cursor_line < state.lines.len().saturating_sub(1) {
                state.cursor_line += 1;
                state.cursor_col = 0;
                if state.cursor_line >= state.scroll_offset + self.editor_viewport_height {
                    state.scroll_offset = state.cursor_line - self.editor_viewport_height + 1;
                }
            }
        }
    }

    pub fn editor_home(&mut self) {
        if let Screen::Editor(state) = &mut self.screen {
            state.cursor_col = 0;
        }
    }

    pub fn editor_end(&mut self) {
        if let Screen::Editor(state) = &mut self.screen {
            state.cursor_col = state.lines[state.cursor_line].chars().count();
        }
    }

    pub fn editor_page_up(&mut self) {
        if let Screen::Editor(state) = &mut self.screen {
            let page = self.editor_viewport_height.saturating_sub(1);
            state.cursor_line = state.cursor_line.saturating_sub(page);
            state.scroll_offset = state.scroll_offset.saturating_sub(page);
            state.clamp_col();
        }
    }

    pub fn editor_page_down(&mut self) {
        if let Screen::Editor(state) = &mut self.screen {
            let page = self.editor_viewport_height.saturating_sub(1);
            let max_line = state.lines.len().saturating_sub(1);
            state.cursor_line = (state.cursor_line + page).min(max_line);
            let max_scroll = state.lines.len().saturating_sub(self.editor_viewport_height);
            state.scroll_offset = (state.scroll_offset + page).min(max_scroll);
            state.clamp_col();
        }
    }

    pub fn editor_insert_char(&mut self, c: char) {
        let line = self.editor().map_or(0, |state| state.cursor_line);
        self.push_undo(self.edit_range(line..=line));
        // Typing over a selection replaces it.
        self.delete_selection();
        let mut from = None;
        if let Screen::Editor(state) = &mut self.screen {
            let line = &mut state.lines[state.cursor_line];
            let byte_idx = char_to_byte(line, state.cursor_col);
            line.insert(byte_idx, c);
            state.cursor_col += 1;
            state.modified = true;
            from = Some(state.cursor_line);
        }
        if let Some(from) = from {
            self.editor_rehighlight_from(from);
        }
        self.finish_edit();
    }

    pub fn editor_backspace(&mut self) {
        let fallback = match self.editor() {
            // Joining with the line above puts that line in range too.
            Some(state) if state.cursor_col == 0 => state.cursor_line.saturating_sub(1)..=state.cursor_line,
            Some(state) => state.cursor_line..=state.cursor_line,
            None => return,
        };
        self.push_undo(self.edit_range(fallback));

        // With a selection, Backspace removes that rather than a character.
        if let Some(from) = self.delete_selection() {
            self.editor_rehighlight_from(from);
            self.finish_edit();
            return;
        }
        let mut from = None;
        if let Screen::Editor(state) = &mut self.screen {
            if state.cursor_col > 0 {
                let line = &mut state.lines[state.cursor_line];
                let byte_start = char_to_byte(line, state.cursor_col - 1);
                let byte_end = char_to_byte(line, state.cursor_col);
                line.replace_range(byte_start..byte_end, "");
                state.cursor_col -= 1;
                state.modified = true;
                from = Some(state.cursor_line);
            } else if state.cursor_line > 0 {
                let current_line = state.lines.remove(state.cursor_line);
                state.cursor_line -= 1;
                state.cursor_col = state.lines[state.cursor_line].chars().count();
                state.lines[state.cursor_line].push_str(&current_line);
                state.modified = true;
                from = Some(state.cursor_line);
                if state.cursor_line < state.scroll_offset {
                    state.scroll_offset = state.cursor_line;
                }
            }
        }
        if let Some(from) = from {
            self.editor_rehighlight_from(from);
        }
        self.finish_edit();
    }

    pub fn editor_delete(&mut self) {
        let fallback = match self.editor() {
            // At end of line the next line is pulled up, so include it.
            Some(state) if state.cursor_col >= state.lines[state.cursor_line].chars().count() => state.cursor_line..=state.cursor_line + 1,
            Some(state) => state.cursor_line..=state.cursor_line,
            None => return,
        };
        self.push_undo(self.edit_range(fallback));

        if let Some(from) = self.delete_selection() {
            self.editor_rehighlight_from(from);
            self.finish_edit();
            return;
        }
        let mut from = None;
        if let Screen::Editor(state) = &mut self.screen {
            let line_len = state.lines[state.cursor_line].chars().count();
            if state.cursor_col < line_len {
                let line = &mut state.lines[state.cursor_line];
                let byte_start = char_to_byte(line, state.cursor_col);
                let byte_end = char_to_byte(line, state.cursor_col + 1);
                line.replace_range(byte_start..byte_end, "");
                state.modified = true;
                from = Some(state.cursor_line);
            } else if state.cursor_line < state.lines.len().saturating_sub(1) {
                let next_line = state.lines.remove(state.cursor_line + 1);
                state.lines[state.cursor_line].push_str(&next_line);
                state.modified = true;
                from = Some(state.cursor_line);
            }
        }
        if let Some(from) = from {
            self.editor_rehighlight_from(from);
        }
        self.finish_edit();
    }

    pub fn editor_enter(&mut self) {
        let line = self.editor().map_or(0, |state| state.cursor_line);
        self.push_undo(self.edit_range(line..=line));
        self.delete_selection();
        let mut from = None;
        if let Screen::Editor(state) = &mut self.screen {
            from = Some(state.cursor_line);
            let line = &mut state.lines[state.cursor_line];
            let byte_idx = char_to_byte(line, state.cursor_col);
            let new_line = line[byte_idx..].to_string();
            line.truncate(byte_idx);
            state.cursor_line += 1;
            state.lines.insert(state.cursor_line, new_line);
            state.cursor_col = 0;
            state.modified = true;
            if state.cursor_line >= state.scroll_offset + self.editor_viewport_height {
                state.scroll_offset = state.cursor_line - self.editor_viewport_height + 1;
            }
        }
        if let Some(from) = from {
            self.editor_rehighlight_from(from);
        }
        self.finish_edit();
    }

    /// Save the file in the editor - unless something else has written it
    /// since it was read here, when nothing is written and the caller asks
    /// first. A file gone altogether counts: saving would bring back what
    /// someone meant to delete.
    pub fn editor_save(&mut self) -> Result<Saved, String> {
        if let Some(state) = self.editor() {
            let now = DiskStamp::of(&state.file_path);
            if now != state.disk_stamp {
                return Ok(Saved::ChangedOnDisk { opened: state.disk_stamp, now });
            }
        }
        self.editor_save_over()?;
        Ok(Saved::Done)
    }

    /// Save the file in the editor, whatever is on disk.
    pub fn editor_save_over(&mut self) -> Result<(), String> {
        if let Screen::Editor(state) = &mut self.screen {
            let content = state.lines.join(state.line_ending);
            crate::fs_ops::save_file(&state.file_path, content.as_bytes()).map_err(|e| e.to_string())?;
            state.modified = false;
            // What is there now is this, and the next save should not take
            // it for somebody else's.
            state.disk_stamp = DiskStamp::of(&state.file_path);
            // A save written in place leaves its directory's mtime alone - only
            // adding, removing or renaming entries moves that - so the refresh
            // that watches it never notices, and the panels would go on showing
            // the size from before the edit. Either of them may be showing the
            // file, and a link to it may be in a directory neither is watching.
            self.reload_panel(true, None);
            self.reload_panel(false, None);
        }
        Ok(())
    }

    pub fn editor_is_modified(&self) -> bool {
        self.editor().is_some_and(|s| s.modified)
    }

    pub fn toggle_selection(&mut self) {
        self.toggle_selection_inner(true);
    }

    pub fn toggle_selection_no_size(&mut self) {
        self.toggle_selection_inner(false);
    }

    fn toggle_selection_inner(&mut self, calculate_size: bool) {
        let mut to_size: Option<PathBuf> = None;

        {
            let (state, children, selected_set, current_dir) = if self.is_left_active {
                (&mut self.state_left, &self.children_left, &mut self.selected_left, &self.dir_left)
            } else {
                (&mut self.state_right, &self.children_right, &mut self.selected_right, &self.dir_right)
            };

            if let Some(index) = state.selected() {
                if index < children.len() && children[index].name != ".." {
                    let item = &children[index];

                    if !selected_set.remove(&item.name_os) {
                        selected_set.insert(item.name_os.clone());

                        if calculate_size && item.is_dir {
                            to_size = Some(item.path_in(current_dir));
                        }
                    }
                }

                // Move to next item
                let len = children.len();
                if len > 0 {
                    state.select(Some((index + 1).min(len - 1)));
                }
            }
        }

        if let Some(path) = to_size {
            self.start_dir_size(path);
        }
    }

    /// Work out a directory's size on a thread of its own, unless that is
    /// already under way.
    pub fn start_dir_size(&mut self, path: PathBuf) {
        if self.dir_sizing.iter().any(|sizing| sizing.path == path) {
            return;
        }
        let cancel = Arc::new(AtomicBool::new(false));
        let (sender, updates) = mpsc::channel();
        let (worker_path, worker_cancel) = (path.clone(), Arc::clone(&cancel));
        std::thread::spawn(move || {
            let (mut found, mut reported) = (0, Instant::now());
            let result = crate::fs_ops::walk_dir_size(&worker_path, &worker_cancel, &mut |bytes| {
                found += bytes;
                if reported.elapsed() >= crate::constants::SIZE_PROGRESS_INTERVAL {
                    reported = Instant::now();
                    let _ = sender.send(SizeUpdate::Found(found));
                }
            });
            let _ = sender.send(SizeUpdate::Finished(result.map_err(|e| e.to_string())));
        });
        self.dir_sizing.push(DirSizing { path, found: 0, cancel, updates });
    }

    /// Take what the sizing threads have sent since the last frame, keeping
    /// each size that is finished.
    pub fn poll_dir_sizes(&mut self) {
        let mut finished = Vec::new();
        self.dir_sizing.retain_mut(|sizing| {
            loop {
                match sizing.updates.try_recv() {
                    Ok(SizeUpdate::Found(found)) => sizing.found = found,
                    Ok(SizeUpdate::Finished(result)) => {
                        finished.push((sizing.path.clone(), result));
                        break false;
                    }
                    Err(TryRecvError::Empty) => break true,
                    // Gone without a word, which only happens if it panicked.
                    Err(TryRecvError::Disconnected) => break false,
                }
            }
        });

        for (path, result) in finished {
            match result {
                Ok(Some(size)) => {
                    self.dir_sizes.insert(path, size);
                }
                Ok(None) => {}
                Err(e) => self.display_error(format!("Cannot calculate size: {}", e)),
            }
        }
    }

    /// Stop every size still being worked out. Each thread notices between
    /// entries; one stuck in a read on a dead mount is simply forgotten, and
    /// whatever it finds is never asked for.
    pub fn cancel_dir_sizes(&mut self) {
        for sizing in self.dir_sizing.drain(..) {
            sizing.cancel.store(true, Ordering::Relaxed);
        }
    }

    /// The running total for a directory still being sized.
    pub fn dir_size_so_far(&self, path: &Path) -> Option<u64> {
        self.dir_sizing.iter().find(|sizing| sizing.path == path).map(|sizing| sizing.found)
    }

    /// True while a popup is covering the screen. What is behind one must sit
    /// still: it cannot be seen, and the popup is answering for it.
    pub fn popup_is_open(&self) -> bool {
        self.error.is_some() || self.job.is_some() || self.dialog.as_ref().is_some_and(Dialog::is_popup)
    }

    /// True while a dialog, viewer or editor owns the screen. Added to the
    /// popups: the viewer and the editor, whole-screen modes that take their
    /// own mouse input, and the rename field, which sits in the panel, where a
    /// click cancels it rather than being swallowed.
    pub fn is_modal_open(&self) -> bool {
        self.popup_is_open() || !matches!(self.screen, Screen::Panels) || matches!(self.dialog, Some(Dialog::Rename(_)))
    }

    /// Hand a long job to a worker thread and start following it.
    fn start_job<F>(&mut self, kind: TransferKind, clashes: Clashes, work: F)
    where
        F: FnOnce(JobProgress<'_>) + Send + 'static,
    {
        let cancel = Arc::new(AtomicBool::new(false));
        let (sender, updates) = mpsc::channel();
        let (answers, worker_answers) = mpsc::channel();
        let worker_cancel = Arc::clone(&cancel);
        std::thread::spawn(move || work(JobProgress::new(&sender, &worker_cancel, &worker_answers, clashes)));

        self.job = Some(TransferJob {
            kind,
            total: None,
            done: 0,
            current: PathBuf::new(),
            started: Instant::now(),
            cancel,
            updates,
            problem: None,
            clash: None,
            answers,
            skipped: 0,
        });
    }

    /// `clashes` says what happens to a file already where one is going:
    /// asked about, written over, or left. A directory onto a directory is
    /// merged whichever it is.
    pub fn start_transfer(&mut self, items: Vec<(PathBuf, PathBuf, bool)>, is_copy: bool, clashes: Clashes) {
        let kind = if is_copy { TransferKind::Copy } else { TransferKind::Move };
        self.start_job(kind, clashes, move |progress| run_transfer(items, is_copy, progress));
    }

    pub fn start_delete(&mut self, items: Vec<(PathBuf, bool)>) {
        self.start_job(TransferKind::Delete, Clashes::Ask, move |progress| run_delete(items, progress));
    }

    pub fn start_trash(&mut self, items: Vec<(PathBuf, bool)>) {
        self.start_job(TransferKind::Trash, Clashes::Ask, move |progress| run_trash(items, progress));
    }

    /// Ask a running transfer to stop. It ends at the next chunk or file, so
    /// the job stays up for a moment afterwards rather than vanishing at once.
    /// One waiting on a question is answered Abort, which is the same thing.
    pub fn cancel_transfer(&mut self) {
        if let Some(job) = &mut self.job {
            job.cancel.store(true, Ordering::Relaxed);
            job.answer(Answer::Abort);
        }
    }

    /// Take whatever the worker has sent since the last frame. Called once per
    /// frame, so the bar advances at the rate the loop already runs at.
    pub fn poll_transfer(&mut self) {
        let Some(job) = &mut self.job else {
            return;
        };

        let mut finished = None;
        loop {
            match job.updates.try_recv() {
                Ok(JobUpdate::Total(amount)) => job.total = Some(amount),
                Ok(JobUpdate::Starting(path)) => job.current = path,
                Ok(JobUpdate::Advanced(amount)) => job.done += amount,
                Ok(JobUpdate::Problem(problem)) => job.problem = Some(problem),
                Ok(JobUpdate::Clash(clash)) => job.clash = Some(clash),
                Ok(JobUpdate::Skipped) => job.skipped += 1,
                Ok(JobUpdate::Finished(result)) => {
                    finished = Some(result);
                    break;
                }
                Err(TryRecvError::Empty) => break,
                // Gone without a word, which only happens if it panicked.
                Err(TryRecvError::Disconnected) => {
                    finished = Some(Err("Transfer stopped unexpectedly".to_string()));
                    break;
                }
            }
        }

        let Some(result) = finished else {
            return;
        };
        let job = self.job.take().expect("checked at the top");

        // Both panels: a move empties one and fills the other, and a copy into
        // the same directory shows up on the side it came from.
        self.reload_panel(true, None);
        self.reload_panel(false, None);
        self.clear_active_selections();
        // Any directory size worked out before may now be wrong - the ones
        // copied into, moved out of or deleted from, and every directory above
        // them. Space works them out again. One still being counted may
        // have walked through them halfway, so it goes too.
        self.dir_sizes.clear();
        self.cancel_dir_sizes();

        // The offer to quit covered this job, and this job is over.
        self.quit_armed = false;

        match result {
            Ok(Transfer::Done) if job.skipped > 0 => {
                let entries = if job.skipped == 1 { "entry" } else { "entries" };
                self.display_error(format!("{} finished, {} {entries} skipped", job.kind.title(), job.skipped))
            }
            Ok(Transfer::Done) => {}
            Ok(Transfer::Cancelled) => {
                let far = match job.kind {
                    TransferKind::Delete => format!("{} entries", job.done),
                    TransferKind::Trash => format!("{} items", job.done),
                    _ => crate::utils::format_size(job.done),
                };
                self.display_error(format!("{} cancelled after {far}", job.kind.title()))
            }
            Err(e) => self.display_error(e),
        }
    }

    fn listing(&self, is_left: bool) -> &Option<PendingListing> {
        if is_left { &self.listing_left } else { &self.listing_right }
    }

    fn listing_mut(&mut self, is_left: bool) -> &mut Option<PendingListing> {
        if is_left { &mut self.listing_left } else { &mut self.listing_right }
    }

    /// The directory a panel is in - or, while it is on its way somewhere
    /// slow to read, the one it is going to, which is the one meant. Asked of
    /// by what reaches into the panel from outside: a copy to it, or a search
    /// from it.
    pub fn panel_dir(&self, is_left: bool) -> PathBuf {
        match self.listing(is_left) {
            Some(pending) if pending.navigate => pending.dir.clone(),
            _ => {
                if is_left {
                    self.dir_left.clone()
                } else {
                    self.dir_right.clone()
                }
            }
        }
    }

    /// True while a panel's directory is still being read, past the moment
    /// the UI waits. Until it lands the panel shows what it did before, and
    /// only Tab and Esc mean anything there.
    pub fn panel_busy(&self, is_left: bool) -> bool {
        self.listing(is_left).is_some()
    }

    /// Point a panel at `dir` and read it. The single way a panel's directory
    /// changes - navigation, and anything else that jumps somewhere. `select`
    /// names the entry to land on, otherwise the cursor goes to the top.
    /// False when the directory was refused and the panel stayed put; true
    /// when it went there, or is still on its way.
    pub fn open_dir(&mut self, is_left: bool, dir: PathBuf, select: Option<&std::ffi::OsStr>) -> bool {
        self.request_listing(is_left, dir, true, select.map(std::ffi::OsStr::to_os_string), None).unwrap_or(true)
    }

    /// Ctrl+Left and Ctrl+Right, as in Total Commander: the arrow names the
    /// panel, and it is sent to the directory under the cursor in the active
    /// one. On `..` that is the parent, landing on the directory left; on a
    /// file it is the directory the file is in, landing on the file. The focus
    /// stays where it is. Pointed at the active panel itself, it simply goes in.
    pub fn open_in_panel(&mut self, is_left: bool) {
        let (children, state, dir) = if self.is_left_active {
            (&self.children_left, &self.state_left, &self.dir_left)
        } else {
            (&self.children_right, &self.state_right, &self.dir_right)
        };
        let item = state.selected().and_then(|index| children.get(index));
        let (target, select) = match item {
            Some(item) if item.name == ".." => match dir.parent() {
                Some(parent) => (parent.to_path_buf(), dir.file_name().map(std::ffi::OsStr::to_os_string)),
                None => return,
            },
            Some(item) if item.is_dir => (item.path_in(dir), None),
            Some(item) => (dir.clone(), Some(item.name_os.clone())),
            None => (dir.clone(), None),
        };
        self.open_dir(is_left, target, select.as_deref());
    }

    /// Reread one panel from disk. `prefer` names the entry to land on - the
    /// file just renamed or created. Otherwise the cursor keeps the *file* it
    /// was on rather than the row, since entries appearing or vanishing above
    /// shift every index below them; if that file is gone, the row is kept.
    /// A panel on its way somewhere else is left to get there: what it lands
    /// on is read fresh anyway.
    pub fn reload_panel(&mut self, is_left: bool, prefer: Option<&std::ffi::OsStr>) {
        if self.listing(is_left).as_ref().is_some_and(|pending| pending.navigate) {
            return;
        }
        let dir = if is_left { self.dir_left.clone() } else { self.dir_right.clone() };
        self.request_listing(is_left, dir, false, prefer.map(std::ffi::OsStr::to_os_string), None);
    }

    /// Read a panel's directory on a thread of its own, and take it in at
    /// once if it comes back inside the moment the UI waits - which on a disk
    /// that answers it always does, so nothing looks any different. Otherwise
    /// the panel goes on showing what it did, and poll_listings takes the
    /// listing in when it lands. Some(false) when it was refused there and
    /// then, None while it is still being read. A listing already on its way
    /// for this panel is dropped for this one.
    fn request_listing(&mut self, is_left: bool, dir: PathBuf, navigate: bool, select: Option<OsString>, tab: Option<TabSwitch>) -> Option<bool> {
        let (sender, answer) = mpsc::channel();
        let (worker_dir, options) = (dir.clone(), self.options.clone());
        std::thread::spawn(move || {
            let _ = sender.send(read_listing(&worker_dir, &options));
        });
        let pending = PendingListing { dir, navigate, select, tab, answer };
        match pending.answer.recv_timeout(self.listing_wait) {
            Ok(listed) => Some(self.apply_listing(is_left, pending, listed)),
            Err(mpsc::RecvTimeoutError::Timeout) => {
                *self.listing_mut(is_left) = Some(pending);
                None
            }
            // Gone without a word, which only happens if it panicked.
            Err(mpsc::RecvTimeoutError::Disconnected) => {
                self.display_error(format!("Cannot read {}", pending.dir.display()));
                self.undo_tab(is_left, pending.tab);
                Some(false)
            }
        }
    }

    /// Take in whichever listings have landed since the last frame.
    pub fn poll_listings(&mut self) {
        for is_left in [true, false] {
            let Some(pending) = self.listing_mut(is_left).take() else {
                continue;
            };
            match pending.answer.try_recv() {
                Ok(listed) => {
                    self.apply_listing(is_left, pending, listed);
                }
                Err(TryRecvError::Empty) => *self.listing_mut(is_left) = Some(pending),
                Err(TryRecvError::Disconnected) => {
                    self.display_error(format!("Cannot read {}", pending.dir.display()));
                    self.undo_tab(is_left, pending.tab);
                }
            }
        }
    }

    /// Esc on a panel still being read: stop waiting for it. The panel stays
    /// where it was, and a tab it was switching to is switched back. Whatever
    /// the thread finds is never asked for.
    pub fn cancel_listing(&mut self, is_left: bool) {
        if let Some(pending) = self.listing_mut(is_left).take() {
            self.undo_tab(is_left, pending.tab);
        }
    }

    /// Put a panel to a listing that has come back. False when it was a
    /// directory that is there but could not be read, which is refused - /root,
    /// to anyone else - and the panel stays where it was. Moved there anyway,
    /// the panel went on listing the directory it left under the name of one it
    /// could not show, and every operation built its paths in the wrong place.
    /// One that is gone is climbed out of, to the nearest parent still there.
    fn apply_listing(&mut self, is_left: bool, pending: PendingListing, listed: Listed) -> bool {
        let Some(found) = listed.dir else {
            self.display_error(format!("No such directory: {}", pending.dir.display()));
            self.undo_tab(is_left, pending.tab);
            return false;
        };
        if pending.navigate
            && found == pending.dir
            && let Err(e) = &listed.items
        {
            self.display_error(format!("Cannot open {}: {}", pending.dir.display(), e));
            self.undo_tab(is_left, pending.tab);
            return false;
        }

        // Gone from under it, and climbed out of to `found`.
        let relocated = found != pending.dir;
        if pending.navigate || relocated {
            // Cursor, search and selection all referred to entries elsewhere.
            if is_left {
                self.dir_left = found.clone();
                self.selected_left.clear();
                self.state_left.select(Some(0));
            } else {
                self.dir_right = found.clone();
                self.selected_right.clear();
                self.state_right.select(Some(0));
            }
            self.search_clear();
        }

        let (children, state) = if is_left { (&self.children_left, &self.state_left) } else { (&self.children_right, &self.state_right) };
        let previous_index = state.selected().unwrap_or(0);
        let wanted = if relocated {
            None
        } else if pending.navigate {
            pending.select
        } else {
            // By the name the filesystem holds: two that are not valid UTF-8
            // can read the same, and the cursor would land on the wrong one.
            pending.select.or_else(|| children.get(previous_index).map(|item| item.name_os.clone()))
        };

        match listed.items {
            Ok(items) => {
                let selected = if is_left { &mut self.selected_left } else { &mut self.selected_right };
                prune_selection(selected, &items);
                let index = wanted.and_then(|name| items.iter().position(|item| item.name_os == name)).unwrap_or(previous_index).min(items.len().saturating_sub(1));
                if is_left {
                    self.children_left = items;
                    self.state_left.select(Some(index));
                } else {
                    self.children_right = items;
                    self.state_right.select(Some(index));
                }
            }
            // Gone unreadable while the panel is in it. Said once: the watcher
            // only speaks up again when the directory changes.
            Err(e) => self.display_error(e.to_string()),
        }

        if is_left {
            self.disk_left = listed.disk;
        } else {
            self.disk_right = listed.disk;
        }
        let watch = if is_left { &self.watch_left } else { &self.watch_right };
        if watch.as_ref().is_none_or(|watch| watch.dir != found) {
            let watch = crate::background::watch_dir(is_left, found.clone(), listed.stamp, listed.disk, self.watch_interval, self.watch_sender.clone());
            if is_left {
                self.watch_left = Some(watch);
            } else {
                self.watch_right = Some(watch);
            }
        }

        // A tab brings back what was selected in it - when the panel got to
        // where the tab was, and not to some parent of it.
        if let Some(tab) = pending.tab {
            let (children, selected) = if is_left { (&self.children_left, &mut self.selected_left) } else { (&self.children_right, &mut self.selected_right) };
            if relocated {
                selected.clear();
            } else {
                *selected = tab.selected;
                prune_selection(selected, children);
            }
        }

        // Both of these keep what they gathered until the cursor moves to some
        // other entry, which is what makes them cheap to hold. A reread is the
        // other way the entry under the cursor changes - it was saved in the
        // editor, written over by a copy, or changed by something else
        // entirely - and neither would notice that on its own. Dropping them
        // here has them gathered again before the next frame, since the loop
        // refreshes both on its way to drawing one.
        self.preview = None;
        self.cursor_detail = None;
        true
    }

    /// A tab switch that did not happen, put back as it was.
    fn undo_tab(&mut self, is_left: bool, tab: Option<TabSwitch>) {
        let Some(tab) = tab else {
            return;
        };
        let tabs = self.tabs_mut(is_left);
        match tab.undo {
            TabUndo::Active(previous) => tabs.active = previous,
            TabUndo::Reopen(index, closed) => {
                tabs.list.insert(index, closed);
                tabs.active = index;
            }
        }
    }

    /// Take in what the watchers have seen since the last frame.
    pub fn poll_watchers(&mut self) {
        while let Ok(event) = self.watch_events.try_recv() {
            match event {
                WatchEvent::Changed { is_left, dir } => {
                    if dir == *(if is_left { &self.dir_left } else { &self.dir_right }) {
                        if is_left {
                            self.stale_left = true;
                        } else {
                            self.stale_right = true;
                        }
                    }
                }
                // Free space moves without the directory changing - a copy
                // anywhere else on the same filesystem shifts it.
                WatchEvent::Disk { is_left, dir, usage } => {
                    if dir == *(if is_left { &self.dir_left } else { &self.dir_right }) {
                        if is_left {
                            self.disk_left = usage;
                        } else {
                            self.disk_right = usage;
                        }
                    }
                }
                WatchEvent::Mounts(mounts) => self.mounts = mounts,
            }
        }
    }

    /// Which panel's drive strip a position is on, if either.
    pub fn drive_strip_at(&self, column: u16, row: u16) -> Option<bool> {
        let position = Position::new(column, row);
        if self.drive_strip_left.area.contains(position) {
            Some(true)
        } else if self.drive_strip_right.area.contains(position) {
            Some(false)
        } else {
            None
        }
    }

    /// The panel and what a click landed on, when it was a drive icon or an
    /// arrow. The strip runs the width of its half, so most of it is neither:
    /// a click on the label beside them, or past the last one, is nothing.
    pub fn drive_at(&self, column: u16, row: u16) -> Option<(bool, StripHit)> {
        let is_left = self.drive_strip_at(column, row)?;
        let strip = if is_left { &self.drive_strip_left } else { &self.drive_strip_right };
        let hit = strip_hit(strip, column)?;
        match hit {
            StripHit::Item(mount) if mount >= self.mounts.len() => None,
            _ => Some((is_left, hit)),
        }
    }

    /// Move a panel's drive strip a page along, when not all of it fits.
    pub fn scroll_drive_strip(&mut self, is_left: bool, forward: bool) {
        let strip = if is_left { &mut self.drive_strip_left } else { &mut self.drive_strip_right };
        strip.scroll(forward);
    }

    /// Which panel's tab strip a position is on, if either.
    pub fn tab_strip_at(&self, column: u16, row: u16) -> Option<bool> {
        let position = Position::new(column, row);
        if self.tabs_left.strip.area.contains(position) {
            Some(true)
        } else if self.tabs_right.strip.area.contains(position) {
            Some(false)
        } else {
            None
        }
    }

    /// The panel and what a click landed on, when it was a tab or an arrow.
    pub fn tab_at(&self, column: u16, row: u16) -> Option<(bool, StripHit)> {
        let is_left = self.tab_strip_at(column, row)?;
        let tabs = if is_left { &self.tabs_left } else { &self.tabs_right };
        let hit = strip_hit(&tabs.strip, column)?;
        match hit {
            StripHit::Item(index) if index >= tabs.list.len() => None,
            _ => Some((is_left, hit)),
        }
    }

    pub fn scroll_tab_strip(&mut self, is_left: bool, forward: bool) {
        let tabs = if is_left { &mut self.tabs_left } else { &mut self.tabs_right };
        tabs.strip.scroll(forward);
    }

    fn tabs_mut(&mut self, is_left: bool) -> &mut Tabs {
        if is_left { &mut self.tabs_left } else { &mut self.tabs_right }
    }

    /// The panel as it stands, as a tab to come back to.
    fn panel_as_tab(&self, is_left: bool) -> Tab {
        let (dir, children, state, selected) = if is_left {
            (&self.dir_left, &self.children_left, &self.state_left, &self.selected_left)
        } else {
            (&self.dir_right, &self.children_right, &self.state_right, &self.selected_right)
        };
        Tab {
            dir: dir.clone(),
            cursor: state.selected().and_then(|index| children.get(index)).map(|item| item.name_os.clone()),
            selected: selected.clone(),
        }
    }

    /// Every tab of a panel's directory, the one it shows as it is now, and
    /// which that is - for the strip's labels and the session file.
    pub fn tab_dirs(&self, is_left: bool) -> (Vec<PathBuf>, usize) {
        let (tabs, dir) = if is_left { (&self.tabs_left, &self.dir_left) } else { (&self.tabs_right, &self.dir_right) };
        let mut dirs: Vec<PathBuf> = tabs.list.iter().map(|tab| tab.dir.clone()).collect();
        dirs[tabs.active] = dir.clone();
        (dirs, tabs.active)
    }

    /// Ctrl+T: a new tab in the active panel, beside the one it is on and in
    /// the same directory, with the cursor where it was and nothing selected
    /// - the selection stays with the tab it was made in.
    pub fn new_tab(&mut self) {
        let is_left = self.is_left_active;
        if self.panel_busy(is_left) {
            return;
        }
        let here = self.panel_as_tab(is_left);
        let tabs = self.tabs_mut(is_left);
        tabs.list[tabs.active] = here.clone();
        tabs.list.insert(tabs.active + 1, Tab { selected: HashSet::new(), ..here });
        tabs.active += 1;
        if is_left { self.selected_left.clear() } else { self.selected_right.clear() }
    }

    /// Ctrl+W, or a middle click: close a tab. The last one a panel has stays,
    /// since a panel has to show something. Closing the one shown moves to the
    /// one after it, or before it at the end, as a browser does - unless that
    /// one's directory cannot be read, when the close is refused and the tab
    /// stays, as it was. Not while the panel is still being read.
    pub fn close_tab(&mut self, is_left: bool, index: usize) {
        if self.panel_busy(is_left) {
            return;
        }
        let tabs = self.tabs_mut(is_left);
        if tabs.list.len() <= 1 || index >= tabs.list.len() {
            return;
        }
        let closed = tabs.list.remove(index);
        if index == tabs.active {
            tabs.active = index.min(tabs.list.len() - 1);
            self.show_tab(is_left, TabUndo::Reopen(index, closed));
        } else if index < tabs.active {
            tabs.active -= 1;
        }
    }

    /// Show another of a panel's tabs, leaving this one as it is to come back
    /// to. One whose directory cannot be read is refused, and this one stays
    /// active: moved there regardless, the panel went on showing the directory
    /// it was in under the other tab, which took that directory over for good
    /// as soon as it was left. Not while the panel is still being read, for
    /// the same reason: it is not yet showing the tab it says it is.
    pub fn select_tab(&mut self, is_left: bool, index: usize) {
        if self.panel_busy(is_left) {
            return;
        }
        let here = self.panel_as_tab(is_left);
        let tabs = self.tabs_mut(is_left);
        if index >= tabs.list.len() || index == tabs.active {
            return;
        }
        let previous = tabs.active;
        tabs.list[previous] = here;
        tabs.active = index;
        self.show_tab(is_left, TabUndo::Active(previous));
    }

    /// Ctrl+PageDown and Ctrl+PageUp: the next tab in the active panel, or the
    /// one before, round from the end to the start.
    pub fn cycle_tab(&mut self, forward: bool) {
        let is_left = self.is_left_active;
        let tabs = self.tabs_mut(is_left);
        let count = tabs.list.len();
        let next = if forward { (tabs.active + 1) % count } else { (tabs.active + count - 1) % count };
        self.select_tab(is_left, next);
    }

    /// Point the panel at the tab now active. A directory that cannot be read
    /// is refused as anywhere else, leaving the panel - selection and all -
    /// where it was, and `undo` puts the tabs back. A directory gone
    /// altogether is climbed out of, as anywhere else, and its selection goes
    /// with it.
    fn show_tab(&mut self, is_left: bool, undo: TabUndo) {
        let tabs = self.tabs_mut(is_left);
        let tab = tabs.list[tabs.active].clone();
        self.request_listing(is_left, tab.dir, true, tab.cursor, Some(TabSwitch { selected: tab.selected, undo }));
    }

    /// The mount a panel is sitting on: the longest one its directory is under.
    pub fn current_mount(&self, is_left: bool) -> Option<usize> {
        let dir = if is_left { &self.dir_left } else { &self.dir_right };
        self.mounts
            .iter()
            .enumerate()
            .filter(|(_, mount)| dir.starts_with(&mount.path))
            .max_by_key(|(_, mount)| mount.path.as_os_str().len())
            .map(|(index, _)| index)
    }

    /// Start choosing a drive for a panel, highlighting the one it is on.
    pub fn open_drive_picker(&mut self, is_left: bool) {
        // Kept current by the watcher, so a stick plugged in a moment ago is
        // already there.
        if self.mounts.is_empty() {
            return;
        }
        let current = self.current_mount(is_left).unwrap_or(0);
        self.dialog = Some(Dialog::DrivePicker { is_left, index: current });
        // Into view, even if the strip was scrolled away from it.
        let strip = if is_left { &mut self.drive_strip_left } else { &mut self.drive_strip_right };
        strip.followed = None;
    }

    pub fn move_drive_picker(&mut self, forward: bool) {
        let count = self.mounts.len();
        if let Some(Dialog::DrivePicker { index, .. }) = &mut self.dialog
            && count > 0
        {
            *index = if forward { (*index + 1) % count } else { (*index + count - 1) % count };
        }
    }

    /// Take the highlighted drive; the panel jumps to that mount point.
    pub fn confirm_drive_picker(&mut self) {
        if let Some(Dialog::DrivePicker { is_left, index }) = self.dialog.take()
            && let Some(mount) = self.mounts.get(index)
        {
            let path = mount.path.clone();
            self.open_dir(is_left, path, None);
        }
    }

    /// Reread any panel whose directory the watcher saw change. Not under an
    /// open dialog, which would move things out from under the user, nor while
    /// the panel is still being read: what lands then is fresh anyway.
    pub fn refresh_stale_panels(&mut self) {
        if self.is_modal_open() {
            return;
        }
        for is_left in [true, false] {
            let stale = if is_left { self.stale_left } else { self.stale_right };
            if stale && !self.panel_busy(is_left) {
                if is_left {
                    self.stale_left = false;
                } else {
                    self.stale_right = false;
                }
                self.reload_panel(is_left, None);
            }
        }
    }

    /// Full path of the entry under the cursor, unless that is the parent entry.
    fn cursor_target(&self) -> Option<(PathBuf, String, bool)> {
        let (children, state, dir) = if self.is_left_active {
            (&self.children_left, &self.state_left, &self.dir_left)
        } else {
            (&self.children_right, &self.state_right, &self.dir_right)
        };
        let item = children.get(state.selected()?)?;
        if item.name == ".." {
            return None;
        }
        Some((item.path_in(dir), item.name_full.clone(), item.is_dir))
    }

    /// Gather what the detail lines say, when the cursor has moved to something
    /// else. Asked of a thread, since it stats the file, reads a link and looks
    /// the owner up, and any of those can wait for good on a dead mount. The
    /// name is known already, and shows at once; the rest follows, at once on
    /// a disk that answers.
    pub fn refresh_cursor_detail(&mut self) {
        let target = self.cursor_target();
        let path = target.as_ref().map(|(path, _, _)| path.clone());
        let mut wait = Duration::ZERO;
        if self.cursor_detail.as_ref().is_none_or(|detail| detail.path != path) {
            let (name, awaiting) = match target {
                Some((path, name, is_dir)) => {
                    self.detail_worker.ask((path, is_dir));
                    wait = self.detail_wait;
                    (name, true)
                }
                None => (String::new(), false),
            };
            self.cursor_detail = Some(CursorDetail {
                path,
                name,
                size: String::new(),
                modified: String::new(),
                owner: String::new(),
                attributes: String::new(),
                link: None,
                awaiting,
            });
        }

        if !self.cursor_detail.as_ref().is_some_and(|detail| detail.awaiting) {
            return;
        }
        let Some(((path, _), described)) = self.detail_worker.answer(wait) else {
            return;
        };
        let date_format = self.options.date_format;
        let Some(detail) = self.cursor_detail.as_mut().filter(|detail| detail.path.as_ref() == Some(&path)) else {
            return;
        };
        detail.awaiting = false;
        // The exact count, since the column rounds it to something like
        // "9 MiB" and the difference is the point of showing it again.
        detail.size = described.as_ref().and_then(|described| described.size_bytes).map(|bytes| format!("{} bytes", crate::utils::grouped(bytes))).unwrap_or_default();
        // To the second, which the column has no room for either.
        detail.modified = described.as_ref().and_then(|described| described.modified).map(|at| crate::utils::format_exact(at, date_format)).unwrap_or_default();
        detail.owner = described.as_ref().map(|described| described.owner.clone()).unwrap_or_default();
        detail.attributes = described.as_ref().map(|described| described.attributes.clone()).unwrap_or_default();
        detail.link = described.and_then(|described| described.link);
    }

    /// Keep the preview pointed at whatever the cursor is on. Reads only when
    /// the target actually changed, so holding an arrow key stays cheap - and
    /// on a thread, like the detail lines, for the same reason.
    pub fn refresh_preview(&mut self) {
        if !self.show_preview {
            self.preview = None;
            return;
        }

        let target = self.cursor_target();
        let path = target.as_ref().map(|(path, _, _)| path.clone());
        let mut wait = Duration::ZERO;
        if self.preview.as_ref().is_none_or(|preview| preview.path != path) {
            let (label, awaiting) = match target {
                Some((path, name, is_dir)) => {
                    self.preview_worker.ask((path, is_dir));
                    wait = self.detail_wait;
                    (name, true)
                }
                None => (String::new(), false),
            };
            self.preview = Some(PreviewState {
                path,
                label,
                lines: Vec::new(),
                bytes: Vec::new(),
                awaiting,
            });
        }

        if !self.preview.as_ref().is_some_and(|preview| preview.awaiting) {
            return;
        }
        let Some(((path, _), content)) = self.preview_worker.answer(wait) else {
            return;
        };
        let Some(preview) = self.preview.as_mut().filter(|preview| preview.path.as_ref() == Some(&path)) else {
            return;
        };
        preview.awaiting = false;
        match content {
            Preview::Lines(lines) => preview.lines = lines,
            Preview::Bytes(bytes) => preview.bytes = bytes,
        }
    }

    pub fn clear_active_selections(&mut self) {
        if self.is_left_active {
            self.selected_left.clear();
        } else {
            self.selected_right.clear();
        }
    }
}

impl EditorState {
    /// The selection as ((line, col), (line, col)) in document order, or None
    /// when nothing is selected.
    pub fn selection(&self) -> Option<((usize, usize), (usize, usize))> {
        let anchor = self.selection_anchor?;
        let cursor = (self.cursor_line, self.cursor_col);
        if anchor == cursor {
            return None;
        }
        Some(if anchor < cursor { (anchor, cursor) } else { (cursor, anchor) })
    }

    /// The selected text, with '\n' between lines whatever the file uses.
    pub fn selected_text(&self) -> Option<String> {
        let ((first_line, first_col), (last_line, last_col)) = self.selection()?;

        if first_line == last_line {
            return Some(char_slice(&self.lines[first_line], first_col, last_col));
        }

        let first = &self.lines[first_line];
        let mut text = char_slice(first, first_col, first.chars().count());
        for line in &self.lines[first_line + 1..last_line] {
            text.push('\n');
            text.push_str(line);
        }
        text.push('\n');
        text.push_str(&char_slice(&self.lines[last_line], 0, last_col));
        Some(text)
    }

    /// Settle the vertical scroll before a frame is drawn. It never runs past
    /// the last screenful - an edit that shortens the file, such as deleting a
    /// selection made with Ctrl+A, would otherwise leave it pointing past the
    /// end - and after a key, which sets auto_scroll, it brings the cursor into
    /// view: a paste, an undo or a deleted selection can each land it off
    /// screen. The mouse wheel clears auto_scroll, so reading elsewhere in the
    /// file does not snap back to the cursor.
    pub fn keep_in_view(&mut self, height: usize) {
        let height = height.max(1);
        if self.auto_scroll {
            if self.cursor_line < self.scroll_offset {
                self.scroll_offset = self.cursor_line;
            } else if self.cursor_line >= self.scroll_offset + height {
                self.scroll_offset = self.cursor_line + 1 - height;
            }
        }
        self.scroll_offset = self.scroll_offset.min(self.lines.len().saturating_sub(height));
    }

    /// Clamp cursor_col to current line length.
    fn clamp_col(&mut self) {
        let line_len = self.lines[self.cursor_line].chars().count();
        self.cursor_col = self.cursor_col.min(line_len);
    }
}

/// Pick the terminator to save a file with. A mixed file normalises to whichever
/// style already dominates; a file with no newline at all gets "\n".
fn detect_line_ending(content: &str) -> &'static str {
    let crlf = content.matches("\r\n").count();
    let lf = content.matches('\n').count() - crlf;
    if crlf > lf { "\r\n" } else { "\n" }
}

/// The worker thread behind a delete. The count comes first so the bar has a
/// denominator; walking the tree twice costs a second pass of readdir, which is
/// cheap beside the removals themselves.
fn run_delete(items: Vec<(PathBuf, bool)>, mut progress: JobProgress<'_>) {
    let _ = progress.updates.send(JobUpdate::Total(count_entries(&items)));

    for (path, is_dir) in items {
        match delete_path(path, is_dir, &mut progress) {
            Ok(Transfer::Done) => {}
            outcome => return progress.finish(outcome),
        }
    }
    progress.finish(Ok(Transfer::Done));
}

/// The worker thread behind a move to the trash. Counted in items rather than
/// entries, since each goes in one piece.
fn run_trash(items: Vec<(PathBuf, bool)>, mut progress: JobProgress<'_>) {
    let _ = progress.updates.send(JobUpdate::Total(items.len() as u64));

    for (path, is_dir) in items {
        match crate::fs_ops::trash_path(path, is_dir, &mut progress) {
            Ok(Transfer::Done) => {}
            outcome => return progress.finish(outcome),
        }
    }
    progress.finish(Ok(Transfer::Done));
}

/// Drop selections whose file is no longer there.
///
/// A selection is keyed by name so it can follow its file across a re-sort, but
/// that leaves the name behind when the file itself goes. Nothing shows it: the
/// count and the operations all walk the files and ask whether each is
/// selected, so a name with no file behind it is silently inert - until
/// something takes that name again, at which point a file the user never picked
/// is selected, and joins the next copy, move or delete. Worse, those read the
/// selection *instead of* the cursor whenever it is not empty, so one such name
/// quietly redirects the whole operation.
fn prune_selection(selected: &mut HashSet<OsString>, items: &[Item]) {
    let names: HashSet<&OsString> = items.iter().map(|item| &item.name_os).collect();
    selected.retain(|name| names.contains(name));
}

/// What a click at `column` lands on, along a strip.
fn strip_hit(strip: &Strip, column: u16) -> Option<StripHit> {
    let index = slot_at(&strip.slots, column.checked_sub(strip.area.x)?)?;
    strip.hits.get(index).copied()
}

/// Which of a strip's slots a column falls in, measured from the strip's left
/// edge. None for the gaps around them: the space the strip opens with, and
/// everything past the last icon, where the mount's name is written.
fn slot_at(slots: &[(u16, u16)], offset: u16) -> Option<usize> {
    slots.iter().position(|&(start, width)| offset >= start && offset < start + width)
}

/// The worker thread behind a copy or move.
///
/// Renames come first and on their own. A move within one filesystem is a
/// rename, which takes no time and moves no bytes - measuring a large tree
/// before doing it would hold up a transfer that was about to be instant.
fn run_transfer(items: Vec<(PathBuf, PathBuf, bool)>, is_copy: bool, mut progress: JobProgress<'_>) {
    let mut remaining = Vec::new();
    for (source, dest, is_dir) in items {
        // rename() replaces a file, or an empty directory, without a word, so
        // only a name nothing has taken goes this way. One that is taken goes
        // through move_path, which asks about a file and merges a directory.
        if !is_copy && !path_exists(&dest) && rename_in_place(&source, &dest) {
            continue;
        }
        remaining.push((source, dest, is_dir));
    }

    // Only what is actually going to be copied needs counting.
    let _ = progress.updates.send(JobUpdate::Total(measure(&remaining)));

    for (source, dest, is_dir) in remaining {
        let result = if is_copy { copy_path(source, dest, is_dir, &mut progress) } else { move_path(source, dest, &mut progress) };
        match result {
            Ok(Transfer::Done) => {}
            outcome => return progress.finish(outcome),
        }
    }
    progress.finish(Ok(Transfer::Done));
}

/// Where a scroll offset belongs after the drawing changed size, so that the
/// middle of the pane goes on showing the same part of the picture. `extent` is
/// the pane's size along the axis being moved.
///
/// A drawing smaller than the pane is centred by the renderer rather than
/// scrolled, so it carries no offset of its own - which is both where such a
/// drawing starts from and where it lands.
fn recentre(offset: usize, extent: usize, before: usize, after: usize) -> usize {
    if before == 0 || after <= extent {
        return 0;
    }
    // Where the middle of the pane falls on the old drawing, as a fraction of
    // it. One that fitted was centred, so its middle was the picture's own.
    let middle = if before <= extent { 0.5 } else { (offset as f64 + extent as f64 / 2.0) / before as f64 };
    let centre = middle * after as f64 - extent as f64 / 2.0;
    (centre.round().max(0.0) as usize).min(after - extent)
}

/// A character range of a line, as a new String.
fn char_slice(line: &str, from: usize, to: usize) -> String {
    line[char_to_byte(line, from)..char_to_byte(line, to)].to_string()
}

/// Convert a char index to a byte index in a string.
fn char_to_byte(s: &str, char_idx: usize) -> usize {
    s.char_indices().nth(char_idx).map(|(i, _)| i).unwrap_or(s.len())
}

#[cfg(test)]
impl AppState {
    /// Put the editor's cursor somewhere, with nothing selected.
    fn editor_state_cursor(&mut self, line: usize, col: usize) {
        if let Some(state) = self.editor_mut() {
            state.cursor_line = line;
            state.cursor_col = col;
            state.selection_anchor = None;
        }
    }
}

#[cfg(test)]
mod editor_tests {
    use super::AppState;

    fn editor_with(name: &str, text: &str) -> (AppState, std::path::PathBuf) {
        let path = std::env::temp_dir().join(format!("fm84-{name}-{}.txt", std::process::id()));
        std::fs::write(&path, text).unwrap();
        let mut app_state = AppState::new();
        app_state.options = crate::options::Options::default();
        app_state.open_editor(path.clone()).unwrap();
        (app_state, path)
    }

    /// Type into the prompt as a user would, and press Enter.
    fn answer_prompt(app_state: &mut AppState, kind: super::PromptKind, text: &str) {
        app_state.open_prompt(kind);
        let input = app_state.dialog_input().unwrap();
        input.set(String::new());
        text.chars().for_each(|c| input.insert(c));
        app_state.confirm_prompt();
    }

    fn selected(app_state: &AppState) -> Option<((usize, usize), (usize, usize))> {
        app_state.editor().unwrap().selection()
    }

    #[test]
    fn find_selects_each_match_in_turn_and_wraps() {
        let (mut app_state, path) = editor_with("find", "alpha beta\nBETA\ngamma beta\n");
        app_state.editor_viewport_height = 10;

        // F3 before anything was looked for asks what to look for.
        app_state.find(true, false);
        assert!(matches!(app_state.dialog, Some(super::Dialog::Prompt(super::PromptKind::Find, _))));
        app_state.dialog = None;

        answer_prompt(&mut app_state, super::PromptKind::Find, "beta");
        assert_eq!(selected(&app_state), Some(((0, 6), (0, 10))));
        assert!(app_state.find_shown);
        assert_eq!(app_state.find_note, None);

        app_state.find(true, false);
        assert_eq!(selected(&app_state), Some(((1, 0), (1, 4))), "lower case finds any case");
        app_state.find(true, false);
        assert_eq!(selected(&app_state), Some(((2, 6), (2, 10))));
        app_state.find(true, false);
        assert_eq!(selected(&app_state), Some(((0, 6), (0, 10))));
        assert_eq!(app_state.find_note.as_deref(), Some("Wrapped to the top"));

        app_state.find(false, false);
        assert_eq!(selected(&app_state), Some(((2, 6), (2, 10))));
        assert_eq!(app_state.find_note.as_deref(), Some("Wrapped to the bottom"));

        // The prompt offers the last term again, and a miss moves nothing.
        app_state.open_prompt(super::PromptKind::Find);
        assert_eq!(app_state.dialog_input().unwrap().text, "beta");
        app_state.dialog = None;
        answer_prompt(&mut app_state, super::PromptKind::Find, "BETAMAX");
        assert_eq!(selected(&app_state), Some(((2, 6), (2, 10))));
        assert_eq!(app_state.find_note.as_deref(), Some("Not found: BETAMAX"));

        // Closing the editor takes the marks with it, and keeps the term.
        app_state.close_editor();
        assert!(!app_state.find_shown);
        assert_eq!(app_state.find_term, "BETAMAX");
        std::fs::remove_file(path).unwrap();
    }

    #[test]
    fn go_to_line_puts_the_cursor_on_it_and_keeps_inside_the_file() {
        let text: String = (1..=100).map(|n| format!("line {n}\n")).collect();
        let (mut app_state, path) = editor_with("goto", &text);
        app_state.editor_viewport_height = 10;

        answer_prompt(&mut app_state, super::PromptKind::GoToLine, "42");
        let state = app_state.editor().unwrap();
        assert_eq!((state.cursor_line, state.cursor_col), (41, 0));
        assert!(state.scroll_offset <= 41 && 41 < state.scroll_offset + 10, "the line is on screen");

        answer_prompt(&mut app_state, super::PromptKind::GoToLine, "100000");
        assert_eq!(app_state.editor().unwrap().cursor_line, 100, "the last line");
        answer_prompt(&mut app_state, super::PromptKind::GoToLine, "0");
        assert_eq!(app_state.editor().unwrap().cursor_line, 0);
        std::fs::remove_file(path).unwrap();
    }

    #[test]
    fn the_viewer_finds_and_goes_to_lines_too() {
        let path = std::env::temp_dir().join(format!("fm84-view-find-{}.txt", std::process::id()));
        let text: String = (1..=50).map(|n| if n == 30 { "\tthe needle\n".to_string() } else { format!("hay {n}\n") }).collect();
        std::fs::write(&path, text).unwrap();
        let mut app_state = AppState::new();
        app_state.options = crate::options::Options::default();
        app_state.open_viewer(path.clone()).unwrap();
        app_state.viewer_viewport_height = 10;
        app_state.viewer_viewport_width = 40;

        answer_prompt(&mut app_state, super::PromptKind::Find, "needle");
        let state = app_state.viewer().unwrap();
        // Columns as drawn, with the tab opened out, so the selection and the
        // copy line up with the screen.
        let start = crate::display::tab_width() + 4;
        assert_eq!(state.selected_range(), Some(((29, start), (29, start + 6))));
        assert_eq!(state.selected_text().as_deref(), Some("needle"));
        assert!(state.scroll_offset <= 29 && 29 < state.scroll_offset + 10);

        answer_prompt(&mut app_state, super::PromptKind::GoToLine, "5");
        assert_eq!(app_state.viewer().unwrap().scroll_offset, 4);
        answer_prompt(&mut app_state, super::PromptKind::GoToLine, "50");
        // As far down as End goes, which leaves the last screenful showing.
        app_state.viewer_end();
        let end = app_state.viewer().unwrap().scroll_offset;
        app_state.viewer_home();
        answer_prompt(&mut app_state, super::PromptKind::GoToLine, "50");
        assert_eq!(app_state.viewer().unwrap().scroll_offset, end, "no further than the end allows");
        std::fs::remove_file(path).unwrap();
    }

    /// A file that starts out as plain ASCII and has a byte that is not UTF-8
    /// further in passes the check on its head. The viewer shows it anyway;
    /// the editor, which would write replacement characters back, says why
    /// it will not.
    #[test]
    fn a_stray_byte_past_the_head_still_views_and_is_refused_for_editing() {
        let path = std::env::temp_dir().join(format!("fm84-latin1-late-{}.txt", std::process::id()));
        let mut bytes = vec![b'a'; 600];
        bytes.extend_from_slice(b"\ncaf\xe9\n");
        std::fs::write(&path, bytes).unwrap();
        let mut app_state = AppState::new();
        app_state.options = crate::options::Options::default();

        app_state.open_viewer(path.clone()).unwrap();
        let state = app_state.viewer().unwrap();
        assert_eq!(state.content_lines[1], "caf\u{fffd}");

        let refused = app_state.open_editor(path.clone()).unwrap_err();
        assert!(refused.contains("not UTF-8"), "{refused}");
        assert!(app_state.editor().is_none());
        std::fs::remove_file(path).unwrap();
    }

    /// Ask to replace `what` with `with`, as Ctrl+R and the two prompts do.
    fn replace(app_state: &mut AppState, what: &str, with: &str) {
        app_state.open_replace();
        app_state.dialog_input().unwrap().set(what.to_string());
        app_state.confirm_prompt();
        app_state.dialog_input().unwrap().set(with.to_string());
        app_state.confirm_prompt();
    }

    fn text(app_state: &AppState) -> String {
        app_state.editor().unwrap().lines.join("\n")
    }

    fn asking(app_state: &AppState) -> bool {
        matches!(app_state.dialog, Some(super::Dialog::Replacing { .. }))
    }

    #[test]
    fn replace_asks_about_each_match_and_stops_where_it_began() {
        let (mut app_state, path) = editor_with("replace-each", "a b a\nb a");
        replace(&mut app_state, "a", "xy");
        // The first match is selected and asked about.
        assert_eq!(selected(&app_state), Some(((0, 0), (0, 1))));
        assert!(app_state.replace_step(true));
        assert!(app_state.replace_step(false));
        // The last one; after it, round the end and back to the start, where
        // the one left alone is not asked about again.
        assert!(!app_state.replace_step(true));
        assert!(!asking(&app_state));
        assert_eq!(text(&app_state), "xy b a\nb xy");
        assert_eq!(app_state.find_note.as_deref(), Some("Replaced 2"));
        std::fs::remove_file(path).unwrap();
    }

    #[test]
    fn replace_all_is_one_step_to_undo_and_never_chases_its_own_text() {
        let (mut app_state, path) = editor_with("replace-all", "a a\na");
        // Started on the last line, it goes round to cover the lines above.
        app_state.editor_state_cursor(1, 0);
        replace(&mut app_state, "a", "aa");
        app_state.replace_all();
        assert_eq!(text(&app_state), "aa aa\naa");
        assert_eq!(app_state.find_note.as_deref(), Some("Replaced 3"));
        app_state.editor_undo();
        assert_eq!(text(&app_state), "a a\na");
        app_state.editor_redo();
        assert_eq!(text(&app_state), "aa aa\naa");
        std::fs::remove_file(path).unwrap();
    }

    /// Started past the last match, with a replacement that holds what it
    /// replaces: once round, every match is done, and it stops - rather than
    /// going round again into the text it put in, for ever.
    #[test]
    fn replace_stops_after_once_round_even_into_its_own_text() {
        let (mut app_state, path) = editor_with("replace-once-round", "let x;\nlet y; z");
        app_state.editor_state_cursor(1, 8);
        replace(&mut app_state, "let", "/* let");
        // Stepped, with a limit, so a regression fails rather than hangs.
        let mut steps = 1;
        while app_state.replace_step(true) {
            steps += 1;
            assert!(steps < 10, "still replacing: {}", text(&app_state));
        }
        assert_eq!(text(&app_state), "/* let x;\n/* let y; z");
        assert_eq!(app_state.find_note.as_deref(), Some("Replaced 2"));
        std::fs::remove_file(path).unwrap();
    }

    /// Replace all highlights once, at the end, and comes out coloured just
    /// as the file would be read afresh - including a change that turns the
    /// rest of the file into a comment.
    #[test]
    fn replace_all_highlights_as_a_fresh_read_would() {
        let text: String = (0..40).map(|n| format!("let foo_{n} = foo(\"foo\"); // foo\n")).collect::<String>() + "fn tail() {}\n";
        let path = std::env::temp_dir().join(format!("fm84-replace-highlight-{}.rs", std::process::id()));
        std::fs::write(&path, &text).unwrap();
        let mut app_state = AppState::new();
        app_state.open_editor(path.clone()).unwrap();
        let shape = |spans: &[Vec<ratatui::text::Span<'static>>]| -> Vec<Vec<(String, Option<ratatui::style::Color>)>> { spans.iter().map(|line| line.iter().map(|span| (span.content.to_string(), span.style.fg)).collect()).collect() };

        for (what, with) in [("foo", "bar"), ("let", "/* let")] {
            replace(&mut app_state, what, with);
            app_state.replace_all();
            let state = app_state.editor().unwrap();
            assert!(!state.line_states.is_empty(), "highlighting back on");
            let (fresh, _) = crate::viewer::highlight_all(&state.lines, "rs");
            assert_eq!(shape(&state.highlighted_lines), shape(&fresh), "after {what} -> {with}");
        }
        std::fs::remove_file(path).unwrap();
    }

    #[test]
    fn replacing_with_nothing_deletes_and_lower_case_matches_any_case() {
        let (mut app_state, path) = editor_with("replace-nothing", "Foo bar foo");
        replace(&mut app_state, "foo", "");
        app_state.replace_all();
        assert_eq!(text(&app_state), " bar ");
        std::fs::remove_file(path).unwrap();
    }

    #[test]
    fn going_round_moves_the_stopping_point_with_the_text_before_it() {
        // From the middle of a line, round to its start: what goes in before
        // the starting point pushes it along, and every match is done once.
        let (mut app_state, path) = editor_with("replace-shift", "ab ab ab");
        app_state.editor_state_cursor(0, 4);
        replace(&mut app_state, "ab", "abab");
        app_state.replace_all();
        assert_eq!(text(&app_state), "abab abab abab");
        assert_eq!(app_state.find_note.as_deref(), Some("Replaced 3"));
        // Nothing there: said so, and nothing is asked.
        replace(&mut app_state, "zzz", "y");
        assert!(!asking(&app_state));
        assert_eq!(app_state.find_note.as_deref(), Some("Not found: zzz"));
        std::fs::remove_file(path).unwrap();
    }

    /// W wraps long lines in the viewer: scrolling goes by rows, while
    /// finding, selecting, copying and going to a line go by lines.
    #[test]
    fn the_viewer_wraps_long_lines_onto_rows() {
        let path = std::env::temp_dir().join(format!("fm84-wrap-{}.txt", std::process::id()));
        std::fs::write(&path, "short\none two three four five six seven needle eight\nlast").unwrap();
        let mut app_state = AppState::new();
        app_state.open_viewer(path.clone()).unwrap();
        (app_state.viewer_viewport_width, app_state.viewer_viewport_height) = (10, 3);

        app_state.viewer_toggle_wrap();
        let state = app_state.viewer().unwrap();
        assert!(state.wrapping());
        assert_eq!(state.line_count(), 3);
        // The long line takes six rows of ten.
        assert_eq!(state.total_lines, 8);
        assert_eq!(state.row(1), (1, 0, 8));

        // Found on the long line's fifth row, which scrolls into view.
        app_state.find_term = "needle".to_string();
        app_state.find(true, true);
        let state = app_state.viewer().unwrap();
        assert_eq!(state.selected_text().as_deref(), Some("needle"));
        let row = state.row_of(1, 38);
        assert!(state.scroll_offset <= row && row < state.scroll_offset + 3, "row {row} off screen from {}", state.scroll_offset);

        // Copied across a break that is only on screen: no newline in it.
        let state = app_state.viewer_mut().unwrap();
        state.selection = Some(((1, 4), (1, 13)));
        assert_eq!(state.selected_text().as_deref(), Some("two three"));
        // A click on the second row of the long line lands in that line.
        state.scroll_offset = 0;
        assert_eq!(state.position_at(2, 3), (1, 11));

        // Go to line 3: the row it starts on, as far down as the end allows.
        app_state.go_to_line(3);
        assert_eq!(app_state.viewer().unwrap().scroll_offset, 5);

        // X to a hexdump is a row a line again; back to text, wrapped again.
        app_state.viewer_next_mode();
        assert!(app_state.viewer().unwrap().rows.is_empty());
        app_state.viewer_next_mode();
        assert!(app_state.fit_viewer_wrap());
        assert_eq!(app_state.viewer().unwrap().total_lines, 8);

        // W again: a row a line, with the line that was at the top still there.
        app_state.viewer_mut().unwrap().scroll_offset = 3;
        app_state.viewer_toggle_wrap();
        let state = app_state.viewer().unwrap();
        assert!(!state.wrapping() && state.rows.is_empty());
        assert_eq!((state.scroll_offset, state.total_lines), (1, 3));

        // The next file opened takes up W as it was left.
        app_state.viewer_toggle_wrap();
        app_state.close_viewer();
        app_state.open_viewer(path.clone()).unwrap();
        assert!(app_state.viewer().unwrap().wrap);
        std::fs::remove_file(path).unwrap();
    }

    fn stacks(app_state: &AppState) -> (usize, usize) {
        let state = app_state.editor().unwrap();
        (state.undo_stack.len(), state.redo_stack.len())
    }

    #[test]
    fn saving_updates_the_size_the_panels_show() {
        let dir = std::env::temp_dir().join(format!("fm84-save-size-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&dir);
        std::fs::create_dir_all(&dir).unwrap();
        let path = dir.join("notes.txt");
        std::fs::write(&path, "ab").unwrap();

        let mut app_state = AppState::new();
        app_state.options = crate::options::Options::default();
        app_state.dir_left = dir.clone();
        app_state.dir_right = dir.clone();
        app_state.reload_panel(true, None);
        app_state.reload_panel(false, None);
        let size = |children: &[super::Item]| children.iter().find(|item| item.name_full == "notes.txt").unwrap().size_bytes;
        assert_eq!(size(&app_state.children_left), 2);

        app_state.open_editor(path.clone()).unwrap();
        app_state.editor_insert_text("more text");
        app_state.editor_save().unwrap();
        assert_eq!(size(&app_state.children_left), 11);
        assert_eq!(size(&app_state.children_right), 11);
        std::fs::remove_dir_all(&dir).unwrap();
    }

    #[test]
    fn an_edit_that_changes_nothing_keeps_the_redo_history() {
        let (mut app_state, path) = editor_with("noop", "ab\ncd");
        // One real edit, undone, so there is something to redo.
        app_state.editor_end();
        app_state.editor_insert_char('x');
        app_state.editor_undo();
        assert_eq!(stacks(&app_state), (0, 1));

        // Backspace at the very start, Delete at the very end, and Ctrl+X with
        // nothing selected: none of them change the text.
        app_state.editor_mut().unwrap().cursor_col = 0;
        app_state.editor_backspace();
        app_state.editor_cut();
        {
            let state = app_state.editor_mut().unwrap();
            state.cursor_line = 1;
            state.cursor_col = 2;
        }
        app_state.editor_delete();
        assert_eq!(stacks(&app_state), (0, 1));
        app_state.editor_redo();
        assert_eq!(app_state.editor().unwrap().lines, ["abx", "cd"]);

        // A real edit still forks the history.
        app_state.editor_undo();
        app_state.editor_insert_char('y');
        assert_eq!(stacks(&app_state), (1, 0));
        std::fs::remove_file(path).unwrap();
    }
}

#[cfg(test)]
mod job_tests {
    use super::AppState;

    #[test]
    fn a_finished_job_forgets_directory_sizes() {
        let dir = std::env::temp_dir().join(format!("fm84-sizes-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&dir);
        std::fs::create_dir_all(&dir).unwrap();
        std::fs::write(dir.join("doomed"), vec![0u8; 100]).unwrap();

        let mut app_state = AppState::new();
        app_state.dir_sizes.insert(dir.clone(), 100);
        app_state.start_delete(vec![(dir.join("doomed"), false)]);
        let started = std::time::Instant::now();
        while app_state.job.is_some() {
            assert!(started.elapsed() < std::time::Duration::from_secs(10), "delete never finished");
            std::thread::sleep(std::time::Duration::from_millis(5));
            app_state.poll_transfer();
        }
        assert!(app_state.dir_sizes.is_empty());
        std::fs::remove_dir_all(&dir).unwrap();
    }
}

#[cfg(test)]
mod tests {
    use super::{AppState, Item, prune_selection, recentre, slot_at};
    use crate::options::Options;
    use std::collections::HashSet;

    #[test]
    fn the_options_highlight_stops_at_either_end() {
        let mut app_state = AppState::new();
        app_state.options_move(false);
        assert_eq!(app_state.options_cursor, 0, "Up on the first row stays there");
        let last = crate::options::OPTION_ROWS.len() - 1;
        for _ in 0..=last {
            app_state.options_move(true);
        }
        assert_eq!(app_state.options_cursor, last, "Down on the last row stays there");
    }

    /// A file name is bytes, and need not be valid UTF-8. The strings the
    /// interface shows come from to_string_lossy, so joining one back together
    /// names a file that is not there - every path has to come from the name
    /// the filesystem gave.
    #[cfg(unix)]
    #[test]
    fn a_name_that_is_not_utf8_still_names_its_file() {
        use std::os::unix::ffi::OsStrExt;

        let dir = std::env::temp_dir().join(format!("fm84-latin1-{}", std::process::id()));
        std::fs::create_dir_all(&dir).unwrap();
        // "café.txt" as Latin-1 writes it, which is not valid UTF-8.
        let raw = std::ffi::OsStr::from_bytes(b"caf\xe9.txt");
        std::fs::write(dir.join(raw), "contents").unwrap();

        let mut app_state = AppState::new();
        app_state.options = Options::default();
        app_state.open_dir(true, dir.clone(), None);
        let item = app_state.children_left.iter().find(|item| item.name_full != "..").unwrap().clone();
        // Blank until the stem was read lossily too, which left the column empty.
        assert!(!item.name.is_empty());

        let index = app_state.children_left.iter().position(|row| row.name_full == item.name_full).unwrap();
        app_state.state_left.select(Some(index));
        let (path, _, _) = app_state.cursor_target().unwrap();
        assert_eq!(std::fs::read_to_string(&path).unwrap(), "contents");
        // What the name alone would have named, and what every operation used
        // to be handed: a path with a replacement character in it, and nothing
        // of that name on disk.
        assert!(!dir.join(&item.name_full).exists());

        std::fs::remove_dir_all(&dir).unwrap();
    }

    /// The preview and the detail lines hold what they gathered until the
    /// cursor moves, so a file that changes under a still cursor has to be
    /// picked up by the reread instead.
    #[test]
    fn a_reread_gathers_the_preview_and_the_detail_again() {
        let dir = std::env::temp_dir().join(format!("fm84-reread-{}", std::process::id()));
        std::fs::create_dir_all(&dir).unwrap();
        std::fs::write(dir.join("notes.txt"), "hello").unwrap();

        let mut app_state = AppState::new();
        app_state.options = Options::default();
        app_state.show_preview = true;
        app_state.open_dir(true, dir.clone(), Some("notes.txt".as_ref()));
        app_state.refresh_cursor_detail();
        app_state.refresh_preview();
        assert_eq!(app_state.cursor_detail.as_ref().unwrap().size, "5 bytes");
        assert_eq!(app_state.preview.as_ref().unwrap().lines, ["hello"]);

        // The file grows where it stands, and the panel rereads - which is
        // what saving in the editor, or a copy landing on it, comes to.
        std::fs::write(dir.join("notes.txt"), "hello, a longer file now").unwrap();
        app_state.reload_panel(true, None);
        app_state.refresh_cursor_detail();
        app_state.refresh_preview();
        assert_eq!(app_state.cursor_detail.as_ref().unwrap().size, "24 bytes");
        assert_eq!(app_state.preview.as_ref().unwrap().lines, ["hello, a longer file now"]);

        std::fs::remove_dir_all(&dir).unwrap();
    }

    /// Space sizes a directory on a thread, so the panel goes on answering
    /// while it counts, and the size lands once the walk is done.
    #[test]
    fn space_sizes_a_directory_off_the_ui_thread() {
        let dir = std::env::temp_dir().join(format!("fm84-sizing-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&dir);
        std::fs::create_dir_all(dir.join("sub")).unwrap();
        std::fs::write(dir.join("sub").join("data.bin"), vec![0u8; 4096]).unwrap();

        let mut app_state = AppState::new();
        app_state.options = Options::default();
        app_state.open_dir(true, dir.clone(), Some("sub".as_ref()));
        app_state.toggle_selection();
        assert_eq!(app_state.dir_sizing.len(), 1);

        let started = std::time::Instant::now();
        while !app_state.dir_sizing.is_empty() {
            assert!(started.elapsed() < std::time::Duration::from_secs(10), "sizing never finished");
            std::thread::sleep(std::time::Duration::from_millis(5));
            app_state.poll_dir_sizes();
        }
        assert_eq!(app_state.dir_sizes.get(&dir.join("sub")), Some(&4096));

        // Esc stops one under way, and nothing it finds is kept.
        app_state.dir_sizes.clear();
        app_state.start_dir_size(dir.join("sub"));
        app_state.cancel_dir_sizes();
        assert!(app_state.dir_sizing.is_empty());
        app_state.poll_dir_sizes();
        assert!(app_state.dir_sizes.is_empty());

        std::fs::remove_dir_all(&dir).unwrap();
    }

    /// A copy that meets an entry it cannot copy stops and asks. Skipped, the
    /// rest goes on, and the end says how many were left.
    #[cfg(unix)]
    #[test]
    fn a_job_asks_about_a_failure_and_goes_on_when_told_to_skip() {
        let dir = std::env::temp_dir().join(format!("fm84-ask-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&dir);
        let tree = dir.join("tree");
        std::fs::create_dir_all(&tree).unwrap();
        std::fs::write(tree.join("a.txt"), "a").unwrap();
        let pipe = std::ffi::CString::new(tree.join("pipe").to_str().unwrap()).unwrap();
        assert_eq!(unsafe { libc::mkfifo(pipe.as_ptr(), 0o600) }, 0);
        std::fs::write(tree.join("z.txt"), "z").unwrap();

        let mut app_state = AppState::new();
        app_state.options = Options::default();
        app_state.start_transfer(vec![(tree.clone(), dir.join("copy"), true)], true, super::Clashes::Ask);

        let started = std::time::Instant::now();
        let wait = |app_state: &mut AppState, done: &dyn Fn(&AppState) -> bool| {
            while !done(app_state) {
                assert!(started.elapsed() < std::time::Duration::from_secs(10), "the job never got there");
                std::thread::sleep(std::time::Duration::from_millis(5));
                app_state.poll_transfer();
            }
        };
        wait(&mut app_state, &|app_state| app_state.job.as_ref().is_some_and(|job| job.problem.is_some()));
        assert_eq!(app_state.job.as_ref().unwrap().problem.as_ref().unwrap().path, tree.join("pipe"));

        app_state.job.as_mut().unwrap().answer(super::Answer::Skip);
        wait(&mut app_state, &|app_state| app_state.job.is_none());
        assert_eq!(app_state.error.as_deref(), Some("Copy finished, 1 entry skipped"));
        assert!(dir.join("copy").join("a.txt").exists());
        assert!(dir.join("copy").join("z.txt").exists());

        // Esc on the question stops the job there, and says it was cancelled
        // rather than reporting the failure it was asked about.
        app_state.start_transfer(vec![(tree.clone(), dir.join("again"), true)], true, super::Clashes::Ask);
        wait(&mut app_state, &|app_state| app_state.job.as_ref().is_some_and(|job| job.problem.is_some()));
        app_state.cancel_transfer();
        wait(&mut app_state, &|app_state| app_state.job.is_none());
        assert!(app_state.error.as_deref().unwrap_or_default().starts_with("Copy cancelled"), "{:?}", app_state.error);

        std::fs::remove_dir_all(&dir).unwrap();
    }

    /// Each file already there is asked about as the job reaches it, and the
    /// answers do what they say: one file, every file, or every older file.
    #[test]
    fn files_in_the_way_are_asked_about_one_at_a_time() {
        use super::{Answer, Clashes};
        let dir = std::env::temp_dir().join(format!("fm84-clashes-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&dir);
        let then = |seconds: u64| std::time::SystemTime::UNIX_EPOCH + std::time::Duration::from_secs(seconds);
        let write = |path: &std::path::Path, text: &str, at: u64| {
            std::fs::write(path, text).unwrap();
            std::fs::File::options().write(true).open(path).unwrap().set_modified(then(at)).unwrap();
        };
        // A tree to copy, onto one holding the same names: some older than
        // what would replace them, one newer.
        let fresh = |name: &str| {
            let (from, onto) = (dir.join(name).join("from"), dir.join(name).join("onto"));
            std::fs::create_dir_all(&from).unwrap();
            std::fs::create_dir_all(&onto).unwrap();
            for file in ["a", "b", "c"] {
                write(&from.join(file), "new", 2_000_000_000);
                write(&onto.join(file), "old", if file == "c" { 2_100_000_000 } else { 1_000_000_000 });
            }
            write(&from.join("only-new"), "new", 2_000_000_000);
            (from, onto)
        };
        // Run a job to the end, answering by the name asked about. How many
        // questions there were, and what each file holds afterwards.
        let run = |clashes: Clashes, answer: &dyn Fn(&str) -> Answer, from: &std::path::Path, onto: &std::path::Path| {
            let mut app_state = AppState::new();
            app_state.start_transfer(vec![(from.to_path_buf(), onto.to_path_buf(), true)], true, clashes);
            let (mut asked, started) = (0, std::time::Instant::now());
            while let Some(job) = app_state.job.as_mut() {
                assert!(started.elapsed() < std::time::Duration::from_secs(10), "the job never finished");
                if let Some(clash) = &job.clash {
                    let name = clash.dest.file_name().unwrap().to_string_lossy().into_owned();
                    asked += 1;
                    job.answer(answer(&name));
                }
                std::thread::sleep(std::time::Duration::from_millis(2));
                app_state.poll_transfer();
            }
            let held: Vec<String> = ["a", "b", "c", "only-new"].iter().map(|file| std::fs::read_to_string(onto.join(file)).unwrap()).collect();
            (asked, held, app_state.error)
        };

        // One at a time: overwrite a, skip b, overwrite c. A file with nothing
        // in its way is never asked about.
        let (from, onto) = fresh("each");
        let (asked, held, said) = run(Clashes::Ask, &|name| if name == "b" { Answer::Skip } else { Answer::Overwrite }, &from, &onto);
        assert_eq!(asked, 3);
        assert_eq!(held, ["new", "old", "new", "new"]);
        assert_eq!(said.as_deref(), Some("Copy finished, 1 entry skipped"));

        // Overwrite all and skip all are asked once, and hold for the rest.
        let (from, onto) = fresh("all");
        let (asked, held, _) = run(Clashes::Ask, &|_| Answer::OverwriteAll, &from, &onto);
        assert_eq!((asked, held), (1, vec!["new".to_string(); 4]));
        let (from, onto) = fresh("none");
        let (asked, held, said) = run(Clashes::Ask, &|_| Answer::SkipAll, &from, &onto);
        assert_eq!((asked, held), (1, vec!["old".into(), "old".into(), "old".into(), "new".into()]));
        assert_eq!(said.as_deref(), Some("Copy finished, 3 entries skipped"));

        // Overwrite older: c is newer than what would replace it, and stays.
        let (from, onto) = fresh("older");
        let (asked, held, _) = run(Clashes::Ask, &|_| Answer::OverwriteOlder, &from, &onto);
        assert_eq!((asked, held), (1, vec!["new".into(), "new".into(), "old".into(), "new".into()]));

        // F11's Overwrite asks nothing at all.
        let (from, onto) = fresh("overwrite");
        let (asked, held, _) = run(Clashes::ReplaceAll, &|_| Answer::Abort, &from, &onto);
        assert_eq!((asked, held), (0, vec!["new".to_string(); 4]));

        std::fs::remove_dir_all(&dir).unwrap();
    }

    /// A directory that cannot be read is refused, and the panel stays where
    /// it was rather than moving there with nothing to show. The error is said
    /// once: the refresh does not raise it again after it is closed.
    #[cfg(unix)]
    #[test]
    fn an_unreadable_directory_is_refused_once() {
        use std::os::unix::fs::PermissionsExt;
        let dir = std::env::temp_dir().join(format!("fm84-unreadable-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&dir);
        let locked = dir.join("locked");
        std::fs::create_dir_all(&locked).unwrap();
        std::fs::write(dir.join("here.txt"), "").unwrap();
        std::fs::set_permissions(&locked, std::fs::Permissions::from_mode(0o000)).unwrap();
        // Root reads anything, so there is nothing to refuse.
        if std::fs::read_dir(&locked).is_ok() {
            std::fs::set_permissions(&locked, std::fs::Permissions::from_mode(0o755)).unwrap();
            return std::fs::remove_dir_all(&dir).unwrap();
        }

        let mut app_state = AppState::new();
        app_state.options = Options::default();
        // Watchers that look every few milliseconds, so the ticks the
        // refresh would answer come round inside the test.
        app_state.watch_interval = std::time::Duration::from_millis(5);
        app_state.open_dir(true, dir.clone(), None);
        let listed = app_state.children_left.len();

        app_state.open_dir(true, locked.clone(), None);
        assert!(app_state.error.is_some());
        assert_eq!(app_state.dir_left, dir);
        assert_eq!(app_state.children_left.len(), listed);

        // Closed, and a refresh comes round: it stays closed.
        app_state.reset_error();
        std::thread::sleep(std::time::Duration::from_millis(50));
        app_state.poll_watchers();
        app_state.refresh_stale_panels();
        assert!(app_state.error.is_none());

        // Gone unreadable while the panel is in it: said once, not every tick.
        app_state.open_dir(true, locked.parent().unwrap().to_path_buf(), None);
        std::fs::set_permissions(&locked, std::fs::Permissions::from_mode(0o755)).unwrap();
        app_state.open_dir(true, locked.clone(), None);
        std::fs::set_permissions(&locked, std::fs::Permissions::from_mode(0o000)).unwrap();
        app_state.reload_panel(true, None);
        assert!(app_state.error.is_some());
        app_state.reset_error();
        std::thread::sleep(std::time::Duration::from_millis(50));
        app_state.poll_watchers();
        app_state.refresh_stale_panels();
        assert!(app_state.error.is_none());

        std::fs::set_permissions(&locked, std::fs::Permissions::from_mode(0o755)).unwrap();
        std::fs::remove_dir_all(&dir).unwrap();
    }

    #[test]
    fn ctrl_arrows_send_the_entry_under_the_cursor_to_a_panel() {
        let dir = std::env::temp_dir().join(format!("fm84-open-in-panel-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&dir);
        std::fs::create_dir_all(dir.join("inner")).unwrap();
        std::fs::write(dir.join("note.txt"), "").unwrap();

        let mut app_state = AppState::new();
        app_state.options = Options::default();
        app_state.open_dir(true, dir.clone(), None);
        app_state.open_dir(false, std::env::temp_dir(), None);
        app_state.is_left_active = true;
        let at = |app_state: &AppState, name: &str| app_state.children_left.iter().position(|item| item.name_full == name);
        let cursor_right = |app_state: &AppState| app_state.state_right.selected().and_then(|index| app_state.children_right.get(index)).map(|item| item.name_full.clone());

        // A directory: the other panel goes into it, and the focus stays.
        app_state.state_left.select(at(&app_state, "inner"));
        app_state.open_in_panel(false);
        assert_eq!(app_state.dir_right, dir.join("inner"));
        assert!(app_state.is_left_active);
        assert_eq!(app_state.dir_left, dir);

        // A file: the directory it is in, on the file.
        app_state.state_left.select(at(&app_state, "note.txt"));
        app_state.open_in_panel(false);
        assert_eq!(app_state.dir_right, dir);
        assert_eq!(cursor_right(&app_state).as_deref(), Some("note.txt"));

        // The parent entry: the parent, on the directory left.
        app_state.state_left.select(at(&app_state, ".."));
        app_state.open_in_panel(false);
        assert_eq!(app_state.dir_right, std::env::temp_dir());
        assert_eq!(cursor_right(&app_state), dir.file_name().map(|name| name.to_string_lossy().into_owned()));

        // Pointed at the active panel, it goes in there.
        app_state.state_left.select(at(&app_state, "inner"));
        app_state.open_in_panel(true);
        assert_eq!(app_state.dir_left, dir.join("inner"));

        std::fs::remove_dir_all(&dir).unwrap();
    }

    fn row(name: &str) -> Item {
        Item {
            name_os: name.into(),
            name_full: name.to_string(),
            name: name.to_string(),
            extension: String::new(),
            is_dir: false,
            size: String::new(),
            size_bytes: 0,
            modified_at: None,
            attributes: String::new(),
        }
    }

    #[test]
    fn plus_minus_and_star_select_by_pattern() {
        let mut app_state = AppState::new();
        app_state.is_left_active = true;
        let directory = Item { is_dir: true, ..row("photos") };
        app_state.children_left = vec![row(".."), directory, row("a.jpg"), row("B.JPG"), row("c.png"), row("notes.txt")];
        let selected = |app_state: &AppState| {
            let mut names: Vec<String> = app_state.selected_left.iter().map(|name| name.to_string_lossy().into_owned()).collect();
            names.sort();
            names
        };

        // Through the prompt, as + then typing then Enter does.
        app_state.open_select_prompt(true);
        app_state.dialog_input().unwrap().set("*.jpg;*.png".to_string());
        app_state.confirm_prompt();
        assert_eq!(selected(&app_state), ["B.JPG", "a.jpg", "c.png"]);
        assert_eq!(app_state.select_pattern, "*.jpg;*.png");

        app_state.open_select_prompt(false);
        app_state.dialog_input().unwrap().set("?.png".to_string());
        app_state.confirm_prompt();
        assert_eq!(selected(&app_state), ["B.JPG", "a.jpg"]);

        // Files are inverted; the directory and .. are left alone.
        app_state.invert_selection(false);
        assert_eq!(selected(&app_state), ["c.png", "notes.txt"]);
        // Unless directories are asked for too.
        app_state.invert_selection(true);
        assert_eq!(selected(&app_state), ["B.JPG", "a.jpg", "photos"]);
        app_state.invert_selection(true);
        assert_eq!(selected(&app_state), ["c.png", "notes.txt"]);

        // * takes files only, */ the directories.
        app_state.select_by(&crate::glob::Glob::new("*").unwrap(), true);
        assert_eq!(selected(&app_state), ["B.JPG", "a.jpg", "c.png", "notes.txt"]);
        app_state.select_by(&crate::glob::Glob::new("*/").unwrap(), true);
        assert_eq!(selected(&app_state), ["B.JPG", "a.jpg", "c.png", "notes.txt", "photos"]);

        // An empty pattern does nothing and is not kept.
        app_state.open_select_prompt(false);
        app_state.dialog_input().unwrap().set(String::new());
        app_state.confirm_prompt();
        assert_eq!(selected(&app_state).len(), 5);
        assert_eq!(app_state.select_pattern, "?.png");
    }

    #[test]
    fn a_selection_outlives_a_re_sort_but_not_its_file() {
        let mut selected: HashSet<std::ffi::OsString> = ["one.txt", "two.txt"].iter().map(|name| name.into()).collect();

        // Re-sorted, renumbered: both files are still there, so both stay
        // selected. This is what keying by name rather than row is for.
        prune_selection(&mut selected, &[row("zzz.txt"), row("two.txt"), row("one.txt")]);
        assert_eq!(selected.len(), 2);

        // one.txt is gone, so its selection goes with it.
        prune_selection(&mut selected, &[row("renamed.txt"), row("two.txt")]);
        assert_eq!(selected.iter().collect::<Vec<_>>(), ["two.txt"]);

        // And it does not come back when something else takes the name, which
        // would otherwise put a file the user never picked into the next delete.
        prune_selection(&mut selected, &[row("one.txt"), row("two.txt")]);
        assert_eq!(selected.iter().collect::<Vec<_>>(), ["two.txt"]);

        // An empty directory clears the lot.
        prune_selection(&mut selected, &[]);
        assert!(selected.is_empty());
    }

    /// Two names that are not valid UTF-8 can read the same once made
    /// printable. Selecting one must not select the other, or the next delete
    /// takes a file nobody picked.
    #[cfg(unix)]
    #[test]
    fn names_that_read_alike_are_selected_apart() {
        use std::os::unix::ffi::OsStrExt;

        let dir = std::env::temp_dir().join(format!("fm84-alike-{}", std::process::id()));
        std::fs::create_dir_all(&dir).unwrap();
        for raw in [&b"a\xfe"[..], &b"a\xff"[..]] {
            std::fs::write(dir.join(std::ffi::OsStr::from_bytes(raw)), "").unwrap();
        }

        let mut app_state = AppState::new();
        app_state.options = Options::default();
        app_state.open_dir(true, dir.clone(), None);
        let rows: Vec<Item> = app_state.children_left.iter().filter(|item| item.name != "..").cloned().collect();
        assert_eq!(rows.len(), 2);
        assert_eq!(rows[0].name_full, rows[1].name_full);

        let index = app_state.children_left.iter().position(|row| row.name_os == rows[0].name_os).unwrap();
        app_state.state_left.select(Some(index));
        app_state.toggle_selection_no_size();
        assert_eq!(app_state.selected_left.iter().collect::<Vec<_>>(), [&rows[0].name_os]);

        std::fs::remove_dir_all(&dir).unwrap();
    }

    #[test]
    fn tabs_keep_where_each_was_left() {
        let dir = std::env::temp_dir().join(format!("fm84-tabs-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&dir);
        std::fs::create_dir_all(dir.join("inner")).unwrap();
        for name in ["one.txt", "two.txt"] {
            std::fs::write(dir.join(name), "").unwrap();
            std::fs::write(dir.join("inner").join(name), "").unwrap();
        }

        let mut app_state = AppState::new();
        app_state.options = Options::default();
        app_state.is_left_active = true;
        app_state.open_dir(true, dir.clone(), None);
        let at = |app_state: &AppState, name: &str| app_state.children_left.iter().position(|item| item.name_full == name);
        let cursor = |app_state: &AppState| app_state.state_left.selected().and_then(|index| app_state.children_left.get(index)).map(|item| item.name_full.clone());

        // Something selected and the cursor on two.txt in the first tab.
        app_state.selected_left.insert("one.txt".into());
        app_state.state_left.select(at(&app_state, "two.txt"));

        // A new tab: same place, nothing selected, and the first keeps its own.
        app_state.new_tab();
        assert_eq!((app_state.tabs_left.list.len(), app_state.tabs_left.active), (2, 1));
        assert_eq!(app_state.dir_left, dir);
        assert!(app_state.selected_left.is_empty());
        assert_eq!(cursor(&app_state).as_deref(), Some("two.txt"));

        // Off somewhere else in the second tab.
        app_state.open_dir(true, dir.join("inner"), None);
        app_state.selected_left.insert("two.txt".into());
        assert_eq!(app_state.tab_dirs(true), (vec![dir.clone(), dir.join("inner")], 1));

        // Back to the first: its directory, cursor and selection.
        app_state.select_tab(true, 0);
        assert_eq!(app_state.dir_left, dir);
        assert_eq!(cursor(&app_state).as_deref(), Some("two.txt"));
        assert_eq!(app_state.selected_left.iter().collect::<Vec<_>>(), [&std::ffi::OsString::from("one.txt")]);

        // Round to the second, and its own come back.
        app_state.cycle_tab(true);
        assert_eq!(app_state.dir_left, dir.join("inner"));
        assert_eq!(app_state.selected_left.iter().collect::<Vec<_>>(), [&std::ffi::OsString::from("two.txt")]);
        app_state.cycle_tab(true);
        assert_eq!(app_state.tabs_left.active, 0);

        // Closing one not shown leaves the panel be and keeps the right one active.
        app_state.select_tab(true, 1);
        app_state.close_tab(true, 0);
        assert_eq!((app_state.tabs_left.list.len(), app_state.tabs_left.active), (1, 0));
        assert_eq!(app_state.dir_left, dir.join("inner"));

        // The last one stays.
        app_state.close_tab(true, 0);
        assert_eq!(app_state.tabs_left.list.len(), 1);

        // Closing the one shown moves to its neighbour.
        app_state.new_tab();
        app_state.open_dir(true, dir.clone(), None);
        app_state.close_tab(true, 1);
        assert_eq!(app_state.dir_left, dir.join("inner"));
        // The other panel's tabs are its own.
        assert_eq!(app_state.tabs_right.list.len(), 1);

        std::fs::remove_dir_all(&dir).unwrap();
    }

    /// A tab whose directory has gone unreadable is refused: the panel, its
    /// tabs and its selection stay as they were, rather than the panel staying
    /// put under the other tab's name and taking that tab over.
    #[cfg(unix)]
    #[test]
    fn a_tab_that_cannot_be_read_is_refused_and_kept() {
        use std::os::unix::fs::PermissionsExt;
        let dir = std::env::temp_dir().join(format!("fm84-tab-locked-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&dir);
        let locked = dir.join("locked");
        std::fs::create_dir_all(&locked).unwrap();
        std::fs::write(dir.join("here.txt"), "").unwrap();

        let mut app_state = AppState::new();
        app_state.options = Options::default();
        app_state.is_left_active = true;
        app_state.open_dir(true, dir.clone(), None);
        app_state.new_tab();
        app_state.open_dir(true, locked.clone(), None);
        app_state.select_tab(true, 0);
        app_state.selected_left.insert("here.txt".into());

        std::fs::set_permissions(&locked, std::fs::Permissions::from_mode(0o000)).unwrap();
        // Root reads anything, so there is nothing to refuse.
        if std::fs::read_dir(&locked).is_ok() {
            std::fs::set_permissions(&locked, std::fs::Permissions::from_mode(0o755)).unwrap();
            return std::fs::remove_dir_all(&dir).unwrap();
        }

        app_state.select_tab(true, 1);
        assert!(app_state.error.is_some());
        assert_eq!(app_state.tabs_left.active, 0);
        assert_eq!(app_state.dir_left, dir);
        assert_eq!(app_state.selected_left.len(), 1);
        assert_eq!(app_state.tab_dirs(true), (vec![dir.clone(), locked.clone()], 0));

        // Closing the tab shown would move to the locked one, so it stays too.
        app_state.reset_error();
        app_state.close_tab(true, 0);
        assert!(app_state.error.is_some());
        assert_eq!(app_state.tab_dirs(true), (vec![dir.clone(), locked.clone()], 0));
        assert_eq!(app_state.selected_left.len(), 1);

        std::fs::set_permissions(&locked, std::fs::Permissions::from_mode(0o755)).unwrap();
        std::fs::remove_dir_all(&dir).unwrap();
    }

    /// A directory that has not answered yet leaves the panel where it was,
    /// busy, with nothing on it acting on the rows about to be replaced; it
    /// is taken in when it lands. Built by hand, so the test decides when.
    #[test]
    fn a_slow_directory_leaves_the_panel_as_it_was_until_it_lands() {
        let dir = std::env::temp_dir().join(format!("fm84-slow-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&dir);
        std::fs::create_dir_all(dir.join("far")).unwrap();
        std::fs::write(dir.join("far").join("there.txt"), "").unwrap();

        let mut app_state = AppState::new();
        app_state.is_left_active = true;
        app_state.open_dir(true, dir.clone(), None);
        let listed = app_state.children_left.len();

        let (sender, answer) = std::sync::mpsc::channel();
        app_state.listing_left = Some(super::PendingListing {
            dir: dir.join("far"),
            navigate: true,
            select: None,
            tab: None,
            answer,
        });
        assert!(app_state.panel_busy(true));
        // The panel is as it was, and its tabs cannot be touched.
        app_state.new_tab();
        assert_eq!(app_state.tabs_left.list.len(), 1);
        assert_eq!((app_state.dir_left.clone(), app_state.children_left.len()), (dir.clone(), listed));
        // Nor does a reread of where it was get in the way of where it is going.
        app_state.reload_panel(true, None);
        assert!(app_state.listing_left.as_ref().is_some_and(|pending| pending.dir == dir.join("far")));
        app_state.poll_listings();
        assert!(app_state.panel_busy(true), "nothing has landed yet");

        sender.send(super::read_listing(&dir.join("far"), &app_state.options)).unwrap();
        app_state.poll_listings();
        assert!(!app_state.panel_busy(true));
        assert_eq!(app_state.dir_left, dir.join("far"));
        assert!(app_state.children_left.iter().any(|item| item.name_full == "there.txt"));
        std::fs::remove_dir_all(&dir).unwrap();
    }

    /// A tab switched to whose directory turns out, late, to be unreadable is
    /// switched back - as it is when Esc stops waiting for it.
    #[test]
    fn a_late_refusal_or_esc_puts_the_tab_back() {
        let dir = std::env::temp_dir().join(format!("fm84-late-tab-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&dir);
        std::fs::create_dir_all(&dir).unwrap();

        let mut app_state = AppState::new();
        app_state.open_dir(true, dir.clone(), None);
        app_state.tabs_left = super::Tabs::new(vec![dir.clone(), dir.join("locked")], 0);

        for refused in [true, false] {
            let (sender, answer) = std::sync::mpsc::channel();
            app_state.tabs_left.active = 1;
            let tab = super::TabSwitch {
                selected: HashSet::new(),
                undo: super::TabUndo::Active(0),
            };
            app_state.listing_left = Some(super::PendingListing {
                dir: dir.join("locked"),
                navigate: true,
                select: None,
                tab: Some(tab),
                answer,
            });
            if refused {
                let denied = std::io::Error::from(std::io::ErrorKind::PermissionDenied);
                sender
                    .send(super::Listed {
                        dir: Some(dir.join("locked")),
                        items: Err(denied),
                        stamp: None,
                        disk: None,
                    })
                    .unwrap();
                app_state.poll_listings();
                assert!(app_state.error.is_some());
                app_state.reset_error();
            } else {
                app_state.cancel_listing(true);
            }
            assert!(!app_state.panel_busy(true));
            assert_eq!(app_state.tabs_left.active, 0);
            assert_eq!(app_state.dir_left, dir);
        }
        std::fs::remove_dir_all(&dir).unwrap();
    }

    /// The watcher sees a directory change and the panel reads it again; the
    /// detail lines and the preview arrive from their threads, the name first.
    #[test]
    fn changes_and_details_arrive_from_their_threads() {
        let dir = std::env::temp_dir().join(format!("fm84-watched-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&dir);
        std::fs::create_dir_all(&dir).unwrap();
        std::fs::write(dir.join("notes.txt"), "hello").unwrap();

        let mut app_state = AppState::new();
        app_state.watch_interval = std::time::Duration::from_millis(5);
        app_state.open_dir(true, dir.clone(), Some("notes.txt".as_ref()));

        // Made behind fm84's back, and found without anything being pressed.
        std::fs::write(dir.join("new.txt"), "").unwrap();
        let started = std::time::Instant::now();
        while !app_state.children_left.iter().any(|item| item.name_full == "new.txt") {
            assert!(started.elapsed() < std::time::Duration::from_secs(10), "the change was never seen");
            std::thread::sleep(std::time::Duration::from_millis(5));
            app_state.poll_watchers();
            app_state.refresh_stale_panels();
        }

        // Without waiting on them: the name at once, the rest when it comes.
        app_state.detail_wait = std::time::Duration::ZERO;
        app_state.show_preview = true;
        let at = app_state.children_left.iter().position(|item| item.name_full == "notes.txt");
        app_state.state_left.select(at);
        app_state.cursor_detail = None;
        app_state.refresh_cursor_detail();
        assert_eq!(app_state.cursor_detail.as_ref().unwrap().name, "notes.txt");
        let started = std::time::Instant::now();
        loop {
            app_state.refresh_cursor_detail();
            app_state.refresh_preview();
            let detail = app_state.cursor_detail.as_ref().unwrap();
            let preview = app_state.preview.as_ref().unwrap();
            if !detail.awaiting && !preview.awaiting {
                assert_eq!(detail.size, "5 bytes");
                assert_eq!(preview.lines, ["hello"]);
                break;
            }
            assert!(started.elapsed() < std::time::Duration::from_secs(10), "the details never came");
            std::thread::sleep(std::time::Duration::from_millis(5));
        }
        std::fs::remove_dir_all(&dir).unwrap();
    }

    #[test]
    fn a_click_lands_on_the_icon_it_looks_like() {
        // Seven icons, each a glyph and the space after it, past the space the
        // strip opens with - the layout drive_strip actually produces.
        let slots: Vec<(u16, u16)> = (0..7).map(|i| (1 + i * 2, 2)).collect();

        assert_eq!(slot_at(&slots, 0), None); // the opening space
        assert_eq!(slot_at(&slots, 1), Some(0)); // first glyph
        assert_eq!(slot_at(&slots, 2), Some(0)); // the space that goes with it
        assert_eq!(slot_at(&slots, 3), Some(1));
        assert_eq!(slot_at(&slots, 13), Some(6)); // last icon
        assert_eq!(slot_at(&slots, 14), Some(6));
        assert_eq!(slot_at(&slots, 15), None); // past the end, where the label goes
        assert_eq!(slot_at(&slots, 200), None);

        // Every column of every slot maps back to that slot, and they never
        // overlap - a gap or an overlap here is a click landing one icon over.
        for (index, &(start, width)) in slots.iter().enumerate() {
            for offset in start..start + width {
                assert_eq!(slot_at(&slots, offset), Some(index), "offset {offset}");
            }
        }

        assert_eq!(slot_at(&[], 1), None);
    }

    #[test]
    fn a_drawing_smaller_than_the_pane_has_no_offset() {
        // The renderer centres it, so scrolling would only push it off-screen.
        // Zooming back in from below 100% used to land here at the far end.
        assert_eq!(recentre(0, 33, 7, 15), 0);
        assert_eq!(recentre(0, 33, 15, 22), 0);
        assert_eq!(recentre(0, 33, 30, 33), 0);
        // Nothing drawn yet.
        assert_eq!(recentre(0, 33, 0, 45), 0);
    }

    #[test]
    fn growing_past_the_pane_centres_what_was_centred() {
        // A 30-row drawing in a 33-row pane was centred, so 45 rows should be
        // centred too: (45 - 33) / 2.
        assert_eq!(recentre(0, 33, 30, 45), 6);
        assert_eq!(recentre(0, 33, 30, 60), 14);
    }

    #[test]
    fn an_overflowing_drawing_keeps_the_middle_of_the_pane() {
        // Centred at 45 rows, still centred at 60.
        assert_eq!(recentre(6, 33, 45, 60), 14);
        // It is the middle of the pane that is held, not the edges: the pane
        // covers less of the bigger drawing, so a view at the top or the bottom
        // moves inwards rather than staying pinned there.
        assert_eq!(recentre(0, 33, 45, 60), 6);
        assert_eq!(recentre(12, 33, 45, 60), 22);
    }

    #[test]
    fn the_offset_never_runs_past_the_end() {
        for before in [1usize, 7, 30, 45, 200] {
            for after in [1usize, 7, 30, 45, 200] {
                for offset in [0, 5, 100] {
                    let landed = recentre(offset, 33, before, after);
                    assert!(landed <= after.saturating_sub(33), "{before}->{after} from {offset}: {landed}");
                }
            }
        }
    }
}