mouser-commander 0.1.5

Mouser's commander mode as a plugin: the shell's folder above the prompt, with previews and the media player
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
//! The commander mode plugin: the model is `crate::commander`; this
//! builds its view (list, grid, carousel, file view) and loads previews.
//!
//! Previews load lazily on a worker thread: only what is on screen is
//! requested (grid: the visible tiles; carousel: the focused item and its
//! two neighbours), and anything that scrolls away is dropped from the queue.

use crate::commander::{self as cmdr, Action, Commander, Entry, Kind, Overlay, Sort, TILE_SIZES, View as Layout};
use crate::fetch;
use crate::host::{Context, Effect, Mode, ModeImage, PADDING, Panel, PanelItem, PanelStyle, Rect, UiAction, View, Waker, fit};
use crate::modes::{Binding, Keymap};
use mouser_mode_api::markdown as md;
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, Condvar, Mutex};

pub use mouser_media::anim::FsAnim;
pub use mouser_views::anim::Slide;
pub use mouser_views::geom::{inside, intersect, overlaps, unpack_xy};
pub use mouser_views::text::{clip_text, header_fit, path_segments, range_label};
pub use mouser_views::zoom::{Zoom, contain_scale, fit_scale, zoom_about, zoom_rect};
#[cfg(test)]
use {mouser_media::anim::lerp_rect, mouser_views::geom::pack_xy};

#[derive(Clone)]
struct Thumb {
    key: u64,
    rgba: Arc<Vec<u8>>,
    w: u32,
    h: u32,
}

type Want = (PathBuf, u32);
/// Options button: label, on, action id, arg.
type Btn<'a> = (String, bool, &'a str, i32);

#[derive(Default)]
struct Shared {
    want: Vec<Want>,
    /// `None`: could not be decoded.
    done: HashMap<Want, Option<Thumb>>,
    waker: Option<Waker>,
    quit: bool,
    /// Decodes done (tests).
    decoded: Vec<Want>,
    /// Being decoded.
    busy: Vec<Want>,
    /// Remote listing: paths are on this host (size, mtime per path).
    remote: Option<RemoteCtx>,
}

/// What the preview workers need to fetch remote files.
#[derive(Clone)]
pub struct RemoteCtx {
    pub remote: fetch::Remote,
    pub meta: Arc<HashMap<PathBuf, (u64, i64)>>,
}

impl RemoteCtx {
    pub fn file(&self, p: &Path) -> Option<fetch::RemoteFile> {
        let &(size, mtime) = self.meta.get(p)?;
        Some(fetch::RemoteFile { remote: self.remote.clone(), path: p.to_path_buf(), size, mtime })
    }
}

/// Preview workers (each remote one may be fetching a file).
const WORKERS: usize = fetch::CONCURRENT_FILES;

/// The preview loader.
#[derive(Default)]
pub struct Previews {
    s: Arc<(Mutex<Shared>, Condvar)>,
    started: bool,
}

/// Texture keys apart from the terminal's image ids.
static NEXT_KEY: AtomicU64 = AtomicU64::new(1 << 62);

impl Previews {
    /// Load exactly these (path, longest side) now; everything else queued
    /// before is dropped.
    pub fn want(&mut self, list: Vec<Want>) {
        let (m, cv) = &*self.s;
        let mut s = m.lock().unwrap();
        if s.want == list {
            return;
        }
        // Keep a few recent ones so scrolling back is instant. Also keep other
        // sizes of a path still on screen: grid tiles and the carousel use
        // different longest-sides, and the smaller thumb covers the kind-label
        // placeholder while the larger one decodes.
        if s.done.len() > 48 {
            s.done.retain(|k, _| list.contains(k) || list.iter().any(|w| w.0 == k.0));
        }
        s.want = list;
        drop(s);
        cv.notify_all();
        if !self.started {
            self.started = true;
            for _ in 0..WORKERS {
                let s = self.s.clone();
                let _ = std::thread::Builder::new().name("commander-previews".into()).spawn(move || worker(&s));
            }
        }
    }

    /// Remote listing context (`None`: local files).
    pub fn set_remote(&self, r: Option<RemoteCtx>) {
        let mut s = self.s.0.lock().unwrap();
        if s.remote.as_ref().map(|r| (&r.remote, r.meta.clone())) != r.as_ref().map(|r| (&r.remote, r.meta.clone())) {
            s.remote = r;
            s.done.clear();
        }
    }

    fn get(&self, w: &Want) -> Option<Option<Thumb>> {
        let s = self.s.0.lock().unwrap();
        if let Some(t) = s.done.get(w) {
            return Some(t.clone());
        }
        // Same file, another size: show it instead of the "image" / "▶ video"
        // placeholder while this size decodes (grid → carousel, slide-in).
        s.done.iter().find(|(k, v)| k.0 == w.0 && v.is_some()).map(|(_, t)| t.clone())
    }

    pub fn set_waker(&self, w: Waker) {
        self.s.0.lock().unwrap().waker = Some(w);
    }

    /// Everything decoded so far, in order (tests).
    pub fn decoded(&self) -> Vec<Want> {
        self.s.0.lock().unwrap().decoded.clone()
    }
}

impl Drop for Previews {
    fn drop(&mut self) {
        self.s.0.lock().unwrap().quit = true;
        self.s.1.notify_all();
    }
}

fn worker(s: &(Mutex<Shared>, Condvar)) {
    let (m, cv) = s;
    loop {
        let job = {
            let mut g = m.lock().unwrap();
            loop {
                if g.quit {
                    return;
                }
                if let Some(w) = g.want.iter().find(|w| !g.done.contains_key(*w) && !g.busy.contains(w)).cloned() {
                    g.busy.push(w.clone());
                    break (w, g.remote.clone());
                }
                g = cv.wait(g).unwrap();
            }
        };
        let (job, remote) = job;
        let thumb = match remote.as_ref().and_then(|r| r.file(&job.0)) {
            Some(f) => {
                // A low-resolution first look while the rest is fetched.
                let early = |img: image::DynamicImage| {
                    let t = to_thumb(img, job.1);
                    let mut g = m.lock().unwrap();
                    g.done.insert(job.clone(), Some(t));
                    if let Some(w) = g.waker.clone() {
                        drop(g);
                        w();
                    }
                };
                let cancel = || {
                    let g = m.lock().unwrap();
                    g.quit || !g.want.contains(&job)
                };
                let had = m.lock().unwrap().done.get(&job).cloned().flatten();
                decode_remote(&f, job.1, &early, &cancel).map(|i| to_thumb(i, job.1)).or(had)
            }
            None => decode(&job.0, job.1),
        };
        let mut g = m.lock().unwrap();
        g.busy.retain(|w| *w != job);
        // Still the same listing (local / remote)?
        if g.remote.as_ref().map(|r| r.remote.clone()) != remote.map(|r| r.remote) {
            continue;
        }
        let thumb = thumb.or_else(|| g.done.get(&job).cloned().flatten());
        g.decoded.push(job.clone());
        g.done.insert(job, thumb);
        if let Some(w) = g.waker.clone() {
            drop(g);
            w();
        }
    }
}

fn decode(p: &Path, max: u32) -> Option<Thumb> {
    let img = if cmdr::kind_of(&p.to_string_lossy()) == Kind::Video {
        video_thumb(p, max)?
    } else {
        image::ImageReader::open(p).ok()?.with_guessed_format().ok()?.decode().ok()?
    };
    Some(to_thumb(img, max))
}

fn to_thumb(img: image::DynamicImage, max: u32) -> Thumb {
    let img = if img.width() > max || img.height() > max { img.thumbnail(max, max) } else { img };
    let rgba = img.to_rgba8();
    Thumb { key: NEXT_KEY.fetch_add(1, Ordering::Relaxed), w: rgba.width(), h: rgba.height(), rgba: Arc::new(rgba.into_raw()) }
}

/// Largest remote file fetched whole just for a tile.
const TILE_FETCH_MAX: u64 = 64 << 20;

/// Cached thumbnail of a remote file (key: host, path, size, mtime) at `max`.
fn remote_thumb_path(f: &fetch::RemoteFile, max: u32) -> PathBuf {
    crate::storage::resolve_home().join("cache/thumbs").join(format!("r{}-{max}.png", f.key()))
}

/// A frame (video: at 10 % of the duration, at most 30 s) scaled to `max`,
/// made by the host's ffmpeg: only the PNG comes over the wire.
fn remote_ffmpeg_png(f: &fetch::RemoteFile, max: u32) -> Option<Vec<u8>> {
    let q = cmdr::shell_quote(&f.path.to_string_lossy());
    let scale = format!("scale=w={max}:h={max}:force_original_aspect_ratio=decrease");
    let cmd = if cmdr::kind_of(&f.path.to_string_lossy()) == Kind::Video {
        format!(
            "d=$(ffprobe -v error -show_entries format=duration -of csv=p=0 {q} 2>/dev/null); \
             t=$(awk -v d=\"$d\" 'BEGIN{{t=d*0.1; if(t>30)t=30; if(t<=0)t=1; printf \"%.3f\", t}}'); \
             ffmpeg -v error -nostdin -ss \"$t\" -i {q} -frames:v 1 -vf {scale} -f image2pipe -c:v png pipe:1 || \
             ffmpeg -v error -nostdin -i {q} -frames:v 1 -vf {scale} -f image2pipe -c:v png pipe:1"
        )
    } else {
        format!("ffmpeg -v error -nostdin -i {q} -frames:v 1 -vf {scale} -f image2pipe -c:v png pipe:1")
    };
    f.remote.run(&cmd).ok().filter(|v| v.starts_with(b"\x89PNG"))
}

fn save_thumb(path: &Path, png: &[u8]) {
    if let Some(d) = path.parent() {
        let _ = std::fs::create_dir_all(d);
    }
    let _ = std::fs::write(path, png);
}

/// A remote file's preview: cached thumbnails first; tiles from the host's
/// ffmpeg when it has one (else a fetch: whole image, or ranged reads of a
/// video through the local ffmpeg); the viewer gets a quick low-resolution
/// look (`early`) and then the full image once fetched.
fn decode_remote(f: &fetch::RemoteFile, max: u32, early: &dyn Fn(image::DynamicImage), cancel: &dyn Fn() -> bool) -> Option<image::DynamicImage> {
    let tp = remote_thumb_path(f, max.min(1024));
    let kind = cmdr::kind_of(&f.path.to_string_lossy());
    let cached = || image::open(&tp).ok();
    let tools = f.remote.tools();
    let small = |m: u32| -> Option<image::DynamicImage> {
        let tp = remote_thumb_path(f, m);
        if let Ok(i) = image::open(&tp) {
            return Some(i);
        }
        let png = remote_ffmpeg_png(f, m)?;
        save_thumb(&tp, &png);
        image::load_from_memory(&png).ok()
    };
    let whole = || -> Option<image::DynamicImage> {
        let h = fetch::open(f, None);
        if !h.wait(0, f.size, std::time::Duration::from_secs(600), cancel) {
            return None;
        }
        image::ImageReader::open(h.cache_path()).ok()?.with_guessed_format().ok()?.decode().ok()
    };
    match kind {
        Kind::Video => {
            if let Some(i) = cached() {
                return Some(i);
            }
            if tools.ffmpeg {
                return small(max.min(1024));
            }
            let h = fetch::open(f, Some(fetch::HEAD));
            let url = h.url();
            let png = ffmpeg_frame(Path::new(&url), max.min(1024))?;
            save_thumb(&tp, &png);
            image::load_from_memory(&png).ok()
        }
        Kind::Image if max <= 1024 => {
            if let Some(i) = cached() {
                return Some(i);
            }
            if tools.ffmpeg
                && let Some(i) = small(max)
            {
                return Some(i);
            }
            if f.size > TILE_FETCH_MAX {
                return None;
            }
            let i = whole()?;
            let mut png = Vec::new();
            if i.thumbnail(max, max).write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).is_ok() {
                save_thumb(&tp, &png);
            }
            Some(i)
        }
        Kind::Image => {
            let first = image::open(remote_thumb_path(f, 1024)).ok().or_else(|| if tools.ffmpeg { small(1024) } else { None });
            if let Some(i) = first.clone() {
                early(i);
            }
            whole().or(first)
        }
        _ => None,
    }
}

/// One frame of `input` (a path or URL ffmpeg reads) at 10 % in, as PNG.
fn ffmpeg_frame(input: &Path, max: u32) -> Option<Vec<u8>> {
    let dur = crate::player::probe(input).map(|i| i.duration).unwrap_or(0.0);
    let at = if dur > 0.0 { (dur * 0.1).min(30.0) } else { 1.0 };
    let scale = format!("scale='if(gt(iw,ih),{max},-2)':'if(gt(iw,ih),-2,{max})'");
    let run = |t: f64| {
        crate::process::command("ffmpeg")
            .args(["-v", "error", "-nostdin", "-ss", &format!("{t:.3}"), "-i"])
            .arg(input)
            .args(["-frames:v", "1", "-vf", &scale, "-f", "image2pipe", "-c:v", "png", "pipe:1"])
            .stdin(std::process::Stdio::null())
            .stderr(std::process::Stdio::null())
            .output()
            .ok()
            .filter(|o| o.status.success() && !o.stdout.is_empty())
    };
    Some(run(at).or_else(|| run(0.0))?.stdout)
}

/// Where a video's thumbnail is cached: `$MOUSER_HOME/cache/thumbs/<hash>.png`,
/// the hash over path, mtime, size and the requested size (a changed file
/// gets a new entry).
pub fn thumb_cache_path(p: &Path, max: u32) -> Option<PathBuf> {
    use std::hash::{Hash, Hasher};
    let m = std::fs::metadata(p).ok()?;
    let mut h = std::collections::hash_map::DefaultHasher::new();
    (p, m.modified().ok(), m.len(), max).hash(&mut h);
    Some(crate::storage::resolve_home().join("cache/thumbs").join(format!("{:016x}.png", h.finish())))
}

/// A representative frame: at 10 % of the duration (at most 30 s in, 1 s for
/// clips without a duration), scaled so the longest side is `max`. Cached on
/// disk; `None` without ffmpeg or for files it cannot read.
fn video_thumb(p: &Path, max: u32) -> Option<image::DynamicImage> {
    let cache = thumb_cache_path(p, max);
    if let Some(c) = &cache
        && let Ok(i) = image::open(c)
    {
        return Some(i);
    }
    let dur = crate::player::probe(p).map(|i| i.duration).unwrap_or(0.0);
    let at = if dur > 0.0 { (dur * 0.1).min(30.0) } else { 1.0 };
    let scale = format!("scale='if(gt(iw,ih),{max},-2)':'if(gt(iw,ih),-2,{max})'");
    let run = |t: f64| {
        crate::process::command("ffmpeg")
            .args(["-v", "error", "-nostdin", "-ss", &format!("{t:.3}"), "-i"])
            .arg(p)
            .args(["-frames:v", "1", "-vf", &scale, "-f", "image2pipe", "-c:v", "png", "pipe:1"])
            .stdin(std::process::Stdio::null())
            .stderr(std::process::Stdio::null())
            .output()
            .ok()
            .filter(|o| o.status.success() && !o.stdout.is_empty())
    };
    let out = run(at).or_else(|| run(0.0))?;
    let img = image::load_from_memory(&out.stdout).ok()?;
    if let Some(c) = &cache {
        let _ = std::fs::create_dir_all(c.parent()?);
        let _ = std::fs::write(c, &out.stdout);
    }
    Some(img)
}

/// What a tile shows while its preview loads or when there is none.
fn kind_label(k: Kind) -> &'static str {
    match k {
        Kind::Dir => "folder",
        Kind::Video => "▶ video",
        Kind::Audio => "♪ audio",
        Kind::Image => "image",
        _ => "file",
    }
}

pub struct CommanderMode {
    pub c: Commander,
    per_row: usize,
    previews: Previews,
    /// First lines of text files on screen.
    texts: HashMap<PathBuf, Vec<String>>,
    /// The file view's text.
    full_text: Option<(PathBuf, Vec<String>, Option<String>)>,
    /// Last click (item, when) for double-click.
    last_click: Option<(usize, std::time::Instant)>,
    /// The media player while a video or audio file is open.
    pub player: Option<crate::player::Player>,
    waker: Option<Waker>,
    /// Width of the view's body (the player decodes to it).
    body_w: i32,
    /// The player's key hints, from the current keymap.
    player_keys: String,
    slide: Slide,
    /// Image view zoom (None: fit).
    zoom: Option<Zoom>,
    /// Natural size of the image in the file view.
    nat: Option<(PathBuf, (u32, u32))>,
    /// Last pointer position over the view (window px).
    pointer: (i32, i32),
    press: Option<Press>,
    hits: Hits,
    /// Header overflow (•••) dropdown open.
    menu_open: bool,
    /// `x–y of N` for the list / grid, shown at the right of the search row.
    range: Option<String>,
    /// The image or player fills the window (alt+e, the header button or a
    /// double-click; Esc leaves).
    pub fullscreen: bool,
    /// Open/close transition; `None` when settled (or `reduce_motion`).
    fs_anim: Option<FsAnim>,
    /// Last fitted dest of the preview image (docked or fullscreen).
    last_preview: Option<Rect>,
    /// Docked dest captured when opening, so close can land on the thumbnail.
    fs_thumb: Option<Rect>,
    /// `appearance.reduce_motion` from the last [`Context`].
    reduce_motion: bool,
    /// Last pointer move or key in fullscreen: the controls show for
    /// [`FS_CONTROLS`] after it.
    fs_active: std::time::Instant,
    /// Last click on the picture, for double-click.
    fs_click: Option<std::time::Instant>,
    /// Bumped on activity; the hide timer only fires for the latest.
    fs_gen: Arc<AtomicU64>,
    last_scrub: Option<std::time::Instant>,
    /// The ssh side channel while the listing is remote.
    ssh: Option<fetch::Remote>,
    /// The folder the shell last reported (local, or the remote shell's).
    /// Commander follows the shell only when this changes (a `cd` typed
    /// there); its own navigation never moves the shell (`s` syncs).
    shell_dir: Option<PathBuf>,
    remote_meta: Arc<HashMap<PathBuf, (u64, i64)>>,
    /// The remote file open in the viewer (or player).
    open_remote: Option<(PathBuf, fetch::Handle)>,
    /// Heads of remote text files on screen (tile snippets).
    heads: HashMap<PathBuf, fetch::Handle>,
    /// Bytes of the open remote text shown so far.
    remote_text_at: u64,
    /// The open markdown file laid out: (path, columns, source lines, rows).
    md_cache: Option<(PathBuf, usize, usize, Arc<Vec<md::Line>>)>,
    /// The mode panel's size the user chose (Mouser's `[` `]` `F`, the edge).
    pub dock: mouser_mode_api::DockSize,
    /// A name or destination being typed for a menu action.
    pub ask: Option<(Ask, String)>,
    /// File changes waiting for the user's yes on Mouser's approval card.
    pub ops: Vec<crate::ops::Op>,
    /// Text to put on the clipboard (through Mouser).
    pub clip: Vec<String>,
    /// Paths `copy` remembered for `paste`.
    yank: Vec<PathBuf>,
    /// Where they are: `None` this machine, else the remote label.
    yank_at: Option<String>,
    /// Tab-completion cycle for the focused prompt (ask / search / pipe).
    complete: mouser_mode_api::complete::Engine,
    complete_hint: String,
}

/// What the typed text is for.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Ask {
    CopyTo(Vec<PathBuf>),
    MoveTo(Vec<PathBuf>),
    Rename(PathBuf),
    NewFolder(PathBuf),
}

impl Ask {
    fn prompt(&self) -> String {
        match self {
            Ask::CopyTo(v) => format!("copy {} item(s) to (folder)", v.len()),
            Ask::MoveTo(v) => format!("move {} item(s) to (folder)", v.len()),
            Ask::Rename(p) => format!("rename {}", p.file_name().unwrap_or_default().to_string_lossy()),
            Ask::NewFolder(_) => "new folder name".into(),
        }
    }
}

#[derive(Clone, Copy, Debug)]
enum Press {
    Pan { at: (i32, i32), c0: (f64, f64) },
    Scrub,
    Volume,
}

/// Where the interactive parts were drawn last frame.
#[derive(Clone, Copy, Debug, Default)]
struct Hits {
    bar: Rect,
    vol: Rect,
    image: Rect,
    video: Rect,
    menu: Rect,
}

impl Default for CommanderMode {
    fn default() -> Self {
        Self::new()
    }
}

fn item(rect: Rect, text: impl Into<String>, style: PanelStyle, action: UiAction) -> PanelItem {
    PanelItem { rect, text: text.into(), style, action }
}

fn act(id: &str, arg: i32) -> UiAction {
    UiAction::Mode { action: id.into(), arg }
}

/// Type badge diameter for cell size (`cw`, `ch`): room for a 3-character mark.
fn badge_size(cw: i32, ch: i32) -> i32 {
    (ch + 10).max(3 * cw + 8)
}

/// The badge of a box `b`: its centre exactly on the box's top-right corner.
fn badge_rect(b: Rect, d: i32) -> Rect {
    Rect { x: b.x + b.w - d / 2, y: b.y - d / 2, w: d, h: d }
}

/// Where a carousel folder's icon sits inside the preview box `b`: centred,
/// about two fifths of the box, 5:4.
fn folder_icon_rect(b: Rect) -> Rect {
    let w = (b.w * 2 / 5).min(b.h * 2 / 5 * 5 / 4).max(0);
    let h = w * 4 / 5;
    Rect { x: b.x + (b.w - w) / 2, y: b.y + (b.h - h) / 2, w, h }
}

/// The floating name tag of a carousel item whose box is `full` (visible
/// part `clip`): centred near the bottom of the box, as wide as the name
/// (at most the box less a margin), cut to the visible part. Long names end
/// in an ellipsis. None when too little of it is on screen.
fn float_label(full: Rect, clip: Rect, name: &str, cw: i32, ch: i32) -> Option<(Rect, String)> {
    let pad = crate::host::BUTTON_PAD;
    let room = full.w - 2 * (cw * 2);
    let cols = ((room - 2 * pad) / cw.max(1)).max(1);
    let text = clip_text(name, cols);
    let w = (text.chars().count() as i32 * cw + 2 * pad).min(room.max(0));
    let h = ch + 10;
    let r = Rect { x: full.x + (full.w - w) / 2, y: full.y + full.h - h - 16, w, h };
    // Only a label wholly on the strip: a cut one reads as noise.
    (r.w > 0 && r.x >= clip.x && r.x + r.w <= clip.x + clip.w).then_some((r, text))
}

/// Builder state for one frame.
/// How long fullscreen controls stay after the last pointer move or key.
pub const FS_CONTROLS: std::time::Duration = std::time::Duration::from_millis(2500);

fn is_media(p: &Path) -> bool {
    matches!(cmdr::kind_of(&p.to_string_lossy()), Kind::Image | Kind::Video | Kind::Audio)
}

/// Fullscreen keys: space and the arrows drive the player / image.
fn fs_key(bytes: &[u8]) -> Option<&'static str> {
    Some(match bytes {
        b" " => "play_pause",
        b"\x1b[D" | b"\x1bOD" => "left_fs",
        b"\x1b[C" | b"\x1bOC" => "right_fs",
        b"\x1b[A" | b"\x1bOA" => "up_fs",
        b"\x1b[B" | b"\x1bOB" => "down_fs",
        _ => return None,
    })
}

/// A slim scrollbar over `track` when not everything fits.
fn scrollbar(o: &mut Out, track: Rect, first: usize, shown: usize, total: usize) {
    o.items.extend(mouser_views::scroll::scrollbar(track, first, shown, total, UiAction::None));
}

struct Out {
    items: Vec<PanelItem>,
    /// Player frames, ready to draw.
    frames: Vec<ModeImage>,
    /// (what, full rect, visible part)
    slots: Vec<(Want, Rect, Rect)>,
    texts: Vec<PathBuf>,
    /// Loading in the background (not drawn yet).
    extra: Vec<Want>,
    /// The open ••• dropdown (images under it are hidden).
    menu: Option<Rect>,
    /// Floating labels, put last so they sit on top (docs/commander.md).
    floats: Vec<PanelItem>,
}

impl CommanderMode {
    pub fn new() -> Self {
        // The player reads [audio] from the same home commander uses.
        mouser_media::set_home(crate::storage::resolve_home);
        Self {
            c: Commander::new(),
            per_row: 1,
            previews: Previews::default(),
            texts: HashMap::new(),
            full_text: None,
            last_click: None,
            player: None,
            waker: None,
            body_w: 0,
            player_keys: String::new(),
            slide: Slide::default(),
            zoom: None,
            nat: None,
            pointer: (0, 0),
            press: None,
            hits: Hits::default(),
            menu_open: false,
            range: None,
            fullscreen: false,
            fs_anim: None,
            last_preview: None,
            fs_thumb: None,
            reduce_motion: false,
            fs_active: std::time::Instant::now(),
            fs_click: None,
            fs_gen: Arc::new(AtomicU64::new(0)),
            last_scrub: None,
            ssh: None,
            shell_dir: None,
            remote_meta: Arc::new(HashMap::new()),
            open_remote: None,
            heads: HashMap::new(),
            remote_text_at: 0,
            md_cache: None,
            dock: Default::default(),
            ask: None,
            ops: Vec::new(),
            clip: Vec::new(),
            yank: Vec::new(),
            yank_at: None,
            complete: mouser_mode_api::complete::Engine::new(),
            complete_hint: String::new(),
        }
    }

    /// Where a menu opened on `item` (or off the items) is.
    pub fn menu_cx(&self, item: Option<usize>) -> crate::menu::Cx {
        use crate::menu::Cx;
        match &self.c.overlay {
            Some(Overlay::Preview(p)) => match cmdr::kind_of(&p.to_string_lossy()) {
                Kind::Image if self.fullscreen => Cx::FsImage,
                Kind::Image => Cx::Image,
                Kind::Video | Kind::Audio if self.fullscreen => Cx::FsPlayer,
                Kind::Video | Kind::Audio => Cx::Player,
                _ => Cx::Text,
            },
            Some(Overlay::Man) => Cx::Text,
            _ => match item.and_then(|i| self.c.visible().get(i).map(|e| e.kind)) {
                Some(Kind::Dir) => Cx::Folder,
                Some(Kind::Image | Kind::Video | Kind::Audio) => Cx::Media,
                Some(_) => Cx::File,
                None => Cx::Empty,
            },
        }
    }

    /// The context menu for `item` (`None`: off the items, or a file view).
    pub fn menu(&self, item: Option<usize>, keys: &Keymap) -> Vec<mouser_mode_api::MenuEntry> {
        let cx = self.menu_cx(item);
        // Local, or remote with a side channel to run the change on the host.
        let can_change = self.op_target().is_ok();
        let viewing = matches!(self.c.overlay, Some(Overlay::Preview(_)) | Some(Overlay::Man));
        let item = if viewing { None } else { item };
        let enabled = |id: &str| match id {
            "copy" | "copy_to" | "move_to" | "rename" | "delete" | "new_folder" => can_change,
            "paste" => can_change && !self.yank.is_empty(),
            "copy_text" => self.full_text.is_some() || self.c.overlay == Some(Overlay::Man),
            "play_pause" | "seek_back" | "seek_forward" | "volume_down" | "volume_up" => self.player.is_some(),
            _ => true,
        };
        crate::menu::entries(cx, item, keys, &enabled)
    }

    /// Where file changes run: this machine (`None`), or the remote host
    /// over the session's side channel. A remote listing without one: no changes.
    pub fn op_target(&self) -> Result<Option<fetch::Remote>, String> {
        match (&self.c.remote, &self.ssh) {
            (None, _) => Ok(None),
            (Some(_), Some(r)) => Ok(Some(r.clone())),
            (Some(l), None) => Err(format!("{l}: no ssh side channel, so files there can't be changed from commander")),
        }
    }

    /// List the folder again after a change (remote: asked on the host).
    pub fn relist(&mut self) {
        match (self.c.remote.is_some(), self.c.cwd.clone()) {
            (true, Some(d)) => {
                let _ = self.browse(d);
            }
            _ => self.c.relist(),
        }
    }

    /// The paths an item action works on: the marked ones when the item is
    /// marked, else just the item.
    fn op_paths(&self) -> Vec<PathBuf> {
        let sel = self.c.selected_entry().map(|e| e.path.clone());
        match sel {
            Some(p) if self.c.marks.contains(&p) => self.c.pipe_paths(),
            Some(p) => vec![p],
            None => Vec::new(),
        }
    }

    /// A picked menu entry (`menu:<id>`, the item index as its argument).
    fn menu_action(&mut self, id: &str, arg: i32) -> Effect {
        let item_action = !matches!(id, "sort" | "sort_name" | "sort_modified" | "sort_size")
            && !matches!(self.c.overlay, Some(Overlay::Preview(_)) | Some(Overlay::Man));
        if item_action
            && arg >= 0
            && (arg as usize) < self.c.visible().len()
            && crate::menu::ACTIONS
                .iter()
                .any(|a| a.id == id && a.cx.iter().any(|c| matches!(c, crate::menu::Cx::Folder | crate::menu::Cx::File | crate::menu::Cx::Media)))
        {
            self.c.selected = arg as usize;
        }
        let dir = self.c.cwd.clone();
        let paths = self.op_paths();
        if matches!(id, "copy" | "copy_to" | "move_to" | "rename" | "delete" | "new_folder" | "paste")
            && let Err(e) = self.op_target()
        {
            return Effect::Say(e);
        }
        match id {
            "open_fullscreen" => {
                let e = self.c.open_selected();
                let e = self.effect(e);
                if matches!(&self.c.overlay, Some(Overlay::Preview(p)) if is_media(p)) && !self.fullscreen {
                    self.toggle_fullscreen();
                }
                e
            }
            "sync_item" => match self.c.selected_entry() {
                Some(en) if en.kind == Kind::Dir => Effect::Cd(en.path.clone()),
                _ => Effect::None,
            },
            "copy" => {
                self.yank = paths;
                self.yank_at = self.c.remote.clone();
                Effect::Say(format!("{} item(s) to paste", self.yank.len()))
            }
            "copy_to" | "move_to" if !paths.is_empty() => {
                let start = dir.map(|d| format!("{}/", d.display())).unwrap_or_default();
                self.ask = Some((if id == "copy_to" { Ask::CopyTo(paths) } else { Ask::MoveTo(paths) }, start));
                Effect::None
            }
            "rename" => match self.c.selected_entry() {
                Some(en) => {
                    let name = en.name.clone();
                    self.ask = Some((Ask::Rename(en.path.clone()), name));
                    Effect::None
                }
                None => Effect::None,
            },
            "delete" if !paths.is_empty() => {
                self.ops.push(crate::ops::Op::Delete(paths));
                Effect::None
            }
            "new_folder" => match dir {
                Some(d) => {
                    self.ask = Some((Ask::NewFolder(d), String::new()));
                    Effect::None
                }
                None => Effect::None,
            },
            "paste" if !self.yank.is_empty() && self.yank_at != self.c.remote => Effect::Say(format!(
                "the copied items are on {}; paste them there (copying between machines isn't supported here)",
                self.yank_at.as_deref().unwrap_or("this machine")
            )),
            "paste" => match dir {
                Some(d) if !self.yank.is_empty() => {
                    // On a folder: into it; else into this folder.
                    let to = self.c.selected_entry().filter(|e| e.kind == Kind::Dir && item_action).map(|e| e.path.clone()).unwrap_or(d);
                    self.ops.push(crate::ops::Op::CopyTo { from: self.yank.clone(), to });
                    Effect::None
                }
                _ => Effect::None,
            },
            "copy_path" => {
                let p = match &self.c.overlay {
                    Some(Overlay::Preview(p)) => Some(p.clone()),
                    _ => self.c.selected_entry().map(|e| e.path.clone()),
                };
                if let Some(p) = p {
                    self.clip.push(p.display().to_string());
                }
                Effect::None
            }
            "copy_text" => {
                if let Some((_, lines, _)) = &self.full_text {
                    self.clip.push(lines.join("\n"));
                }
                Effect::None
            }
            "copy_to" | "move_to" | "delete" => Effect::None,
            other => self.action(other, if other == "sort" { arg } else { 0 }),
        }
    }

    /// Typed text while a name or destination is asked: Enter goes on to
    /// the approval card, Esc cancels. Tab completes paths or names.
    fn ask_key(&mut self, bytes: &[u8]) -> Effect {
        if bytes == b"\t" || bytes == b"\x1b[Z" {
            self.complete_ask(bytes == b"\x1b[Z");
            return Effect::None;
        }
        if bytes == b"\r" {
            let (ask, text) = self.ask.take().unwrap_or((Ask::NewFolder(PathBuf::new()), String::new()));
            self.complete.reset();
            self.complete_hint.clear();
            let t = text.trim();
            let op = match ask {
                Ask::CopyTo(from) if !t.is_empty() => crate::ops::Op::CopyTo { from, to: PathBuf::from(t) },
                Ask::MoveTo(from) if !t.is_empty() => crate::ops::Op::MoveTo { from, to: PathBuf::from(t) },
                Ask::Rename(p) if crate::ops::valid_name(t) => crate::ops::Op::Rename { to: p.with_file_name(t), from: p },
                Ask::NewFolder(d) if crate::ops::valid_name(t) => crate::ops::Op::NewFolder(d.join(t)),
                _ => return Effect::Say("not a valid name".into()),
            };
            self.ops.push(op);
            return Effect::None;
        }
        let Some((_, text)) = self.ask.as_mut() else { return Effect::None };
        match bytes {
            b"\x7f" | b"\x08" => {
                text.pop();
            }
            _ => {
                if let Ok(t) = std::str::from_utf8(bytes)
                    && !t.chars().any(char::is_control)
                {
                    text.push_str(t);
                }
            }
        }
        self.complete.reset();
        self.complete_hint.clear();
        Effect::None
    }

    fn path_source(&self) -> CommanderSource<'_> {
        CommanderSource { entries: &self.c.entries, cwd: self.c.cwd.as_deref(), remote: self.ssh.as_ref(), is_remote: self.c.remote.is_some() }
    }

    fn complete_ask(&mut self, reverse: bool) {
        let Some((ask, text)) = self.ask.as_ref() else { return };
        let text = text.clone();
        let names_only = matches!(ask, Ask::Rename(_) | Ask::NewFolder(_));
        let (stem, token, matches) = if names_only {
            let names: Vec<String> = self.c.entries.iter().map(|e| e.name.clone()).collect();
            mouser_mode_api::complete::value_matches(&text, &names)
        } else {
            let cwd = self.c.cwd.clone().unwrap_or_else(|| PathBuf::from("."));
            mouser_mode_api::complete::path_matches(&text, &cwd, &self.path_source(), false)
        };
        let out = self.complete.tab(&text, &stem, &token, &matches, reverse);
        if let Some((_, t)) = self.ask.as_mut() {
            *t = out.text.clone();
        }
        self.complete_hint = out.list_hint(72);
    }

    fn complete_search(&mut self, reverse: bool) {
        let names: Vec<String> = self.c.entries.iter().map(|e| e.name.clone()).collect();
        let (stem, token, matches) = mouser_mode_api::complete::value_matches(&self.c.filter, &names);
        let out = self.complete.tab(&self.c.filter, &stem, &token, &matches, reverse);
        self.c.filter = out.text.clone();
        self.c.selected = 0;
        self.c.scroll = 0;
        self.complete_hint = out.list_hint(72);
    }

    fn complete_pipe(&mut self, reverse: bool) {
        let input = self.c.pipe_cmd.clone();
        let cwd = self.c.cwd.clone().unwrap_or_else(|| PathBuf::from("."));
        let (stem, token, matches) = match input.find(char::is_whitespace) {
            None => (String::new(), input.clone(), mouser_mode_api::complete::executables(&input)),
            Some(i) => {
                let head = &input[..i];
                let rest = input[i..].trim_start();
                let (pstem, ptoken, matches) = mouser_mode_api::complete::path_matches(rest, &cwd, &self.path_source(), false);
                (format!("{head} {pstem}"), ptoken, matches)
            }
        };
        let out = self.complete.tab(&input, &stem, &token, &matches, reverse);
        self.c.pipe_cmd = out.text.clone();
        self.complete_hint = out.list_hint(72);
    }

    pub fn previews(&self) -> &Previews {
        &self.previews
    }

    fn size(&self, e: &Entry) -> String {
        if self.c.flags.human { cmdr::human_size(e.size) } else { e.size.to_string() }
    }

    fn text_lines(&mut self, p: &Path) -> &[String] {
        if self.c.remote.is_some() && !self.texts.contains_key(p) {
            // Remote: the first 4 KB, fetched in the background.
            static LOADING: Vec<String> = Vec::new();
            let Some(f) = self.remote_file(p) else { return &LOADING };
            let waker = self.waker.clone();
            let h = self.heads.entry(p.to_path_buf()).or_insert_with(|| {
                let mut h = fetch::open(&f, Some(4096));
                if let Some(w) = waker {
                    h.on_progress(w);
                }
                h
            });
            let n = 4096.min(f.size);
            if h.map().prefix() < n {
                return &LOADING;
            }
            let buf = h.read(0, n, std::time::Duration::ZERO).unwrap_or_default();
            let lines = if buf.contains(&0) {
                vec!["(binary)".into()]
            } else {
                String::from_utf8_lossy(&buf).lines().take(40).map(|l| l.replace('\t', "  ")).collect()
            };
            return self.texts.entry(p.to_path_buf()).or_insert(lines);
        }
        self.texts.entry(p.to_path_buf()).or_insert_with(|| {
            let mut buf = vec![0; 4096];
            let n = std::fs::File::open(p).and_then(|mut f| std::io::Read::read(&mut f, &mut buf)).unwrap_or(0);
            buf.truncate(n);
            if buf.contains(&0) {
                return vec!["(binary)".into()];
            }
            String::from_utf8_lossy(&buf).lines().take(40).map(|l| l.replace('\t', "  ")).collect()
        })
    }

    /// The preview of `e` inside `full` (visible part `clip`).
    fn content(&mut self, e: &Entry, (full, clip): (Rect, Rect), max: u32, (cw, ch): (i32, i32), o: &mut Out) {
        // Remote without a side channel: never read a local file of that name.
        if self.c.remote.is_some() && self.ssh.is_none() {
            let label = if e.kind == Kind::Dir { "folder".to_string() } else { format!("{} · remote", kind_label(e.kind)) };
            let w = (label.chars().count() as i32 * cw).min(clip.w);
            let r = Rect { x: clip.x + (clip.w - w).max(0) / 2, y: clip.y + (clip.h - ch) / 2, w, h: ch };
            o.items.push(item(r, label, if e.kind == Kind::Dir { PanelStyle::Label } else { PanelStyle::Hint }, UiAction::None));
            return;
        }
        match e.kind {
            Kind::Image | Kind::Video => {
                o.slots.push(((e.path.clone(), max), full, clip));
            }
            Kind::Text => {
                o.texts.push(e.path.clone());
                let cols = clip.w / cw.max(1);
                let rows = (clip.h / ch.max(1)) as usize;
                if md::is_markdown(&e.name) {
                    // Rendered, not raw: headings, lists, code blocks (docs/markdown.md).
                    let src = self.text_lines(&e.path).join("\n");
                    let lines = md::layout(&src, cols.max(1) as usize);
                    md::items(&lines, 0, rows, clip.x, clip.y, (cw, ch), clip.w, &mut |_| UiAction::None, &mut o.items);
                    return;
                }
                let lines: Vec<String> = self.text_lines(&e.path).iter().take(rows).map(|l| clip_text(l, cols)).collect();
                for (i, l) in lines.into_iter().enumerate() {
                    o.items.push(item(Rect { x: clip.x, y: clip.y + i as i32 * ch, w: clip.w, h: ch }, l, PanelStyle::Hint, UiAction::None));
                }
            }
            k => {
                let label = kind_label(k);
                let w = label.chars().count() as i32 * cw;
                let r = Rect { x: clip.x + (clip.w - w).max(0) / 2, y: clip.y + (clip.h - ch) / 2, w: w.min(clip.w), h: ch };
                o.items.push(item(r, label, if k == Kind::Dir { PanelStyle::Label } else { PanelStyle::Hint }, UiAction::None));
            }
        }
    }

    fn list(&mut self, body: Rect, cw: i32, ch: i32, o: &mut Out) {
        let row_h = ch + 4;
        let rows = ((body.h / row_h) - 1).max(1) as usize;
        self.c.page = rows;
        self.c.follow(rows);
        let cols = body.w / cw.max(1);
        let name_w = (cols - 10 - 2 - 6 - 2 - 2 - 13 - 2).max(8) as usize;
        let head = format!(" {:<10} {:>6}  {:<name_w$}  {}", "Attributes", "Size", "Name", "Last Modified");
        o.items.push(item(Rect { x: body.x, y: body.y, w: body.w, h: row_h }, head, PanelStyle::Hint, UiAction::None));
        let vis: Vec<Entry> = self.c.visible().into_iter().cloned().collect();
        let track = Rect { x: body.x + body.w - 5, y: body.y + row_h, w: 5, h: row_h * rows as i32 };
        scrollbar(o, track, self.c.scroll, rows, vis.len());
        self.range = Some(range_label(self.c.scroll, rows.min(vis.len()), vis.len()));
        let body = if vis.len() > rows { Rect { w: body.w - 10, ..body } } else { body };
        for (n, e) in vis.iter().enumerate().skip(self.c.scroll).take(rows) {
            let y = body.y + row_h * (1 + (n - self.c.scroll) as i32);
            let name = if e.kind == Kind::Dir && e.name != "." && e.name != ".." { format!("{}/", e.name) } else { e.name.clone() };
            let t = e.modified.map(cmdr::format_time).unwrap_or_default();
            let mark = if self.c.marks.contains(&e.path) { '*' } else { ' ' };
            let text = format!("{mark}{:<10} {:>6}  {:<name_w$}  {t}", e.mode, self.size(e), clip_text(&name, name_w as i32));
            o.items.push(item(
                Rect { x: body.x, y, w: body.w, h: row_h },
                text,
                PanelStyle::Row { selected: n == self.c.selected },
                act("item", n as i32),
            ));
        }
    }

    fn grid(&mut self, body: Rect, cw: i32, ch: i32, o: &mut Out) {
        let ts = TILE_SIZES[self.c.tile.min(TILE_SIZES.len() - 1)];
        // Room for the badges that overhang each tile's top-right corner.
        let d = badge_size(cw, ch);
        let (gap, label_h) = ((d / 2 + 6).max(10), ch + 4);
        let body = Rect { y: body.y + d / 2 + 2, h: body.h - d / 2 - 2, ..body };
        let vis: Vec<Entry> = self.c.visible().into_iter().cloned().collect();
        let g = mouser_views::grid::Grid::new(
            body,
            mouser_views::grid::Tiles { size: ts, gap, label_h, reserve: d / 2 + 6 },
            vis.len(),
            self.c.selected,
            self.c.scroll,
        );
        self.per_row = g.per_row;
        self.c.page = g.page();
        self.c.scroll = g.first;
        let start = g.start();
        scrollbar(o, Rect { x: body.x + body.w - 5, y: body.y, w: 5, h: body.h }, g.first, g.vis_rows, g.total_rows);
        self.range = Some(range_label(start, g.page().min(vis.len().saturating_sub(start)), vis.len()));
        for n in g.shown(vis.len()) {
            let e = &vis[n];
            let tile = g.tile_rect(n);
            o.items.push(item(tile, "", PanelStyle::Tile { selected: n == self.c.selected }, act("item", n as i32)));
            let inner = Rect { x: tile.x + 4, y: tile.y + 4, w: ts - 8, h: ts - 8 };
            self.content(e, (inner, inner), (ts as u32 * 2).max(256), (cw, ch), o);
            let label = if self.c.marks.contains(&e.path) { format!("* {}", e.name) } else { e.name.clone() };
            let label = clip_text(&label, ts / cw.max(1));
            o.items.push(item(Rect { x: tile.x, y: tile.y + ts + 2, w: ts, h: label_h }, label, PanelStyle::Label, act("item", n as i32)));
            let b = cmdr::badge_of(&e.name, e.kind, &e.mode);
            o.floats.push(item(badge_rect(tile, d), "", PanelStyle::Badge(b.index()), UiAction::None));
        }
    }

    fn carousel(&mut self, body: Rect, cw: i32, ch: i32, o: &mut Out) {
        self.c.page = 5;
        let vis: Vec<Entry> = self.c.visible().into_iter().cloned().collect();
        let Some(e) = vis.get(self.c.selected).cloned() else { return };
        let pos = self.slide.at(self.c.selected as f64, std::time::Instant::now());
        if self.slide.moving() {
            self.keep_redrawing();
        }
        let label_h = ch + 6;
        // Room above and between the boxes for the corner badges.
        let d = badge_size(cw, ch);
        let body = Rect { y: body.y + d / 2 + 2, h: body.h - d / 2 - 2, ..body };
        let ih = (body.h - label_h - 6).max(ch);
        let w = (body.w * 55 / 100).max(cw * 10);
        let gap = (d / 2 + 8).max(14);
        // Items sit on a strip (mouser-views): `pos` (fractional while
        // sliding) in the middle, neighbours the same size, cut off by the
        // edges; the one nearest the middle loads (and draws) first.
        let strip = mouser_views::carousel::Strip::new(body, w, gap);
        for i in mouser_views::carousel::Strip::order(pos, self.c.selected, vis.len()) {
            let full = strip.rect(i, pos, ih);
            let Some(clip) = strip.visible(full, 8) else {
                // Off the strip still: load it so it is ready when it slides in.
                if matches!(vis[i].kind, Kind::Image | Kind::Video) {
                    o.slots.push(((vis[i].path.clone(), 1024), full, Rect { w: 0, h: 0, ..full }));
                }
                continue;
            };
            o.items.push(item(clip, "", PanelStyle::Tile { selected: i == self.c.selected }, act("item", i as i32)));
            let inner = |r: Rect| Rect { x: r.x + 6, y: r.y + 6, w: r.w - 12, h: r.h - 12 };
            if vis[i].kind == Kind::Dir {
                // A folder icon in the middle (only once it is wholly on the strip).
                let icon = folder_icon_rect(inner(full));
                if icon.x >= clip.x && icon.x + icon.w <= clip.x + clip.w {
                    o.items.push(item(icon, "", PanelStyle::FolderIcon, UiAction::None));
                }
            } else {
                self.content(&vis[i], (inner(full), inner(clip)), 1024, (cw, ch), o);
            }
            // The name floats over the preview, at the same place on every item.
            let mk = if self.c.marks.contains(&vis[i].path) { "* " } else { "" };
            if let Some((r, t)) = float_label(full, clip, &format!("{mk}{}", vis[i].name), cw, ch) {
                o.floats.push(item(r, t, PanelStyle::FloatLabel, UiAction::None));
            }
            // Its type badge, when the corner is on the strip.
            let br = badge_rect(full, d);
            if br.x >= body.x && br.x + br.w <= body.x + body.w {
                let b = cmdr::badge_of(&vis[i].name, vis[i].kind, &vis[i].mode);
                o.floats.push(item(br, "", PanelStyle::Badge(b.index()), UiAction::None));
            }
        }
        let t = e.modified.map(cmdr::format_time).unwrap_or_default();
        let label = format!("{}   {}   {} of {}", t, self.size(&e), self.c.selected + 1, vis.len());
        self.range = None;
        if vis.len() > 1 {
            // Where we are along the strip.
            let tr = Rect { x: body.x + body.w / 3, y: body.y + ih + 1, w: body.w / 3, h: 4 };
            scrollbar(o, tr, self.c.selected, 1, vis.len());
        }
        let lw = (label.chars().count() as i32 * cw).min(body.w);
        o.items.push(item(
            Rect { x: body.x + (body.w - lw) / 2, y: body.y + ih + 6, w: lw, h: label_h },
            clip_text(&label, body.w / cw.max(1)),
            PanelStyle::Hint,
            UiAction::None,
        ));
    }

    /// Wake the UI every ~8 ms until the carousel stops (only while it moves).
    fn keep_redrawing(&mut self) {
        if self.slide.ticking {
            return;
        }
        let Some(w) = self.waker.clone() else { return };
        self.slide.ticking = true;
        let until = self.slide.end();
        let _ = std::thread::Builder::new().name("carousel-anim".into()).spawn(move || {
            while std::time::Instant::now() < until + std::time::Duration::from_millis(10) {
                std::thread::sleep(std::time::Duration::from_millis(8));
                w();
            }
        });
    }

    /// The full-width view of a file.
    fn file_view(&mut self, p: &Path, body: Rect, cw: i32, ch: i32, o: &mut Out) {
        if self.player.as_ref().is_some_and(|pl| pl.path == p) {
            return self.player_view(body, cw, ch, o);
        }
        if cmdr::kind_of(&p.to_string_lossy()) == Kind::Image {
            self.hits.image = body;
            let nat = self.natural(p);
            if let Some(nat) = nat {
                // Fullscreen fits the whole picture (letterboxed); the docked
                // view fits the width.
                let fs = self.fullscreen;
                let fitw = if fs { contain_scale(body, nat) } else { fit_scale(body, nat) };
                if self.zoom.as_ref().is_none_or(|z| z.path != p) {
                    self.zoom = Some(Zoom { path: p.to_path_buf(), scale: fitw, cx: 0.5, cy: if fs { 0.5 } else { 0.0 }, fit: true });
                }
                if let Some(z) = self.zoom.as_mut().filter(|z| z.fit) {
                    z.scale = fitw;
                    if fs {
                        (z.cx, z.cy) = (0.5, 0.5);
                    }
                }
            }
            self.remote_status(body, ch, o);
            let zoomed = self.zoom.as_ref().is_some_and(|z| z.path == p);
            match (nat, zoomed) {
                (Some(nat), true) => {
                    let z = self.zoom.as_mut().unwrap();
                    let r = zoom_rect(body, nat, z);
                    // Past the 2048 px preview: the full image, the preview until it loads.
                    let hi = (p.to_path_buf(), 16384);
                    if r.w.max(r.h) > 2048 && !matches!(self.previews.get(&hi), Some(Some(_))) {
                        o.extra.push(hi);
                        o.slots.push(((p.to_path_buf(), 2048), r, body));
                    } else if r.w.max(r.h) > 2048 {
                        o.slots.push((hi, r, body));
                    } else {
                        o.slots.push(((p.to_path_buf(), 2048), r, body));
                    }
                }
                _ => o.slots.push(((p.to_path_buf(), 2048), body, body)),
            }
            return;
        }
        if let Some((_, h)) = self.open_remote.as_ref().filter(|r| r.0 == p) {
            // Remote: what has arrived from the start; grows as it loads.
            let size = h.file().size;
            let have = h.map().prefix().min(1 << 20);
            if self.full_text.as_ref().is_none_or(|t| t.0 != p) || have != self.remote_text_at {
                self.remote_text_at = have;
                let b = h.read(0, have, std::time::Duration::ZERO).unwrap_or_default();
                let (l, e) = cmdr::text_from_bytes(&b, have >= (1 << 20), &p.display().to_string());
                self.full_text = Some((p.to_path_buf(), l, e));
            }
            if have < size.min(1 << 20) {
                h.prioritize(have);
            }
            self.remote_status(body, ch, o);
        } else if self.full_text.as_ref().is_none_or(|t| t.0 != p) {
            let (l, e) = cmdr::text_preview(p);
            self.full_text = Some((p.to_path_buf(), l, e));
        }
        let (_, lines, err) = self.full_text.as_ref().unwrap();
        if let Some(e) = err {
            o.items.push(item(Rect { x: body.x, y: body.y, w: body.w, h: ch + 4 }, e.clone(), PanelStyle::Error, UiAction::None));
            return;
        }
        let mut rows = (body.h / ch.max(1)).max(1) as usize;
        let rendered = if md::is_markdown(&p.to_string_lossy()) {
            let cols = ((body.w - 10) / cw.max(1)).max(8) as usize;
            if self.md_cache.as_ref().is_none_or(|c| c.0 != p || c.1 != cols || c.2 != lines.len()) {
                self.md_cache = Some((p.to_path_buf(), cols, lines.len(), Arc::new(md::layout(&lines.join("\n"), cols))));
            }
            self.md_cache.as_ref().map(|c| c.3.clone())
        } else {
            None
        };
        let total = rendered.as_ref().map_or(lines.len(), |r| r.len());
        let long = total > rows;
        if long {
            // The last row says where we are.
            rows = rows.saturating_sub(1).max(1);
        }
        let scroll = self.c.overlay_scroll.min(total.saturating_sub(rows));
        self.c.overlay_scroll = scroll;
        let tw = if long { body.w - 10 } else { body.w };
        if long {
            scrollbar(o, Rect { x: body.x + body.w - 5, y: body.y, w: 5, h: rows as i32 * ch }, scroll, rows, total);
            let t = format!("lines {}", range_label(scroll, rows, total));
            let lw = t.chars().count() as i32 * cw;
            o.items.push(item(Rect { x: body.x + body.w - lw, y: body.y + rows as i32 * ch, w: lw, h: ch }, t, PanelStyle::Hint, UiAction::None));
        }
        if let Some(r) = rendered {
            md::items(&r, scroll, rows, body.x, body.y, (cw, ch), tw, &mut |_| UiAction::None, &mut o.items);
            return;
        }
        for (i, l) in lines.iter().skip(scroll).take(rows).enumerate() {
            o.items.push(item(
                Rect { x: body.x, y: body.y + i as i32 * ch, w: tw, h: ch },
                clip_text(&l.replace('\t', "    "), tw / cw.max(1)),
                PanelStyle::Label,
                UiAction::None,
            ));
        }
    }

    /// Natural size of an image (cached for the open file). Remote: from
    /// the header once the first read is in, else the quick preview's shape.
    fn natural(&mut self, p: &Path) -> Option<(u32, u32)> {
        if self.nat.as_ref().is_none_or(|n| n.0 != p) {
            let d = match self.open_remote.as_ref().filter(|r| r.0 == p) {
                Some((_, h)) => {
                    let m = h.map();
                    let header = (m.prefix() >= fetch::HEAD.min(h.file().size))
                        .then(|| image::ImageReader::open(h.cache_path()).ok()?.with_guessed_format().ok()?.into_dimensions().ok())
                        .flatten();
                    match header {
                        Some(d) => d,
                        None => {
                            // Not cached: a provisional shape, asked again next frame.
                            let t = self.previews.get(&(p.to_path_buf(), 2048)).flatten()?;
                            return Some((t.w, t.h));
                        }
                    }
                }
                None if self.c.remote.is_some() => return None,
                None => image::image_dimensions(p).ok()?,
            };
            self.nat = Some((p.to_path_buf(), d));
        }
        self.nat.as_ref().map(|n| n.1)
    }

    /// Remote file in the view: how much has arrived, or why it failed.
    fn remote_status(&self, body: Rect, ch: i32, o: &mut Out) {
        let Some((_, h)) = &self.open_remote else { return };
        let r = Rect { x: body.x, y: body.y + body.h - ch, w: body.w, h: ch };
        if let Some(e) = h.error() {
            o.items.push(item(r, format!("remote fetch failed: {e}"), PanelStyle::Error, UiAction::None));
        } else if !h.complete() {
            let mb = |b: u64| b as f64 / 1048576.0;
            let t =
                format!("fetching from {} · {:.1} / {:.1} MB", self.c.remote.as_deref().unwrap_or("remote"), mb(h.map().filled()), mb(h.file().size));
            o.items.push(item(r, t, PanelStyle::Hint, UiAction::None));
        }
    }

    /// The remote file behind `p` (listing metadata).
    fn remote_file(&self, p: &Path) -> Option<fetch::RemoteFile> {
        let r = self.ssh.clone()?;
        self.c.remote.as_ref()?;
        RemoteCtx { remote: r, meta: self.remote_meta.clone() }.file(p)
    }

    /// Keep a transfer of the remote file open in the viewer / player.
    fn ensure_open_remote(&mut self, p: &Path) {
        if self.open_remote.as_ref().is_some_and(|r| r.0 == p) {
            return;
        }
        self.open_remote = None;
        let Some(f) = self.remote_file(p) else { return };
        let mut h = fetch::open(&f, None);
        if let Some(w) = self.waker.clone() {
            h.on_progress(w);
        }
        self.nat = None;
        self.remote_text_at = u64::MAX;
        self.open_remote = Some((p.to_path_buf(), h));
    }

    /// Zoom label for the header ("fit 37%", "200%").
    fn zoom_label(&mut self, p: &Path) -> Option<String> {
        let body = self.hits.image;
        let nat = self.natural(p)?;
        Some(match self.zoom.as_ref().filter(|z| z.path == p) {
            Some(z) if z.fit => format!("fit {:.0}%", z.scale * 100.0),
            Some(z) => format!("{:.0}%", z.scale * 100.0),
            None => format!("fit {:.0}%", fit_scale(body, nat) * 100.0),
        })
    }

    /// Zoom the open image; `factor` None = fit, Some(0.0) = 100%.
    fn zoom_image(&mut self, factor: Option<f64>, anchor: Option<(i32, i32)>) -> bool {
        let Some(Overlay::Preview(p)) = self.c.overlay.clone() else { return false };
        if cmdr::kind_of(&p.to_string_lossy()) != Kind::Image {
            return false;
        }
        let Some(nat) = self.natural(&p) else { return true };
        let body = self.hits.image;
        let fit = fit_scale(body, nat);
        let mut z = self.zoom.clone().filter(|z| z.path == p).unwrap_or(Zoom { path: p.clone(), scale: fit, cx: 0.5, cy: 0.0, fit: true });
        let centre = (body.x + body.w / 2, body.y + body.h / 2);
        match factor {
            None => {
                self.zoom = Some(Zoom { path: p, scale: fit, cx: 0.5, cy: 0.0, fit: true });
                return true;
            }
            Some(0.0) => {
                let k = 1.0 / z.scale;
                zoom_about(body, nat, &mut z, k, centre)
            }
            Some(f) => zoom_about(body, nat, &mut z, f, anchor.unwrap_or(centre)),
        }
        z.fit = (z.scale - fit).abs() < 1e-3;
        self.zoom = Some(z);
        true
    }

    /// Pan the zoomed image by pixels.
    fn pan(&mut self, dx: i32, dy: i32) -> bool {
        let Some(nat) = self.nat.as_ref().map(|n| n.1) else { return false };
        let Some(z) = self.zoom.as_mut().filter(|z| matches!(&self.c.overlay, Some(Overlay::Preview(p)) if *p == z.path)) else { return false };
        let before = zoom_rect(self.hits.image, nat, z);
        z.cx += dx as f64 / (nat.0 as f64 * z.scale);
        z.cy += dy as f64 / (nat.1 as f64 * z.scale);
        // Moved at all (else: left/right step to the next file, as unzoomed).
        zoom_rect(self.hits.image, nat, z) != before
    }

    fn pointer(&mut self, id: &str, at: (i32, i32)) {
        if self.fullscreen && at != self.pointer {
            self.fs_poke();
        }
        self.pointer = at;
        if id == "pointer_down" && (inside(self.hits.image, at) || inside(self.hits.video, at)) {
            let now = std::time::Instant::now();
            if self.fs_click.is_some_and(|t| now.duration_since(t) < std::time::Duration::from_millis(400)) {
                // Double-click: toggle fullscreen (and undo the first click's play/pause).
                self.fs_click = None;
                if inside(self.hits.video, at)
                    && let Some(pl) = self.player.as_mut()
                {
                    pl.toggle();
                }
                self.toggle_fullscreen();
                return;
            }
            self.fs_click = Some(now);
        }
        let frac = |r: Rect| ((at.0 - r.x) as f64 / r.w.max(1) as f64).clamp(0.0, 1.0);
        match id {
            "pointer_down" => {
                self.press = None;
                if let Some(pl) = self.player.as_mut() {
                    if inside(self.hits.bar, at) {
                        pl.seek_to(frac(self.hits.bar) * pl.info.duration);
                        self.press = Some(Press::Scrub);
                    } else if inside(self.hits.vol, at) {
                        let v = (frac(self.hits.vol) * 100.0).round() as i32;
                        pl.change_volume(v - pl.volume as i32);
                        self.press = Some(Press::Volume);
                    } else if inside(self.hits.video, at) {
                        pl.toggle();
                    }
                } else if let Some(z) = &self.zoom
                    && inside(self.hits.image, at)
                {
                    self.press = Some(Press::Pan { at, c0: (z.cx, z.cy) });
                }
            }
            "pointer_move" => match self.press {
                Some(Press::Scrub) => {
                    let now = std::time::Instant::now();
                    if self.last_scrub.is_none_or(|t| now.duration_since(t).as_millis() >= 120)
                        && let Some(pl) = self.player.as_mut()
                    {
                        pl.seek_to(frac(self.hits.bar) * pl.info.duration);
                        self.last_scrub = Some(now);
                    }
                }
                Some(Press::Volume) => {
                    if let Some(pl) = self.player.as_mut() {
                        let v = (frac(self.hits.vol) * 100.0).round() as i32;
                        pl.change_volume(v - pl.volume as i32);
                    }
                }
                Some(Press::Pan { at: a0, c0 }) => {
                    if let (Some(z), Some(nat)) = (self.zoom.as_mut(), self.nat.as_ref().map(|n| n.1)) {
                        z.cx = c0.0 - (at.0 - a0.0) as f64 / (nat.0 as f64 * z.scale);
                        z.cy = c0.1 - (at.1 - a0.1) as f64 / (nat.1 as f64 * z.scale);
                        zoom_rect(self.hits.image, nat, z);
                    }
                }
                None => {}
            },
            _ => {
                if let (Some(Press::Scrub), Some(pl)) = (self.press, self.player.as_mut()) {
                    pl.seek_to(frac(self.hits.bar) * pl.info.duration);
                }
                self.press = None;
                self.last_scrub = None;
            }
        }
    }

    /// Video fitted to the width with the controls below; audio: name,
    /// progress and controls.
    fn player_view(&mut self, body: Rect, cw: i32, ch: i32, o: &mut Out) {
        let controls = self.player_keys.clone();
        let (fullscreen, shown) = (self.fullscreen, self.fs_anim.is_none() && self.fs_controls_shown());
        let Some(pl) = self.player.as_mut() else { return };
        pl.tick();
        let row_h = ch + 6;
        let pos = pl.position();
        let dur = pl.info.duration;
        let mut y = body.y;
        let name = pl.path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
        let bare = fullscreen && pl.info.video && !shown;
        if bare {
            // Fullscreen with the controls hidden: only the picture, letterboxed.
            self.hits.video = body;
            (self.hits.bar, self.hits.vol) = (Rect::default(), Rect::default());
            if let Some(f) = pl.frame() {
                o.frames.push(ModeImage { key: f.key, rgba: f.rgba, width: f.w, height: f.h, src: (0, 0, f.w, f.h), rect: fit(body, f.w, f.h) })
            }
            return;
        }
        if fullscreen && !pl.info.video {
            // Audio: a full-window controls view, centred.
            let w = body.w.min(cw * 90);
            let h = (6 * row_h + 8).min(body.h);
            y = body.y + (body.h - h) / 2;
            let body2 = Rect { x: body.x + (body.w - w) / 2, y, w, h };
            return self.audio_view(body2, cw, ch, o);
        }
        if pl.info.video {
            let r = Rect { x: body.x, y, w: body.w, h: (body.h - 3 * row_h - 4).max(ch) };
            self.hits.video = r;
            match pl.frame() {
                Some(f) => {
                    o.frames.push(ModeImage { key: f.key, rgba: f.rgba, width: f.w, height: f.h, src: (0, 0, f.w, f.h), rect: fit(r, f.w, f.h) })
                }
                None => o.items.push(item(Rect { x: r.x, y: r.y, w: r.w, h: ch }, "loading…", PanelStyle::Hint, UiAction::None)),
            }
            y = r.y + r.h;
        } else {
            self.hits.video = Rect::default();
            o.items.push(item(Rect { x: body.x, y, w: body.w, h: row_h }, format!("♪ {name}"), PanelStyle::Title, UiAction::None));
            y += row_h * 2;
        }
        if let Some(e) = &pl.error {
            o.items.push(item(Rect { x: body.x, y, w: body.w, h: row_h }, e.clone(), PanelStyle::Error, UiAction::None));
            y += row_h;
        }
        // Seek bar: time, bar (click seeks, drag scrubs, hover shows the time), length.
        let per = |t: f64| if dur > 0.0 { ((t / dur).clamp(0.0, 1.0) * 1000.0) as u16 } else { 0 };
        let (l, rt) = (crate::player::clock(pos), crate::player::clock(dur));
        let lw = (l.chars().count() as i32 + 1) * cw;
        let rw = (rt.chars().count() as i32 + 1) * cw;
        let bar = Rect { x: body.x + lw, y, w: (body.w - lw - rw).max(cw), h: row_h };
        let hover = if inside(bar, self.pointer) || matches!(self.press, Some(Press::Scrub)) {
            Some(((self.pointer.0 - bar.x) as f64 / bar.w as f64).clamp(0.0, 1.0) * dur)
        } else {
            None
        };
        o.items.push(item(Rect { x: body.x, w: lw, ..bar }, l, PanelStyle::Label, UiAction::None));
        o.items.push(item(bar, "", PanelStyle::Progress { done: per(pos), hover: hover.map_or(u16::MAX, per) }, UiAction::None));
        o.items.push(item(Rect { x: bar.x + bar.w + cw, w: rw, ..bar }, rt, PanelStyle::Label, UiAction::None));
        self.hits.bar = bar;
        y += row_h + 2;
        // Buttons, state (or the hovered time), volume.
        let mut x = body.x;
        let bh = row_h - 2;
        let play = if pl.playing() { "❚❚ pause" } else { "▶ play" };
        for (t, a) in [("« 10s", "seek_back"), (play, "play_pause"), ("10s »", "seek_forward")] {
            let bw = (t.chars().count() as i32 + 2) * cw;
            o.items.push(item(Rect { x, y, w: bw, h: bh }, t, PanelStyle::Button { primary: a == "play_pause" }, act(a, 0)));
            x += bw + cw / 2;
        }
        let status = match (hover, &pl.error) {
            (Some(t), _) => format!("→ {}", crate::player::clock(t)),
            (None, _) => {
                let st = if pl.playing() { "playing" } else { "paused" };
                match pl.audio_host() {
                    Some(h) => format!("{st} · {h}"),
                    None => st.to_string(),
                }
            }
        };
        let vw = (cw * 12).min(body.w / 5);
        let vlabel = format!("vol {}%", pl.volume);
        let vlw = (vlabel.chars().count() as i32 + 1) * cw;
        let vol = Rect { x: body.x + body.w - vw, y, w: vw, h: bh };
        o.items.push(item(Rect { x: x + cw, y, w: (vol.x - vlw - x - cw).max(0), h: bh }, status, PanelStyle::Label, UiAction::None));
        o.items.push(item(Rect { x: vol.x - vlw, y, w: vlw, h: bh }, vlabel, PanelStyle::Label, UiAction::None));
        o.items.push(item(vol, "", PanelStyle::Progress { done: pl.volume as u16 * 10, hover: u16::MAX }, UiAction::None));
        self.hits.vol = vol;
        y += row_h;
        o.items.push(item(Rect { x: body.x, y, w: body.w, h: row_h }, clip_text(&controls, body.w / cw.max(1)), PanelStyle::Hint, UiAction::None));
    }

    fn audio_view(&mut self, body: Rect, cw: i32, ch: i32, o: &mut Out) {
        self.fullscreen = false;
        self.player_view(body, cw, ch, o);
        self.fullscreen = true;
    }

    /// Fullscreen: the title strip (while the controls show) over the whole
    /// window; returns the body for the picture / player.
    fn fullscreen_chrome(&mut self, p: &Path, full: Rect, cw: i32, ch: i32, keys: &Keymap, o: &mut Out) -> Rect {
        o.items.clear();
        o.menu = None;
        self.menu_open = false;
        self.hits.menu = Rect::default();
        let audio = self.player.as_ref().is_some_and(|pl| !pl.info.video);
        if !(audio || self.fs_controls_shown()) {
            self.fs_schedule_hide();
            return full;
        }
        if !audio {
            self.fs_schedule_hide();
        }
        let row_h = ch + 8;
        let (x0, y0) = (full.x + 10, full.y + 6);
        let label = format!("exit fullscreen ({} / esc)", keys.label("fullscreen"));
        let bw = (label.chars().count() as i32 + 2) * cw;
        let bx = full.x + full.w - 10 - bw;
        o.items.push(item(Rect { x: bx, y: y0, w: bw, h: row_h - 2 }, label, PanelStyle::Button { primary: false }, act("fullscreen", 0)));
        let name = p.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
        let t = match self.zoom_label(p) {
            Some(z) => format!("{z} · {name}"),
            None => name,
        };
        o.items.push(item(
            Rect { x: x0, y: y0, w: (bx - x0 - cw).max(0), h: row_h },
            clip_text(&t, ((bx - x0) / cw - 1).max(0)),
            PanelStyle::Title,
            UiAction::None,
        ));
        let top = y0 + row_h + 6;
        Rect { x: full.x + 10, y: top, w: full.w - 20, h: full.y + full.h - top - 8 }
    }

    fn toggle_fullscreen(&mut self) {
        let now = std::time::Instant::now();
        self.zoom = None;
        self.fs_poke();
        if self.reduce_motion {
            self.fs_anim = None;
            self.fullscreen = !self.fullscreen;
            return;
        }
        if let Some(anim) = self.fs_anim.take() {
            let cur = anim.rect(now);
            self.fs_anim = Some(if anim.opening {
                FsAnim { opening: false, from: cur, to: self.fs_thumb.unwrap_or(cur), start: now, ticking: false }
            } else {
                self.fullscreen = true;
                FsAnim { opening: true, from: cur, to: cur, start: now, ticking: false }
            });
            return;
        }
        if !self.fullscreen {
            self.fs_thumb = self.last_preview.filter(|r| r.w > 0 && r.h > 0);
            let from = self.fs_thumb.unwrap_or(self.hits.image);
            self.fullscreen = true;
            if from.w > 0 && from.h > 0 {
                self.fs_anim = Some(FsAnim { opening: true, from, to: from, start: now, ticking: false });
            }
        } else {
            let from = self.last_preview.filter(|r| r.w > 0 && r.h > 0).unwrap_or(self.hits.image);
            let to = self.fs_thumb.filter(|r| r.w > 0 && r.h > 0).unwrap_or(from);
            if from.w > 0 && from.h > 0 {
                self.fs_anim = Some(FsAnim { opening: false, from, to, start: now, ticking: false });
            } else {
                self.fullscreen = false;
            }
        }
    }

    /// Patch the flying picture, fade the veil, and keep redrawing until the
    /// open/close transition ends.
    fn apply_fs_anim(&mut self, images: &mut [(ModeImage, Rect)], frames: &mut [ModeImage], items: &mut Vec<PanelItem>, win: Rect) {
        let Some(anim) = self.fs_anim.as_mut() else { return };
        let now = std::time::Instant::now();
        if anim.opening
            && let Some(dest) = images.first().map(|(i, _)| i.rect).or_else(|| frames.first().map(|f| f.rect)).filter(|r| r.w > 0 && r.h > 0)
        {
            anim.to = dest;
        }
        let r = anim.rect(now);
        let veil = anim.veil(now);
        for (img, clip) in images.iter_mut() {
            img.rect = r;
            *clip = win;
        }
        for f in frames.iter_mut() {
            f.rect = r;
        }
        items.insert(0, item(win, "", PanelStyle::Dim(veil), UiAction::None));
        self.fs_keep_redrawing();
    }

    fn fs_keep_redrawing(&mut self) {
        let Some(anim) = self.fs_anim.as_mut() else { return };
        if anim.ticking {
            return;
        }
        let Some(w) = self.waker.clone() else { return };
        anim.ticking = true;
        let until = anim.end();
        let _ = std::thread::Builder::new().name("fs-anim".into()).spawn(move || {
            while std::time::Instant::now() < until + std::time::Duration::from_millis(10) {
                std::thread::sleep(std::time::Duration::from_millis(8));
                w();
            }
        });
    }

    /// Pointer moved / key pressed in fullscreen: show the controls again.
    fn fs_poke(&mut self) {
        self.fs_active = std::time::Instant::now();
        self.fs_gen.fetch_add(1, Ordering::SeqCst);
    }

    fn fs_controls_shown(&self) -> bool {
        self.fs_active.elapsed() < FS_CONTROLS
    }

    /// Redraw once the controls are due to hide (a paused picture gets no
    /// other frames).
    fn fs_schedule_hide(&self) {
        let Some(w) = self.waker.clone() else { return };
        let g = self.fs_gen.clone();
        let mine = g.load(Ordering::SeqCst);
        static ARMED: Mutex<u64> = Mutex::new(u64::MAX);
        {
            let mut a = ARMED.lock().unwrap();
            if *a == mine {
                return;
            }
            *a = mine;
        }
        let left = FS_CONTROLS.saturating_sub(self.fs_active.elapsed()) + std::time::Duration::from_millis(30);
        std::thread::spawn(move || {
            std::thread::sleep(left);
            if g.load(Ordering::SeqCst) == mine {
                w();
            }
        });
    }

    fn options_panel(&self, ctx: &Context) -> Panel {
        let vp = ctx.viewport;
        let (cw, ch) = (vp.cell_w, vp.cell_h);
        let row_h = ch + 10;
        let w = (cw * 56).min(vp.width - 16);
        let h = (row_h * 8 + 24).min(vp.height - 16);
        let rect = Rect { x: (vp.width - w) / 2, y: (vp.height - h) / 2, w, h };
        let (x0, mut y) = (rect.x + 14, rect.y + 12);
        let mut items = vec![
            item(
                Rect { x: x0, y, w: w - 28 - 8 * cw, h: row_h },
                format!("Commander options   ls {}", self.c.flags.ls()),
                PanelStyle::Title,
                UiAction::None,
            ),
            item(Rect { x: rect.x + w - 14 - 7 * cw, y, w: 7 * cw, h: row_h - 4 }, "close", PanelStyle::Button { primary: false }, act("close", 0)),
        ];
        y += row_h + 6;
        let f = &self.c.flags;
        let rows: [(&str, Vec<Btn<'_>>); 5] = [
            (
                "View",
                ["list", "grid", "carousel"].iter().enumerate().map(|(i, n)| (n.to_string(), self.c.view as usize == i, "view", i as i32)).collect(),
            ),
            (
                "Tiles",
                vec![
                    ("smaller".into(), false, "smaller", 0),
                    (format!("{}px", TILE_SIZES[self.c.tile]), true, "", 0),
                    ("bigger".into(), false, "bigger", 0),
                ],
            ),
            ("Show", vec![("dotfiles (-a)".into(), f.all, "hidden", 0), ("human sizes (-h)".into(), f.human, "human", 0)]),
            (
                "Sort",
                [("name", Sort::Name), ("modified (-t)", Sort::Modified), ("size (-S)", Sort::Size)]
                    .iter()
                    .enumerate()
                    .map(|(i, (n, s))| (n.to_string(), f.sort == *s, "sort", i as i32))
                    .collect(),
            ),
            ("Order", vec![("reverse (-r)".into(), f.reverse, "reverse", 0)]),
        ];
        for (label, btns) in rows {
            items.push(item(Rect { x: x0, y, w: 8 * cw, h: row_h - 4 }, label, PanelStyle::Label, UiAction::None));
            let mut x = x0 + 9 * cw;
            for (t, on, id, arg) in btns {
                let bw = (t.chars().count() as i32 + 2) * cw;
                let a = if id.is_empty() { UiAction::None } else { act(id, arg) };
                items.push(item(Rect { x, y, w: bw, h: row_h - 4 }, t, PanelStyle::Button { primary: on }, a));
                x += bw + cw;
            }
            y += row_h;
        }
        Panel { rect, items }
    }

    fn man_panel(&mut self, ctx: &Context, keys: &Keymap) -> Panel {
        let vp = ctx.viewport;
        let lines = cmdr::manual(keys);
        let rows = ((vp.height - 80) / (vp.cell_h + 6)).max(1) as usize;
        self.c.overlay_scroll = self.c.overlay_scroll.min(lines.len().saturating_sub(rows));
        let shown: Vec<(String, String)> = lines.into_iter().skip(self.c.overlay_scroll).take(rows).map(|l| (l, String::new())).collect();
        crate::host::list_panel(vp, "commander(1)", &shown, |_| UiAction::None)
    }
}

impl Mode for CommanderMode {
    fn name(&self) -> &'static str {
        "commander"
    }

    fn hotkey(&self) -> char {
        'c'
    }

    fn bindings(&self) -> &'static [Binding] {
        cmdr::BINDINGS
    }

    fn deactivate(&mut self) {
        self.c.reset();
        self.previews.want(Vec::new());
    }

    fn cwd_changed(&mut self, dir: &Path) {
        let was_remote = self.ssh.take().is_some();
        if was_remote {
            self.previews.set_remote(None);
            self.open_remote = None;
            self.heads.clear();
            self.texts.clear();
        }
        // Every prompt reports the shell's folder; commander follows only a
        // change there (a `cd` typed in the shell), not the shell staying put
        // while commander browses elsewhere.
        if !was_remote && self.c.remote.is_none() && self.shell_dir.as_deref() == Some(dir) && self.c.cwd.is_some() {
            return;
        }
        self.shell_dir = Some(dir.to_path_buf());
        self.c.set_cwd(Some(dir.to_path_buf()));
    }

    fn remote_ssh(&mut self, ssh: Option<&crate::remote::SshTarget>) {
        let r = ssh.cloned().map(fetch::Remote::new);
        if r != self.ssh {
            self.ssh = r;
            self.open_remote = None;
            self.heads.clear();
            self.texts.clear();
        }
    }

    fn remote_changed(&mut self, label: &str, dir: Option<&Path>, listing: Option<Result<Vec<Entry>, String>>) {
        // The remote shell staying in a folder commander has browsed away from.
        if let Some(d) = dir
            && self.c.remote.as_deref() == Some(label)
            && self.shell_dir.as_deref() == Some(d)
            && self.c.cwd.as_deref().is_some_and(|c| c != d)
        {
            return;
        }
        if dir.is_some() {
            self.shell_dir = dir.map(Path::to_path_buf);
        }
        let fresh = listing.as_ref().is_some_and(|l| l.is_ok());
        self.c.set_remote(label.to_string(), dir.map(Path::to_path_buf), listing);
        if fresh {
            let secs =
                |t: Option<std::time::SystemTime>| t.and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok()).map_or(0, |d| d.as_secs() as i64);
            let meta: HashMap<PathBuf, (u64, i64)> = self.c.entries.iter().map(|e| (e.path.clone(), (e.size, secs(e.modified)))).collect();
            if *self.remote_meta != meta {
                self.remote_meta = Arc::new(meta);
            }
        }
        self.previews.set_remote(self.ssh.clone().map(|remote| RemoteCtx { remote, meta: self.remote_meta.clone() }));
    }

    fn set_waker(&mut self, w: Waker) {
        self.waker = Some(w.clone());
        self.previews.set_waker(w);
    }

    fn text(&mut self, bytes: &[u8]) -> Option<Effect> {
        if bytes == b"\t" || bytes == b"\x1b[Z" {
            let reverse = bytes == b"\x1b[Z";
            if self.ask.is_some() {
                return Some(self.ask_key(bytes));
            }
            if self.c.piping {
                self.complete_pipe(reverse);
                return Some(Effect::None);
            }
            if self.c.searching {
                self.complete_search(reverse);
                return Some(Effect::None);
            }
        }
        if self.ask.is_some() {
            if bytes == b"\x1b" {
                self.ask = None;
                self.complete.reset();
                self.complete_hint.clear();
                return Some(Effect::None);
            }
            return (bytes == b"\x1b[Z" || bytes.len() == 1 || bytes[0] != 0x1b).then(|| self.ask_key(bytes));
        }
        if self.fullscreen && bytes != b"\x1b" {
            if let Some(id) = fs_key(bytes) {
                self.fs_poke();
                let e = self.action(id, if id == "scroll" { 1 } else { 0 });
                return Some(if e == Effect::Pass { Effect::None } else { e });
            }
            // Other keys go to the bindings (the host swallows the rest while
            // the mode has focus, so nothing types into the hidden shell).
            return None;
        }
        // Arrows and other escape sequences still reach the bindings while searching.
        if bytes.len() > 1 && bytes[0] == 0x1b {
            return None;
        }
        if let Some(e) = self.c.pipe_key(bytes) {
            self.complete.reset();
            self.complete_hint.clear();
            return Some(self.effect(e));
        }
        let took = self.c.search_key(bytes);
        if took {
            self.complete.reset();
            self.complete_hint.clear();
        }
        took.then_some(Effect::None)
    }

    fn wants_text(&self) -> bool {
        self.c.searching || self.c.piping || self.fullscreen || self.ask.is_some()
    }

    fn wants_key(&self, bytes: &[u8]) -> bool {
        // Fullscreen: the arrows go to the player / image, not the shell.
        self.fullscreen && fs_key(bytes).is_some()
    }

    fn escape(&mut self) -> bool {
        if self.ask.take().is_some() {
            self.complete.reset();
            self.complete_hint.clear();
            true
        } else if self.fullscreen {
            if self.fs_anim.as_ref().is_some_and(|a| !a.opening) {
                self.fs_anim = None;
                self.fullscreen = false;
            } else {
                self.toggle_fullscreen();
            }
            true
        } else if self.menu_open {
            self.menu_open = false;
            true
        } else if self.c.piping {
            self.c.pipe_key(b"\x1b");
            true
        } else if self.c.searching {
            self.c.search_key(b"\x1b");
            true
        } else {
            self.c.overlay.take().is_some()
        }
    }

    fn action(&mut self, id: &str, arg: i32) -> Effect {
        if let Some(m) = id.strip_prefix("menu:") {
            let m = m.to_string();
            return self.menu_action(&m, arg);
        }
        if matches!(id, "pointer_down" | "pointer_move" | "pointer_up") {
            self.pointer(id, unpack_xy(arg));
            return Effect::None;
        }
        // Keys for what the context menu offers: the same action, on the
        // marked or selected items.
        if matches!(
            id,
            "open_fullscreen"
                | "sync_item"
                | "copy"
                | "paste"
                | "copy_to"
                | "move_to"
                | "rename"
                | "delete"
                | "new_folder"
                | "copy_path"
                | "copy_text"
        ) {
            if self.ask.is_some() {
                return Effect::None;
            }
            return self.menu_action(id, -1);
        }
        // One key per view and per sort order.
        let (id, arg) = match id {
            "view_list" => ("view", 0),
            "view_grid" => ("view", 1),
            "view_carousel" => ("view", 2),
            "sort_name" => ("sort", 0),
            "sort_modified" => ("sort", 1),
            "sort_size" => ("sort", 2),
            "help" => ("keys", 0),
            i => (i, arg),
        };
        if id == "fullscreen" {
            let media = matches!(&self.c.overlay, Some(Overlay::Preview(p)) if is_media(p));
            if !media && !self.fullscreen {
                return Effect::Pass;
            }
            self.toggle_fullscreen();
            return Effect::None;
        }
        let playing = self.player.is_some();
        let id = match id {
            "left_fs" if playing => "seek_back",
            "right_fs" if playing => "seek_forward",
            "up_fs" if playing => "volume_up",
            "down_fs" if playing => "volume_down",
            "left_fs" => "left",
            "right_fs" => "right",
            "up_fs" => "up",
            "down_fs" => "down",
            i => i,
        };
        if id == "menu" {
            if self.hits.menu.w == 0 && !self.menu_open {
                return Effect::Pass;
            }
            self.menu_open = !self.menu_open;
            return Effect::None;
        }
        self.menu_open = false;
        let viewing_image = matches!(&self.c.overlay, Some(Overlay::Preview(p)) if cmdr::kind_of(&p.to_string_lossy()) == Kind::Image);
        // The zoom and volume keys are shared by default: each view takes its own.
        let id = match id {
            "volume_up" if viewing_image => "zoom_in",
            "volume_down" if viewing_image => "zoom_out",
            "zoom_in" if self.player.is_some() => "volume_up",
            "zoom_out" if self.player.is_some() => "volume_down",
            i => i,
        };
        match id {
            "zoom_in" | "zoom_out" | "zoom_fit" | "zoom_actual" | "zoom_wheel" => {
                let f = match id {
                    "zoom_in" => Some(1.25),
                    "zoom_out" => Some(0.8),
                    "zoom_fit" => None,
                    "zoom_actual" => Some(0.0),
                    _ => Some(if arg > 0 { 1.15f64.powi(arg) } else { 0.87f64.powi(-arg) }),
                };
                let anchor = (id == "zoom_wheel").then_some(self.pointer);
                return if self.zoom_image(f, anchor) { Effect::None } else { Effect::Pass };
            }
            _ => {}
        }
        if self.zoom.is_some() && viewing_image {
            let step = (self.hits.image.h / 8).max(16);
            let (dx, dy) = match id {
                "left" => (-step, 0),
                "right" => (step, 0),
                "up" => (0, -step),
                "down" => (0, step),
                "scroll" => (0, arg * step / 2),
                _ => (0, 0),
            };
            if (dx, dy) != (0, 0) && self.pan(dx, dy) {
                return Effect::None;
            }
        }
        if id == "scroll"
            && let Some(p) = self.player.as_mut()
            && inside(self.hits.vol, self.pointer)
        {
            p.change_volume(-arg * 5);
            return Effect::None;
        }
        // Player keys belong to the player; without one they go to the shell.
        if matches!(id, "play_pause" | "seek_back" | "seek_forward" | "volume_down" | "volume_up") {
            let Some(p) = self.player.as_mut() else { return Effect::Pass };
            match id {
                "play_pause" => p.toggle(),
                "seek_back" => p.seek(-10.0),
                "seek_forward" => p.seek(10.0),
                "volume_down" => p.change_volume(-10),
                _ => p.change_volume(10),
            }
            return Effect::None;
        }
        let n = self.c.visible().len();
        let previewing = matches!(self.c.overlay, Some(Overlay::Preview(_)));
        let reading = previewing || self.c.overlay == Some(Overlay::Man);
        match id {
            "item" => {
                let i = (arg.max(0) as usize).min(n.saturating_sub(1));
                // A second click on the same item within 400 ms opens it.
                let now = std::time::Instant::now();
                let double = self.last_click.is_some_and(|(j, t)| j == i && now.duration_since(t) < std::time::Duration::from_millis(400));
                self.c.selected = i;
                if double {
                    self.last_click = None;
                    let e = self.c.open_selected();
                    return self.effect(e);
                }
                self.last_click = Some((i, now));
                return Effect::None;
            }
            "view" => {
                self.c.view = [Layout::List, Layout::Grid, Layout::Carousel][arg.clamp(0, 2) as usize];
                self.c.scroll = 0;
                return Effect::None;
            }
            "human" => self.c.flags.human = !self.c.flags.human,
            "reverse" => self.c.flags.reverse = !self.c.flags.reverse,
            "sort" => self.c.flags.sort = [Sort::Name, Sort::Modified, Sort::Size][arg.clamp(0, 2) as usize],
            "close" => {
                self.fs_anim = None;
                self.fullscreen = false;
                self.c.overlay = None
            }
            "keys" => return Effect::ShowKeys,
            "sync" => return self.sync(),
            "up_to" => {
                let mut d = self.c.cwd.clone();
                for _ in 0..arg.max(0) {
                    d = d.and_then(|d| d.parent().map(Path::to_path_buf));
                }
                return match d {
                    Some(d) => {
                        let e = self.c.jump(d);
                        self.effect(e)
                    }
                    None => Effect::None,
                };
            }
            // In the file view (and the player) back closes the view first.
            "parent" | "back" if previewing => {
                self.fs_anim = None;
                self.fullscreen = false;
                self.c.overlay = None;
                self.c.close_file();
                return Effect::None;
            }
            "scroll" => {
                if reading {
                    self.c.overlay_scroll = (self.c.overlay_scroll as i64 + arg as i64 * 3).max(0) as usize;
                } else {
                    let step = if self.c.view == Layout::Grid { self.per_row as i64 } else { 1 };
                    self.c.selected = (self.c.selected as i64 + arg as i64 * step).clamp(0, n.saturating_sub(1) as i64) as usize;
                }
                return Effect::None;
            }
            _ => {
                let Some(a) = Action::from_id(id) else { return Effect::None };
                if reading && matches!(a, Action::Up | Action::Down | Action::PageUp | Action::PageDown) {
                    let d = match a {
                        Action::Up => -1,
                        Action::Down => 1,
                        Action::PageUp => -20,
                        _ => 20,
                    };
                    self.c.overlay_scroll = (self.c.overlay_scroll as i64 + d).max(0) as usize;
                    return Effect::None;
                }
                let e = self.c.apply(a, self.per_row);
                if previewing && matches!(a, Action::Left | Action::Right) {
                    // Step through files in the file view.
                    if let Some(en) = self.c.selected_entry().cloned()
                        && !matches!(en.kind, Kind::Dir | Kind::Video | Kind::Audio)
                    {
                        self.c.overlay = Some(Overlay::Preview(en.path));
                        self.c.overlay_scroll = 0;
                    }
                }
                // `hidden` changes the listing.
                self.c.relist();
                return self.effect(e);
            }
        }
        // Flags changed: re-list.
        self.c.relist();
        Effect::None
    }

    fn view(&mut self, ctx: &Context, keys: &Keymap) -> View {
        self.reduce_motion = ctx.reduce_motion;
        if self.fs_anim.as_ref().is_some_and(|a| a.finished(std::time::Instant::now())) {
            if self.fs_anim.as_ref().is_some_and(|a| !a.opening) {
                self.fullscreen = false;
            }
            self.fs_anim = None;
        }
        let vp = ctx.viewport;
        let (cw, ch) = (vp.cell_w.max(1), vp.cell_h.max(1));
        let a = ctx.area;
        let max_h = (a.h - ch * 8).max(ch * 4);
        let h = self.dock.height(a, ch, (a.h / 2).max(ch * 10).min(max_h));
        let rect = Rect { x: a.x + PADDING, y: a.y, w: a.w - 2 * PADDING, h };
        // A remote file in the viewer: its transfer (dropped when it closes).
        match &self.c.overlay {
            Some(Overlay::Preview(p)) if self.c.remote.is_some() => {
                let p = p.clone();
                self.ensure_open_remote(&p);
            }
            _ => self.open_remote = None,
        }
        // Playback stops when the viewer closes or shows another file.
        if self.player.as_ref().is_some_and(|pl| !matches!(&self.c.overlay, Some(Overlay::Preview(p)) if *p == pl.path)) {
            self.player = None;
        }
        let mut o =
            Out { items: Vec::new(), frames: Vec::new(), slots: Vec::new(), texts: Vec::new(), extra: Vec::new(), menu: None, floats: Vec::new() };
        let row_h = ch + 8;
        let (x0, y0, w) = (rect.x + 10, rect.y + 6, rect.w - 20);
        // Header: where we are, then the buttons.
        let mut bx = x0 + w;
        let file = match &self.c.overlay {
            Some(Overlay::Preview(p)) => Some(p.clone()),
            _ => None,
        };
        let buttons: Vec<(String, UiAction)> = if file.is_some() {
            let mut b = vec![("close (esc)".into(), act("close", 0))];
            if file.as_deref().is_some_and(is_media) {
                b.insert(0, (format!("fullscreen ({})", keys.label("fullscreen")), act("fullscreen", 0)));
            }
            b
        } else {
            vec![
                ("help".into(), act("keys", 0)),
                ("man".into(), act("man", 0)),
                ("options".into(), act("options", 0)),
                (format!("{} ({})", self.c.view.name(), keys.label("switch_view")), act("switch_view", 0)),
            ]
        };
        // Narrow: the path shortens first (down to ~16 columns), then the
        // buttons that still do not fit go, one by one, into a ••• menu.
        let widths: Vec<i32> = buttons.iter().map(|(t, _)| (t.chars().count() as i32 + 2) * cw + cw / 2).collect();
        let menu_w = 5 * cw + cw / 2;
        let back_min = 8 * cw;
        let fits = header_fit(&widths, w - back_min - 16 * cw, menu_w);
        let mut rest = buttons;
        let hidden = rest.split_off(fits);
        self.hits.menu = Rect::default();
        if !hidden.is_empty() {
            bx -= menu_w - cw / 2;
            let mr = Rect { x: bx, y: y0, w: menu_w - cw / 2, h: row_h - 2 };
            self.hits.menu = mr;
            o.items.push(item(mr, "•••", PanelStyle::Button { primary: self.menu_open }, act("menu", 0)));
            bx -= cw / 2;
            if self.menu_open {
                let mw = hidden.iter().map(|(t, _)| t.chars().count() as i32 + 4).max().unwrap_or(8) * cw;
                let r = Rect { x: (mr.x + mr.w - mw).max(rect.x + 4), y: mr.y + mr.h + 4, w: mw, h: hidden.len() as i32 * row_h + 8 };
                o.menu = Some(r);
                o.items.push(item(r, "", PanelStyle::Popup, UiAction::None));
                for (i, (t, a)) in hidden.into_iter().enumerate() {
                    let rr = Rect { x: r.x + 4, y: r.y + 4 + i as i32 * row_h, w: r.w - 8, h: row_h };
                    o.items.push(item(rr, t, PanelStyle::Option { selected: false, highlight: 0 }, a));
                }
            }
        } else {
            self.menu_open = false;
        }
        for (t, a) in rest {
            let bw = (t.chars().count() as i32 + 2) * cw;
            bx -= bw;
            o.items.push(item(Rect { x: bx, y: y0, w: bw, h: row_h - 2 }, t, PanelStyle::Button { primary: false }, a));
            bx -= cw / 2;
        }
        let home = std::env::var_os("HOME").map(PathBuf::from);
        let show = |p: &Path| match home.as_ref().and_then(|h| p.strip_prefix(h).ok()) {
            Some(r) if r.as_os_str().is_empty() => "~".to_string(),
            Some(r) => format!("~/{}", r.display()),
            None => p.display().to_string(),
        };
        // Back control: goes to the parent folder (or closes the file view);
        // disabled at /.
        let can_back = file.is_some() || self.c.cwd.as_ref().is_some_and(|d| d.parent().is_some());
        let back =
            if (x0 + w - bx) / cw.max(1) + 40 < w / cw.max(1) { format!("‹ back ({})", keys.label("parent")) } else { "‹ back".to_string() };
        let back_w = (back.chars().count() as i32 + 2) * cw;
        o.items.push(item(
            Rect { x: x0, y: y0, w: back_w, h: row_h - 2 },
            back,
            if can_back { PanelStyle::Button { primary: false } } else { PanelStyle::Hint },
            if can_back { act("parent", 0) } else { UiAction::None },
        ));
        let mut tx = x0 + back_w + cw;
        let room = |tx: i32| ((bx - tx) / cw - 1).max(0);
        match (&file, &self.c.cwd) {
            (Some(p), _) => {
                let t = match self.zoom_label(p) {
                    Some(z) => format!("{z} · {}", show(p)),
                    None => show(p),
                };
                let t = clip_text(&t, room(tx));
                o.items.push(item(Rect { x: tx, y: y0, w: (bx - tx).max(0), h: row_h }, t, PanelStyle::Title, UiAction::None));
            }
            (None, Some(d)) => {
                if let Some(r) = &self.c.remote {
                    let t = format!("{r}:");
                    let n = (t.chars().count() as i32).min(room(tx));
                    o.items.push(item(Rect { x: tx, y: y0, w: n * cw, h: row_h }, clip_text(&t, n), PanelStyle::Title, UiAction::None));
                    tx += n * cw;
                }
                // Path segments: a click goes to that folder. Too long: the
                // leading ones give way to "…".
                let shown = if self.c.remote.is_some() { d.display().to_string() } else { show(d) };
                let mut segs = path_segments(&shown);
                let width = |v: &[(String, usize)]| v.iter().map(|s| s.0.chars().count() as i32).sum::<i32>();
                if width(&segs) > room(tx) {
                    while segs.len() > 1 && width(&segs) + 1 > room(tx) {
                        segs.remove(0);
                    }
                    o.items.push(item(Rect { x: tx, y: y0, w: cw, h: row_h }, "…", PanelStyle::Hint, UiAction::None));
                    tx += cw;
                }
                for (label, depth) in segs {
                    let n = (label.chars().count() as i32).min(room(tx));
                    let label = clip_text(&label, n);
                    let up = depth;
                    let a = if up > 0 { act("up_to", up as i32) } else { UiAction::None };
                    o.items.push(item(Rect { x: tx, y: y0, w: n * cw, h: row_h }, label, PanelStyle::Title, a));
                    tx += n * cw;
                }
                let marks = if self.c.marks.is_empty() { String::new() } else { format!(" · {} marked", self.c.marks.len()) };
                let rest = format!("   {} items{marks} · ls {}", self.c.visible().len(), self.c.flags.ls());
                o.items.push(item(
                    Rect { x: tx, y: y0, w: (bx - tx).max(0), h: row_h },
                    clip_text(&rest, room(tx)),
                    PanelStyle::Hint,
                    UiAction::None,
                ));
            }
            (None, None) => {
                let t = self.c.remote.as_ref().map_or("commander".to_string(), |r| format!("{r}: (remote, folder unknown)"));
                o.items.push(item(Rect { x: tx, y: y0, w: (bx - tx).max(0), h: row_h }, clip_text(&t, room(tx)), PanelStyle::Title, UiAction::None))
            }
        }
        let mut body = Rect { x: x0, y: y0 + row_h + 6, w, h: rect.y + h - (y0 + row_h + 6) - 8 };
        self.body_w = body.w;
        self.player_keys = format!(
            "{} play/pause · {} / {} seek 10s · {} / {} volume · {} close",
            keys.label("play_pause"),
            keys.label("seek_back"),
            keys.label("seek_forward"),
            keys.label("volume_down"),
            keys.label("volume_up"),
            keys.label("close")
        );
        if self.fullscreen && !file.as_deref().is_some_and(is_media) {
            self.fs_anim = None;
            self.fullscreen = false;
        }
        let rect = if self.fullscreen { Rect { x: 0, y: 0, w: vp.width, h: vp.height } } else { rect };
        if let (true, Some(p)) = (self.fullscreen, &file) {
            if self.fs_anim.is_none() {
                body = self.fullscreen_chrome(p, rect, cw, ch, keys, &mut o);
            } else {
                o.items.clear();
                o.menu = None;
                self.menu_open = false;
                self.hits.menu = Rect::default();
                body = rect;
            }
        }
        if let Some(p) = file {
            self.file_view(&p, body, cw, ch, &mut o);
        } else {
            // Search field, or the pipe prompt.
            let fw = (cw * 40).min(w);
            if let Some((ask, text)) = &self.ask {
                let fr = Rect { x: x0, y: body.y, w: (cw * 60).min(w), h: row_h };
                o.items.push(item(fr, text.clone(), PanelStyle::Field { focused: true, valid: true }, UiAction::None));
                o.items.push(item(
                    Rect { x: fr.x + fr.w + cw, y: fr.y, w: (w - fr.w - cw).max(0), h: row_h },
                    {
                        let extra = if self.complete_hint.is_empty() { "Tab completes".to_string() } else { self.complete_hint.clone() };
                        format!("{} · {extra} · Enter asks to confirm · Esc cancels", ask.prompt())
                    },
                    PanelStyle::Hint,
                    UiAction::None,
                ));
            } else if self.c.piping {
                let n = self.c.pipe_paths().len();
                let fr = Rect { x: x0, y: body.y, w: (cw * 60).min(w), h: row_h };
                o.items.push(item(fr, format!("| {}", self.c.pipe_cmd), PanelStyle::Field { focused: true, valid: true }, UiAction::None));
                o.items.push(item(
                    Rect { x: fr.x + fr.w + cw, y: fr.y, w: (w - fr.w - cw).max(0), h: row_h },
                    {
                        let extra = if self.complete_hint.is_empty() { "Tab completes".to_string() } else { self.complete_hint.clone() };
                        format!("pipe {n} path(s) · {extra} · Enter runs · Esc cancels")
                    },
                    PanelStyle::Hint,
                    UiAction::None,
                ));
            } else {
                let fr = Rect { x: x0, y: body.y, w: fw, h: row_h };
                o.items.push(item(
                    fr,
                    self.c.filter.clone(),
                    PanelStyle::Field { focused: self.c.searching, valid: !self.c.visible().is_empty() || self.c.filter.is_empty() },
                    act("search", 0),
                ));
                if self.c.filter.is_empty() && !self.c.searching {
                    o.items.push(item(
                        Rect { x: fr.x + cw, w: fw - 2 * cw, ..fr },
                        format!("search ({})", keys.label("search")),
                        PanelStyle::Hint,
                        act("search", 0),
                    ));
                }
                // Feedback: what is filtered, how many match, and that typing goes here.
                let n = self.c.visible().len();
                let fb = match (self.c.searching, self.c.filter.is_empty()) {
                    (true, true) => {
                        if self.complete_hint.is_empty() {
                            "searching · type to filter · Tab completes · Enter keeps · Esc cancels".to_string()
                        } else {
                            format!("{} · Enter keeps · Esc cancels", self.complete_hint)
                        }
                    }
                    (s, false) => {
                        let m = if n == 0 {
                            format!("no matches for \"{}\"", self.c.filter)
                        } else {
                            format!("{n} match{} for \"{}\"", if n == 1 { "" } else { "es" }, self.c.filter)
                        };
                        if s { format!("{m} · Enter keeps · Esc clears") } else { format!("{m} · {} to edit", keys.label("search")) }
                    }
                    (false, true) => self.c.notice.clone().unwrap_or_default(),
                };
                if !fb.is_empty() {
                    let room = (w - fr.w - cw - 24 * cw).max(0);
                    o.items.push(item(
                        Rect { x: fr.x + fr.w + cw, y: fr.y, w: room, h: row_h },
                        clip_text(&fb, room / cw),
                        if n == 0 { PanelStyle::Error } else { PanelStyle::Hint },
                        UiAction::None,
                    ));
                }
            }
            let search_y = body.y;
            body.y += row_h + 8;
            body.h -= row_h + 8;
            self.range = None;
            if let Some(e) = &self.c.error {
                o.items.push(item(Rect { x: body.x, y: body.y, w: body.w, h: row_h }, e.clone(), PanelStyle::Error, UiAction::None));
            } else {
                match self.c.view {
                    Layout::List => {
                        self.per_row = 1;
                        self.list(body, cw, ch, &mut o)
                    }
                    Layout::Grid => self.grid(body, cw, ch, &mut o),
                    Layout::Carousel => {
                        self.per_row = 1;
                        self.carousel(body, cw, ch, &mut o)
                    }
                }
            }
            if let Some(r) = self.range.clone() {
                let lw = (r.chars().count() as i32 + 1) * cw;
                o.items.push(item(Rect { x: x0 + w - lw, y: search_y, w: lw, h: row_h }, r, PanelStyle::Hint, UiAction::None));
            }
        }
        // Only what is on screen loads; text snippets of files that left are dropped.
        self.previews.want(o.slots.iter().map(|s| s.0.clone()).chain(o.extra.iter().cloned()).collect());
        self.texts.retain(|p, _| o.texts.contains(p));
        // Off screen: their transfers stop.
        self.heads.retain(|p, _| o.texts.contains(p));
        let mut images = Vec::new();
        for (want, full, clip) in &o.slots {
            match self.previews.get(want) {
                Some(Some(t)) => {
                    let r = fit(*full, t.w, t.h);
                    images.push((ModeImage { key: t.key, rgba: t.rgba.clone(), width: t.w, height: t.h, src: (0, 0, t.w, t.h), rect: r }, *clip));
                }
                // Loading or no preview: the item's kind, centred and dim
                // (a video without ffmpeg stays "▶ video").
                _ => {
                    let label = kind_label(cmdr::kind_of(&want.0.to_string_lossy()));
                    let lw = (label.chars().count() as i32 * cw).min(clip.w);
                    let r = Rect { x: clip.x + (clip.w - lw).max(0) / 2, y: clip.y + (clip.h - ch).max(0) / 2, w: lw, h: ch };
                    o.items.push(item(r, label, PanelStyle::Hint, UiAction::None));
                }
            }
        }
        let panel = match self.c.overlay {
            Some(Overlay::Options) => Some(self.options_panel(ctx)),
            Some(Overlay::Man) => Some(self.man_panel(ctx, keys)),
            _ => None,
        };
        // Images are drawn as a layer above text; under a popup window they
        // would show through it, so they are left out while one is open.
        if let Some(p) = &panel {
            images.retain(|(i, _)| !overlaps(i.rect, p.rect));
        }
        let menu = o.menu;
        // Never outside the view (e.g. over the prompt below it), and clear
        // of its rounded corners.
        let inner = if self.fullscreen { rect } else { Rect { x: rect.x + crate::host::RADIUS, w: rect.w - 2 * crate::host::RADIUS, ..rect } };
        let mut images: Vec<(ModeImage, Rect)> = images.into_iter().map(|(i, c)| (i, intersect(c, inner))).collect();
        let mut frames = o.frames;
        self.apply_fs_anim(&mut images, &mut frames, &mut o.items, Rect { x: 0, y: 0, w: vp.width, h: vp.height });
        if let Some(m) = menu {
            images.retain(|(i, c)| !overlaps(intersect(i.rect, *c), m));
            frames.retain(|f| !overlaps(f.rect, m));
        }
        let mut items = o.items;
        // Floating labels are drawn over the images; not over the ••• menu.
        items.extend(o.floats.into_iter().filter(|f| menu.is_none_or(|m| !overlaps(f.rect, m))));
        let images: Vec<ModeImage> = images.into_iter().chain(frames.into_iter().map(|f| (f, inner))).filter_map(|(i, clip)| crop(i, clip)).collect();
        if self.fs_anim.is_none() {
            if let Some(i) = images.first() {
                self.last_preview = Some(i.rect);
            } else if matches!(self.c.overlay, Some(Overlay::Preview(_))) {
                self.last_preview = None;
            }
        }
        View { dock: Some(Panel { rect, items }), panel, images, fullscreen: self.fullscreen }
    }
}

impl CommanderMode {
    /// Escape would close something (the plugin tells Mouser, which asks
    /// before it handles Escape itself).
    pub fn escape_takes(&self) -> bool {
        self.fullscreen || self.menu_open || self.c.piping || self.c.searching || self.c.overlay.is_some() || self.ask.is_some()
    }

    /// Escape sequences taken as text now ([`Mode::wants_key`]).
    pub fn taken_keys(&self) -> Vec<String> {
        const ALL: [&str; 8] = ["\x1b[D", "\x1bOD", "\x1b[C", "\x1bOC", "\x1b[A", "\x1bOA", "\x1b[B", "\x1bOB"];
        let mut v: Vec<String> = ALL.iter().filter(|k| self.wants_key(k.as_bytes())).map(|k| k.to_string()).collect();
        if self.ask.is_some() || self.c.searching || self.c.piping {
            v.push("\x1b[Z".into());
        }
        v
    }

    /// Show `dir` without touching the shell: list it here, or over the ssh
    /// side channel when the listing is remote.
    fn browse(&mut self, dir: PathBuf) -> Effect {
        match self.c.remote.clone() {
            None => self.c.set_cwd(Some(dir)),
            Some(label) => {
                let listing = match &self.ssh {
                    Some(r) => r.run(&crate::remote::listing_command(&dir)).map(|out| crate::remote::parse_ls(&String::from_utf8_lossy(&out), &dir)),
                    None => Err(format!("{}: no ssh side channel to list it", dir.display())),
                };
                let fresh = listing.is_ok();
                self.c.set_remote(label, Some(dir), Some(listing));
                if fresh {
                    let secs = |t: Option<std::time::SystemTime>| {
                        t.and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok()).map_or(0, |d| d.as_secs() as i64)
                    };
                    self.remote_meta = Arc::new(self.c.entries.iter().map(|e| (e.path.clone(), (e.size, secs(e.modified)))).collect());
                    self.previews.set_remote(self.ssh.clone().map(|remote| RemoteCtx { remote, meta: self.remote_meta.clone() }));
                }
            }
        }
        Effect::None
    }

    /// `s` (sync): move the shell to commander's folder. The host does it silently
    /// through the shell integration (nothing typed, no history), or says why not.
    fn sync(&mut self) -> Effect {
        match self.c.cwd.clone() {
            Some(d) => Effect::Cd(d),
            None => Effect::Say("commander has no folder to sync to".into()),
        }
    }

    fn effect(&mut self, e: cmdr::Effect) -> Effect {
        match e {
            cmdr::Effect::None => Effect::None,
            // Commander's own navigation: list the folder here; the shell stays.
            cmdr::Effect::Cd(p) => self.browse(p),
            // The in-app player; the desktop opener only without ffmpeg.
            // Remote media: ffmpeg reads it through the fetch layer's local
            // HTTP server (seeks become prioritised ranged reads).
            cmdr::Effect::External(p) if self.c.remote.is_some() => {
                if !crate::player::available() {
                    self.c.notice = Some("playing remote media needs ffmpeg here".into());
                    return Effect::None;
                }
                self.c.overlay = Some(Overlay::Preview(p.clone()));
                self.c.overlay_scroll = 0;
                self.ensure_open_remote(&p);
                let Some((_, h)) = &self.open_remote else {
                    self.c.notice = Some(format!("{}: no ssh side channel to fetch it", p.display()));
                    return Effect::None;
                };
                let url = h.url();
                let mut pl = crate::player::Player::open_input(&p, Path::new(&url), self.body_w.max(320) as u32, self.waker.clone());
                pl.keep = Some(Box::new(h.clone()));
                self.player = Some(pl);
                Effect::None
            }
            cmdr::Effect::External(p) if crate::player::available() => {
                self.player = Some(crate::player::Player::open(&p, self.body_w.max(320) as u32, self.waker.clone()));
                self.c.overlay = Some(Overlay::Preview(p));
                self.c.overlay_scroll = 0;
                Effect::None
            }
            cmdr::Effect::External(p) => Effect::Open(p),
            cmdr::Effect::Run(s) => Effect::Run(s),
        }
    }
}

/// Cut an image drawn at `i.rect` to the visible part `clip` (carousel
/// neighbours): the destination shrinks and `src` follows.
fn crop(mut i: ModeImage, clip: Rect) -> Option<ModeImage> {
    let (src, at) = mouser_views::geom::crop(i.rect, (i.width, i.height), clip)?;
    i.src = src;
    i.rect = at;
    Some(i)
}

struct CommanderSource<'a> {
    entries: &'a [Entry],
    cwd: Option<&'a Path>,
    remote: Option<&'a fetch::Remote>,
    is_remote: bool,
}

impl mouser_mode_api::complete::PathSource for CommanderSource<'_> {
    fn list(&self, dir: &Path) -> Vec<mouser_mode_api::complete::DirEnt> {
        if !self.is_remote {
            return mouser_mode_api::complete::FsSource.list(dir);
        }
        if self.cwd == Some(dir) {
            return self.entries.iter().map(|e| mouser_mode_api::complete::DirEnt { name: e.name.clone(), is_dir: e.kind == Kind::Dir }).collect();
        }
        let Some(r) = self.remote else {
            return Vec::new();
        };
        match r.run(&crate::remote::listing_command(dir)) {
            Ok(out) => crate::remote::parse_ls(&String::from_utf8_lossy(&out), dir)
                .into_iter()
                .map(|e| mouser_mode_api::complete::DirEnt { name: e.name, is_dir: e.kind == Kind::Dir })
                .collect(),
            Err(_) => Vec::new(),
        }
    }

    fn home(&self) -> Option<PathBuf> {
        if self.is_remote { None } else { mouser_mode_api::complete::FsSource.home() }
    }
}

#[cfg(test)]
pub(crate) mod tests {
    use super::*;
    use crate::host::UiViewport;

    #[test]
    fn range_label_formats_and_clamps() {
        assert_eq!(range_label(0, 10, 42), "1–10 of 42");
        assert_eq!(range_label(40, 10, 42), "41–42 of 42");
        assert_eq!(range_label(0, 0, 0), "0 of 0");
    }

    #[test]
    fn scrollbar_only_when_overflowing() {
        let mut o = Out { items: vec![], frames: vec![], slots: vec![], texts: vec![], extra: vec![], menu: None, floats: vec![] };
        let r = Rect { x: 0, y: 0, w: 4, h: 100 };
        scrollbar(&mut o, r, 0, 10, 5);
        assert!(o.items.is_empty());
        scrollbar(&mut o, r, 50, 25, 100);
        assert!(matches!(o.items[0].style, PanelStyle::Scrollbar { start: 500, len: 250 }));
    }

    /// Tests that set MOUSER_HOME / MOUSER_SSH_BIN run one at a time.
    pub(crate) static ENV: Mutex<()> = Mutex::new(());

    fn ctx() -> Context {
        let viewport = UiViewport { width: 1200, height: 900, cell_w: 9, cell_h: 18 };
        Context { viewport, area: Rect { x: 0, y: 8, w: 1000, h: 892 }, reduce_motion: true }
    }

    fn png(p: &Path) {
        image::RgbaImage::from_pixel(40, 20, image::Rgba([255, 0, 0, 255])).save(p).unwrap();
    }

    fn wait_loaded(m: &mut CommanderMode, n: usize) -> View {
        let k = Keymap::new(cmdr::BINDINGS);
        for _ in 0..200 {
            let v = m.view(&ctx(), &k);
            if v.images.len() >= n {
                return v;
            }
            std::thread::sleep(std::time::Duration::from_millis(10));
        }
        m.view(&ctx(), &k)
    }

    #[test]
    fn badge_centre_sits_on_the_top_right_corner() {
        let b = Rect { x: 100, y: 50, w: 200, h: 120 };
        for d in [26, 33, 40] {
            let r = badge_rect(b, d);
            assert_eq!((r.x + r.w / 2, r.y + r.h / 2), (b.x + b.w, b.y), "d={d}");
        }
        assert!(badge_size(9, 18) >= 3 * 9 + 8);
    }

    #[test]
    fn grid_and_carousel_badges_have_room() {
        let t = tempfile::tempdir().unwrap();
        std::fs::create_dir(t.path().join("dir")).unwrap();
        for n in ["a.png", "b.rs", "c.md", "d.pdf", "e.zip", "f.json", "g.ttf", "h.docx", "i.qqq"] {
            std::fs::write(t.path().join(n), "x").unwrap();
        }
        let mut m = CommanderMode::new();
        m.c.flags.all = false;
        m.cwd_changed(t.path());
        let k = Keymap::new(cmdr::BINDINGS);
        for view in [1, 2] {
            m.action("view", view);
            m.c.selected = 1;
            m.slide = Default::default();
            let v = m.view(&ctx(), &k);
            let d = v.dock.unwrap();
            let tiles: Vec<Rect> = d.items.iter().filter(|i| matches!(i.style, PanelStyle::Tile { .. })).map(|i| i.rect).collect();
            let badges: Vec<&PanelItem> = d.items.iter().filter(|i| matches!(i.style, PanelStyle::Badge(_))).collect();
            assert!(!badges.is_empty(), "view {view}");
            for b in &badges {
                let r = b.rect;
                // Inside the view, centred on some tile's corner, clear of other tiles.
                assert!(r.y >= d.rect.y && r.x + r.w <= d.rect.x + d.rect.w, "view {view}: {r:?} in {:?}", d.rect);
                let own = tiles.iter().find(|t| t.x + t.w == r.x + r.w / 2 && t.y == r.y + r.h / 2);
                assert!(own.is_some() || view == 2, "view {view}: badge on a corner");
                for t in tiles.iter().filter(|t| Some(*t) != own && t.x + t.w != r.x + r.w / 2) {
                    assert!(!overlaps(*t, r), "view {view}: badge {r:?} hits tile {t:?}");
                }
            }
            if view == 1 {
                assert_eq!(badges.len(), tiles.len(), "one per grid tile");
                assert!(badges.iter().any(|b| b.style == PanelStyle::Badge(cmdr::Badge::Folder.index())));
            }
        }
    }

    #[test]
    fn carousel_names_float_and_folders_get_an_icon() {
        let t = tempfile::tempdir().unwrap();
        std::fs::create_dir(t.path().join("a folder")).unwrap();
        std::fs::write(t.path().join("b.txt"), "hello\n").unwrap();
        let long = format!("c{}.txt", "x".repeat(200));
        std::fs::write(t.path().join(&long), "x\n").unwrap();
        let mut m = CommanderMode::new();
        m.c.flags.all = false;
        m.cwd_changed(t.path());
        m.action("view", 2);
        let mut seen = Vec::new();
        for (n, name) in ["a folder", "b.txt"].iter().enumerate() {
            m.c.selected = n;
            m.slide = Default::default();
            let v = m.view(&ctx(), &Keymap::new(cmdr::BINDINGS));
            let d = v.dock.unwrap();
            let tile = d.items.iter().find(|i| matches!(i.style, PanelStyle::Tile { selected: true })).unwrap().rect;
            let fl = d.items.iter().find(|i| i.style == PanelStyle::FloatLabel && i.text == *name).expect("floating name");
            // Inside the box, after (on top of) everything else.
            assert!(fl.rect.x > tile.x && fl.rect.x + fl.rect.w < tile.x + tile.w && fl.rect.y + fl.rect.h < tile.y + tile.h);
            let last_plain = d.items.iter().rposition(|i| !matches!(i.style, PanelStyle::FloatLabel | PanelStyle::Badge(_))).unwrap();
            assert!(d.items.iter().position(|i| i.style == PanelStyle::FloatLabel).unwrap() > last_plain);
            // The old name line under the strip is gone.
            assert!(!d.items.iter().any(|i| i.style != PanelStyle::FloatLabel && i.text.contains(name)), "{name} only in the float");
            let icon = d.items.iter().find(|i| i.style == PanelStyle::FolderIcon);
            if n == 0 {
                let ic = icon.expect("folder icon").rect;
                let (cx, cy) = (ic.x + ic.w / 2, ic.y + ic.h / 2);
                assert!((cx - (tile.x + tile.w / 2)).abs() <= 8 && (cy - (tile.y + tile.h / 2)).abs() <= 8, "centred");
                assert!(ic.y + ic.h <= fl.rect.y, "name under the icon");
            } else {
                assert!(icon.is_none(), "files keep their preview");
            }
            seen.push((fl.rect.y - tile.y, fl.rect.x + fl.rect.w / 2 - tile.x));
        }
        assert!(seen[0].0 == seen[1].0 && (seen[0].1 - seen[1].1).abs() <= 1, "same place for every item: {seen:?}");
        m.c.selected = 2;
        m.slide = Default::default();
        let d = m.view(&ctx(), &Keymap::new(cmdr::BINDINGS)).dock.unwrap();
        let fl = d.items.iter().find(|i| i.style == PanelStyle::FloatLabel && i.text.starts_with('c')).unwrap();
        assert!(fl.text.ends_with('…') && fl.text.chars().count() < 200);
        let tile = d.items.iter().find(|i| matches!(i.style, PanelStyle::Tile { selected: true })).unwrap().rect;
        assert!(fl.rect.w < tile.w);
    }

    #[test]
    fn carousel_loads_three_and_follows() {
        let t = tempfile::tempdir().unwrap();
        for i in 0..8 {
            png(&t.path().join(format!("p{i}.png")));
        }
        let mut m = CommanderMode::new();
        m.c.flags.all = false;
        m.cwd_changed(t.path());
        m.action("view", 2);
        m.c.selected = 3;
        let v = wait_loaded(&mut m, 3);
        assert_eq!(v.images.len(), 3, "focused + two partial neighbours");
        let mut got: Vec<_> = m.previews().decoded().into_iter().map(|w| w.0.file_name().unwrap().to_string_lossy().into_owned()).collect();
        got.sort();
        assert_eq!(got, ["p2.png", "p3.png", "p4.png"], "nothing off screen is loaded");
        // The neighbours are cut by the view's edges: a part of the image.
        let side = v.images.iter().min_by_key(|i| i.rect.x).unwrap();
        assert!(side.src.2 < side.width, "left neighbour is partial");
        m.action("right", 0);
        for _ in 0..200 {
            wait_loaded(&mut m, 3);
            if m.previews().decoded().iter().any(|w| w.0.ends_with("p5.png")) {
                break;
            }
        }
        assert!(m.previews().decoded().iter().any(|w| w.0.ends_with("p5.png")), "the next one loads as it moves");
        assert!(!m.previews().decoded().iter().any(|w| w.0.ends_with("p6.png")));
    }

    #[test]
    fn list_grid_and_open() {
        let t = tempfile::tempdir().unwrap();
        std::fs::create_dir(t.path().join("sub dir")).unwrap();
        std::fs::write(t.path().join("a.txt"), "hello\nworld\n").unwrap();
        let mut m = CommanderMode::new();
        m.c.flags.all = false;
        m.cwd_changed(t.path());
        let k = Keymap::new(cmdr::BINDINGS);
        let v = m.view(&ctx(), &k);
        let d = v.dock.unwrap();
        assert!(d.items.iter().any(|i| i.text.contains("Attributes") && i.text.contains("Last Modified")));
        assert!(d.items.iter().any(|i| i.text.contains("sub dir/") && i.action == act("item", 1)));
        assert!(d.rect.h < 892, "leaves room for the prompt");
        m.action("item", 0);
        assert_eq!(m.action("item", 0), Effect::None, "a.txt: file view");
        let v = m.view(&ctx(), &k);
        assert!(v.dock.unwrap().items.iter().any(|i| i.text == "world"));
        assert!(m.escape());
        assert_eq!(m.action("item", 1), Effect::None, "first click selects");
        m.last_click = None;
        assert_eq!(m.action("item", 1), Effect::None, "a slow second click only selects");
        assert_eq!(m.action("item", 1), Effect::None, "opening a folder browses it; the shell stays");
        assert_eq!(m.c.cwd.as_deref(), Some(t.path().join("sub dir").as_path()));
        assert_eq!(m.action("sync", 0), Effect::Cd(t.path().join("sub dir")), "s moves the shell there");
        m.action("back", 0);
        m.action("switch_view", 0);
        let v = m.view(&ctx(), &k);
        assert!(v.dock.unwrap().items.iter().filter(|i| matches!(i.style, PanelStyle::Tile { .. })).count() == 2);
        assert!(m.text(b"x").is_none(), "not searching: typing goes to the shell");
        m.action("search", 0);
        assert_eq!(m.text(b"s"), Some(Effect::None));
        assert_eq!(m.c.filter, "s");
        assert!(m.text(b"\x1bt").is_none(), "bound keys still work while searching");
    }

    fn menu_ids(m: &CommanderMode, item: Option<usize>) -> Vec<String> {
        m.menu(item, &Keymap::new(cmdr::BINDINGS)).into_iter().map(|e| e.id.trim_start_matches("menu:").to_string()).collect()
    }

    /// The context menu in each context lists what applies there, and file
    /// changes wait for the approval card (nothing is touched before it).
    #[test]
    fn context_menus_by_view_and_item() {
        use crate::menu::Cx;
        let t = tempfile::tempdir().unwrap();
        let d = t.path();
        std::fs::write(d.join("a.txt"), "hello\n").unwrap();
        std::fs::create_dir(d.join("sub")).unwrap();
        png(&d.join("p.png"));
        std::fs::write(d.join("v.mp4"), b"not really").unwrap();
        let mut m = CommanderMode::new();
        m.c.flags.all = false;
        m.cwd_changed(d);
        let k = Keymap::new(cmdr::BINDINGS);
        m.view(&ctx(), &k);
        let at = |m: &CommanderMode, n: &str| m.c.visible().iter().position(|e| e.name == n).unwrap();
        let (file, dir, vid) = (at(&m, "a.txt"), at(&m, "sub"), at(&m, "v.mp4"));
        assert_eq!(m.menu_cx(Some(file)), Cx::File);
        assert_eq!(m.menu_cx(Some(dir)), Cx::Folder);
        assert_eq!(m.menu_cx(Some(vid)), Cx::Media);
        assert_eq!(m.menu_cx(None), Cx::Empty);
        let f = menu_ids(&m, Some(file));
        for id in ["open", "copy", "copy_to", "move_to", "rename", "delete", "copy_path"] {
            assert!(f.contains(&id.to_string()), "list file: {id}");
        }
        assert!(menu_ids(&m, Some(vid)).contains(&"open_fullscreen".to_string()), "media: play and fullscreen");
        let fo = menu_ids(&m, Some(dir));
        assert!(["open", "parent", "sync_item"].iter().all(|i| fo.contains(&i.to_string())));
        let e = menu_ids(&m, None);
        assert!(["new_folder", "paste", "sort_name", "sort_size", "view_grid", "keys"].iter().all(|i| e.contains(&i.to_string())));
        assert!(!m.menu(None, &k).iter().find(|e| e.id == "menu:paste").unwrap().enabled, "nothing copied yet");
        // Delete asks first; the file stays until the card says yes.
        m.action("menu:delete", file as i32);
        assert!(matches!(m.ops.as_slice(), [crate::ops::Op::Delete(v)] if v == &[d.join("a.txt")]));
        assert!(d.join("a.txt").exists());
        m.ops.clear();
        // Rename: type the name, Enter queues it for the card.
        m.action("menu:rename", file as i32);
        assert!(m.wants_text());
        m.text(b"\x7f");
        m.text(b"x");
        m.text(b"\r");
        assert_eq!(m.ops, vec![crate::ops::Op::Rename { from: d.join("a.txt"), to: d.join("a.txx") }]);
        assert!(d.join("a.txt").exists() && !d.join("a.txx").exists());
        m.ops.clear();
        // Copy, then paste into the empty area: again only queued.
        m.action("menu:copy", file as i32);
        assert!(m.menu(None, &k).iter().find(|e| e.id == "menu:paste").unwrap().enabled);
        m.action("menu:paste", -1);
        assert!(matches!(m.ops.as_slice(), [crate::ops::Op::CopyTo { .. }]));
        m.ops.clear();
        m.action("menu:copy_path", file as i32);
        assert_eq!(m.clip, vec![d.join("a.txt").display().to_string()]);
        m.action("menu:sort", 2);
        assert_eq!(m.c.flags.sort, Sort::Size);
        // The image view, then fullscreen.
        // (Sorted by size now: look the image up again.)
        m.c.selected = at(&m, "p.png");
        m.action("menu:open", m.c.selected as i32);
        assert_eq!(m.menu_cx(None), Cx::Image);
        m.toggle_fullscreen();
        assert_eq!(m.menu_cx(Some(0)), Cx::FsImage, "a file view: the item does not matter");
        let fi = menu_ids(&m, None);
        assert!(["close", "zoom_in", "zoom_out", "zoom_fit", "zoom_actual", "left", "fullscreen"].iter().all(|i| fi.contains(&i.to_string())));
        assert!(!fi.contains(&"delete".to_string()));
        m.action("menu:close", 0);
        // Text view.
        m.c.overlay = Some(Overlay::Preview(d.join("a.txt")));
        m.view(&ctx(), &k);
        assert_eq!(m.menu_cx(None), Cx::Text);
        let tx = menu_ids(&m, None);
        assert!(["up", "page_down", "close", "copy_text"].iter().all(|i| tx.contains(&i.to_string())));
        // A video in the player, fullscreen.
        m.c.overlay = Some(Overlay::Preview(d.join("v.mp4")));
        m.fullscreen = true;
        assert_eq!(m.menu_cx(None), Cx::FsPlayer);
        let pl = menu_ids(&m, None);
        assert!(
            ["play_pause", "seek_back", "seek_forward", "volume_up", "volume_down", "fullscreen", "close"]
                .iter()
                .all(|i| pl.contains(&i.to_string()))
        );
    }

    /// Every option has a key, and the key does what the menu entry does:
    /// views, sorts, the keyboard help, and file changes (queued for the
    /// approval card, never done straight away; remote: on that host only).
    #[test]
    fn every_option_key_does_its_action() {
        let t = tempfile::tempdir().unwrap();
        let d = t.path();
        std::fs::write(d.join("a.txt"), "hello\n").unwrap();
        std::fs::write(d.join("big.bin"), vec![0u8; 4096]).unwrap();
        std::fs::create_dir(d.join("sub")).unwrap();
        let mut m = CommanderMode::new();
        m.c.flags.all = false;
        m.cwd_changed(d);
        let k = Keymap::new(cmdr::BINDINGS);
        m.view(&ctx(), &k);
        let press = |m: &mut CommanderMode, key: &[u8]| {
            let id = k.lookup(key).unwrap_or_else(|| panic!("{:?} is bound", String::from_utf8_lossy(key))).to_string();
            m.action(&id, 0)
        };
        let at = |m: &CommanderMode, n: &str| m.c.visible().iter().position(|e| e.name == n).unwrap();
        // Views.
        for (key, view) in [(b"G", Layout::Grid), (b"C", Layout::Carousel), (b"L", Layout::List)] {
            press(&mut m, key);
            assert_eq!(m.c.view, view);
        }
        // Sorts and reverse.
        for (key, sort) in [(b"S", Sort::Size), (b"D", Sort::Modified), (b"N", Sort::Name)] {
            press(&mut m, key);
            assert_eq!(m.c.flags.sort, sort);
        }
        press(&mut m, b"R");
        assert!(m.c.flags.reverse);
        press(&mut m, b"R");
        assert!(!m.c.flags.reverse);
        // Keyboard help: ? and F1 (both F1 encodings).
        for key in [&b"?"[..], b"\x1bOP", b"\x1b[11~"] {
            assert_eq!(press(&mut m, key), Effect::ShowKeys);
        }
        // Copy path, copy, paste, delete: queued only.
        m.c.selected = at(&m, "a.txt");
        press(&mut m, b"Y");
        assert_eq!(m.clip, vec![d.join("a.txt").display().to_string()]);
        press(&mut m, b"y");
        assert_eq!(m.yank, vec![d.join("a.txt")]);
        m.c.selected = at(&m, "big.bin");
        press(&mut m, b"p");
        assert_eq!(m.ops, vec![crate::ops::Op::CopyTo { from: vec![d.join("a.txt")], to: d.to_path_buf() }]);
        m.ops.clear();
        press(&mut m, b"d");
        assert_eq!(m.ops, vec![crate::ops::Op::Delete(vec![d.join("big.bin")])]);
        assert!(d.join("big.bin").exists(), "nothing deleted before the card");
        m.ops.clear();
        // Prompts: rename, new folder, copy to, move to.
        press(&mut m, b"r");
        assert!(matches!(&m.ask, Some((Ask::Rename(p), n)) if p == &d.join("big.bin") && n == "big.bin"));
        assert_eq!(press(&mut m, b"d"), Effect::None, "keys wait while a name is asked");
        assert!(m.ops.is_empty());
        m.ask = None;
        press(&mut m, b"n");
        assert!(matches!(&m.ask, Some((Ask::NewFolder(p), n)) if p == d && n.is_empty()));
        m.ask = None;
        press(&mut m, b"c");
        assert!(matches!(&m.ask, Some((Ask::CopyTo(v), s)) if v == &[d.join("big.bin")] && s == &format!("{}/", d.display())));
        m.ask = None;
        press(&mut m, b"M");
        assert!(matches!(&m.ask, Some((Ask::MoveTo(v), _)) if v == &[d.join("big.bin")]));
        m.ask = None;
        // Sync to the selected folder; fullscreen open of a non-media file just opens it.
        m.c.selected = at(&m, "sub");
        assert_eq!(press(&mut m, b"e"), Effect::Cd(d.join("sub")));
        m.c.selected = at(&m, "a.txt");
        press(&mut m, b"O");
        assert!(matches!(&m.c.overlay, Some(Overlay::Preview(p)) if p == &d.join("a.txt")) && !m.fullscreen);
        m.view(&ctx(), &k);
        m.clip.clear();
        press(&mut m, b"T");
        assert_eq!(m.clip, vec!["hello".to_string()], "copy text of the file view");
        m.action("close", 0);

        // Remote without a side channel: changes are refused, nothing queued.
        let ent = |n: &str| Entry {
            name: n.into(),
            path: PathBuf::from(format!("/srv/{n}")),
            kind: cmdr::kind_of(n),
            mode: "-rw-r--r--".into(),
            size: 3,
            modified: None,
        };
        m.remote_changed("me@web1", Some(Path::new("/srv")), Some(Ok(vec![ent("x.txt")])));
        m.c.selected = 0;
        assert!(matches!(press(&mut m, b"d"), Effect::Say(e) if e.contains("no ssh side channel")));
        assert!(m.ops.is_empty() && m.op_target().is_err());
        // With one: the change is queued for that host.
        m.remote_ssh(Some(&crate::remote::SshTarget { opts: vec![], dest: "me@web1".into() }));
        assert!(matches!(m.op_target(), Ok(Some(_))));
        press(&mut m, b"d");
        assert_eq!(m.ops, vec![crate::ops::Op::Delete(vec![PathBuf::from("/srv/x.txt")])]);
        m.ops.clear();
        // Copied there, pasted here: refused (no copying between machines).
        press(&mut m, b"y");
        m.remote_ssh(None);
        m.c.remote = None;
        m.cwd_changed(d);
        assert_eq!(m.op_target(), Ok(None));
        assert!(matches!(press(&mut m, b"p"), Effect::Say(e) if e.contains("me@web1")));
        assert!(m.ops.is_empty());
    }

    #[test]
    fn pages_marks_and_pipe_in_every_view() {
        let t = tempfile::tempdir().unwrap();
        for i in 0..60 {
            std::fs::write(t.path().join(format!("f{i:02}.txt")), "x").unwrap();
        }
        let k = Keymap::new(cmdr::BINDINGS);
        for view in 0..3 {
            let mut m = CommanderMode::new();
            m.c.flags.all = false;
            m.cwd_changed(t.path());
            m.action("view", view);
            m.view(&ctx(), &k);
            let page = m.c.page;
            assert!(page >= 1);
            m.action("page_down", 0);
            assert_eq!(m.c.selected, page.min(59), "view {view}");
            m.action("last", 0);
            assert_eq!(m.c.selected, 59);
            let v = m.view(&ctx(), &k);
            let sel =
                v.dock.unwrap().items.iter().any(|i| {
                    i.action == act("item", 59) && matches!(i.style, PanelStyle::Row { selected: true } | PanelStyle::Tile { selected: true })
                });
            assert!(sel, "view {view}: the selection scrolled into sight");
            m.action("first", 0);
            m.action("mark", 0);
            // Mark moves on in list and carousel; go back so f00 is on screen.
            m.action("first", 0);
            // The carousel's names ride on the boxes: let the slide finish.
            m.slide = Default::default();
            let v = m.view(&ctx(), &k);
            assert!(v.dock.unwrap().items.iter().any(|i| i.text.contains("* f00.txt") || i.text.starts_with("*-")), "view {view}: marks shown");
            m.action("pipe", 0);
            assert!(m.wants_text());
            for b in [b"c", b"a", b"t"] {
                m.text(b);
            }
            let Some(Effect::Run(line)) = m.text(b"\r") else { panic!() };
            assert!(line.contains("f00.txt") && line.ends_with("| cat"), "{line}");
        }
    }

    #[test]
    fn media_opens_the_player_and_closing_stops_it() {
        let k = Keymap::new(cmdr::BINDINGS);
        let mut m = CommanderMode::new();
        assert_eq!(m.action("play_pause", 0), Effect::Pass, "no player: alt+k goes to the shell");
        if !crate::player::available() {
            eprintln!("ffmpeg not installed, skipped");
            return;
        }
        let t = tempfile::tempdir().unwrap();
        let ok = crate::process::command("ffmpeg")
            .args(["-loglevel", "error", "-f", "lavfi", "-i", "testsrc=size=160x90:rate=10:duration=4", "-pix_fmt", "yuv420p"])
            .arg(t.path().join("v.mp4"))
            .status()
            .is_ok_and(|s| s.success());
        if !ok {
            return;
        }
        m.c.flags.all = false;
        m.cwd_changed(t.path());
        m.view(&ctx(), &k);
        m.action("open", 0);
        assert!(m.player.is_some(), "the in-app player, not the desktop opener");
        let mut got = false;
        for _ in 0..150 {
            std::thread::sleep(std::time::Duration::from_millis(20));
            let v = m.view(&ctx(), &k);
            if !v.images.is_empty() {
                assert!(v.dock.unwrap().items.iter().any(|i| i.text.contains("k play/pause")));
                got = true;
                break;
            }
        }
        assert!(got, "a frame is shown");
        assert_eq!(m.action("play_pause", 0), Effect::None);
        assert!(!m.player.as_ref().unwrap().playing());
        // Fullscreen: space plays / pauses, arrows seek, the bar is clickable;
        // idle, only the letterboxed picture remains.
        assert_eq!(m.action("fullscreen", 0), Effect::None);
        let c = ctx();
        let v = m.view(&c, &k);
        assert!(v.fullscreen && m.hits.bar.w > 0, "controls at first");
        assert_eq!(m.text(b" "), Some(Effect::None));
        assert!(m.player.as_ref().unwrap().playing(), "space: play");
        assert_eq!(m.text(b" "), Some(Effect::None));
        let before = m.player.as_ref().unwrap().position();
        assert_eq!(m.text(b"\x1b[C"), Some(Effect::None), "right: seek");
        assert!(m.player.as_ref().unwrap().position() >= before);
        m.fs_active = std::time::Instant::now() - FS_CONTROLS * 2;
        let v = m.view(&c, &k);
        assert_eq!(m.hits.bar, Rect::default(), "controls hidden");
        assert_eq!(m.hits.video, Rect { x: 0, y: 0, w: c.viewport.width, h: c.viewport.height });
        if let Some(i) = v.images.first() {
            assert!(i.rect.w == c.viewport.width || i.rect.h == c.viewport.height, "letterboxed to the window: {:?}", i.rect);
        }
        assert!(m.escape(), "Esc leaves fullscreen first");
        assert!(m.player.is_some());
        assert!(m.escape());
        m.view(&ctx(), &k);
        assert!(m.player.is_none(), "closing the viewer stops playback");
    }

    #[test]
    fn browsing_never_moves_the_shell_and_a_typed_cd_still_leads() {
        let t = tempfile::tempdir().unwrap();
        for d in ["a", "b", "c"] {
            std::fs::create_dir(t.path().join(d)).unwrap();
        }
        let mut m = CommanderMode::new();
        m.cwd_changed(t.path());
        m.c.selected = m.c.visible().iter().position(|e| e.name == "a").unwrap();
        assert_eq!(m.action("open", 0), Effect::None, "no cd typed, nothing sent");
        assert_eq!(m.c.cwd.as_deref(), Some(t.path().join("a").as_path()));
        // The next prompt reports the shell where it was: commander stays.
        m.cwd_changed(t.path());
        assert_eq!(m.c.cwd.as_deref(), Some(t.path().join("a").as_path()));
        // A cd typed in the shell moves commander.
        m.cwd_changed(&t.path().join("c"));
        assert_eq!(m.c.cwd.as_deref(), Some(t.path().join("c").as_path()));
        // s (sync): the host moves the shell; its report lands where commander is.
        m.c.selected = 0;
        assert_eq!(m.action("sync", 0), Effect::Cd(t.path().join("c")));
        m.cwd_changed(&t.path().join("c"));
        assert_eq!(m.c.cwd.as_deref(), Some(t.path().join("c").as_path()));
    }

    // POSIX paths in the header (Windows paths are one segment).
    #[cfg(unix)]
    #[test]
    fn back_control_segments_and_no_dot_entries() {
        let t = tempfile::tempdir().unwrap();
        std::fs::create_dir_all(t.path().join("a/b")).unwrap();
        let k = Keymap::new(cmdr::BINDINGS);
        let mut m = CommanderMode::new();
        m.cwd_changed(&t.path().join("a/b"));
        let d = m.view(&ctx(), &k).dock.unwrap();
        let back = d.items.iter().find(|i| i.text.starts_with("‹ back")).expect("back control");
        assert_eq!(back.text, "‹ back (u)");
        assert_eq!(back.action, act("parent", 0));
        assert!(!d.items.iter().any(|i| i.text.contains(" ..") || i.text.ends_with(" .")), "no . or ..");
        // The parent's segment jumps one level up; the current one is not a link.
        assert!(d.items.iter().any(|i| i.text == "/a" && i.action == act("up_to", 1)));
        assert!(d.items.iter().any(|i| i.text == "/b" && i.action == UiAction::None));
        assert_eq!(m.action("up_to", 2), Effect::None);
        assert_eq!(m.c.cwd.as_deref(), Some(t.path()));
        assert_eq!(m.action("parent", 0), Effect::None);
        assert_eq!(m.c.cwd.as_deref(), t.path().parent());
        // At / the control is disabled.
        m.cwd_changed(Path::new("/"));
        let d = m.view(&ctx(), &k).dock.unwrap();
        let back = d.items.iter().find(|i| i.text.starts_with("‹ back")).unwrap();
        assert_eq!((back.style, back.action.clone()), (PanelStyle::Hint, UiAction::None));
        assert_eq!(path_segments("~/x/y"), [("~".to_string(), 2), ("/x".into(), 1), ("/y".into(), 0)]);
        assert_eq!(path_segments("/"), [("/".to_string(), 0)]);
        assert_eq!(path_segments("/usr/lib"), [("/".to_string(), 2), ("usr".into(), 1), ("/lib".into(), 0)]);
    }

    #[test]
    fn search_shows_query_and_count() {
        let t = tempfile::tempdir().unwrap();
        for n in ["apple.txt", "apricot.txt", "banana.txt"] {
            std::fs::write(t.path().join(n), "x").unwrap();
        }
        let k = Keymap::new(cmdr::BINDINGS);
        let mut m = CommanderMode::new();
        m.cwd_changed(t.path());
        let texts = |m: &mut CommanderMode| m.view(&ctx(), &k).dock.unwrap().items.into_iter().map(|i| i.text).collect::<Vec<_>>();
        assert!(!texts(&mut m).iter().any(|t| t.contains("searching")), "not focused until invoked");
        m.action("search", 0);
        assert!(texts(&mut m).iter().any(|t| t.starts_with("searching")));
        m.text(b"a");
        m.text(b"p");
        assert!(texts(&mut m).iter().any(|t| t.starts_with("2 matches for \"ap\"")), "{:?}", texts(&mut m));
        m.text(b"z");
        assert!(texts(&mut m).iter().any(|t| t.starts_with("no matches for \"apz\"")));
    }

    #[test]
    fn popups_hide_images_beneath_and_images_stay_in_the_view() {
        let t = tempfile::tempdir().unwrap();
        for i in 0..6 {
            png(&t.path().join(format!("p{i}.png")));
        }
        let mut m = CommanderMode::new();
        m.cwd_changed(t.path());
        m.action("view", 1);
        let v = wait_loaded(&mut m, 6);
        let dock = v.dock.unwrap().rect;
        assert!(!v.images.is_empty());
        assert!(v.images.iter().all(|i| i.rect.y >= dock.y && i.rect.y + i.rect.h <= dock.y + dock.h), "never over the prompt");
        m.action("options", 0);
        let v = m.view(&ctx(), &Keymap::new(cmdr::BINDINGS));
        let p = v.panel.unwrap().rect;
        assert!(v.images.iter().all(|i| !overlaps(i.rect, p)), "nothing shows through the options window");
    }

    #[test]
    #[serial_test::serial]
    fn video_tiles_get_a_cached_thumbnail() {
        let _env = ENV.lock().unwrap_or_else(|e| e.into_inner());
        let t = tempfile::tempdir().unwrap();
        // SAFETY: only this test reads MOUSER_HOME in this binary.
        unsafe { std::env::set_var("MOUSER_HOME", t.path().join("home")) };
        let media = t.path().join("m");
        std::fs::create_dir(&media).unwrap();
        let v = media.join("clip.mp4");
        let ok = crate::player::available()
            && crate::process::command("ffmpeg")
                .args(["-loglevel", "error", "-f", "lavfi", "-i", "testsrc=size=320x180:rate=10:duration=3", "-pix_fmt", "yuv420p"])
                .arg(&v)
                .status()
                .is_ok_and(|s| s.success());
        let k = Keymap::new(cmdr::BINDINGS);
        let mut m = CommanderMode::new();
        if !ok {
            // Without ffmpeg the tile says what it is.
            std::fs::write(&v, b"not really").unwrap();
            m.cwd_changed(&media);
            m.action("view", 1);
            let _ = wait_loaded(&mut m, 1);
            assert!(m.view(&ctx(), &k).dock.unwrap().items.iter().any(|i| i.text == "▶ video"));
            return;
        }
        m.cwd_changed(&media);
        m.action("view", 1);
        let view = wait_loaded(&mut m, 1);
        assert_eq!(view.images.len(), 1, "the video tile has a picture");
        let (w, want) = (view.images[0].width, m.previews().decoded()[0].clone());
        assert!(w <= want.1 && w > 0);
        assert!(thumb_cache_path(&v, want.1).unwrap().exists(), "cached on disk by path+mtime+size");
        assert!(thumb_cache_path(&v, want.1).unwrap().starts_with(t.path().join("home/cache/thumbs")));
        // Carousel also shows it.
        m.action("view", 2);
        assert_eq!(wait_loaded(&mut m, 1).images.len(), 1);
    }

    #[test]
    fn carousel_slide_eases_and_retargets_smoothly() {
        use std::time::{Duration, Instant};
        assert_eq!((Slide::ease(0.0), Slide::ease(1.0)), (0.0, 1.0));
        assert!(Slide::ease(0.1) < 0.1 && Slide::ease(0.9) > 0.9, "slow at both ends");
        let t0 = Instant::now();
        let mut s = Slide::default();
        assert_eq!(s.at(3.0, t0), 3.0, "first frame: no slide");
        assert!(!s.moving());
        assert_eq!(s.at(4.0, t0), 3.0, "starts where it was");
        let mid = s.at(4.0, t0 + Duration::from_millis(90));
        assert!((mid - 3.5).abs() < 0.01, "{mid}");
        // A second key mid-slide: continues from the current position.
        let again = s.at(5.0, t0 + Duration::from_millis(90));
        assert!((again - mid).abs() < 1e-9, "no jump on retarget");
        assert_eq!(s.at(5.0, t0 + Duration::from_millis(90) + Slide::DUR), 5.0);
        assert!(!s.moving(), "stops: no more redraws");
        // Far jumps only slide the last item.
        s.at(40.0, t0 + Duration::from_secs(1));
        assert!((s.at(40.0, t0 + Duration::from_secs(1)) - 39.0).abs() < 1e-9);
    }

    #[test]
    fn carousel_slide_loads_the_incoming_item_too() {
        let t = tempfile::tempdir().unwrap();
        for i in 0..8 {
            png(&t.path().join(format!("p{i}.png")));
        }
        let mut m = CommanderMode::new();
        m.c.flags.all = false;
        m.cwd_changed(t.path());
        m.action("view", 2);
        m.c.selected = 3;
        wait_loaded(&mut m, 3);
        m.action("right", 0);
        let k = Keymap::new(cmdr::BINDINGS);
        let v = m.view(&ctx(), &k);
        assert!(m.slide.moving());
        let _ = v;
        std::thread::sleep(Slide::DUR / 2);
        let v = m.view(&ctx(), &k);
        let tiles = v.dock.unwrap().items.iter().filter(|i| matches!(i.style, PanelStyle::Tile { .. })).count();
        assert!(tiles >= 2, "mid-slide: two halves on the strip");
        assert!(m.previews.s.0.lock().unwrap().want.iter().any(|w| w.0.ends_with("p5.png")), "the incoming one is wanted");
        assert!(!m.previews.s.0.lock().unwrap().want.iter().any(|w| w.0.ends_with("p6.png")));
        std::thread::sleep(Slide::DUR + std::time::Duration::from_millis(20));
        let v = m.view(&ctx(), &k);
        assert!(!m.slide.moving());
        assert_eq!(v.dock.unwrap().items.iter().filter(|i| matches!(i.style, PanelStyle::Tile { .. })).count(), 3);
    }

    #[test]
    fn remote_header_badges_and_unknown_state() {
        let k = Keymap::new(cmdr::BINDINGS);
        let mut m = CommanderMode::new();
        let ent = |n: &str, dir: bool| Entry {
            name: n.into(),
            path: PathBuf::from(format!("/srv/{n}")),
            kind: if dir { Kind::Dir } else { cmdr::kind_of(n) },
            mode: "-rw-r--r--".into(),
            size: 3,
            modified: None,
        };
        m.remote_changed("me@web1", None, None);
        let d = m.view(&ctx(), &k).dock.unwrap();
        assert!(d.items.iter().any(|i| i.text.contains("no directory info")), "clear unknown state");
        assert!(d.items.iter().any(|i| i.text.starts_with("me@web1:")));
        m.remote_changed("me@web1", Some(Path::new("/srv")), Some(Ok(vec![ent("a.png", false), ent("app", true)])));
        m.action("view", 1);
        let d = m.view(&ctx(), &k).dock.unwrap();
        assert!(d.items.iter().any(|i| i.text == "me@web1:"));
        assert!(d.items.iter().any(|i| i.text == "/srv" || i.text == "/"), "{:?}", d.items.iter().map(|i| &i.text).collect::<Vec<_>>());
        assert!(d.items.iter().any(|i| i.text == "image · remote"), "no side channel: a badge, nothing read");
        assert!(m.previews().decoded().is_empty());
        m.c.selected = 1;
        assert_eq!(m.action("open", 0), Effect::None, "browsing never types into the remote shell");
        assert_eq!(m.c.cwd.as_deref(), Some(Path::new("/srv/app")));
        assert!(m.c.error.as_deref().is_some_and(|e| e.contains("no ssh side channel")), "{:?}", m.c.error);
        // The remote shell still reports /srv: commander stays where it browsed.
        m.remote_changed("me@web1", Some(Path::new("/srv")), Some(Ok(vec![ent("app", true)])));
        assert_eq!(m.c.cwd.as_deref(), Some(Path::new("/srv/app")));
        assert_eq!(m.action("sync", 0), Effect::Cd("/srv/app".into()), "s asks the host to move the shell");
    }

    #[test]
    fn fullscreen_image_fills_the_window_and_controls_hide() {
        let t = tempfile::tempdir().unwrap();
        image::RgbaImage::from_pixel(400, 300, image::Rgba([0, 255, 0, 255])).save(t.path().join("p.png")).unwrap();
        std::fs::write(t.path().join("a.txt"), "hello").unwrap();
        let k = Keymap::new(cmdr::BINDINGS);
        assert_eq!(k.label("fullscreen"), "f");
        let mut m = CommanderMode::new();
        m.cwd_changed(t.path());
        // Not on a text file (f does nothing there).
        m.c.overlay = Some(Overlay::Preview(t.path().join("a.txt")));
        assert_eq!(m.action("fullscreen", 0), Effect::Pass);
        m.c.overlay = Some(Overlay::Preview(t.path().join("p.png")));
        let v = wait_loaded(&mut m, 1);
        assert!(!v.fullscreen);
        let btn = v.dock.as_ref().unwrap().items.iter().find(|i| i.text.starts_with("fullscreen (f)")).expect("header button").action.clone();
        assert_eq!(btn, act("fullscreen", 0));
        assert_eq!(m.action("fullscreen", 0), Effect::None);
        let c = ctx();
        let v = m.view(&c, &k);
        assert!(v.fullscreen);
        let d = v.dock.as_ref().unwrap();
        assert_eq!(d.rect, Rect { x: 0, y: 0, w: c.viewport.width, h: c.viewport.height }, "the whole window");
        assert!(d.items.iter().any(|i| i.text.starts_with("exit fullscreen (f / esc)")), "controls show at first");
        // Letterboxed: the whole picture, centred, inside the window.
        let r = v.images[0].rect;
        assert!(r.x >= 0 && r.y >= 0 && r.x + r.w <= c.viewport.width && r.y + r.h <= c.viewport.height, "{r:?}");
        assert!((r.w as f64 / r.h as f64 - 4.0 / 3.0).abs() < 0.02, "aspect kept: {r:?}");
        // Idle: the controls hide and the picture takes the whole window.
        m.fs_active = std::time::Instant::now() - FS_CONTROLS * 2;
        let v = m.view(&c, &k);
        assert!(v.dock.as_ref().unwrap().items.iter().all(|i| !i.text.contains("fullscreen")), "controls hidden");
        assert_eq!(m.hits.image, Rect { x: 0, y: 0, w: c.viewport.width, h: c.viewport.height });
        // A pointer move brings them back.
        m.action("pointer_move", pack_xy(300, 300));
        assert!(m.view(&c, &k).dock.unwrap().items.iter().any(|i| i.text.starts_with("exit fullscreen")));
        // Keys: arrows and space are the view's, other keys go to the bindings
        // (the host drops unbound ones while commander has the keyboard).
        assert!(m.wants_text() && m.wants_key(b"\x1b[C") && !m.wants_key(b"f"));
        assert_eq!(m.text(b"x"), None);
        assert_eq!(m.text(b"f"), None);
        assert_eq!(m.text(b"\x1b"), None, "Esc goes to escape()");
        // Resize: the rect follows the window.
        let small = Context {
            viewport: UiViewport { width: 640, height: 480, cell_w: 9, cell_h: 18 },
            area: Rect { x: 0, y: 8, w: 640, h: 472 },
            reduce_motion: true,
        };
        assert_eq!(m.view(&small, &k).dock.unwrap().rect, Rect { x: 0, y: 0, w: 640, h: 480 });
        // Esc leaves fullscreen, then closes the view.
        assert!(m.escape());
        assert!(!m.fullscreen && m.c.overlay.is_some());
        // Double-click on the picture toggles it.
        let v = m.view(&c, &k);
        let _ = v;
        let mid = (m.hits.image.x + m.hits.image.w / 2, m.hits.image.y + 10);
        m.action("pointer_down", pack_xy(mid.0, mid.1));
        m.action("pointer_up", pack_xy(mid.0, mid.1));
        m.action("pointer_down", pack_xy(mid.0, mid.1));
        assert!(m.fullscreen, "double-click enters");
        m.action("pointer_up", pack_xy(mid.0, mid.1));
        m.action("fullscreen", 0);
        assert!(!m.fullscreen, "the same key leaves");
        // Closing the view drops fullscreen.
        m.action("fullscreen", 0);
        m.action("close", 0);
        assert!(!m.fullscreen);
    }

    fn near(a: Rect, b: Rect, px: i32) -> bool {
        (a.x - b.x).abs() <= px && (a.y - b.y).abs() <= px && (a.w - b.w).abs() <= px && (a.h - b.h).abs() <= px
    }

    fn motion_ctx() -> Context {
        let viewport = UiViewport { width: 1200, height: 900, cell_w: 9, cell_h: 18 };
        Context { viewport, area: Rect { x: 0, y: 8, w: 1000, h: 892 }, reduce_motion: false }
    }

    #[test]
    fn fs_anim_eases_in_out_over_220ms() {
        let from = Rect { x: 10, y: 20, w: 100, h: 50 };
        let to = Rect { x: 0, y: 0, w: 400, h: 200 };
        let start = std::time::Instant::now();
        let a = FsAnim { opening: true, from, to, start, ticking: false };
        assert_eq!(a.rect(start), from);
        assert_eq!(a.veil(start), 0);
        let mid = start + std::time::Duration::from_millis(110);
        assert_eq!(a.rect(mid), lerp_rect(from, to, 0.5), "cubic ease-in-out is 0.5 at the midpoint");
        assert_eq!(a.veil(mid), 100);
        let end = start + FsAnim::DUR;
        assert_eq!(a.rect(end), to);
        assert!(a.finished(end));
        assert_eq!(a.veil(end), 200);
        let close = FsAnim { opening: false, from: to, to: from, start, ticking: false };
        assert_eq!(close.veil(start), 200);
        assert_eq!(close.veil(end), 0);
        assert_eq!(FsAnim::DUR, std::time::Duration::from_millis(220));
    }

    #[test]
    fn fullscreen_eases_from_the_thumbnail_and_back() {
        let t = tempfile::tempdir().unwrap();
        image::RgbaImage::from_pixel(400, 300, image::Rgba([0, 255, 0, 255])).save(t.path().join("p.png")).unwrap();
        let k = Keymap::new(cmdr::BINDINGS);
        let mut m = CommanderMode::new();
        m.cwd_changed(t.path());
        m.c.overlay = Some(Overlay::Preview(t.path().join("p.png")));
        let _ = wait_loaded(&mut m, 1);
        let motion = motion_ctx();
        let v = m.view(&motion, &k);
        assert!(!v.fullscreen);
        assert!(!v.images.is_empty(), "thumbnail-cache must keep the decoded preview");
        let thumb = v.images[0].rect;
        assert!(thumb.w > 0 && thumb.h > 0, "{thumb:?}");

        assert_eq!(m.action("fullscreen", 0), Effect::None);
        assert!(m.fullscreen && m.fs_anim.is_some_and(|a| a.opening));
        let v = m.view(&motion, &k);
        assert!(v.fullscreen);
        assert!(
            near(v.images[0].rect, thumb, 12),
            "open starts at the thumbnail {:?}
{:?}",
            thumb,
            v.images[0].rect
        );
        assert!(v.dock.as_ref().unwrap().items.iter().any(|i| matches!(i.style, PanelStyle::Dim(_))), "backdrop crossfade");
        assert!(v.dock.as_ref().unwrap().items.iter().all(|i| !i.text.contains("exit fullscreen")), "chrome waits until the open finishes");

        std::thread::sleep(FsAnim::DUR + std::time::Duration::from_millis(30));
        let v = m.view(&motion, &k);
        assert!(v.fullscreen && m.fs_anim.is_none());
        let full = v.images[0].rect;
        assert!(full.w > thumb.w && full.h > thumb.h, "settled fullscreen dest {full:?} vs {thumb:?}");
        assert!((full.w as f64 / full.h as f64 - 4.0 / 3.0).abs() < 0.02, "{full:?}");
        assert!(v.dock.as_ref().unwrap().items.iter().any(|i| i.text.starts_with("exit fullscreen")));

        assert_eq!(m.action("fullscreen", 0), Effect::None);
        assert!(m.fullscreen && m.fs_anim.is_some_and(|a| !a.opening), "close keeps fullscreen until it lands");
        let v = m.view(&motion, &k);
        assert!(
            near(v.images[0].rect, full, 16),
            "close starts at the fullscreen dest {:?}
{:?}",
            full,
            v.images[0].rect
        );
        assert!(v.dock.as_ref().unwrap().items.iter().any(|i| matches!(i.style, PanelStyle::Dim(_))));

        std::thread::sleep(FsAnim::DUR + std::time::Duration::from_millis(30));
        let v = m.view(&motion, &k);
        assert!(!m.fullscreen && m.fs_anim.is_none() && !v.fullscreen);
        assert!(!v.images.is_empty(), "close must reuse the cached thumbnail, not flash a placeholder");
        assert!(
            near(v.images[0].rect, thumb, 12),
            "close lands on the thumbnail {:?}
{:?}",
            thumb,
            v.images[0].rect
        );
        assert!(v.dock.as_ref().unwrap().items.iter().all(|i| i.text != "image" && !i.text.contains("▶")));
    }

    #[test]
    fn image_zoom_keys_wheel_pan_and_header_percent() {
        let t = tempfile::tempdir().unwrap();
        image::RgbaImage::from_pixel(400, 200, image::Rgba([0, 0, 255, 255])).save(t.path().join("big.png")).unwrap();
        let k = Keymap::new(cmdr::BINDINGS);
        let mut m = CommanderMode::new();
        m.cwd_changed(t.path());
        m.c.overlay = Some(Overlay::Preview(t.path().join("big.png")));
        let v = wait_loaded(&mut m, 1);
        let title = |v: &View| v.dock.as_ref().unwrap().items.iter().find(|i| i.style == PanelStyle::Title).unwrap().text.clone();
        assert!(title(&v).starts_with("fit "), "{}", title(&v));
        // volume keys zoom in the image view (shared keys), alt+1 = 100%.
        assert_eq!(m.action("volume_up", 0), Effect::None);
        assert!(m.zoom.is_some());
        assert_eq!(m.action("zoom_actual", 0), Effect::None);
        let v = m.view(&ctx(), &k);
        assert!(title(&v).starts_with("100% · "), "{}", title(&v));
        for _ in 0..8 {
            m.action("zoom_in", 0);
        }
        let v = m.view(&ctx(), &k);
        let body = m.hits.image;
        // Clipped to the view: never larger than the body.
        for i in &v.images {
            assert!(i.rect.x >= body.x - 1 && i.rect.y >= body.y - 1 && i.rect.y + i.rect.h <= body.y + body.h + 1, "{:?} {:?}", i.rect, body);
        }
        // Pan with arrows and drag moves the centre.
        let c0 = m.zoom.as_ref().unwrap().cx;
        m.action("right", 0);
        assert!(m.zoom.as_ref().unwrap().cx > c0);
        let mid = (body.x + body.w / 2, body.y + body.h / 2);
        m.action("pointer_down", pack_xy(mid.0, mid.1));
        m.action("pointer_move", pack_xy(mid.0 + 50, mid.1));
        m.action("pointer_up", pack_xy(mid.0 + 50, mid.1));
        assert!(m.zoom.as_ref().unwrap().cx < c0 + 0.2);
        // Ctrl+wheel zooms about the pointer: the image point under it stays put.
        m.action("zoom_fit", 0);
        assert!(m.zoom.as_ref().unwrap().fit);
        // Fit is to the WIDTH.
        let v = m.view(&ctx(), &k);
        assert!((v.images[0].rect.w - body.w).abs() <= 1, "fills the width");
        let nat = (400, 200);
        let mut z = Zoom { path: "x".into(), scale: fit_scale(body, nat), cx: 0.5, cy: 0.5, fit: true };
        let a = (body.x + body.w / 4, body.y + body.h / 2);
        let r0 = zoom_rect(body, nat, &mut z);
        let u0 = (a.0 - r0.x) as f64 / r0.w as f64;
        zoom_about(body, nat, &mut z, 2.0, a);
        let r1 = zoom_rect(body, nat, &mut z);
        assert!((((a.0 - r1.x) as f64 / r1.w as f64) - u0).abs() < 0.01);
        // Without an image view the zoom keys go to the shell.
        m.c.overlay = None;
        assert_eq!(m.action("zoom_fit", 0), Effect::Pass);
    }

    #[test]
    fn narrow_header_collapses_buttons_into_menu() {
        assert_eq!(header_fit(&[50, 50, 50], 200, 30), 3);
        assert_eq!(header_fit(&[50, 50, 50], 140, 30), 2, "progressive: only what does not fit");
        assert_eq!(header_fit(&[50, 50, 50], 40, 30), 0);
        let t = tempfile::tempdir().unwrap();
        std::fs::create_dir_all(t.path().join("a/b")).unwrap();
        let k = Keymap::new(cmdr::BINDINGS);
        let mut m = CommanderMode::new();
        m.cwd_changed(&t.path().join("a/b"));
        let wide = m.view(&ctx(), &k).dock.unwrap();
        assert!(!wide.items.iter().any(|i| i.text == "•••"));
        assert_eq!(m.action("menu", 0), Effect::Pass, "no menu when everything fits");
        let narrow = Context {
            viewport: UiViewport { width: 420, height: 600, cell_w: 9, cell_h: 18 },
            area: Rect { x: 0, y: 8, w: 420, h: 592 },
            reduce_motion: true,
        };
        let d = m.view(&narrow, &k).dock.unwrap();
        let dots = d.items.iter().find(|i| i.text == "•••").expect("overflow button");
        assert!(dots.rect.x + dots.rect.w > 360, "upper right");
        assert!(d.items.iter().any(|i| i.text.starts_with("‹ back")), "back stays");
        assert!(d.items.iter().any(|i| i.text == "help"), "help still fits");
        assert!(!d.items.iter().any(|i| i.text == "options"));
        assert_eq!(m.action("menu", 0), Effect::None);
        let d = m.view(&narrow, &k).dock.unwrap();
        let opt = d.items.iter().find(|i| i.text == "options").expect("in the dropdown");
        assert!(matches!(opt.style, PanelStyle::Option { .. }));
        assert!(d.items.iter().any(|i| i.style == PanelStyle::Popup));
        assert_eq!(m.action("options", 0), Effect::None);
        assert!(!m.menu_open, "choosing closes it");
        m.action("menu", 0);
        assert!(m.escape() && !m.menu_open);
    }

    #[test]
    fn player_bar_and_volume_hits() {
        let mut m = CommanderMode::new();
        m.hits.vol = Rect { x: 100, y: 10, w: 100, h: 20 };
        m.pointer = (150, 15);
        // No player: pointer events are harmless.
        m.action("pointer_down", pack_xy(150, 15));
        m.action("pointer_up", pack_xy(150, 15));
        assert!(m.press.is_none());
        assert_eq!(unpack_xy(pack_xy(1234, 987)), (1234, 987));
    }

    #[cfg(unix)]
    #[test]
    #[serial_test::serial]
    fn remote_files_preview_view_and_text_over_fake_ssh() {
        let _env = ENV.lock().unwrap_or_else(|e| e.into_inner());
        use std::os::unix::fs::PermissionsExt;
        let t = tempfile::tempdir().unwrap();
        let ssh = t.path().join("fake-ssh");
        std::fs::write(
            &ssh,
            "#!/bin/sh\nwhile [ $# -gt 0 ]; do case \"$1\" in -o|-F|-p|-l|-i|-J) shift 2;; -*) shift;; *) break;; esac; done\nshift\n[ \"$1\" = -- ] && shift\nPATH=/nonexistent:/usr/bin:/bin exec sh -c \"$*\"\n",
        )
        .unwrap();
        std::fs::set_permissions(&ssh, std::fs::Permissions::from_mode(0o755)).unwrap();
        unsafe {
            std::env::set_var("MOUSER_HOME", t.path().join("home"));
            std::env::set_var("MOUSER_SSH_BIN", &ssh);
            std::env::set_var("MOUSER_REMOTE_BACKEND", "cat");
        }
        // The "remote" files live here; the listing says they are on fakehost.
        let srv = t.path().join("srv");
        std::fs::create_dir(&srv).unwrap();
        image::RgbaImage::from_pixel(300, 100, image::Rgba([0, 200, 0, 255])).save(srv.join("r.png")).unwrap();
        std::fs::write(srv.join("notes.txt"), "line one\nline two\n").unwrap();
        let ent = |n: &str| {
            let p = srv.join(n);
            let m = std::fs::metadata(&p).unwrap();
            Entry { name: n.into(), path: p, kind: cmdr::kind_of(n), mode: "-rw-r--r--".into(), size: m.len(), modified: m.modified().ok() }
        };
        let k = Keymap::new(cmdr::BINDINGS);
        let mut m = CommanderMode::new();
        let target = crate::remote::SshTarget { opts: vec![], dest: "fakehost".into() };
        m.remote_ssh(Some(&target));
        m.remote_changed("fakehost", Some(&srv), Some(Ok(vec![ent("notes.txt"), ent("r.png")])));
        m.action("view", 1);
        // Grid: the image tile and the text snippet come over "ssh".
        let mut ok = (false, false);
        for _ in 0..300 {
            let v = m.view(&ctx(), &k);
            ok.0 |= !v.images.is_empty();
            ok.1 |= v.dock.as_ref().unwrap().items.iter().any(|i| i.text == "line one");
            if ok == (true, true) {
                break;
            }
            std::thread::sleep(std::time::Duration::from_millis(10));
        }
        assert_eq!(ok, (true, true), "remote tile preview and text snippet");
        // Viewer: fit to width, zoom works, header shows the size from the header bytes.
        m.c.selected = m.c.visible().iter().position(|e| e.name == "r.png").unwrap();
        m.action("open", 0);
        assert_eq!(m.c.overlay, Some(Overlay::Preview(srv.join("r.png"))));
        let mut v = m.view(&ctx(), &k);
        for _ in 0..300 {
            v = m.view(&ctx(), &k);
            if !v.images.is_empty() && m.nat.as_ref().is_some_and(|n| n.1 == (300, 100)) {
                break;
            }
            std::thread::sleep(std::time::Duration::from_millis(10));
        }
        assert_eq!(m.nat.as_ref().map(|n| n.1), Some((300, 100)));
        assert!((v.images[0].rect.w - m.hits.image.w).abs() <= 1);
        assert_eq!(m.action("zoom_actual", 0), Effect::None);
        assert!(m.open_remote.as_ref().unwrap().1.complete());
        // Text in the viewer.
        m.c.overlay = Some(Overlay::Preview(srv.join("notes.txt")));
        let mut found = false;
        for _ in 0..300 {
            let v = m.view(&ctx(), &k);
            if v.dock.unwrap().items.iter().any(|i| i.text == "line two") {
                found = true;
                break;
            }
            std::thread::sleep(std::time::Duration::from_millis(10));
        }
        assert!(found, "remote text in the viewer");
        // Closing drops the transfer.
        m.c.overlay = None;
        m.view(&ctx(), &k);
        assert!(m.open_remote.is_none());
    }

    /// Timing over a real sshd: `MX_REMOTE_DIR=/dir MX_SSH_DEST=host
    /// MOUSER_SSH_CONFIG=cfg cargo test -p mouser-render --lib measure_remote -- --ignored --nocapture`
    /// (files: big.jpg, big.mp4 in the dir).
    #[test]
    #[ignore]
    fn measure_remote() {
        let _env = ENV.lock().unwrap_or_else(|e| e.into_inner());
        let dir = PathBuf::from(std::env::var("MX_REMOTE_DIR").unwrap());
        let dest = std::env::var("MX_SSH_DEST").unwrap();
        let home = tempfile::tempdir().unwrap();
        unsafe { std::env::set_var("MOUSER_HOME", home.path()) };
        let ent = |n: &str| {
            let p = dir.join(n);
            let m = std::fs::metadata(&p).unwrap();
            Entry { name: n.into(), path: p, kind: cmdr::kind_of(n), mode: "-rw-r--r--".into(), size: m.len(), modified: m.modified().ok() }
        };
        let k = Keymap::new(cmdr::BINDINGS);
        let ms = |t: std::time::Instant| t.elapsed().as_secs_f64() * 1000.0;
        let target = crate::remote::SshTarget { opts: vec![], dest: dest.clone() };
        let tools = fetch::Remote::new(target.clone()).tools();
        println!("backend {:?} remote tools {tools:?}", fetch::backend(&fetch::Remote::new(target.clone())));
        // Image: tile, first look, full.
        let mut m = CommanderMode::new();
        m.remote_ssh(Some(&target));
        m.remote_changed(&dest, Some(&dir), Some(Ok(vec![ent("big.jpg"), ent("big.mp4")])));
        m.action("view", 1);
        let t0 = std::time::Instant::now();
        let mut tiles = 0;
        while tiles < 2 && t0.elapsed().as_secs() < 120 {
            tiles = m.view(&ctx(), &k).images.len();
            std::thread::sleep(std::time::Duration::from_millis(5));
        }
        println!("grid: both tiles {:.0} ms", ms(t0));
        let big = |m: &CommanderMode, n: &str| m.c.visible().iter().position(|e| e.name == n).unwrap();
        m.c.selected = big(&m, "big.jpg");
        let t0 = std::time::Instant::now();
        m.action("open", 0);
        let (mut first, mut header) = (None, None);
        loop {
            let v = m.view(&ctx(), &k);
            if first.is_none() && !v.images.is_empty() {
                first = Some(ms(t0));
            }
            if header.is_none() && m.nat.as_ref().is_some_and(|n| n.1 == (8000, 6000)) {
                header = Some(ms(t0));
            }
            let done = m.previews.get(&(dir.join("big.jpg"), 2048)).flatten().is_some_and(|t| t.w == 2048)
                && m.open_remote.as_ref().is_some_and(|r| r.1.complete());
            if done || t0.elapsed().as_secs() > 300 {
                break;
            }
            std::thread::sleep(std::time::Duration::from_millis(5));
        }
        println!("image 33 MB: first preview {first:?} ms, header {header:?} ms, full + decoded {:.0} ms", ms(t0));
        // Video: first frame, seek, full.
        m.c.overlay = None;
        m.view(&ctx(), &k);
        m.c.selected = big(&m, "big.mp4");
        let t0 = std::time::Instant::now();
        m.action("open", 0);
        let mut ff = None;
        while t0.elapsed().as_secs() < 120 {
            m.view(&ctx(), &k);
            if m.player.as_ref().is_some_and(|p| p.frame().is_some()) {
                ff = Some(ms(t0));
                break;
            }
            std::thread::sleep(std::time::Duration::from_millis(5));
        }
        println!("video 153 MB (moov at end): first frame after {ff:?} ms; err {:?}", m.player.as_ref().and_then(|p| p.error.clone()));
        let mut full: Option<f64> = None;
        let mut run = |m: &mut CommanderMode, secs: u64| {
            let t = std::time::Instant::now();
            while t.elapsed().as_secs() < secs {
                m.view(&ctx(), &k);
                if full.is_none() && m.open_remote.as_ref().is_some_and(|r| r.1.complete()) {
                    full = Some(ms(t0));
                    println!("video: all {} MB here after {:.0} ms", m.open_remote.as_ref().unwrap().1.file().size >> 20, ms(t0));
                }
                std::thread::sleep(std::time::Duration::from_millis(8));
            }
        };
        run(&mut m, 6);
        let t1 = std::time::Instant::now();
        m.player.as_mut().unwrap().seek_to(90.0);
        let mut sk = None;
        while t1.elapsed().as_secs() < 60 {
            m.view(&ctx(), &k);
            if m.player.as_ref().is_some_and(|p| p.last_seek_gap.is_some()) {
                sk = Some(ms(t1));
                break;
            }
            std::thread::sleep(std::time::Duration::from_millis(5));
        }
        println!("seek to 90 s (not fetched yet): playing again after {sk:?} ms; gap {:?}", m.player.as_ref().unwrap().last_seek_gap);
        run(&mut m, 6);
        println!("dropped frames {}", m.player.as_ref().unwrap().dropped());
        let h = m.open_remote.as_ref().unwrap().1.clone();
        println!("at close: {:.1} of {:.1} MB here", h.map().filled() as f64 / 1048576.0, h.file().size as f64 / 1048576.0);
        m.c.overlay = None;
        m.view(&ctx(), &k);
        // Full transfer (on its own; the player is gone).
        let t2 = std::time::Instant::now();
        let g = fetch::open(h.file(), None);
        drop(h);
        g.wait(0, g.file().size, std::time::Duration::from_secs(600), &|| false);
        println!("video rest fetched in {:.0} ms more ({:?}, complete {})", ms(t2), g.error(), g.complete());
    }
}