konoma 0.1.0

Full-screen preview-focused terminal file browser (macOS Apple Silicon)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
//! Application state: the `App` struct and its methods — mode (Tree/Preview), the tree,
//! tabs, and the current preview target. Git view methods live in the `git_view` submodule.

use std::collections::BTreeSet;
use std::path::{Path, PathBuf};

use anyhow::Result;
use ratatui::layout::Rect;
use ratatui::text::{Line, Span};
use ratatui_image::errors::Errors;
use ratatui_image::picker::Picker;
use ratatui_image::protocol::Protocol;
use ratatui_image::thread::{ResizeRequest, ResizeResponse, ThreadProtocol};
use ratatui_image::{FilterType, Resize};
use tokio::sync::mpsc::UnboundedSender;

use crate::config::Config;
use crate::i18n::tr;
use crate::preview::PreviewKind;

mod bookmark_actions;
mod file_actions;
mod git_view;

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Mode {
    Tree,
    Preview,
}

/// Display mode (outer): what is currently shown full-screen. The **outer chip** in the status bar (colors assigned by `ui`).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DisplayMode {
    Tree,
    Preview,
    Image,
}

/// Internal mode (inner): what is currently being operated. Shows the **inner chip** only while active and switches the footer keys too.
/// Priority: dialog > each footer mode (filter/search/sort/bookmarks) > visual.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum InternalMode {
    Visual,
    Filter,
    Search,
    Sort,
    Mark,
    Goto,
    Bookmarks,
    Info,
    Create,
    Rename,
    BatchRename,
    RenamePreview,
    DeleteConfirm,
    DropConfirm,
    QuitConfirm,
    GitChanges,
    GitDiff,
    Commit,
    GitLog,
    GitDetail,
    GitBranch,
    GitGraph,
    GitGraphPicker,
}

/// Preview paging key style. Specified via the `ui.keys` setting (default vim).
/// Diffs use only the page/half-page keys. j/k line movement, arrows, and PageUp/Down are common to both styles.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum KeyScheme {
    /// vim style: Ctrl-f/Ctrl-b=page, Ctrl-d/Ctrl-u=half.
    Vim,
    /// less style: Space/b=page, d/u=half.
    Less,
}

impl KeyScheme {
    pub fn parse(s: &str) -> Self {
        match s {
            "less" => Self::Less,
            _ => Self::Vim,
        }
    }
}

/// diff layout (config `git.diff`; cycle at runtime with `s`). Auto picks vertical/horizontal automatically from the terminal width.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DiffLayout {
    /// Vertical (unified).
    Unified,
    /// Side-by-side.
    Split,
    /// Horizontal if wide, vertical if narrow.
    Auto,
}

impl DiffLayout {
    /// Parse a config value. "split"/"horizontal"/"side-by-side"=horizontal / "auto"=auto / otherwise=vertical.
    pub fn parse(s: &str) -> Self {
        let n: String = s
            .chars()
            .filter(|c| !matches!(c, ' ' | '-' | '_'))
            .flat_map(|c| c.to_lowercase())
            .collect();
        match n.as_str() {
            "split" | "horizontal" | "sidebyside" | "side" => Self::Split,
            "auto" => Self::Auto,
            _ => Self::Unified, // "unified" / "vertical" / 不明
        }
    }
    /// Resolve whether to lay out side-by-side at the actual display width `width`. Auto decides by a threshold.
    pub fn is_split(self, width: u16) -> bool {
        match self {
            DiffLayout::Unified => false,
            DiffLayout::Split => true,
            DiffLayout::Auto => width >= DIFF_AUTO_MIN_WIDTH,
        }
    }
    /// Cycle to the next layout (vertical→horizontal→Auto→vertical). For `s`.
    #[cfg_attr(not(feature = "git"), allow(dead_code))]
    pub fn next(self) -> Self {
        match self {
            DiffLayout::Unified => DiffLayout::Split,
            DiffLayout::Split => DiffLayout::Auto,
            DiffLayout::Auto => DiffLayout::Unified,
        }
    }
}

/// Minimum inner width for side-by-side under Auto (below this, vertical). A guideline so two-column code is not cramped.
const DIFF_AUTO_MIN_WIDTH: u16 = 90;

/// Layout of the status chrome (config `ui.statusbar`).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum StatusbarLayout {
    /// Context (mode/path/zoom) on top (right of the tab row), key hints at the bottom (default).
    Split,
    /// Combine both context and key hints into a single bottom line.
    Bottom,
}

impl StatusbarLayout {
    pub fn parse(s: &str) -> Self {
        match s {
            "bottom" => Self::Bottom,
            _ => Self::Split,
        }
    }
}

/// Path display style. Used for the title (tree/preview). Cycle with the `p` key.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PathStyle {
    /// Relative to the launch directory name (e.g. konoma/src/main.rs). Default.
    Relative,
    /// Relative to HOME (e.g. ~/work/konoma).
    Home,
    /// Full path (e.g. /Users/me/work/konoma).
    Full,
}

impl PathStyle {
    pub fn parse(s: &str) -> Self {
        match s {
            "home" => Self::Home,
            "full" => Self::Full,
            _ => Self::Relative,
        }
    }
    pub fn next(self) -> Self {
        match self {
            Self::Relative => Self::Home,
            Self::Home => Self::Full,
            Self::Full => Self::Relative,
        }
    }
}

/// A single entry shown in the tree.
#[derive(Debug, Clone)]
pub struct Entry {
    pub path: PathBuf,
    pub is_dir: bool,
    pub depth: usize,
    pub expanded: bool,
}

/// Tree sort key (FR / M7 auxiliary). Switch via the footer menu (`s`).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SortKey {
    Name,
    Size,
    Modified,
    Ext,
}

/// Sort settings. `reverse`=flip ascending/descending, `dirs_first`=group directories at the top.
/// Default is "name, ascending, directories first" (matches the previous behavior). Global (not per-tab).
#[derive(Clone, Copy)]
pub struct Sort {
    pub key: SortKey,
    pub reverse: bool,
    pub dirs_first: bool,
}

impl Default for Sort {
    fn default() -> Self {
        Self {
            key: SortKey::Name,
            reverse: false,
            dirs_first: true,
        }
    }
}

impl SortKey {
    /// Parse a config string (case-insensitive). Unknown/empty falls back to Name.
    pub fn parse(s: &str) -> Self {
        match s.trim().to_lowercase().as_str() {
            "size" => SortKey::Size,
            "modified" | "mtime" | "mod" => SortKey::Modified,
            "ext" | "extension" | "type" => SortKey::Ext,
            _ => SortKey::Name,
        }
    }
}

impl Sort {
    /// Build the startup sort order from the `[ui.sort]` config.
    pub fn from_config(c: &crate::config::SortConfig) -> Self {
        Self {
            key: SortKey::parse(&c.key),
            reverse: c.reverse,
            dirs_first: c.dirs_first,
        }
    }
}

/// State of waiting for a letter key after `m` (set) / `'` (jump) (M7 auxiliary, bookmarks).
#[derive(Clone, Copy, PartialEq, Eq)]
enum MarkAction {
    Set,
    Jump,
}

/// Destructive/creation operations confirmed through a modal dialog (M7 Phase B, safety first).
// git 専用バリアント(GitDiscard/GitDeleteBranch)は非 git ビルドでは構築経路が無い(その構築元は
// git ディスパッチ専用)。バリアント自体は match の網羅性のため残し、非 git のみ dead_code を許す。
#[cfg_attr(not(feature = "git"), allow(dead_code))]
#[derive(Clone)]
enum PendingOp {
    /// Create with the entered name. A trailing `/` means a folder. `dir` is the destination (based on the cursor).
    Create { dir: PathBuf },
    /// Rename the target to the entered name within the same parent.
    Rename { target: PathBuf },
    /// Send the target to the trash (recoverable).
    Delete { targets: Vec<PathBuf> },
    /// Template-input stage of batch rename (`targets`=targets in display order). On confirm, builds a plan and moves to preview.
    BatchRenameInput { targets: Vec<PathBuf> },
    /// Preview→apply stage of batch rename (`plan`=(old, new) pairs).
    BatchRenameApply { plan: Vec<(PathBuf, PathBuf)> },
    /// In the Git view, `x`=discard a file's changes (via a confirmation dialog). On confirm, git::discard.
    GitDiscard { path: PathBuf },
    /// In the Git view, `c`=enter a commit message. On confirm, git::commit (uses the staged index).
    GitCommit,
    /// In the branch list, `n`=enter a new branch name. On confirm, git::create_branch (create and switch).
    GitCreateBranch,
    /// In the branch list, `d`=delete confirmation. `y`=safe (-d) / `!`=force (-D).
    GitDeleteBranch { name: String },
    /// A transfer received via file drag & drop (through a terminal paste). `c`=copy / `m`=move / Esc=cancel.
    /// `sources`=the dropped existing paths, `dir`=the drop destination (directory based on the cursor).
    DropTransfer { sources: Vec<PathBuf>, dir: PathBuf },
    /// Quit the whole app. A confirmation is requested before exiting (see `ui.confirm_quit`).
    Quit,
}

/// A confirmation (yes/no) or text-input modal. On confirm, calls fileops according to `op`.
struct Dialog {
    op: PendingOp,
    kind: DialogKind,
}

/// Dialog kind. Confirm=y/n for a destructive op (delete) / Input=name entry for create/rename.
/// `allow_permanent`=whether the delete confirmation also offers `!`=permanent delete (unrecoverable) (true=delete confirmation only).
enum DialogKind {
    Confirm {
        message: String,
        allow_permanent: bool,
    },
    Input {
        title: String,
        buffer: String,
        /// Insertion position (**character** index within buffer, 0..=char count). Move with ←→/Home/End.
        cursor: usize,
    },
    /// Confirmation preview for batch rename. `lines`=the "old → new" list, `scroll`=the top visible line.
    Preview {
        title: String,
        lines: Vec<String>,
        scroll: usize,
    },
}

/// File clipboard operation kind. Copy=duplicate / Cut=move (consumed on paste).
#[derive(Clone, Copy, PartialEq, Eq)]
enum ClipOp {
    Copy,
    Cut,
}

/// Copy/cut targets pushed with `Y`/`X`. Apply them with `P` to the cursor-based directory.
#[derive(Clone)]
struct Clipboard {
    op: ClipOp,
    paths: Vec<PathBuf>,
}

/// Snapshot of one tab's tree context (FR-5).
/// The active tab's working state lives in App's fields as the source of truth, and is saved/loaded here on switch.
/// It keeps not just the tree but also the **mode/preview state per tab**, restoring them on switch instead of dropping to Tree.
/// The heavy image state (protocol/source image) is not carried over and is reloaded on restore (zoom/center are kept).
#[derive(Clone)]
struct TabState {
    root: PathBuf,
    open_dir: PathBuf,
    entries: Vec<Entry>,
    selected: usize,
    show_hidden: bool,
    tree_viewport: u16,
    mode: Mode,
    preview_path: Option<PathBuf>,
    preview_kind: Option<PreviewKind>,
    preview_scroll: u16,
    preview_hscroll: u16,
    preview_viewport: u16,
    preview_byte_top: u64,
    preview_top_line: usize,
    image_zoom: f64,
    image_center: (f64, f64),
    // PDF の現在ページ/総ページ数もタブごとに保持(別タブから戻ったとき同じページを再描画する)。
    pdf_page: u32,
    pdf_pages: Option<u32>,
    // git オーバーレイもタブごとに保持する(別タブでドキュメントを見て戻っても git モードのまま)。
    git_view: bool,
    git_view_sel: usize,
    git_view_entries: Vec<crate::git::ChangeEntry>,
    came_from_git_view: bool,
    git_log: Option<Vec<crate::git::CommitInfo>>,
    git_log_sel: usize,
    git_detail: Option<Vec<crate::git::DiffLine>>,
    git_detail_meta: Option<crate::git::CommitMeta>,
    git_detail_title: Option<String>,
    git_detail_scroll: u16,
    git_detail_hscroll: u16,
    git_detail_viewport: u16,
    git_detail_total: usize,
    git_branches: Option<Vec<crate::git::BranchInfo>>,
    git_branch_sel: usize,
    git_branch_filter: String,
    git_branch_filtering: bool,
    git_graph: Option<Vec<crate::git::GraphRow>>,
    git_graph_sel: usize,
    // --- タブ毎の選択 / 絞り込み / プレビュー検索 (#2/#6: タブ跨ぎのデータ損失 footgun 対策) ---
    // これらが TabState に無いと、タブAで選択 → 別タブ/別 dir で D/X/Y/P したとき、
    // 見えていない旧選択のファイルが操作対象になる(マーカー不可視で気付けない)。
    // クリップボード(Y/X/P の paths バッファ)は app 全体共有のままで、ここには入れない(ユーザ確定事項)。
    selection: BTreeSet<PathBuf>,
    visual_anchor: Option<usize>,
    tree_filter: Option<String>,
    filter_input: Option<String>,
    filter_pool: Vec<Entry>,
    preview_search: Option<String>,
    search_input: Option<String>,
    search_matches: Vec<(u64, usize, usize)>,
    search_idx: usize,
}

/// The media payload loaded on a separate thread (sent back to the UI thread).
pub enum MediaPayload {
    /// A still image (SVG raster result / single-frame GIF, etc.) → goes to image_src.
    Static(image::DynamicImage),
    /// All GIF frames (composited RGBA + delay) → goes to gif_frames.
    Gif(Vec<(image::DynamicImage, std::time::Duration)>),
}

/// Result of media loading from another thread. Matched by generation via `gen`; results made stale by navigation are discarded.
pub struct MediaResult {
    gen: u64,
    /// None = decode/rasterize failure (the render side shows a fallback).
    payload: Option<MediaPayload>,
}

/// Heavy media loading to run on a separate thread (pure work that does not reference App).
enum MediaJob {
    /// Rasterize an SVG (path, max-edge px).
    Svg(PathBuf, u32),
    /// Expand all GIF frames. Falls back to still-image decode for single-frame/non-animated GIFs.
    Gif(PathBuf),
    /// Extract one representative frame from a video (delegated to ffmpegthumbnailer/ffmpeg). Thumbnail only; no playback.
    Video(PathBuf),
    /// Rasterize page N (1-based) of a PDF (delegated to pdftocairo/pdftoppm/qlmanage/sips). Loaded one page at a time.
    Pdf(PathBuf, u32),
}

impl MediaJob {
    /// Load the actual data (called on a separate thread or via the synchronous fallback). None on failure.
    fn run(self) -> Option<MediaPayload> {
        match self {
            MediaJob::Svg(p, max_px) => {
                crate::preview::svg::rasterize(&p, max_px).map(MediaPayload::Static)
            }
            MediaJob::Gif(p) => match crate::preview::image::decode_gif(&p) {
                Some(frames) => Some(MediaPayload::Gif(frames)),
                // 単一フレーム/アニメでない GIF → 静止画として表示。
                None => crate::preview::image::decode_static(&p).map(MediaPayload::Static),
            },
            MediaJob::Video(p) => crate::preview::video::thumbnail(&p).map(MediaPayload::Static),
            MediaJob::Pdf(p, page) => {
                crate::preview::pdf::render_page(&p, page).map(MediaPayload::Static)
            }
        }
    }
}

/// Result of the **heavy ignored set (`git::ignored`)** computed on a separate thread. Staleness is judged by `gen`, and
/// only the latest generation is applied (results from after moving to another repo while computing are discarded). `workdir` is the
/// repo workdir being computed; on apply it is put into `git_ignored_for` to serve as the Phase G cache key.
pub struct IgnoredResult {
    gen: u64,
    workdir: PathBuf,
    set: std::collections::HashSet<PathBuf>,
}

pub struct App {
    pub mode: Mode,
    pub root: PathBuf,
    /// The directory opened at startup. The base for relative-path display (kept separately because root moves up with h).
    pub open_dir: PathBuf,
    /// The directory opened at startup (immutable). The reset target for `A` ResetAnchor. Kept separately because open_dir moves with `a`.
    launch_dir: PathBuf,
    pub path_style: PathStyle,
    pub key_scheme: KeyScheme,
    pub lang: crate::i18n::Lang,
    pub cfg: Config,

    /// The tree flattened into display order. For M0 it is fine to simply rebuild it every time.
    pub entries: Vec<Entry>,
    pub selected: usize,
    pub show_hidden: bool,
    /// Tree sort settings (FR / M7 auxiliary). Global (not per-tab). Changed via the `s` menu.
    pub sort: Sort,
    /// Whether the `s` sort-selection menu is showing (while true, main intercepts keys).
    sort_menu: bool,
    /// Bookmarks (M7 auxiliary). Lowercase a-z=local (per launch dir) / uppercase A-Z=global.
    pub bookmarks: crate::bookmarks::Bookmarks,
    /// State of waiting for a letter after `m`/`'` (Set=register / Jump=jump).
    mark_pending: Option<MarkAction>,
    /// Whether the bookmark-list overlay is showing.
    bookmark_list: bool,
    /// Selection position in the list (a flat index over local on top and global below, concatenated).
    bookmark_list_sel: usize,
    /// Confirmation/input dialog (create `a` / rename `R` / delete `D`). While showing, main intercepts keys.
    dialog: Option<Dialog>,
    /// Multi-selection (M7 Phase B). The set of **absolute paths** selected via `V`/visual. The target of batch delete, etc.
    /// Held by path (not by index), so the selection is preserved across tree rebuilds and filtering.
    selection: BTreeSet<PathBuf>,
    /// Anchor of visual (range) selection mode (entries index). Visual mode is active while it is Some.
    /// Range = anchor to cursor. On confirm, it is taken into `selection`.
    visual_anchor: Option<usize>,
    /// File clipboard (M7 Phase B). Push with `Y`=copy/`X`=cut, apply with `P`=paste.
    clipboard: Option<Clipboard>,
    /// Height (in rows) of the tree display area at the last render. Used as the page size for paging.
    pub tree_viewport: u16,

    /// Tree filter (`/`). Some=filter is active (the query). entries holds the result of narrowing filter_pool.
    tree_filter: Option<String>,
    /// Editing buffer for the filter query. Some=input mode (intercepts keys).
    filter_input: Option<String>,
    /// All entries to filter from (recursively collected under root). Built once when `/` starts.
    filter_pool: Vec<Entry>,

    /// The target, kind, and scroll position (vertical/horizontal) while in Preview mode.
    /// Horizontal scroll is used to view long lines when not wrapping (ui.wrap=false).
    /// To avoid scrolling past the end, the actual clamp is done at render time (when content and screen size are known).
    pub preview_path: Option<PathBuf>,
    pub preview_kind: Option<PreviewKind>,
    pub preview_scroll: u16,
    pub preview_hscroll: u16,
    /// Height (in rows) of the text display area at the last render. Used as the page size for paging.
    pub preview_viewport: u16,

    /// less-style windowed reading for Code/Text (does not read the whole file). Always Some during a Code/Text preview.
    /// While Some, scrolling uses preview_byte_top (the line-head byte) instead of preview_scroll.
    preview_win: Option<crate::preview::window::FileWindow>,
    /// Byte offset of the top line of the window (the scroll position when windowed).
    preview_byte_top: u64,
    /// Absolute line number of the top of the window (0-based). For the line-number gutter. Changes with scrolling, and
    /// is corrected from the total line count when reaching the end.
    preview_top_line: usize,
    /// Cache of the total line count (computed once with count_lines when line numbers are ON).
    preview_total_lines: Option<usize>,
    /// Cache of the highlighted window (avoids re-highlighting on every render).
    win_cache: Option<WinCache>,

    /// Whether the current Code preview is a "heavy first time" (waiting for grammar compilation of a cold language).
    /// While true, the render shows a loading display (indicator) or plain text (progressive).
    /// Judged with `code::is_ext_warm` at preview start; if already warm, false from the start (immediate coloring).
    hl_pending: bool,
    /// Whether a background-thread warm is in progress (prevents double-launch). Common to indicator/progressive.
    hl_warming: bool,
    /// Frame index of the central spinner (advanced by the run loop while waiting on the indicator = animation).
    spinner_frame: usize,

    /// The file requested for external-editor launch via `e`. The run loop takes it, suspends the TUI, and launches
    /// (because entering/leaving the terminal must happen on the render thread, here we only raise the "request").
    pending_edit: Option<PathBuf>,

    /// Flag requesting launch of an external git tool (lazygit, etc.) via `O`. The run loop takes it, suspends the TUI, and launches.
    pending_git_tool: bool,

    /// Cache of decorated preview content (Markdown/Mermaid).
    /// Avoids re-parsing (pulldown-cmark/syntect/mermaid layout) on every scroll.
    /// It depends on width (to fit mermaid to the display width), so the key is (path, width).
    md_cache: Option<MdCache>,

    /// Cache of raw diff lines for the GitDiff preview (per path). Avoids recomputing `git diff` every frame.
    diff_cache: Option<DiffCache>,

    /// Links in the Markdown preview (collected on each render). Focus with Tab/⇧Tab, open with Enter.
    md_links: Vec<MdLink>,
    /// Index of the focused link (within md_links). None=nothing selected.
    focused_link: Option<usize>,

    /// In-preview search (`/`, less style). Some=search is active (the query). Highlights matches and moves with n/N.
    /// Currently only Code/Text (windowed) previews are supported.
    preview_search: Option<String>,
    /// Editing buffer for the search query. Some=input mode (intercepts keys, runs on Enter).
    search_input: Option<String>,
    /// For each occurrence: (line-head byte offset, 0-based line number, byte column within the line). The result of `find_all_matches`.
    /// Multiple occurrences on one line become separate elements (so `n`/`N` move per occurrence).
    search_matches: Vec<(u64, usize, usize)>,
    /// Index of the current match (within search_matches).
    search_idx: usize,

    /// Image backend (M2). None if the terminal is unsupported or uninitialized, in which case images fall back to text.
    /// For rendering, ui::preview passes `image` by &mut to StatefulImage. Resize/encode is
    /// offloaded to a separate thread via `img_tx`, and the result is applied in apply_image_resize.
    picker: Option<Picker>,
    img_tx: Option<UnboundedSender<ResizeRequest>>,
    pub image: Option<ThreadProtocol>,
    /// The source image (decoded). Zoom/pan crops this at render time and rebuilds the protocol
    /// (because ratatui-image has no offset pan).
    image_src: Option<image::DynamicImage>,
    /// Zoom factor. 1.0=the whole image fits, >1.0 zooms in (overflowing the viewport clips and enables pan).
    pub image_zoom: f64,
    /// Display center (image-normalized coordinates [0,1]). Moved by pan. Default is the center.
    image_center: (f64, f64),
    /// The most recently built crop rectangle (source-image px: x,y,w,h). The protocol is rebuilt only when it changes.
    image_crop: Option<(u32, u32, u32, u32)>,
    /// The most recent visible fraction (0..1, w/h). Less than 1 = the image overflows the viewport and is clipped = pan is possible.
    image_vis_frac: (f64, f64),

    /// PDF: current page (1-based). Each page is rasterized on demand (one at a time) into image_src.
    pdf_page: u32,
    /// PDF: total page count from poppler `pdfinfo`. None = unknown (no poppler) → page navigation disabled.
    pdf_pages: Option<u32>,
    /// mtime of the previewed media file at load time. Media (image/svg/gif/video/pdf) is reloaded on an
    /// FS event only when this changes (avoids re-decoding / re-running external tools on unrelated edits).
    preview_media_mtime: Option<std::time::SystemTime>,

    /// GIF animation (M6). All frames (composited RGBA) + each display duration. Empty means no animation (still image).
    /// A separate path from the still-image asynchronous ThreadProtocol: to avoid the "render an unencoded
    /// new protocol → nothing shows" churn in an animation whose frame changes each time, the current frame is **synchronously encoded**
    /// and atomically swapped into `gif_protocol` (see below). Zoom/pan share image_zoom/image_center.
    gif_frames: Vec<(image::DynamicImage, std::time::Duration)>,
    /// Index of the currently displayed GIF frame.
    gif_idx: usize,
    /// The time the current frame began showing (the start point for the next-frame deadline). None=before the first tick.
    gif_shown_at: Option<std::time::Instant>,
    /// The render protocol (kitty, etc.) of the current frame synchronously encoded to the display size. Drawn with the Image widget.
    gif_protocol: Option<Protocol>,
    /// The (frame index, crop rectangle) gif_protocol was built from. Re-encoded only when it changes (avoids wasteful re-encode).
    gif_proto_key: Option<(usize, (u32, u32, u32, u32))>,

    /// Sending end that offloads heavy media loading (SVG rasterize / GIF full-frame decode) to a separate thread.
    /// The result is received by main's poll loop and applied in apply_media. None=synchronous fallback (tests, etc.).
    media_tx: Option<std::sync::mpsc::Sender<MediaResult>>,
    /// Media-load generation. Incremented in enter_preview/clear to make old thread results stale.
    media_gen: u64,
    /// Whether waiting on another thread's media load (used by the render side to show "Loading…").
    media_loading: bool,

    /// Run2 keymap (Surface × key → Action). Built from the config at startup.
    pub keymaps: crate::keymap::KeyMap,
    /// which-key leader-pending state (`Space`=file management / `y`=path copy). After the press, a
    /// which-key menu is shown in the footer and the next keystroke confirms/cancels (a generalization of the old two-key pending_chord).
    pub pending_leader: Option<crate::keymap::LeaderId>,

    /// A transient message (copy result, etc.). Cleared on the next key input. Shown in the status line.
    pub flash: Option<String>,

    /// Visibility state and scroll position of the `?` help (full key list) overlay.
    pub show_help: bool,
    pub help_scroll: u16,
    /// Visibility state of the `i` file-info popup.
    pub show_info: bool,

    /// Tabs (FR-5). Each tab is a tree context. The active tab's working state is held in the fields above as the source of truth.
    tabs: Vec<TabState>,
    active_tab: usize,

    /// git status (FR-7). Absolute path → kind. Cached per root and re-fetched when root changes.
    git_status: std::collections::HashMap<PathBuf, crate::git::FileStatus>,
    /// The set of top-level gitignore-excluded entries (`git::ignored`). Used to decide which tree entries are dimmed.
    /// Since it is a heavy computation, it is cached **per repo (workdir)** (`git_ignored_for`), so moving root to a
    /// subdirectory within the same repository does not rebuild it.
    git_ignored: std::collections::HashSet<PathBuf>,
    /// The root at which `git_status`/`git_branch` were computed. If it differs from the current root, a (cheap) re-fetch is needed.
    git_status_for: Option<PathBuf>,
    /// The **repo workdir** at which `git_ignored` (heavy) was computed. If it is the same, root moves within the same repository
    /// do not rebuild it (avoids the 410ms recomputation when descending into a subdirectory with `l`).
    git_ignored_for: Option<PathBuf>,
    /// The workdir for which `ignored` is being computed on a separate thread (a guard against duplicate dispatch). None=not computing.
    git_ignored_pending: Option<PathBuf>,
    /// Generation of the `ignored` computation. Incremented by +1 on dispatch; a result is applied only if it matches this generation
    /// (discards stale results from after moving to another repo while computing).
    git_ignored_gen: u64,
    /// Flag to **rebuild even for the same repo** because the ignore rules (`.gitignore`/`.git/info/exclude`) changed.
    /// Comes from FS events. Set when a recompute is wanted even if workdir is the same (the old set is kept until the result is applied).
    git_ignored_dirty: bool,
    /// Sender that returns results to the worker computing `ignored` in the background. If not attached (tests, etc.), a synchronous fallback is used.
    ignored_tx: Option<std::sync::mpsc::Sender<IgnoredResult>>,
    /// git diff layout (vertical/horizontal/Auto). Initialized from the `git.diff` setting and cycled with `s`. Used by both the GitDiff preview
    /// and the commit/working-tree detail.
    diff_layout: DiffLayout,
    /// Title override for the detail (git_detail). Used when opening all working-tree changes from the git view, etc.
    git_detail_title: Option<String>,
    /// The current branch name (fetched at the same time as git status). None if not a repo.
    git_branch: Option<String>,

    /// Whether the Git view (the changes hub) is showing. While true, content shows the change list instead of the tree, and
    /// main intercepts keys. When the feature is disabled or it is not a repo, open_git_view does not set it, so it is always false.
    git_view: bool,
    /// Cursor position in the Git view (index within git_view_entries).
    git_view_sel: usize,
    /// The list of changed files shown in the Git view (rebuilt after open/refresh/write).
    git_view_entries: Vec<crate::git::ChangeEntry>,
    /// Whether the GitDiff preview was entered from the Git view. If true, Esc/q returns to the Git view.
    came_from_git_view: bool,

    /// Some if showing the git log (linear, newest first). Shows a full-screen list in content, and main intercepts keys.
    /// When the feature is disabled, it is not a repo, or there are no commits, open_git_log does not set it, so it stays None.
    git_log: Option<Vec<crate::git::CommitInfo>>,
    /// Cursor position in the git log (index within git_log).
    git_log_sel: usize,
    /// Some if showing the commit detail (the DiffLine list from commit_diff). A full screen overlaid on the log.
    git_detail: Option<Vec<crate::git::DiffLine>>,
    /// The **full message, etc. shown at the top** of the commit detail (on Enter from log/graph). None for worktree diffs.
    git_detail_meta: Option<crate::git::CommitMeta>,
    /// Vertical scroll amount of the commit detail.
    git_detail_scroll: u16,
    /// Horizontal scroll amount of the commit detail (for long diff lines).
    git_detail_hscroll: u16,
    /// Number of visible rows when rendering the detail (for clamping g/G and scrolling; updated by the render side).
    git_detail_viewport: u16,
    /// Total line count when rendering the detail (the commit-message header + diff; for clamping the scroll limit; updated by the render side).
    git_detail_total: usize,
    /// Some if showing the branch list (`b`). Shows a full-screen list in content and main intercepts keys.
    git_branches: Option<Vec<crate::git::BranchInfo>>,
    /// Cursor position in the branch list (index within the **filtered** display list).
    git_branch_sel: usize,
    /// Branch filter query (`/`). Empty means all entries.
    git_branch_filter: String,
    /// Whether the branch filter is being typed (while true, main picks up keys as characters).
    git_branch_filtering: bool,
    /// Some if showing the commit graph (`G`, SourceTree/Git Graph style). Shown full-screen in content.
    git_graph: Option<Vec<crate::git::GraphRow>>,
    /// Cursor position in the graph (index within git_graph; sits on a commit row).
    git_graph_sel: usize,
    /// Phase 2: the base branch tip OID for the graph (if Some, pinned in a straight line on lane0). `s`=set / `x`=clear.
    git_graph_base: Option<String>,
    /// Display label for the base (for the title `base: …`; a branch name or a short hash).
    git_graph_base_label: Option<String>,
    /// The **set of local branch names shown** in the graph (for the cap/toggle when there are many branches).
    /// At startup, auto-selected up to `ui.graph_max_branches` by HEAD + base + recency. If it equals the total branch count, `--all`.
    git_graph_visible: std::collections::HashSet<String>,
    /// Legend (branch ⇄ lane color). Computed and cached on graph rebuild.
    git_graph_legend: Vec<crate::git::LegendEntry>,
    /// The number of local branches **hidden by the cap/toggle** (for the legend's `(+K hidden)`).
    git_graph_hidden: usize,
    /// Whether the branch-visibility panel (`b`) is open.
    git_graph_picker: bool,
    /// Cursor position in the panel (row = branch).
    git_graph_picker_sel: usize,
    /// Tentative selection while editing the panel (committed to `git_graph_visible` with Enter / discarded with q).
    git_graph_picker_set: std::collections::HashSet<String>,
    /// The graph's **priority order (display order of all local branches)**. Initialized by `[ui.graph_base_branches]`→HEAD→recency, and
    /// reordered for the current session only with the panel's `J`/`K`. Used for the order of the legend/panel/cap selection/base derivation.
    git_graph_order: Vec<String>,
    /// Whether `J`/`K` reordering was done in the panel (so the base is re-derived to the top branch on Enter confirm).
    git_graph_reordered: bool,
}

/// Path-copy kind (FR-6). Chosen by the key after `c`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CopyKind {
    /// File name only (`cn`).
    Name,
    /// Full path (`cp`).
    Full,
    /// Path relative to where it was opened (`cr`).
    Relative,
    /// Full path of the parent directory (`cd`).
    Parent,
}

/// Commit-info copy kind (chosen after `y` in git log/graph/detail).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(not(feature = "git"), allow(dead_code))]
pub enum GitCopyKind {
    /// Short hash (7 digits).
    ShortHash,
    /// Full hash (40 digits).
    FullHash,
    /// Subject (the first line of the message).
    Subject,
    /// Full message (subject + body, multi-line).
    Message,
    /// Author name.
    Author,
    /// Date.
    Date,
}

/// Cache of decorated preview content. The key is (path, display width).
struct MdCache {
    path: PathBuf,
    width: u16,
    lines: Vec<Line<'static>>,
}

/// Cache of raw diff lines for the GitDiff preview. `file_diff` (the git call) does not depend on display width
/// (side-by-side/coloring is done separately at render time), so the key is the path only. This avoids re-invoking git on every
/// scroll/horizontal scroll/resize (aligned with log/graph: load once on open).
/// Since the diff changes when the working tree changes, it is invalidated by `refresh()` (FS events / manual refresh).
struct DiffCache {
    path: PathBuf,
    lines: Vec<crate::git::DiffLine>,
}

/// A single link within Markdown. `line`=index of the decorated line (for scrolling), `target`=URL/relative path.
/// tui-markdown renders a link as "text (URL)" and makes the URL an underlined blue span, so
/// it can be collected directly from the render result (no source re-parsing needed).
struct MdLink {
    line: usize,
    target: String,
}

/// Cache of highlighted lines for windowed reading.
/// The key is (path, top byte, height). Rebuilt only when scroll/vertical resize changes it.
/// (Line content does not depend on display width, so width is not part of the key.)
struct WinCache {
    path: PathBuf,
    byte_top: u64,
    height: u16,
    lines: Vec<Line<'static>>,
}

impl App {
    pub fn new(root: PathBuf, cfg: Config) -> Result<Self> {
        let path_style = PathStyle::parse(&cfg.ui.path_style);
        let key_scheme = KeyScheme::parse(&cfg.ui.keys);
        let lang = crate::i18n::Lang::resolve(&cfg.ui.lang);
        let sort = Sort::from_config(&cfg.ui.sort);
        // diff の並び初期値 (設定 git.diff)。実行時 `s` で 縦→横→Auto を巡回。
        let diff_layout = DiffLayout::parse(&cfg.git.diff);
        // Run2 キーマップ: 既定 + 設定 (`[keys.<surface>]` + 旧 copy_* alias) をマージし衝突を検証する。
        // page/half プロファイルは ui.keys (vim/less) に従う。Stage 2 は構築のみ (ディスパッチ未接続)。
        let keymaps = crate::keymap::KeyMap::from_config(
            crate::keymap::scheme_from_str(&cfg.ui.keys),
            &cfg.keys.to_keymap_config(),
        );
        let mut app = Self {
            mode: Mode::Tree,
            root: root.clone(),
            open_dir: root.clone(),
            launch_dir: root.clone(),
            path_style,
            key_scheme,
            lang,
            cfg,
            entries: Vec::new(),
            selected: 0,
            show_hidden: false,
            sort,
            sort_menu: false,
            bookmarks: crate::bookmarks::Bookmarks::load(&root),
            mark_pending: None,
            bookmark_list: false,
            bookmark_list_sel: 0,
            dialog: None,
            selection: BTreeSet::new(),
            visual_anchor: None,
            clipboard: None,
            tree_viewport: 0,
            tree_filter: None,
            filter_input: None,
            filter_pool: Vec::new(),
            preview_path: None,
            preview_kind: None,
            preview_scroll: 0,
            preview_hscroll: 0,
            preview_viewport: 0,
            preview_win: None,
            preview_byte_top: 0,
            preview_top_line: 0,
            preview_total_lines: None,
            win_cache: None,
            hl_pending: false,
            hl_warming: false,
            spinner_frame: 0,
            pending_edit: None,
            pending_git_tool: false,
            md_cache: None,
            diff_cache: None,
            md_links: Vec::new(),
            focused_link: None,
            preview_search: None,
            search_input: None,
            search_matches: Vec::new(),
            search_idx: 0,
            picker: None,
            img_tx: None,
            image: None,
            image_src: None,
            image_zoom: 1.0,
            image_center: (0.5, 0.5),
            image_crop: None,
            image_vis_frac: (1.0, 1.0),
            pdf_page: 1,
            pdf_pages: None,
            preview_media_mtime: None,
            gif_frames: Vec::new(),
            gif_idx: 0,
            gif_shown_at: None,
            gif_protocol: None,
            gif_proto_key: None,
            media_tx: None,
            media_gen: 0,
            media_loading: false,
            keymaps,
            pending_leader: None,
            flash: None,
            show_help: false,
            show_info: false,
            help_scroll: 0,
            tabs: Vec::new(),
            active_tab: 0,
            git_status: std::collections::HashMap::new(),
            git_ignored: std::collections::HashSet::new(),
            git_status_for: None,
            git_ignored_for: None,
            git_ignored_pending: None,
            git_ignored_gen: 0,
            git_ignored_dirty: false,
            ignored_tx: None,
            diff_layout,
            git_detail_title: None,
            git_branch: None,
            git_view: false,
            git_view_sel: 0,
            git_view_entries: Vec::new(),
            came_from_git_view: false,
            git_log: None,
            git_log_sel: 0,
            git_detail: None,
            git_detail_meta: None,
            git_detail_scroll: 0,
            git_detail_hscroll: 0,
            git_detail_viewport: 0,
            git_detail_total: 0,
            git_branches: None,
            git_branch_sel: 0,
            git_branch_filter: String::new(),
            git_branch_filtering: false,
            git_graph: None,
            git_graph_sel: 0,
            git_graph_base: None,
            git_graph_base_label: None,
            git_graph_visible: std::collections::HashSet::new(),
            git_graph_legend: Vec::new(),
            git_graph_hidden: 0,
            git_graph_picker: false,
            git_graph_picker_sel: 0,
            git_graph_picker_set: std::collections::HashSet::new(),
            git_graph_order: Vec::new(),
            git_graph_reordered: false,
        };
        app.rebuild_tree()?;
        // 最初のタブとして現在の状態を登録する。
        app.tabs.push(app.snapshot_tab());
        Ok(app)
    }

    /// Summarize startup keymap conflicts / ignored settings into one line (for the startup flash; i18n).
    /// Conflicts have already safely fallen back to defaults (#17/FR-8). None if there is nothing.
    pub fn keymap_report(&self) -> Option<String> {
        let nc = self.keymaps.conflicts.len();
        let nw = self.keymaps.warnings.len();
        if nc == 0 && nw == 0 {
            return None;
        }
        let mut parts: Vec<String> = Vec::new();
        if nc > 0 {
            parts.push(match self.lang {
                crate::i18n::Lang::Jp => format!("キー衝突{nc}件(既定で継続)"),
                crate::i18n::Lang::En => format!("{nc} key conflict(s) (using defaults)"),
            });
        }
        if nw > 0 {
            parts.push(match self.lang {
                crate::i18n::Lang::Jp => format!("無効な設定{nw}件を無視"),
                crate::i18n::Lang::En => format!("{nw} invalid key setting(s) ignored"),
            });
        }
        let head = tr(self.lang, crate::i18n::Msg::Keymap);
        Some(format!("{head}: {}", parts.join(" / ")))
    }

    /// Starting from directly under root, recursively expand the expanded directories and flatten them.
    /// A naive implementation for M0. Support for large directories will later be replaced with lazy loading.
    pub fn rebuild_tree(&mut self) -> Result<()> {
        let mut out = Vec::new();
        let expanded_dirs: Vec<PathBuf> = self
            .entries
            .iter()
            .filter(|e| e.is_dir && e.expanded)
            .map(|e| e.path.clone())
            .collect();

        build_dir(
            &self.root,
            0,
            &expanded_dirs,
            self.show_hidden,
            self.sort,
            &mut out,
        )?;
        self.entries = out;
        if self.selected >= self.entries.len() {
            self.selected = self.entries.len().saturating_sub(1);
        }
        // entries を作り直したら visual_anchor(entries 添字)は stale。必ず無効化する。
        self.visual_anchor = None;
        Ok(())
    }

    /// Calls `rebuild_tree`, and on failure does not swallow it but reports via flash. Returns `true` on success.
    /// Used on paths that cannot bail out with `?` (bookmark jump, clearing the filter, rebuilding after a git discard).
    /// The return value lets the caller decide whether to show a subsequent success flash (=false means don't).
    fn rebuild_tree_notify(&mut self) -> bool {
        if let Err(e) = self.rebuild_tree() {
            self.flash = Some(format!(
                "{}{e}",
                crate::i18n::tr(self.lang, crate::i18n::Msg::OperationFailed)
            ));
            false
        } else {
            true
        }
    }

    // --- ソート (FR・M7 補助) -------------------------------------------------
    /// Whether the `s` sort-selection menu is showing.
    pub fn is_sort_menu(&self) -> bool {
        self.sort_menu
    }
    /// Open the sort menu with `s`. main routes the next key here.
    pub fn open_sort_menu(&mut self) {
        self.sort_menu = true;
    }
    /// Close the sort menu (Esc or an out-of-scope key).
    pub fn close_sort_menu(&mut self) {
        self.sort_menu = false;
    }
    /// Key handling for the sort menu. n/s/m/e=select the key (closes after selecting), r=flip asc/desc, .=directories first
    /// (toggles keep it open). Out-of-scope keys close it. If the order changes, rebuild (while filtering, applied after clearing).
    pub fn sort_menu_key(&mut self, c: char) -> Result<()> {
        let keep_open = match c {
            'n' => {
                self.sort.key = SortKey::Name;
                false
            }
            's' => {
                self.sort.key = SortKey::Size;
                false
            }
            'm' => {
                self.sort.key = SortKey::Modified;
                false
            }
            'e' => {
                self.sort.key = SortKey::Ext;
                false
            }
            'r' => {
                self.sort.reverse = !self.sort.reverse;
                true
            }
            '.' => {
                self.sort.dirs_first = !self.sort.dirs_first;
                true
            }
            _ => {
                self.sort_menu = false;
                return Ok(());
            }
        };
        // 絞り込み中は結果順を変えない(クリア後にツリー再構築で反映)。
        if self.tree_filter.is_none() {
            self.rebuild_tree()?;
        }
        self.sort_menu = keep_open;
        Ok(())
    }
    /// Current sort display for the top context bar (e.g. `sort: mod ↑`).
    pub fn sort_label(&self) -> String {
        let k = match self.sort.key {
            SortKey::Name => "name",
            SortKey::Size => "size",
            SortKey::Modified => "mod",
            SortKey::Ext => "ext",
        };
        let arrow = if self.sort.reverse { "" } else { "" };
        format!("sort: {k} {arrow}")
    }

    // --- モード表示 (2軸: 表示モード × 内部モード) ----------------------------
    /// Display mode (for the outer chip). Preview becomes Image if it is an image.
    pub fn display_mode(&self) -> DisplayMode {
        match self.mode {
            Mode::Tree => DisplayMode::Tree,
            Mode::Preview => {
                if self.is_image_preview() {
                    DisplayMode::Image
                } else {
                    DisplayMode::Preview
                }
            }
        }
    }
    /// Internal mode (for the inner chip and footer switching). None if nothing is being operated.
    /// Priority: dialog > filter/search/sort/mark/bookmarks > visual.
    pub fn internal_mode(&self) -> Option<InternalMode> {
        if let Some(d) = &self.dialog {
            return Some(match &d.kind {
                // アプリ終了確認は非破壊。削除/ドロップとは別チップ/フッターにする。
                DialogKind::Confirm { .. } if self.confirm_is_quit() => InternalMode::QuitConfirm,
                // D&D 転送は破壊的でないので削除確認とは別チップ/フッターにする。
                DialogKind::Confirm { .. } if self.confirm_is_drop() => InternalMode::DropConfirm,
                DialogKind::Confirm { .. } => InternalMode::DeleteConfirm,
                DialogKind::Preview { .. } => InternalMode::RenamePreview,
                DialogKind::Input { .. } => match &d.op {
                    PendingOp::Create { .. } => InternalMode::Create,
                    PendingOp::BatchRenameInput { .. } => InternalMode::BatchRename,
                    PendingOp::GitCommit => InternalMode::Commit,
                    PendingOp::GitCreateBranch => InternalMode::GitBranch,
                    _ => InternalMode::Rename,
                },
            });
        }
        // コミット詳細は log の上に被さるので先に判定する。
        if self.is_git_detail() {
            return Some(InternalMode::GitDetail);
        }
        if self.is_git_log() {
            return Some(InternalMode::GitLog);
        }
        // パネルはグラフの上に被さる(is_git_graph も true なので先に判定)。
        if self.is_git_graph_picker() {
            return Some(InternalMode::GitGraphPicker);
        }
        if self.is_git_graph() {
            return Some(InternalMode::GitGraph);
        }
        if self.is_git_branches() {
            return Some(InternalMode::GitBranch);
        }
        if self.is_git_view() {
            return Some(InternalMode::GitChanges);
        }
        if self.is_git_diff_preview() {
            return Some(InternalMode::GitDiff);
        }
        if self.is_filtering() {
            return Some(InternalMode::Filter);
        }
        if self.is_searching() {
            return Some(InternalMode::Search);
        }
        if self.is_sort_menu() {
            return Some(InternalMode::Sort);
        }
        match self.mark_is_set() {
            Some(true) => return Some(InternalMode::Mark),
            Some(false) => return Some(InternalMode::Goto),
            None => {}
        }
        if self.is_bookmark_list() {
            return Some(InternalMode::Bookmarks);
        }
        if self.is_info() {
            return Some(InternalMode::Info);
        }
        if self.is_visual() {
            return Some(InternalMode::Visual);
        }
        None
    }

    /// The **frontmost surface** that currently receives keys (the single source of truth for Run2 keymap dispatch).
    /// Strictly follows the same priority as internal_mode, while also including the base full screens (Tree/Preview) and overlays (§4).
    /// Off the render path; references only existing bool predicates (same cost as now).
    pub fn surface(&self) -> crate::keymap::Surface {
        use crate::keymap::Surface as S;
        // ダイアログ最優先 (種別で細分: 入力 / 削除確認 / ドロップ確認 / リネームプレビュー)。
        if self.is_dialog() {
            if self.dialog_is_preview() {
                return S::DialogRenamePreview;
            }
            if self.dialog_is_confirm() {
                if self.confirm_is_quit() {
                    return S::DialogConfirmQuit;
                }
                if self.confirm_is_drop() {
                    return S::DialogConfirmDrop;
                }
                return S::DialogConfirmDelete;
            }
            return S::DialogInput;
        }
        // ヘルプ (全要素の上)。
        if self.show_help {
            return S::Help;
        }
        // Git オーバーレイ (詳細 > log > graph > branches > 変更ハブ > diff)。feature 無効時は到達しない。
        #[cfg(feature = "git")]
        {
            if self.is_git_detail() {
                return S::GitDetail;
            }
            if self.is_git_log() {
                return S::GitLog;
            }
            // パネルはグラフの上に被さる(is_git_graph も true なので先に判定)。
            if self.is_git_graph_picker() {
                return S::GitGraphPicker;
            }
            if self.is_git_graph() {
                return S::GitGraph;
            }
            if self.is_git_branches() {
                return if self.git_branch_filtering() {
                    S::BranchFilter
                } else {
                    S::GitBranches
                };
            }
            if self.is_git_view() {
                return S::GitChanges;
            }
            if self.is_git_diff_preview() {
                return S::PreviewGitDiff;
            }
        }
        // 入力系 / メニュー / 一覧 / 情報 / ビジュアル。
        if self.is_filtering() {
            return S::Filter;
        }
        if self.is_searching() {
            return S::Search;
        }
        if self.is_sort_menu() {
            return S::Sort;
        }
        if self.is_marking() {
            return S::Mark;
        }
        if self.is_bookmark_list() {
            return S::Bookmarks;
        }
        if self.is_info() {
            return S::Info;
        }
        if self.is_visual() {
            return S::Visual;
        }
        // 基本全画面 (Preview は画像/テキストで分岐)。
        match self.mode {
            Mode::Preview => {
                if self.is_image_preview() {
                    S::PreviewImage
                } else {
                    S::PreviewText
                }
            }
            Mode::Tree => S::Tree,
        }
    }

    // --- コピー/カット&ペースト (M7 Phase B・既定キー Y/X/P・keymap で変更可) ---
    /// Label for the context display: "copy 3" / "cut 3". None if the clipboard is empty.
    pub fn clipboard_label(&self) -> Option<String> {
        self.clipboard.as_ref().map(|c| {
            let verb = match c.op {
                ClipOp::Copy => crate::i18n::tr(self.lang, crate::i18n::Msg::CopyHint),
                ClipOp::Cut => crate::i18n::tr(self.lang, crate::i18n::Msg::CutHint),
            };
            format!("{verb} {}", c.paths.len())
        })
    }
    /// `Y`=copy: push the selection (or the cursor if none) to the clipboard (for duplication). The selection is cleared.
    pub fn copy_selection(&mut self) {
        let targets = self.op_targets();
        if targets.is_empty() {
            self.flash = Some(crate::i18n::tr(self.lang, crate::i18n::Msg::NoTarget).into());
            return;
        }
        let n = targets.len();
        self.clipboard = Some(Clipboard {
            op: ClipOp::Copy,
            paths: targets,
        });
        self.clear_selection();
        self.flash = Some(format!(
            "{} ({n})",
            crate::i18n::tr(self.lang, crate::i18n::Msg::Copied)
        ));
    }
    /// `X`=cut: push the selection (or the cursor if none) to the clipboard (for moving). The selection is cleared.
    pub fn cut_selection(&mut self) {
        let targets = self.op_targets();
        if targets.is_empty() {
            self.flash = Some(crate::i18n::tr(self.lang, crate::i18n::Msg::NoTarget).into());
            return;
        }
        let n = targets.len();
        self.clipboard = Some(Clipboard {
            op: ClipOp::Cut,
            paths: targets,
        });
        self.clear_selection();
        self.flash = Some(format!(
            "{} ({n})",
            crate::i18n::tr(self.lang, crate::i18n::Msg::CutDone)
        ));
    }
    /// `P`=paste: apply to the cursor-based directory. Copy duplicates, cut moves (consumed). **Never overwrites.**
    pub fn paste(&mut self) -> Result<()> {
        let Some(clip) = self.clipboard.clone() else {
            self.flash = Some(crate::i18n::tr(self.lang, crate::i18n::Msg::ClipboardEmpty).into());
            return Ok(());
        };
        let dir = self.op_base_dir();
        let (mut ok, mut last, mut err) = (0usize, None, None);
        for src in &clip.paths {
            // 自分自身(やその中)への貼り付けは無限コピーになるので弾く。
            if dir.starts_with(src) {
                err = Some(
                    crate::i18n::tr(self.lang, crate::i18n::Msg::CannotPasteIntoSelf).to_string(),
                );
                continue;
            }
            let res = match clip.op {
                ClipOp::Copy => crate::fileops::copy_into(&dir, src),
                ClipOp::Cut => crate::fileops::move_into(&dir, src),
            };
            match res {
                Ok(p) => {
                    ok += 1;
                    last = Some(p);
                }
                Err(e) => err = Some(e.to_string()),
            }
        }
        if matches!(clip.op, ClipOp::Cut) {
            self.clipboard = None; // カットは消費(元が移動済み)
        }
        self.refresh()?;
        if let Some(p) = &last {
            self.reveal_and_select(p)?;
        }
        self.flash = Some(match err {
            Some(e) => format!(
                "{} {ok} / {}: {e}",
                crate::i18n::tr(self.lang, crate::i18n::Msg::Pasted),
                crate::i18n::tr(self.lang, crate::i18n::Msg::Failed),
            ),
            None => format!(
                "{} ({ok})",
                crate::i18n::tr(self.lang, crate::i18n::Msg::Pasted)
            ),
        });
        Ok(())
    }

    /// The selection listed in the **current sort order (tree display order)**. Used as the numbering order for sequential rename.
    /// Selections not present in entries (collapsed, etc.) are appended at the end in path order.
    fn selection_in_display_order(&self) -> Vec<PathBuf> {
        let mut v: Vec<PathBuf> = self
            .entries
            .iter()
            .filter(|e| self.selection.contains(&e.path))
            .map(|e| e.path.clone())
            .collect();
        for p in &self.selection {
            if !v.contains(p) {
                v.push(p.clone());
            }
        }
        v
    }
    /// Heading for the batch-rename input dialog (the count + a placeholder legend).
    fn batch_rename_title(&self, count: usize) -> String {
        format!(
            "{} {} {}  {{n}} {{n:0W}} {{name}} {{ext}}",
            crate::i18n::tr(self.lang, crate::i18n::Msg::BatchRename),
            count,
            crate::i18n::tr(self.lang, crate::i18n::Msg::Items),
        )
    }
    /// `R` (with a selection)=batch rename. Opens template input that numbers the selection sequentially in display order.
    pub fn start_batch_rename(&mut self) {
        let targets = self.selection_in_display_order();
        if targets.is_empty() {
            self.flash = Some(crate::i18n::tr(self.lang, crate::i18n::Msg::NoTarget).into());
            return;
        }
        let title = self.batch_rename_title(targets.len());
        self.dialog = Some(Dialog {
            op: PendingOp::BatchRenameInput { targets },
            kind: DialogKind::Input {
                title,
                buffer: String::new(),
                cursor: 0,
            },
        });
    }

    /// `a`=create. Opens an input dialog to create with the entered name in the cursor-based directory (a trailing `/` makes a folder).
    pub fn start_create(&mut self) {
        let dir = self.op_base_dir();
        let where_ = self.format_path(&dir);
        self.dialog = Some(Dialog {
            op: PendingOp::Create { dir },
            kind: DialogKind::Input {
                title: format!(
                    "{} in {where_}  ({})",
                    crate::i18n::tr(self.lang, crate::i18n::Msg::Create),
                    crate::i18n::tr(self.lang, crate::i18n::Msg::TrailingSlashFolder),
                ),
                buffer: String::new(),
                cursor: 0,
            },
        });
    }

    /// `R`=rename. An input dialog to change the cursor's file/directory name (prefilled with the current name).
    pub fn start_rename(&mut self) {
        let Some(target) = self.entries.get(self.selected).map(|e| e.path.clone()) else {
            self.flash = Some(crate::i18n::tr(self.lang, crate::i18n::Msg::NoTarget).into());
            return;
        };
        let name = target
            .file_name()
            .and_then(|n| n.to_str())
            .unwrap_or("")
            .to_string();
        let cursor = name.chars().count(); // 末尾にカーソルを置く。
        self.dialog = Some(Dialog {
            op: PendingOp::Rename { target },
            kind: DialogKind::Input {
                title: crate::i18n::tr(self.lang, crate::i18n::Msg::Rename).into(),
                buffer: name,
                cursor,
            },
        });
    }

    /// `D`=delete (with confirmation). Opens a confirmation dialog targeting **all selected items if there is a selection**, or the cursor item otherwise.
    /// `y`=send to trash (recoverable) / `!`=permanent delete (unrecoverable) / `n`,Esc=cancel.
    pub fn start_delete(&mut self) {
        let targets = self.op_targets();
        if targets.is_empty() {
            self.flash = Some(crate::i18n::tr(self.lang, crate::i18n::Msg::NoTarget).into());
            return;
        }
        // メッセージ: 1件は名前、複数件は「N 件 (先頭名 他)」。
        let label = if targets.len() == 1 {
            targets[0]
                .file_name()
                .and_then(|n| n.to_str())
                .unwrap_or("?")
                .to_string()
        } else {
            let first = targets[0]
                .file_name()
                .and_then(|n| n.to_str())
                .unwrap_or("?");
            format!(
                "{} {} ({first} {})",
                targets.len(),
                crate::i18n::tr(self.lang, crate::i18n::Msg::Items),
                crate::i18n::tr(self.lang, crate::i18n::Msg::Etc),
            )
        };
        self.dialog = Some(Dialog {
            op: PendingOp::Delete { targets },
            kind: DialogKind::Confirm {
                message: format!(
                    "{}: {label}",
                    crate::i18n::tr(self.lang, crate::i18n::Msg::DeleteTarget),
                ),
                allow_permanent: true,
            },
        });
    }

    /// A mutable reference to the (buffer, cursor) being edited. None if not an input dialog.
    fn dialog_input_mut(&mut self) -> Option<(&mut String, &mut usize)> {
        match self.dialog.as_mut() {
            Some(Dialog {
                kind: DialogKind::Input { buffer, cursor, .. },
                ..
            }) => Some((buffer, cursor)),
            _ => None,
        }
    }

    /// Insert one character at the cursor position in the input dialog and advance the cursor by one.
    pub fn dialog_input_push(&mut self, c: char) {
        if let Some((buffer, cursor)) = self.dialog_input_mut() {
            let at = char_byte(buffer, *cursor);
            buffer.insert(at, c);
            *cursor += 1;
        }
    }
    /// Delete the character just before the cursor (Backspace).
    pub fn dialog_input_backspace(&mut self) {
        if let Some((buffer, cursor)) = self.dialog_input_mut() {
            if *cursor > 0 {
                let start = char_byte(buffer, *cursor - 1);
                let end = char_byte(buffer, *cursor);
                buffer.replace_range(start..end, "");
                *cursor -= 1;
            }
        }
    }
    /// Delete the character at the cursor position (Delete). The cursor does not move.
    pub fn dialog_input_delete(&mut self) {
        if let Some((buffer, cursor)) = self.dialog_input_mut() {
            let count = buffer.chars().count();
            if *cursor < count {
                let start = char_byte(buffer, *cursor);
                let end = char_byte(buffer, *cursor + 1);
                buffer.replace_range(start..end, "");
            }
        }
    }
    /// Move the cursor left (←).
    pub fn dialog_cursor_left(&mut self) {
        if let Some((_, cursor)) = self.dialog_input_mut() {
            *cursor = cursor.saturating_sub(1);
        }
    }
    /// Move the cursor right (→). Clamped at the end.
    pub fn dialog_cursor_right(&mut self) {
        if let Some((buffer, cursor)) = self.dialog_input_mut() {
            *cursor = (*cursor + 1).min(buffer.chars().count());
        }
    }
    /// Move the cursor to the start (Home).
    pub fn dialog_cursor_home(&mut self) {
        if let Some((_, cursor)) = self.dialog_input_mut() {
            *cursor = 0;
        }
    }
    /// Move the cursor to the end (End).
    pub fn dialog_cursor_end(&mut self) {
        if let Some((buffer, cursor)) = self.dialog_input_mut() {
            *cursor = buffer.chars().count();
        }
    }
    /// Cancel the dialog (Esc / confirm n).
    pub fn dialog_cancel(&mut self) {
        self.dialog = None;
    }

    /// Handle a quit request (`q` at the top level / `Q` from anywhere). If `ui.confirm_quit` is on,
    /// open a yes/no confirmation dialog and return `true` (the caller must NOT quit yet). Otherwise
    /// return `false` (the caller quits immediately).
    pub fn request_quit(&mut self) -> bool {
        if !self.cfg.ui.confirm_quit {
            return false;
        }
        self.dialog = Some(Dialog {
            op: PendingOp::Quit,
            kind: DialogKind::Confirm {
                message: crate::i18n::tr(self.lang, crate::i18n::Msg::QuitConfirm).into(),
                allow_permanent: false,
            },
        });
        true
    }

    /// Confirm the text-input dialog (Enter). Performs create/rename.
    pub fn dialog_submit(&mut self) -> Result<()> {
        let Some(dialog) = self.dialog.take() else {
            return Ok(());
        };
        let DialogKind::Input { buffer, .. } = dialog.kind else {
            return Ok(()); // 確認ダイアログはここへ来ない
        };
        // コミットは名前と扱いが違う(末尾 / を剥がさない・独自の空チェック)ので先に分岐。
        if matches!(dialog.op, PendingOp::GitCommit) {
            let message = buffer.trim();
            if message.is_empty() {
                self.flash =
                    Some(crate::i18n::tr(self.lang, crate::i18n::Msg::MessageEmpty).into());
                return Ok(());
            }
            match crate::git::commit(&self.root, message) {
                Ok(()) => {
                    // ステージ済み index でコミット成功 → git データ再取得+ビュー更新。
                    self.refresh()?;
                    if self.is_git_view() {
                        self.git_view_reload();
                    }
                    self.flash =
                        Some(crate::i18n::tr(self.lang, crate::i18n::Msg::Committed).into());
                }
                Err(e) => {
                    // 失敗(stderr)を表示し、同じメッセージで入力ダイアログを再オープン(やり直せる)。
                    self.flash = Some(format!("{e}"));
                    let cursor = message.chars().count();
                    self.dialog = Some(Dialog {
                        op: PendingOp::GitCommit,
                        kind: DialogKind::Input {
                            title: crate::i18n::tr(self.lang, crate::i18n::Msg::CommitMessage)
                                .into(),
                            buffer: message.to_string(),
                            cursor,
                        },
                    });
                }
            }
            return Ok(());
        }
        // 新規ブランチ作成(コミット同様、名前を素直に trim して扱う)。
        if matches!(dialog.op, PendingOp::GitCreateBranch) {
            let bname = buffer.trim();
            if bname.is_empty() {
                self.flash = Some(crate::i18n::tr(self.lang, crate::i18n::Msg::NameEmpty).into());
                return Ok(());
            }
            match crate::git::create_branch(&self.root, bname) {
                Ok(()) => {
                    self.refresh()?;
                    self.refresh_git_if_needed(); // ブランチ名/状態のキャッシュを即更新
                    self.close_git_branches(); // 作成&切替済み → 一覧を閉じて Git ビューへ
                    self.flash = Some(format!(
                        "{}: {bname}",
                        crate::i18n::tr(self.lang, crate::i18n::Msg::CreatedBranch)
                    ));
                }
                Err(e) => {
                    self.flash = Some(format!("{e}"));
                    let cursor = bname.chars().count();
                    self.dialog = Some(Dialog {
                        op: PendingOp::GitCreateBranch,
                        kind: DialogKind::Input {
                            title: crate::i18n::tr(self.lang, crate::i18n::Msg::NewBranch).into(),
                            buffer: bname.to_string(),
                            cursor,
                        },
                    });
                }
            }
            return Ok(());
        }
        let name = buffer.trim().trim_end_matches('/').trim();
        let want_folder = buffer.trim_end().ends_with('/');
        if name.is_empty() {
            self.flash = Some(crate::i18n::tr(self.lang, crate::i18n::Msg::NameEmpty).into());
            return Ok(());
        }
        match dialog.op {
            PendingOp::Create { dir } => {
                let created = if want_folder {
                    crate::fileops::create_dir(&dir, name)
                } else {
                    crate::fileops::create_file(&dir, name)
                };
                match created {
                    Ok(path) => {
                        self.refresh()?;
                        self.reveal_and_select(&path)?;
                        self.flash = Some(format!(
                            "{}: {}",
                            crate::i18n::tr(self.lang, crate::i18n::Msg::Created),
                            self.format_path(&path)
                        ));
                    }
                    Err(e) => {
                        self.flash = Some(format!(
                            "{}: {e}",
                            crate::i18n::tr(self.lang, crate::i18n::Msg::Failed)
                        ))
                    }
                }
            }
            PendingOp::Rename { target } => match crate::fileops::rename(&target, name) {
                Ok(path) => {
                    self.refresh()?;
                    self.reveal_and_select(&path)?;
                    self.flash = Some(format!(
                        "{}: {}",
                        crate::i18n::tr(self.lang, crate::i18n::Msg::Renamed),
                        self.format_path(&path)
                    ));
                }
                Err(e) => {
                    self.flash = Some(format!(
                        "{}: {e}",
                        crate::i18n::tr(self.lang, crate::i18n::Msg::Failed)
                    ))
                }
            },
            PendingOp::BatchRenameInput { targets } => {
                match build_rename_plan(&targets, name) {
                    Ok(plan) => {
                        // プレビュー(旧 → 新)へ遷移。適用は dialog_preview_apply。
                        let lines: Vec<String> = plan
                            .iter()
                            .map(|(s, d)| {
                                format!(
                                    "{}{}",
                                    s.file_name().and_then(|n| n.to_str()).unwrap_or("?"),
                                    d.file_name().and_then(|n| n.to_str()).unwrap_or("?"),
                                )
                            })
                            .collect();
                        let title = format!(
                            "{} {} {}",
                            crate::i18n::tr(self.lang, crate::i18n::Msg::Rename),
                            plan.len(),
                            crate::i18n::tr(self.lang, crate::i18n::Msg::Items),
                        );
                        self.dialog = Some(Dialog {
                            op: PendingOp::BatchRenameApply { plan },
                            kind: DialogKind::Preview {
                                title,
                                lines,
                                scroll: 0,
                            },
                        });
                    }
                    Err(e) => {
                        // 入力をやり直せるよう、同じテンプレで入力ダイアログを再オープン。
                        self.flash = Some(format!(
                            "{}: {e}",
                            crate::i18n::tr(self.lang, crate::i18n::Msg::Failed)
                        ));
                        let cursor = name.chars().count();
                        let title = self.batch_rename_title(targets.len());
                        self.dialog = Some(Dialog {
                            op: PendingOp::BatchRenameInput { targets },
                            kind: DialogKind::Input {
                                title,
                                buffer: name.to_string(),
                                cursor,
                            },
                        });
                    }
                }
            }
            // 削除/Git 破棄は確認ダイアログ側 / 一括リネーム適用はプレビュー側。
            // GitCommit は上で早期 return 済みなので到達しない。
            PendingOp::Delete { .. }
            | PendingOp::BatchRenameApply { .. }
            | PendingOp::GitDiscard { .. }
            | PendingOp::GitCommit
            | PendingOp::GitCreateBranch
            | PendingOp::GitDeleteBranch { .. }
            | PendingOp::DropTransfer { .. }
            | PendingOp::Quit => {}
        }
        Ok(())
    }

    /// In the preview, `y`=apply the batch rename. Two-phase rename → reload → clear selection.
    pub fn dialog_preview_apply(&mut self) -> Result<()> {
        let Some(dialog) = self.dialog.take() else {
            return Ok(());
        };
        if let PendingOp::BatchRenameApply { plan } = dialog.op {
            match crate::fileops::batch_rename(&plan) {
                Ok(()) => {
                    self.refresh()?;
                    self.clear_selection();
                    self.flash = Some(format!(
                        "{} ({})",
                        crate::i18n::tr(self.lang, crate::i18n::Msg::Renamed),
                        plan.len()
                    ));
                }
                Err(e) => {
                    self.flash = Some(format!(
                        "{}: {e}",
                        crate::i18n::tr(self.lang, crate::i18n::Msg::Failed)
                    ))
                }
            }
        }
        Ok(())
    }

    /// Response to a confirmation dialog. yes=execute (delete → trash, recoverable) / no=cancel.
    pub fn dialog_confirm(&mut self, yes: bool) -> Result<()> {
        let Some(dialog) = self.dialog.take() else {
            return Ok(());
        };
        if !yes {
            self.flash = Some(crate::i18n::tr(self.lang, crate::i18n::Msg::Canceled).into());
            return Ok(());
        }
        match dialog.op {
            PendingOp::Delete { targets } => match crate::fileops::move_to_trash(&targets) {
                Ok(()) => {
                    self.refresh()?;
                    self.clear_selection();
                    self.flash = Some(format!(
                        "{} ({})",
                        crate::i18n::tr(self.lang, crate::i18n::Msg::MovedToTrash),
                        targets.len()
                    ));
                }
                Err(e) => {
                    self.flash = Some(format!(
                        "{}: {e}",
                        crate::i18n::tr(self.lang, crate::i18n::Msg::Failed)
                    ))
                }
            },
            // Git ビューの破棄: git::discard → 一覧/ツリーの git status を取り直す。
            // GitDiff プレビューからの破棄(came_from_git_view)なら Git ビューを開き直して戻す。
            PendingOp::GitDiscard { path } => match crate::git::discard(&self.root, &path) {
                Ok(()) => {
                    let from_diff = self.is_git_diff_preview();
                    if from_diff {
                        // プレビューを畳んで Git ビューへ復帰。
                        self.came_from_git_view = false;
                        self.back_to_tree();
                        self.open_git_view();
                    }
                    self.git_view_reload();
                    // 破棄自体は成功。ツリー再構築が失敗した時はその旨を通知し、
                    // 成功 flash で上書きしない(誤って「成功」と見せない)。
                    if self.rebuild_tree_notify() {
                        self.flash = Some(format!(
                            "{}: {}",
                            crate::i18n::tr(self.lang, crate::i18n::Msg::Discarded),
                            self.format_path(&path)
                        ));
                    }
                }
                Err(e) => {
                    self.flash = Some(format!(
                        "{}: {e}",
                        crate::i18n::tr(self.lang, crate::i18n::Msg::Failed)
                    ))
                }
            },
            // ブランチ削除(安全): git branch -d。失敗(未マージ等)は git の stderr を flash。
            PendingOp::GitDeleteBranch { name } => self.git_delete_branch(&name, false),
            _ => {}
        }
        Ok(())
    }

    /// In a confirmation dialog, `!`=**permanent delete / force** (delete=without going through the trash / branch=`-D` force).
    pub fn dialog_delete_permanent(&mut self) -> Result<()> {
        let Some(dialog) = self.dialog.take() else {
            return Ok(());
        };
        // ブランチの強制削除 (`-D`)。
        if let PendingOp::GitDeleteBranch { name } = &dialog.op {
            self.git_delete_branch(&name.clone(), true);
            return Ok(());
        }
        if let PendingOp::Delete { targets } = dialog.op {
            match crate::fileops::delete_permanently(&targets) {
                Ok(()) => {
                    self.refresh()?;
                    self.clear_selection();
                    self.flash = Some(format!(
                        "{} ({})",
                        crate::i18n::tr(self.lang, crate::i18n::Msg::DeletedPermanently),
                        targets.len()
                    ));
                }
                Err(e) => {
                    self.flash = Some(format!(
                        "{}: {e}",
                        crate::i18n::tr(self.lang, crate::i18n::Msg::Failed)
                    ))
                }
            }
        }
        Ok(())
    }

    pub fn tree_next(&mut self) {
        if self.selected + 1 < self.entries.len() {
            self.selected += 1;
        }
    }

    pub fn tree_prev(&mut self) {
        self.selected = self.selected.saturating_sub(1);
    }

    /// To the top of the tree.
    pub fn tree_first(&mut self) {
        self.selected = 0;
    }

    /// To the bottom of the tree.
    pub fn tree_last(&mut self) {
        self.selected = self.entries.len().saturating_sub(1);
    }

    /// Page the tree by one (dir: +1=next / -1=previous). Overlaps one row to keep context.
    pub fn tree_page(&mut self, dir: i32) {
        let page = self.tree_viewport.saturating_sub(1).max(1) as i32;
        self.tree_move(dir * page);
    }

    /// Half-page the tree (vim: Ctrl-d/Ctrl-u, less: d/u).
    pub fn tree_half_page(&mut self, dir: i32) {
        let half = (self.tree_viewport / 2).max(1) as i32;
        self.tree_move(dir * half);
    }

    /// Move the selection by delta rows and clamp it to [0, end].
    fn tree_move(&mut self, delta: i32) {
        self.selected = clamp_cursor(self.selected, delta, self.entries.len());
    }

    /// If a directory, toggle expansion; if a file, transition to Preview.
    /// While filtering (a flat result list), expand-toggle is meaningless, so behave the same as `tree_descend`.
    pub fn tree_activate(&mut self) -> Result<()> {
        if self.tree_filter.is_some() {
            return self.tree_descend();
        }
        let Some(entry) = self.entries.get(self.selected).cloned() else {
            return Ok(());
        };
        if entry.is_dir {
            // expanded をトグルして再構築
            if let Some(e) = self.entries.get_mut(self.selected) {
                e.expanded = !e.expanded;
            }
            self.rebuild_tree()?;
        } else {
            self.enter_preview(&entry.path);
        }
        Ok(())
    }

    /// Before switching root, discard state that points to items of the old root.
    /// `selection` is held by path, so under a different root it stays invisible yet becomes a target for mis-operations (a footgun), and
    /// `visual_anchor` is an entries index, so it goes stale under a different root. The filter and preview search are also
    /// for the old root, so they are cleared together (rebuild_tree also invalidates visual_anchor, but we do it explicitly).
    fn clear_for_root_change(&mut self) {
        self.selection.clear();
        self.visual_anchor = None;
        self.clear_filter_state();
        self.search_clear();
    }

    /// Move to the parent directory (raise the root). For `h`. While filtering, first clear the filter (the normal tree of the current root).
    pub fn tree_leave(&mut self) -> Result<()> {
        if self.tree_filter.is_some() {
            self.filter_clear();
            return Ok(());
        }
        if let Some(parent) = self.root.parent().map(Path::to_path_buf) {
            self.clear_for_root_change();
            self.root = parent;
            self.entries.clear();
            self.selected = 0;
            self.rebuild_tree()?;
        }
        Ok(())
    }

    /// Descend into the selected directory (make that directory the new root). For `l`.
    /// Symmetric to `h` (to the parent). If a file, transition to Preview.
    /// Works on filter results too: directory → move there and clear the filter / file → preview.
    pub fn tree_descend(&mut self) -> Result<()> {
        let Some(entry) = self.entries.get(self.selected).cloned() else {
            return Ok(());
        };
        let was_filtering = self.tree_filter.is_some();
        if entry.is_dir {
            // root を変えるので旧 root の選択/ビジュアル/絞り込み/検索を破棄する(持ち越さない)。
            self.clear_for_root_change();
            self.root = entry.path;
            self.entries.clear();
            self.selected = 0;
            self.rebuild_tree()?;
        } else {
            // ファイルは絞り込みを保ったままプレビュー(戻ると結果一覧に復帰)。
            let _ = was_filtering;
            self.enter_preview(&entry.path);
        }
        Ok(())
    }

    pub fn toggle_hidden(&mut self) -> Result<()> {
        self.show_hidden = !self.show_hidden;
        self.rebuild_tree()
    }

    fn enter_preview(&mut self, path: &Path) {
        self.preview_path = Some(path.to_path_buf());
        // 設定駆動でプレビュー種別を解決。未対応は CanNotPreview。
        let kind = self.cfg.resolve_preview(path);
        self.preview_scroll = 0;
        self.preview_hscroll = 0;
        self.preview_byte_top = 0;
        self.preview_top_line = 0;
        // 画像状態は毎回リセット。SVG/GIF は別スレッドで読み込み開始(UI を塞がない)。
        self.clear_image();
        // PDF はページ数を先に求める(pdfinfo・~数 ms)。None なら単ページ扱い=ページ移動なし。
        if matches!(kind, PreviewKind::Pdf(_)) {
            self.pdf_pages = crate::preview::pdf::page_count(path);
        }
        self.start_media_load(&kind, path);
        self.preview_kind = Some(kind);
        self.md_cache = None; // 別ファイルに切替: 装飾キャッシュを無効化
        self.md_links.clear();
        self.focused_link = None;
        self.preview_search = None;
        self.search_input = None;
        self.search_matches.clear();
        self.search_idx = 0;
        self.setup_windowed(); // 大きい Code/Text なら less 風ウィンドウ読みに切替
        self.mode = Mode::Preview;
    }

    /// Code/Text previews use less-style windowed reading **regardless of size**.
    /// This avoids whole-file highlighting (1.3s/debug for 1600 lines) and reads/colors only the visible window (tens of lines), so
    /// opening is instant even for small files and behavior is symmetric with huge files. Images/md/mermaid are excluded
    /// (md/mermaid need their whole structure understood and are usually small).
    fn setup_windowed(&mut self) {
        self.preview_win = None;
        self.win_cache = None;
        self.preview_total_lines = None;
        // 重いハイライト待ち状態を判定: Code かつ ハイライト有効 かつ 文法が未コンパイル(cold)なら
        // 初回だけローディング表示/段階表示が要る。温まっていれば最初から即時着色。
        self.hl_pending = self.cfg.ui.syntax_highlight
            && matches!(self.preview_kind, Some(PreviewKind::Code(_)))
            && !crate::preview::code::is_ext_warm(self.current_preview_ext());
        self.hl_warming = false;
        let windowed_kind = matches!(
            self.preview_kind,
            Some(PreviewKind::Code(_)) | Some(PreviewKind::Text(_))
        );
        if !windowed_kind {
            return;
        }
        let Some(path) = self.preview_path.clone() else {
            return;
        };
        if let Ok(w) = crate::preview::window::FileWindow::open(&path) {
            self.preview_win = Some(w);
        }
    }

    /// Extension of the current preview target file (empty string if none). Used for the highlight-warm check, etc.
    pub fn current_preview_ext(&self) -> &str {
        self.preview_path
            .as_deref()
            .and_then(|p| p.extension())
            .and_then(|e| e.to_str())
            .unwrap_or("")
    }

    /// Whether waiting on heavy code highlighting (whether the render shows a loading/progressive display).
    pub fn is_highlight_pending(&self) -> bool {
        self.hl_pending
    }

    /// Whether the loading display is the "central spinner" style (false=progressive=immediate plain text).
    pub fn loading_is_indicator(&self) -> bool {
        self.cfg.ui.preview_loading != "progressive"
    }

    /// Clear the loading state on warm completion (swap in the colored version). Common to indicator/progressive.
    pub fn clear_highlight_pending(&mut self) {
        self.hl_pending = false;
        self.hl_warming = false;
    }

    /// If the background warm has not started yet, return the launch target (the caller runs `code::warm_file` on a separate thread).
    /// Both indicator and progressive **compile on a background thread** so the UI is not stalled (the spinner keeps spinning).
    /// Launch only when the return value is Some((ext, path)) (= prevents double-launch).
    pub fn take_warm_job(&mut self) -> Option<(String, PathBuf)> {
        if self.hl_pending && !self.hl_warming {
            if let Some(path) = self.preview_path.clone() {
                self.hl_warming = true;
                return Some((self.current_preview_ext().to_string(), path));
            }
        }
        None
    }

    /// Advance the spinner by one frame (the run loop calls this periodically while waiting = keeps it spinning).
    pub fn tick_spinner(&mut self) {
        self.spinner_frame = self.spinner_frame.wrapping_add(1);
    }

    /// The current spinner glyph (no emoji; the classic braille-pattern spinner = single-width and color-free in the terminal).
    pub fn spinner_glyph(&self) -> &'static str {
        const FRAMES: [&str; 10] = ["", "", "", "", "", "", "", "", "", ""];
        FRAMES[self.spinner_frame % FRAMES.len()]
    }

    /// `e`: decide the target to open in the external editor and raise the request. Tree=the selected file / Preview=the file being shown.
    /// For a directory or no target, notify via flash and do nothing (only files can be edited).
    pub fn request_edit(&mut self) {
        let target = match self.mode {
            Mode::Tree => match self.entries.get(self.selected) {
                Some(e) if e.is_dir => {
                    self.flash = Some(tr(self.lang, crate::i18n::Msg::CannotEditDirectory).into());
                    return;
                }
                Some(e) => Some(e.path.clone()),
                None => None,
            },
            Mode::Preview => self.preview_path.clone(),
        };
        match target {
            Some(p) => self.pending_edit = Some(p),
            None => self.flash = Some(tr(self.lang, crate::i18n::Msg::NoFileToEdit).into()),
        }
    }

    /// Taken by the run loop: if set, return the editor-launch target path and clear it.
    pub fn take_pending_edit(&mut self) -> Option<PathBuf> {
        self.pending_edit.take()
    }

    /// `O`: request launching an external git tool (lazygit, etc.) (the run loop picks it up, suspends, then launches).
    #[cfg_attr(not(feature = "git"), allow(dead_code))]
    pub fn launch_git_tool(&mut self) {
        self.pending_git_tool = true;
    }

    /// Taken by the run loop: if a git-tool launch request is set, return true and clear it.
    pub fn take_launch_git_tool(&mut self) -> bool {
        std::mem::take(&mut self.pending_git_tool)
    }

    /// Reopen the preview after the external editor exits (reflect the edited content). Caches are also discarded.
    /// Even if the editor replaces the file (temp→rename), the FileWindow is reopened so the latest is read.
    pub fn reload_preview(&mut self) {
        self.md_cache = None;
        self.win_cache = None;
        if matches!(self.mode, Mode::Preview) {
            self.setup_windowed();
            self.reload_media_if_changed();
        }
    }

    /// On an FS-driven reload, re-load media (image/svg/gif/video/pdf) **only when the previewed file
    /// actually changed** (mtime guard). Without this, an image preview stays stale after an external
    /// edit: text/markdown follows via the md_cache clear, but images go through a separate path and were
    /// missed — so when a file is edited externally (e.g. an editor on the right), the konoma preview on the left did not refresh.
    /// The mtime guard avoids re-decoding / re-running external tools (pdftocairo/ffmpeg) on unrelated FS
    /// events. Zoom / pan / page are preserved across the reload.
    fn reload_media_if_changed(&mut self) {
        let is_media = matches!(
            self.preview_kind,
            Some(
                PreviewKind::Image(_)
                    | PreviewKind::Svg(_)
                    | PreviewKind::Video(_)
                    | PreviewKind::Pdf(_)
            )
        );
        if !is_media {
            return;
        }
        let Some(path) = self.preview_path.clone() else {
            return;
        };
        let Some(kind) = self.preview_kind.clone() else {
            return;
        };
        if file_mtime(&path) == self.preview_media_mtime {
            return; // 対象ファイルは未変更 → 無駄な再デコード/外部ツール実行を避ける
        }
        // 表示状態(ズーム/中心/ページ)を保持して再ロード。
        let (zoom, center, page) = (self.image_zoom, self.image_center, self.pdf_page);
        self.clear_image(); // ズーム/中心/ページ/メディア世代をリセット
        if matches!(kind, PreviewKind::Pdf(_)) {
            self.pdf_pages = crate::preview::pdf::page_count(&path);
            self.pdf_page = page.clamp(1, self.pdf_pages.unwrap_or(1).max(1));
        }
        self.start_media_load(&kind, &path); // preview_media_mtime も更新される
        self.image_zoom = zoom;
        self.image_center = center;
    }

    /// Whether in windowed (large file) mode. Used for the render and scroll branching.
    pub fn is_windowed(&self) -> bool {
        self.preview_win.is_some()
    }

    pub fn back_to_tree(&mut self) {
        self.mode = Mode::Tree;
        self.preview_path = None;
        self.preview_kind = None;
        self.clear_image(); // graphics 状態を解放
        self.md_cache = None;
        self.preview_win = None;
        self.win_cache = None;
        self.preview_total_lines = None;
        self.hl_pending = false;
        self.hl_warming = false;
        self.preview_byte_top = 0;
        self.preview_top_line = 0;
        self.md_links.clear();
        self.focused_link = None;
        self.preview_search = None;
        self.search_input = None;
        self.search_matches.clear();
        self.search_idx = 0;
        self.came_from_git_view = false;
    }

    /// Release and reset the image display state (protocol, source image, zoom/pan).
    fn clear_image(&mut self) {
        self.image = None;
        self.image_src = None;
        self.image_zoom = 1.0;
        self.image_center = (0.5, 0.5);
        self.image_crop = None;
        self.image_vis_frac = (1.0, 1.0);
        self.gif_frames = Vec::new();
        self.gif_idx = 0;
        self.gif_shown_at = None;
        self.gif_protocol = None;
        self.gif_proto_key = None;
        self.pdf_page = 1;
        self.pdf_pages = None;
        // 世代を進めて、別ファイルの読み込み中に届く前ファイルのメディア結果を陳腐化させる。
        self.media_gen = self.media_gen.wrapping_add(1);
        self.media_loading = false;
    }

    /// Return the decorated lines for a Markdown/Mermaid/code preview (inside the frame of display width `width`).
    /// If (path, width) matches, the cache is reused and regenerated only when it changes (avoids re-highlighting
    /// /re-parsing on every scroll; rebuilt only on a width change = resize). The return value is cloned every frame for rendering.
    /// For targets other than these, returns empty (the caller uses the text path).
    pub fn decorated_lines(&mut self, width: u16) -> Vec<Line<'static>> {
        let Some(path) = self.preview_path.clone() else {
            return Vec::new();
        };
        let hit = matches!(&self.md_cache, Some(c) if c.path == path && c.width == width);
        if !hit {
            let lines = self.build_decorated(&path, width);
            self.md_cache = Some(MdCache {
                path: path.clone(),
                width,
                lines,
            });
        }
        self.md_cache
            .as_ref()
            .map(|c| c.lines.clone())
            .unwrap_or_default()
    }

    /// Read the file with a cap and generate decorated lines according to its kind. A read failure becomes a single safe line.
    fn build_decorated(&self, path: &Path, width: u16) -> Vec<Line<'static>> {
        let src = match crate::preview::text::load(path) {
            Ok(content) => {
                let mut s = content.lines.join("\n");
                if content.truncated {
                    s.push_str("\n\n— (省略: 表示上限に達しました) —");
                }
                s
            }
            Err(e) => return vec![Line::from(format!("[can not preview: 読み込み失敗] {e}"))],
        };
        match &self.preview_kind {
            Some(PreviewKind::Markdown(_)) => {
                let theme = &self.cfg.ui.theme;
                let code = crate::preview::markdown::CodeStyle {
                    bg: theme.code_bg(),
                    label_bg: theme.code_label_bg(),
                    label_right: theme.code_label_right(),
                    tab_width: self.cfg.ui.tab_width,
                };
                crate::preview::markdown::render_markdown(&src, width, code, &theme.code_theme)
            }
            Some(PreviewKind::Mermaid(_)) => {
                crate::preview::markdown::render_mermaid_file(&src, width)
            }
            // 単体コードファイルは syntect でシンタックスハイライト。
            Some(PreviewKind::Code(_)) => {
                crate::preview::code::highlight(&src, path, &self.cfg.ui.theme.code_theme)
            }
            _ => Vec::new(),
        }
    }

    /// Attach the image backend (terminal Picker and the offload tx) at startup.
    pub fn attach_image_backend(&mut self, picker: Picker, tx: UnboundedSender<ResizeRequest>) {
        self.picker = Some(picker);
        self.img_tx = Some(tx);
    }

    /// Attach the sending end that offloads heavy media loading (SVG/GIF) to a separate thread.
    pub fn attach_media_loader(&mut self, tx: std::sync::mpsc::Sender<MediaResult>) {
        self.media_tx = Some(tx);
    }

    /// Drop tx and the image state on exit (to terminate the worker thread).
    pub fn detach_image_backend(&mut self) {
        self.clear_image();
        self.img_tx = None;
    }

    /// Decode a still image and place it in image_src (the ThreadProtocol is built asynchronously at render time).
    /// Still images (PNG/JPG) decode fast, so this stays synchronous. On decode failure / no backend, image_src=None.
    fn load_image(&mut self, path: &Path) {
        if self.picker.is_none() || self.img_tx.is_none() {
            return; // バックエンド無し: 描画側がテキストにフォールバック
        }
        let Some(dyn_img) = crate::preview::image::decode_static(path) else {
            return;
        };
        self.set_static_image(dyn_img);
    }

    /// Common processing to set a still image (including SVG raster results / single-frame GIFs) as the display source.
    /// zoom/center are left untouched (enter_preview has the preceding clear_image set defaults, and tab restore has already
    /// overwritten them with the restored values; so that a late asynchronous result does not break the restored zoom/center).
    fn set_static_image(&mut self, img: image::DynamicImage) {
        self.image_src = Some(img);
        self.image_crop = None; // 次の描画(prepare_image)でプロトコルを構築させる
    }

    /// Common processing to set all GIF frames into the display state (used from both the synchronous and asynchronous paths).
    /// zoom/center are left untouched for the same reason as set_static_image.
    fn set_gif_frames(&mut self, frames: Vec<(image::DynamicImage, std::time::Duration)>) {
        self.gif_frames = frames;
        self.gif_idx = 0;
        self.gif_shown_at = None; // 最初の tick で計時開始
        self.gif_protocol = None;
        self.gif_proto_key = None;
        self.image_crop = None;
    }

    /// Start loading image-type media according to the preview kind (from enter_preview / tab restore).
    /// Still images are synchronous, while **heavy SVG rasterization / GIF full-frame decode are offloaded to a separate thread**
    /// (to start display fast without blocking the UI thread). With no media_tx (tests, etc.), a synchronous fallback is used.
    fn start_media_load(&mut self, kind: &PreviewKind, path: &Path) {
        // メディア自動再読込の基準時刻を記録(reload_media_if_changed が mtime 比較に使う)。
        self.preview_media_mtime = file_mtime(path);
        match kind {
            PreviewKind::Image(_) if Self::looks_like_gif(path) => {
                self.spawn_or_sync_media(MediaJob::Gif(path.to_path_buf()))
            }
            // 静止画(PNG/JPG 等)はデコードが速いので同期のまま(エンコードは描画時に worker が非同期化)。
            PreviewKind::Image(_) => self.load_image(path),
            PreviewKind::Svg(_) => {
                self.spawn_or_sync_media(MediaJob::Svg(path.to_path_buf(), self.cfg.ui.svg_max_px))
            }
            PreviewKind::Video(_) => self.spawn_or_sync_media(MediaJob::Video(path.to_path_buf())),
            PreviewKind::Pdf(_) => {
                self.spawn_or_sync_media(MediaJob::Pdf(path.to_path_buf(), self.pdf_page))
            }
            _ => {}
        }
    }

    /// Run a media-load job on a separate thread (when media_tx is present). Otherwise run it synchronously.
    /// If there is no backend (picker), do nothing (the render side falls back).
    fn spawn_or_sync_media(&mut self, job: MediaJob) {
        if self.picker.is_none() {
            return; // 端末非対応: 描画側がテキスト/メッセージへフォールバック
        }
        let Some(tx) = self.media_tx.clone() else {
            // 同期フォールバック(テスト/チャネル未装着)。
            if let Some(payload) = job.run() {
                self.apply_payload(payload);
            }
            return;
        };
        self.media_gen = self.media_gen.wrapping_add(1);
        self.media_loading = true;
        let gen = self.media_gen;
        std::thread::spawn(move || {
            let _ = tx.send(MediaResult {
                gen,
                payload: job.run(),
            });
        });
    }

    /// Apply a media-load result from another thread. Stale results (from after moving to another file) are discarded.
    /// Returns true if the state changes from applying / staleness judgment (the caller re-renders).
    pub fn apply_media(&mut self, result: MediaResult) -> bool {
        if result.gen != self.media_gen {
            return false; // 陳腐化: 既に別ファイルへ移っている
        }
        self.media_loading = false;
        match result.payload {
            Some(payload) => {
                self.apply_payload(payload);
                true
            }
            None => true, // 失敗: loading を解除し描画側のフォールバック(生XML/メッセージ)へ
        }
    }

    fn apply_payload(&mut self, payload: MediaPayload) {
        match payload {
            MediaPayload::Static(img) => self.set_static_image(img),
            MediaPayload::Gif(frames) => self.set_gif_frames(frames),
        }
    }

    /// Whether waiting on another thread's media load (used by the render side to decide on the "Loading…" display).
    pub fn is_media_loading(&self) -> bool {
        self.media_loading
    }

    /// Decide whether it is a GIF by the leading bytes (looks at the magic, not the extension).
    fn looks_like_gif(path: &Path) -> bool {
        use std::io::Read;
        let Ok(mut f) = std::fs::File::open(path) else {
            return false;
        };
        let mut head = [0u8; 6];
        if f.read_exact(&mut head).is_err() {
            return false;
        }
        &head[..4] == b"GIF8" // GIF87a / GIF89a
    }

    /// Drive the GIF animation. If the current frame's display time has elapsed, advance to the next frame index.
    /// The actual re-encode is done by prepare_gif on the next render (detecting the gif_idx change).
    /// Returns true if advanced (the caller re-renders). Always false if not a GIF.
    pub fn advance_gif_if_due(&mut self) -> bool {
        if self.gif_frames.len() < 2 {
            return false;
        }
        let now = std::time::Instant::now();
        let Some(shown_at) = self.gif_shown_at else {
            // 最初の tick: 計時を開始するだけ(先頭フレームは表示済み)。
            self.gif_shown_at = Some(now);
            return false;
        };
        let delay = self.gif_frames[self.gif_idx].1;
        if now.duration_since(shown_at) < delay {
            return false;
        }
        self.gif_idx = (self.gif_idx + 1) % self.gif_frames.len();
        self.gif_shown_at = Some(now);
        true
    }

    /// Whether a GIF animation is active (used for branching in the render path and footer/zoom checks).
    pub fn is_gif_active(&self) -> bool {
        self.gif_frames.len() >= 2
    }

    /// The render protocol of the current GIF frame synchronously encoded to the display size (referenced by the render side).
    pub fn gif_protocol(&self) -> Option<&Protocol> {
        self.gif_protocol.as_ref()
    }

    /// Call just before rendering (for GIF). Compute the display rectangle target and crop from the current (gif_idx, zoom, center, inner), and
    /// if the frame/crop has changed, **synchronously encode** the current frame and swap it into gif_protocol.
    /// Being synchronous, "render an unencoded protocol → empty" does not happen, and the frame switches atomically (no churn).
    /// The return value is the render-target target. None when there is no backend / size 0.
    pub fn prepare_gif(&mut self, inner: Rect) -> Option<Rect> {
        let picker = self.picker.as_ref()?;
        let scale = self.cfg.ui.image_render_scale;
        let src = &self.gif_frames.get(self.gif_idx)?.0;
        let (target, crop_rect, center, frac) = image_layout(
            src,
            picker.font_size(),
            self.image_zoom,
            self.image_center,
            inner,
            scale,
        )?;
        let key = (self.gif_idx, crop_rect);
        // フレーム or crop(ズーム/パン/リサイズ)が変わったときだけ再エンコード。
        let built = if self.gif_proto_key != Some(key) {
            let (x0, y0, cw, ch) = crop_rect;
            let crop = src.crop_imm(x0, y0, cw, ch);
            let size = ratatui::layout::Size::new(target.width.max(1), target.height.max(1));
            // src/picker の借用はこの式で完結(結果は所有値)→以降 self を変更可。
            // GIF は UI スレッドで毎フレーム同期エンコードするため、軽量で滑らかな Triangle(bilinear) を使う
            // (最近傍 None だとアニメ各フレームがジャギる。最高品質の Lanczos3 は静止画側で使用)。
            Some(picker.new_protocol(crop, size, Resize::Scale(Some(FilterType::Triangle))))
        } else {
            None
        };
        if let Some(res) = built {
            match res {
                Ok(p) => {
                    self.gif_protocol = Some(p);
                    self.gif_proto_key = Some(key);
                }
                Err(_) => {
                    // エンコード失敗: 描画側はメッセージにフォールバック。次フレームで再試行。
                    self.gif_protocol = None;
                    self.gif_proto_key = None;
                }
            }
        }
        self.image_center = center;
        self.image_vis_frac = frac;
        self.image_crop = Some(crop_rect);
        Some(target)
    }

    /// Wait time until the next frame while a GIF is playing (for the poll timeout). None when not playing.
    /// Clamped to [10ms, 100ms] for smoothness (100ms is the same as the normal idle-tick upper bound).
    pub fn gif_poll_timeout(&self) -> Option<std::time::Duration> {
        use std::time::Duration;
        if self.gif_frames.len() < 2 {
            return None;
        }
        let remaining = match self.gif_shown_at {
            None => Duration::ZERO, // まだ計時前: すぐ次の tick を回して計時開始
            Some(t) => self.gif_frames[self.gif_idx]
                .1
                .checked_sub(t.elapsed())
                .unwrap_or(Duration::ZERO),
        };
        Some(remaining.clamp(Duration::from_millis(10), Duration::from_millis(100)))
    }

    /// Whether the current preview is a (renderable) image. Used to route image-only keys (zoom/pan).
    /// Still images are judged by image_src, GIFs by gif_frames (image_src is not used). SVGs are already rasterized.
    pub fn is_image_preview(&self) -> bool {
        (self.image_src.is_some() || self.is_gif_active())
            && matches!(
                self.preview_kind,
                Some(
                    PreviewKind::Image(_)
                        | PreviewKind::Svg(_)
                        | PreviewKind::Video(_)
                        | PreviewKind::Pdf(_)
                )
            )
    }

    /// Whether the current preview is a PDF (used to enable page-navigation keys / footer hints).
    pub fn is_pdf_preview(&self) -> bool {
        matches!(self.preview_kind, Some(PreviewKind::Pdf(_)))
    }

    /// (current, total) page for the PDF preview, or None when not a PDF or the page count is unknown
    /// (no poppler → single-page fallback, navigation disabled). Used for the footer/status indicator.
    pub fn pdf_page_indicator(&self) -> Option<(u32, u32)> {
        if !self.is_pdf_preview() {
            return None;
        }
        let total = self.pdf_pages?;
        Some((self.pdf_page.min(total), total))
    }

    /// Whether PDF page navigation is possible (a known multi-page PDF; requires poppler for both the
    /// count and per-page rendering, so this gates `J`/`K` from doing anything on single-page/no-poppler PDFs).
    pub fn pdf_can_navigate(&self) -> bool {
        matches!(self.pdf_pages, Some(n) if n > 1)
    }

    /// Go to the next PDF page (clamped to the last page). Re-rasterizes that page on demand (one at a time).
    pub fn pdf_next_page(&mut self) {
        self.pdf_goto(self.pdf_page.saturating_add(1));
    }

    /// Go to the previous PDF page (clamped to page 1).
    pub fn pdf_prev_page(&mut self) {
        self.pdf_goto(self.pdf_page.saturating_sub(1));
    }

    /// Jump to a 1-based page (clamped to [1, total]). No-op if not a navigable PDF or already there.
    /// Kicks off an off-thread rasterization of the new page and resets the view to fit (each page shows whole).
    fn pdf_goto(&mut self, page: u32) {
        if !self.pdf_can_navigate() {
            return;
        }
        let Some(total) = self.pdf_pages else { return };
        let page = page.clamp(1, total);
        if page == self.pdf_page {
            return;
        }
        self.pdf_page = page;
        // 新ページは全体が見えるよう fit に戻す(set_static_image は zoom/center を触らないので明示リセット)。
        self.image_zoom = 1.0;
        self.image_center = (0.5, 0.5);
        self.image_crop = None;
        if let Some(PreviewKind::Pdf(p)) = self.preview_kind.clone() {
            // 旧ページの画像は到着まで表示したまま(media_gen で陳腐化判定・スピナーが重畳)。
            self.spawn_or_sync_media(MediaJob::Pdf(p, self.pdf_page));
        }
    }

    /// Zoom (multiply the magnification by `factor`; clamped to 1.0–16.0). The actual crop is applied at render time.
    pub fn image_zoom_by(&mut self, factor: f64) {
        if self.image_src.is_none() && !self.is_gif_active() {
            return;
        }
        self.image_zoom = (self.image_zoom * factor).clamp(1.0, 16.0);
    }

    /// Reset to 1x (fit). Zoom=1 and recenter.
    pub fn image_zoom_reset(&mut self) {
        if self.image_src.is_none() && !self.is_gif_active() {
            return;
        }
        self.image_zoom = 1.0;
        self.image_center = (0.5, 0.5);
    }

    /// Pan. dx/dy are directions (-1/0/+1). Only clipped axes move the center, scaled by the visible fraction.
    /// Clamping is done at render time (prepare_image), looking at the visible fraction.
    pub fn image_pan(&mut self, dx: f64, dy: f64) {
        if self.image_src.is_none() && !self.is_gif_active() {
            return;
        }
        let (fw, fh) = self.image_vis_frac;
        // 1回で可視窓の約25%。見切れていない軸(frac>=1)は動かしても描画時にクランプされる。
        self.image_center.0 += dx * 0.25 * fw;
        self.image_center.1 += dy * 0.25 * fh;
    }

    /// Call just before rendering. From the current (zoom, center, display area inner), compute the image's display rectangle target
    /// (centered; z=1=fit, grows when zooming and clips once it exceeds the viewport) and the source-image crop of
    /// the visible portion; rebuild the protocol if the crop changed. The return value is the render-target target.
    /// Realizes "fit the render area to the image size (fit) → grow when zooming → clip + pan once exceeded".
    pub fn prepare_image(&mut self, inner: Rect) -> Option<Rect> {
        let src = self.image_src.as_ref()?;
        let picker = self.picker.as_ref()?;
        let scale = self.cfg.ui.image_render_scale;
        let (target, crop_rect, center, frac) = image_layout(
            src,
            picker.font_size(),
            self.image_zoom,
            self.image_center,
            inner,
            scale,
        )?;
        // crop が変わったときだけプロトコル再構築(毎フレームの再エンコードを避ける)。
        let new_tp = if self.image_crop != Some(crop_rect) {
            let (x0, y0, cw, ch) = crop_rect;
            let crop = src.crop_imm(x0, y0, cw, ch);
            let proto = picker.new_resize_protocol(crop);
            // src/picker/img_tx の借用はこの式で完結(tp は所有値)→以降 self を変更可。
            Some(ThreadProtocol::new(
                self.img_tx.as_ref()?.clone(),
                Some(proto),
            ))
        } else {
            None
        };
        if let Some(tp) = new_tp {
            self.image = Some(tp);
        }
        self.image_center = center;
        self.image_vis_frac = frac;
        self.image_crop = Some(crop_rect);
        Some(target)
    }

    /// Page the text preview by one page (dir: +1=next page / -1=previous page).
    /// Overlaps one row to keep context. The upper bound is clamped at render time.
    pub fn preview_page(&mut self, dir: i32) {
        let page = self.preview_viewport.saturating_sub(1).max(1) as i32;
        self.preview_scroll(dir * page);
    }

    /// Half-page the text preview (vim: Ctrl-d/Ctrl-u, less: d/u).
    pub fn preview_half_page(&mut self, dir: i32) {
        let half = (self.preview_viewport / 2).max(1) as i32;
        self.preview_scroll(dir * half);
    }

    /// To the top of the preview.
    pub fn preview_to_top(&mut self) {
        if self.is_windowed() {
            self.preview_byte_top = 0;
            self.preview_top_line = 0;
        } else {
            self.preview_scroll = 0;
        }
    }

    /// To the bottom of the preview. The actual maximum is clamped at render time, when content and screen size are known.
    /// When windowed, moves to the line-head byte of the last page (found by a backward seek, without scanning the whole file).
    /// If line numbers are ON, the bottom line number is also corrected from the total line count.
    pub fn preview_to_bottom(&mut self) {
        if !self.is_windowed() {
            self.preview_scroll = u16::MAX;
            return;
        }
        let vh = self.preview_viewport.max(1) as usize;
        let total = if self.cfg.ui.line_numbers {
            self.win_total()
        } else {
            None
        };
        let cur = self.preview_top_line;
        if let Some(b) = self
            .preview_win
            .as_mut()
            .map(|w| w.last_page_top(vh).unwrap_or(0))
        {
            self.preview_byte_top = b;
            self.preview_top_line = total.map(|t| t.saturating_sub(vh)).unwrap_or(cur);
        }
    }

    /// Total line count (computed and cached only when line numbers are ON). Scans the whole file, so call it minimally.
    fn win_total(&mut self) -> Option<usize> {
        if let Some(t) = self.preview_total_lines {
            return Some(t);
        }
        let t = self.preview_win.as_mut()?.count_lines().ok()?;
        self.preview_total_lines = Some(t);
        Some(t)
    }

    /// Apply a re-encode result from the worker to the current image state. Returns true if applied.
    pub fn apply_image_resize(&mut self, resp: Result<ResizeResponse, Errors>) -> bool {
        let Ok(resp) = resp else {
            return false; // エンコード失敗は無視(クラッシュさせない)
        };
        match self.image.as_mut() {
            Some(state) => state.update_resized_protocol(resp),
            None => false,
        }
    }

    pub fn preview_scroll(&mut self, delta: i32) {
        if self.is_windowed() {
            self.win_scroll_lines(delta);
            return;
        }
        let next = self.preview_scroll as i32 + delta;
        // 下限のみここで。上限 (末尾) は内容・画面サイズが判る描画時にクランプする。
        self.preview_scroll = next.max(0) as u16;
    }

    /// Windowed scroll (delta lines). Computes the surrounding line-head bytes each time to move preview_byte_top, and
    /// updates preview_top_line (the line number) by the actual number of moved lines. Downward is clamped so as not to pass the last page.
    /// On end-clamp, the line number is corrected from the total line count when line numbers are ON.
    fn win_scroll_lines(&mut self, delta: i32) {
        let vh = self.preview_viewport.max(1) as usize;
        let top = self.preview_byte_top;
        let line = self.preview_top_line;
        let total = if self.cfg.ui.line_numbers {
            self.win_total()
        } else {
            None
        };
        let result = self.preview_win.as_mut().map(|w| {
            if delta > 0 {
                let (adv, moved) = w.advance(top, delta as usize).unwrap_or((top, 0));
                let maxt = w.last_page_top(vh).unwrap_or(top);
                if adv >= maxt {
                    // 末尾ページ到達: 行番号は総行数から(無ければ素朴に加算)。
                    let bl = total.map(|t| t.saturating_sub(vh)).unwrap_or(line + moved);
                    (maxt, bl)
                } else {
                    (adv, line + moved)
                }
            } else if delta < 0 {
                let (ret, moved) = w.retreat(top, (-delta) as usize).unwrap_or((0, 0));
                (ret, line.saturating_sub(moved))
            } else {
                (top, line)
            }
        });
        if let Some((nt, nl)) = result {
            self.preview_byte_top = nt;
            self.preview_top_line = nl;
        }
    }

    /// For windowed display, read the current window (from the top byte for the height), highlight Code with syntect
    /// / leave Text plain, and return it as a list of ratatui Lines. Cached by (path, top byte, height),
    /// re-read only on scroll/resize. If the top exceeds the last page, it is clamped.
    pub fn windowed_lines(&mut self, height: u16, width: u16) -> Vec<Line<'static>> {
        let _ = width; // 行内容は幅に依存しない(折返しは描画側)。将来用に受けておく。
        let h = height.max(1) as usize;
        // リサイズ等で末尾を超えていたらクランプ(行番号も総行数から補正)。
        let top0 = self.preview_byte_top;
        let maxt = self
            .preview_win
            .as_mut()
            .and_then(|w| w.last_page_top(h).ok());
        if let Some(maxt) = maxt {
            if top0 > maxt {
                self.preview_byte_top = maxt;
                // 行番号ガター OFF でも検索の現在一致(橙)が abs=preview_top_line+i で
                // 参照するため、末尾ページへのクランプ時は line_numbers の有無に関わらず
                // 常に preview_top_line を総行数から補正する(#5)。
                if let Some(t) = self.win_total() {
                    self.preview_top_line = t.saturating_sub(h);
                }
            }
        }
        let top = self.preview_byte_top;
        let path = self.preview_path.clone().unwrap_or_default();
        // syntax を着けるか: ハイライト無効(off-switch) / progressive で待ち中(hl_pending)/ 非 Code は素。
        // progressive 待ち中だけは「差し替え前の素テキスト」なのでキャッシュしない(後で着色版に替わる)。
        let want_syntax = self.cfg.ui.syntax_highlight
            && matches!(self.preview_kind, Some(PreviewKind::Code(_)))
            && (!self.hl_pending || self.loading_is_indicator());
        let mut content: Vec<Line<'static>> = if want_syntax {
            let hit = matches!(
                &self.win_cache,
                Some(c) if c.path == path && c.byte_top == top && c.height == height
            );
            if !hit {
                let raw = self
                    .preview_win
                    .as_mut()
                    .and_then(|w| w.read_lines(top, h).ok())
                    .unwrap_or_default();
                let src = raw.join("\n");
                let lines =
                    crate::preview::code::highlight(&src, &path, &self.cfg.ui.theme.code_theme);
                self.win_cache = Some(WinCache {
                    path,
                    byte_top: top,
                    height,
                    lines,
                });
            }
            self.win_cache
                .as_ref()
                .map(|c| c.lines.clone())
                .unwrap_or_default()
        } else {
            // 素テキスト(キャッシュしない): off-switch / progressive 待ち中 / Text。
            let raw = self
                .preview_win
                .as_mut()
                .and_then(|w| w.read_lines(top, h).ok())
                .unwrap_or_default();
            raw.into_iter().map(Line::from).collect()
        };
        // タブを可視マーカー(→)+タブストップ空白へ展開する(端末はタブを桁揃えしないため)。
        // 行番号ガター/検索強調の前に行う=桁追跡が本文の先頭(0桁)基準になる。窓の可視行のみ=軽い。
        content = crate::preview::code::expand_tabs(content, self.cfg.ui.tab_width);
        // 検索中は一致箇所(クエリ)を強調する(ガターより先=本文だけ強調)。
        // 現在の出現(search_idx)1箇所だけオレンジ、他は黄色。表示行 i の絶対行 = preview_top_line + i。
        // その行が現在の出現の行なら、その列(col)の出現だけオレンジにする(同一行に複数あっても1つ)。
        if let Some(q) = self.preview_search.clone() {
            // 現在一致(search_idx)の行と、その「行内での出現順位」(0始まり)を求める。
            // タブ展開でバイト列がずれるため、列(バイト位置)ではなく出現順位で
            // 現在一致を同定する(#14)。同一行の一致は search_matches 内で連続・列昇順。
            let (cur_line, cur_rank) = match self.search_matches.get(self.search_idx).copied() {
                Some((_, line, _)) => {
                    let rank = self.search_matches[..self.search_idx]
                        .iter()
                        .filter(|(_, l, _)| *l == line)
                        .count();
                    (Some(line), Some(rank))
                }
                None => (None, None),
            };
            let top_line = self.preview_top_line;
            content = content
                .into_iter()
                .enumerate()
                .map(|(i, l)| {
                    let abs = top_line + i;
                    let rank = if cur_line == Some(abs) {
                        cur_rank
                    } else {
                        None
                    };
                    highlight_query_in_line(l, &q, rank)
                })
                .collect();
        }
        // 行番号ガター(設定 ON のときだけ)。先頭行番号 = preview_top_line。
        if self.cfg.ui.line_numbers {
            with_line_numbers(content, self.preview_top_line)
        } else {
            content
        }
    }

    /// Windowed scroll progress (0..=100 %). For the title display. None if not windowed.
    pub fn window_progress(&self) -> Option<u16> {
        let w = self.preview_win.as_ref()?;
        let len = w.len();
        if len == 0 {
            return Some(0);
        }
        Some((self.preview_byte_top.min(len) * 100 / len) as u16)
    }

    /// Whether in-preview search input mode is active (intercepting keys).
    pub fn is_searching(&self) -> bool {
        self.search_input.is_some()
    }

    /// The active search query (for highlighting).
    pub fn preview_search_query(&self) -> Option<&str> {
        self.preview_search.as_deref()
    }

    /// The search input being edited (for the footer prompt).
    pub fn search_input(&self) -> Option<&str> {
        self.search_input.as_deref()
    }

    /// Search status (current/total). Some((1-based, total)) when active and there are matches.
    pub fn search_status(&self) -> Option<(usize, usize)> {
        if self.preview_search.is_some() && !self.search_matches.is_empty() {
            Some((self.search_idx + 1, self.search_matches.len()))
        } else {
            None
        }
    }

    /// Start a search (`/`). Currently only Code/Text (windowed) previews are supported. Enters input mode.
    pub fn start_search(&mut self) {
        if self.preview_win.is_none() {
            self.flash = Some(tr(self.lang, crate::i18n::Msg::SearchCodeTextOnly).into());
            return;
        }
        self.search_input = Some(String::new());
    }

    pub fn search_input_push(&mut self, c: char) {
        if let Some(s) = self.search_input.as_mut() {
            s.push(c);
        }
    }

    pub fn search_input_backspace(&mut self) {
        if let Some(s) = self.search_input.as_mut() {
            s.pop();
        }
    }

    /// Confirm input (Enter): run the query (collect all matching lines) and jump to the first match at or after the current position.
    pub fn search_commit(&mut self) {
        let q = self.search_input.take().unwrap_or_default();
        if q.is_empty() {
            self.preview_search = None;
            self.search_matches.clear();
            return;
        }
        const CAP: usize = 5000;
        let matches = self
            .preview_win
            .as_mut()
            .and_then(|w| w.find_all_matches(&q, CAP).ok())
            .unwrap_or_default();
        self.preview_search = Some(q);
        self.search_matches = matches;
        if self.search_matches.is_empty() {
            self.flash = Some(tr(self.lang, crate::i18n::Msg::NoMatch).into());
            return;
        }
        // 現在の表示位置(byte_top)以降の最初の出現へ。無ければ先頭へ巡回。
        let top = self.preview_byte_top;
        self.search_idx = self
            .search_matches
            .iter()
            .position(|(off, _, _)| *off >= top)
            .unwrap_or(0);
        self.jump_to_match();
    }

    /// `n`/`N`: to the next/previous match (cyclic).
    pub fn search_next(&mut self, dir: i32) {
        if self.search_matches.is_empty() {
            return;
        }
        let n = self.search_matches.len() as i32;
        self.search_idx = (self.search_idx as i32 + dir).rem_euclid(n) as usize;
        self.jump_to_match();
    }

    /// Clear the search (Esc).
    pub fn search_clear(&mut self) {
        self.preview_search = None;
        self.search_input = None;
        self.search_matches.clear();
        self.search_idx = 0;
    }

    /// Bring the line of the current occurrence to the top of the display (updates the line-head byte and line number). For moves within the same line,
    /// the top does not change, and only the highlight color (orange) moves to that occurrence (the column is referenced by the render side).
    fn jump_to_match(&mut self) {
        if let Some(&(off, line, _col)) = self.search_matches.get(self.search_idx) {
            self.preview_byte_top = off;
            self.preview_top_line = line;
        }
    }

    pub fn preview_hscroll(&mut self, delta: i32) {
        let next = self.preview_hscroll as i32 + delta;
        self.preview_hscroll = next.max(0) as u16;
    }
    /// Reset horizontal scroll to the line start (left edge) in one step. `0`. When wrapping, it is already 0, so no effect.
    pub fn preview_hscroll_home(&mut self) {
        self.preview_hscroll = 0;
    }
    /// Send horizontal scroll to the line end (right edge) in one step. `$`. The actual maximum is clamped to the longest line width at render time
    /// (here we set the upper bound, and the render side's `.min(max_h)` settles it at the correct right edge).
    pub fn preview_hscroll_end(&mut self) {
        self.preview_hscroll = u16::MAX;
    }

    /// Arrange the links in decorated Markdown lines to "show label only", build `md_links`, and return the line list with the focused
    /// link rendered inverted (called just before rendering).
    /// Since tui-markdown outputs the "label (URL)" form, `collapse_links` folds the accompanying URL
    /// (the URL is the hidden destination) and styles the label as a link plus (when configured) an icon. Follows the normal display of glow, etc.
    pub fn decorate_links(&mut self, lines: Vec<Line<'static>>) -> Vec<Line<'static>> {
        let (lines, targets) = collapse_links(lines, self.cfg.ui.icons);
        // 畳んだリンク span を順に走査し、同順の targets と対応付けて md_links を作る。
        let mut links = Vec::new();
        let mut k = 0usize;
        for (li, line) in lines.iter().enumerate() {
            for span in &line.spans {
                if is_link_span(span) {
                    let target = targets.get(k).cloned().unwrap_or_default();
                    links.push(MdLink { line: li, target });
                    k += 1;
                }
            }
        }
        // フォーカス添字を範囲内にクランプ。
        match self.focused_link {
            Some(_) if links.is_empty() => self.focused_link = None,
            Some(f) if f >= links.len() => self.focused_link = Some(links.len() - 1),
            _ => {}
        }
        self.md_links = links;

        let Some(target_idx) = self.focused_link else {
            return lines;
        };
        // フォーカス中リンク(n 番目の下線青 span)を反転して強調。
        use ratatui::style::Modifier;
        let mut seen = 0usize;
        lines
            .into_iter()
            .map(|line| {
                let style = line.style;
                let spans = line
                    .spans
                    .into_iter()
                    .map(|mut span| {
                        if is_link_span(&span) {
                            if seen == target_idx {
                                span.style = span.style.add_modifier(Modifier::REVERSED);
                            }
                            seen += 1;
                        }
                        span
                    })
                    .collect::<Vec<_>>();
                Line::from(spans).style(style)
            })
            .collect()
    }

    /// Move the link focus of the Markdown preview (dir: +1=next / -1=previous, cyclic).
    /// If the focused line is off-screen, scroll until it is visible. If there are no links, do nothing.
    pub fn link_focus(&mut self, dir: i32) {
        if self.md_links.is_empty() {
            return;
        }
        let n = self.md_links.len() as i32;
        let next = match self.focused_link {
            Some(f) => (f as i32 + dir).rem_euclid(n),
            None if dir >= 0 => 0,
            None => n - 1,
        } as usize;
        self.focused_link = Some(next);
        // フォーカス行を表示範囲に収める。
        let line = self.md_links[next].line;
        let vh = self.preview_viewport.max(1) as usize;
        let scroll = self.preview_scroll as usize;
        if line < scroll {
            self.preview_scroll = line as u16;
        } else if line >= scroll + vh {
            self.preview_scroll = (line + 1).saturating_sub(vh) as u16;
        }
    }

    /// Open the focused link. URLs open externally (browser, etc.), local ones open within konoma.
    pub fn open_focused_link(&mut self) -> Result<()> {
        let Some(f) = self.focused_link else {
            return Ok(());
        };
        let Some(link) = self.md_links.get(f) else {
            return Ok(());
        };
        let target = link.target.clone();
        self.open_link_target(&target)
    }

    /// Open a link target. `scheme://`/`mailto:`, etc. are delegated externally; local paths open in konoma
    /// (file=preview / directory=make it the new root and Tree).
    fn open_link_target(&mut self, target: &str) -> Result<()> {
        let t = target.trim();
        if t.contains("://") || t.starts_with("mailto:") || t.starts_with("tel:") {
            return self.open_external(t);
        }
        if t.starts_with('#') {
            self.flash = Some(tr(self.lang, crate::i18n::Msg::AnchorsUnsupported).into());
            return Ok(());
        }
        // ローカルパス: md ファイルのディレクトリ基準で解決 (# 以降のアンカーは捨てる)。
        let path_part = t.split('#').next().unwrap_or(t);
        let base = self
            .preview_path
            .as_ref()
            .and_then(|p| p.parent())
            .map(Path::to_path_buf)
            .unwrap_or_else(|| self.root.clone());
        let p = Path::new(path_part);
        let resolved = if p.is_absolute() {
            p.to_path_buf()
        } else {
            base.join(p)
        };
        let resolved = std::fs::canonicalize(&resolved).unwrap_or(resolved);
        if resolved.is_dir() {
            self.back_to_tree();
            // root を変えるので旧 root の選択/ビジュアル/絞り込み/検索を破棄する(持ち越さない)。
            self.clear_for_root_change();
            self.root = resolved;
            self.open_dir = self.root.clone();
            self.entries.clear();
            self.selected = 0;
            self.rebuild_tree()?;
        } else if resolved.is_file() {
            self.enter_preview(&resolved);
        } else {
            self.flash = Some(format!(
                "{}{}",
                tr(self.lang, crate::i18n::Msg::NotFound),
                path_part
            ));
        }
        Ok(())
    }

    /// Open a URL/file with an external command (macOS `open`). The result is reported via flash.
    fn open_external(&mut self, url: &str) -> Result<()> {
        match std::process::Command::new("open").arg(url).spawn() {
            Ok(_) => self.flash = Some(format!("{}{url}", tr(self.lang, crate::i18n::Msg::Opened))),
            Err(e) => {
                self.flash = Some(format!(
                    "{}{e}",
                    tr(self.lang, crate::i18n::Msg::OpenFailed)
                ))
            }
        }
        Ok(())
    }

    pub fn cycle_path_style(&mut self) {
        self.path_style = self.path_style.next();
    }

    /// Toggle the `?` help. When opening, reset scroll to the top.
    pub fn toggle_help(&mut self) {
        self.show_help = !self.show_help;
        self.help_scroll = 0;
    }

    /// Toggle the `i` file-info popup. Does not open if there is no target.
    pub fn toggle_info(&mut self) {
        if self.show_info {
            self.show_info = false;
        } else if self.info_target().is_some() {
            self.show_info = true;
        } else {
            self.flash = Some(crate::i18n::tr(self.lang, crate::i18n::Msg::NoTarget).into());
        }
    }
    /// Whether the file-info popup is showing.
    pub fn is_info(&self) -> bool {
        self.show_info
    }
    /// The target path for the info display: Tree=the cursor item / Preview=the file being previewed.
    pub fn info_target(&self) -> Option<PathBuf> {
        match self.mode {
            Mode::Tree => self.entries.get(self.selected).map(|e| e.path.clone()),
            Mode::Preview => self.preview_path.clone(),
        }
    }

    /// Scroll within the help. The upper bound is clamped at render time (since content and screen size are then known).
    pub fn help_scroll_by(&mut self, delta: i32) {
        self.help_scroll = (self.help_scroll as i32 + delta).max(0) as u16;
    }

    /// The path to copy. In Preview it is the preview target; in Tree it is the entry selected in the tree.
    fn copy_target(&self) -> Option<PathBuf> {
        // Git 変更ハブ表示中は、ツリーの選択ではなく**変更ファイル**のパスをコピー対象にする。
        #[cfg(feature = "git")]
        if self.surface() == crate::keymap::Surface::GitChanges {
            return self.git_view_selected();
        }
        match self.mode {
            Mode::Preview => self.preview_path.clone(),
            Mode::Tree => self.entries.get(self.selected).map(|e| e.path.clone()),
        }
    }

    /// Copy the selected path to the clipboard according to the kind, and show the result in flash (FR-6).
    pub fn copy_path(&mut self, kind: CopyKind) {
        let Some(path) = self.copy_target() else {
            self.flash = Some(tr(self.lang, crate::i18n::Msg::NoCopyTarget).into());
            return;
        };
        let text = copy_text(&path, &self.open_dir, kind);
        match set_clipboard(&text) {
            Ok(()) => {
                self.flash = Some(format!(
                    "{}{text}",
                    tr(self.lang, crate::i18n::Msg::CopiedPrefix)
                ))
            }
            Err(e) => {
                self.flash = Some(format!(
                    "{}{e}",
                    tr(self.lang, crate::i18n::Msg::CopyFailed)
                ))
            }
        }
    }

    /// Get metadata for the selected commit in log/graph/detail. detail uses the already-loaded data, while log/graph
    /// fetch `commit_meta` from the selected commit id. None for non-commits (uncommitted rows, etc.) or out-of-scope surfaces.
    #[cfg(feature = "git")]
    fn current_commit_meta(&self) -> Option<crate::git::CommitMeta> {
        use crate::keymap::Surface;
        match self.surface() {
            Surface::GitDetail => self.git_detail_meta.clone(),
            Surface::GitLog => {
                let id = self.git_log_selected_id()?;
                crate::git::commit_meta(&self.root, &id)
            }
            Surface::GitGraph => {
                let id = self
                    .git_graph_selected_row()
                    .and_then(|r| r.commit.clone())?;
                crate::git::commit_meta(&self.root, &id)
            }
            _ => None,
        }
    }

    /// git log/graph/detail: copy the selected commit's info (short/full hash, subject, full message, author, date)
    /// to the clipboard. If there is no commit, notify via flash.
    #[cfg(feature = "git")]
    pub fn git_copy(&mut self, kind: GitCopyKind) {
        let Some(meta) = self.current_commit_meta() else {
            self.flash = Some(tr(self.lang, crate::i18n::Msg::NoCommitToCopy).into());
            return;
        };
        let text = match kind {
            GitCopyKind::ShortHash => meta.short,
            GitCopyKind::FullHash => meta.id,
            GitCopyKind::Subject => meta.message.lines().next().unwrap_or("").to_string(),
            GitCopyKind::Message => meta.message,
            GitCopyKind::Author => meta.author,
            GitCopyKind::Date => meta.date,
        };
        self.set_clipboard_flash(&text);
    }

    /// branches view: copy the selected branch name to the clipboard.
    #[cfg(feature = "git")]
    pub fn git_copy_branch_name(&mut self) {
        let Some(b) = self.git_branch_selected() else {
            self.flash = Some(tr(self.lang, crate::i18n::Msg::NoCopyTarget).into());
            return;
        };
        let name = b.name;
        self.set_clipboard_flash(&name);
    }

    /// Write to the clipboard and flash success/failure (common processing for copy operations). On success, shows a one-line preview
    /// (multi-line content such as a full message is rounded to the first line + `…` so the footer does not overflow).
    #[cfg(feature = "git")]
    fn set_clipboard_flash(&mut self, text: &str) {
        match set_clipboard(text) {
            Ok(()) => {
                let first = text.lines().next().unwrap_or("");
                let mut preview: String = first.chars().take(60).collect();
                if first.chars().count() > 60 || text.lines().nth(1).is_some() {
                    preview.push('');
                }
                self.flash = Some(format!(
                    "{}{preview}",
                    tr(self.lang, crate::i18n::Msg::CopiedPrefix)
                ));
            }
            Err(e) => {
                self.flash = Some(format!(
                    "{}{e}",
                    tr(self.lang, crate::i18n::Msg::CopyFailed)
                ))
            }
        }
    }

    // ---- タブ (FR-5) ----

    /// Snapshot the current tree working state.
    fn snapshot_tab(&self) -> TabState {
        TabState {
            root: self.root.clone(),
            open_dir: self.open_dir.clone(),
            entries: self.entries.clone(),
            selected: self.selected,
            show_hidden: self.show_hidden,
            tree_viewport: self.tree_viewport,
            mode: self.mode,
            preview_path: self.preview_path.clone(),
            preview_kind: self.preview_kind.clone(),
            preview_scroll: self.preview_scroll,
            preview_hscroll: self.preview_hscroll,
            preview_viewport: self.preview_viewport,
            preview_byte_top: self.preview_byte_top,
            preview_top_line: self.preview_top_line,
            image_zoom: self.image_zoom,
            image_center: self.image_center,
            pdf_page: self.pdf_page,
            pdf_pages: self.pdf_pages,
            git_view: self.git_view,
            git_view_sel: self.git_view_sel,
            git_view_entries: self.git_view_entries.clone(),
            came_from_git_view: self.came_from_git_view,
            git_log: self.git_log.clone(),
            git_log_sel: self.git_log_sel,
            git_detail: self.git_detail.clone(),
            git_detail_meta: self.git_detail_meta.clone(),
            git_detail_title: self.git_detail_title.clone(),
            git_detail_scroll: self.git_detail_scroll,
            git_detail_hscroll: self.git_detail_hscroll,
            git_detail_viewport: self.git_detail_viewport,
            git_detail_total: self.git_detail_total,
            git_branches: self.git_branches.clone(),
            git_branch_sel: self.git_branch_sel,
            git_branch_filter: self.git_branch_filter.clone(),
            git_branch_filtering: self.git_branch_filtering,
            git_graph: self.git_graph.clone(),
            git_graph_sel: self.git_graph_sel,
            // 選択 / 絞り込み / プレビュー検索もタブ毎に保存する(切替で旧タブへ持ち越さない)。
            selection: self.selection.clone(),
            visual_anchor: self.visual_anchor,
            tree_filter: self.tree_filter.clone(),
            filter_input: self.filter_input.clone(),
            filter_pool: self.filter_pool.clone(),
            preview_search: self.preview_search.clone(),
            search_input: self.search_input.clone(),
            search_matches: self.search_matches.clone(),
            search_idx: self.search_idx,
        }
    }

    /// Save the current working state to the active tab.
    fn save_active(&mut self) {
        let snap = self.snapshot_tab();
        self.tabs[self.active_tab] = snap;
    }

    /// Load the active tab's snapshot into the working fields.
    /// **Also restores that tab's mode/preview** (does not drop to Tree). Images are restored by reloading.
    fn load_active(&mut self) {
        let t = self.tabs[self.active_tab].clone();
        self.root = t.root;
        self.open_dir = t.open_dir;
        self.entries = t.entries;
        self.selected = t.selected;
        self.show_hidden = t.show_hidden;
        self.tree_viewport = t.tree_viewport;
        self.mode = t.mode;
        self.preview_path = t.preview_path;
        self.preview_kind = t.preview_kind;
        self.preview_scroll = t.preview_scroll;
        self.preview_hscroll = t.preview_hscroll;
        self.preview_viewport = t.preview_viewport;
        self.preview_byte_top = t.preview_byte_top;
        self.preview_top_line = t.preview_top_line;
        // git オーバーレイもそのタブの状態を復元する(タブごとに git モードを保持)。
        self.git_view = t.git_view;
        self.git_view_sel = t.git_view_sel;
        self.git_view_entries = t.git_view_entries;
        self.came_from_git_view = t.came_from_git_view;
        self.git_log = t.git_log;
        self.git_log_sel = t.git_log_sel;
        self.git_detail = t.git_detail;
        self.git_detail_meta = t.git_detail_meta;
        self.git_detail_title = t.git_detail_title;
        self.git_detail_scroll = t.git_detail_scroll;
        self.git_detail_hscroll = t.git_detail_hscroll;
        self.git_detail_viewport = t.git_detail_viewport;
        self.git_detail_total = t.git_detail_total;
        self.git_branches = t.git_branches;
        self.git_branch_sel = t.git_branch_sel;
        self.git_branch_filter = t.git_branch_filter;
        self.git_branch_filtering = t.git_branch_filtering;
        self.git_graph = t.git_graph;
        self.git_graph_sel = t.git_graph_sel;
        // 選択 / 絞り込み / プレビュー検索もそのタブの状態を復元する(entries も同時に復元するため
        // visual_anchor(entries 添字)は整合する)。load_active は rebuild_tree を呼ばない。
        self.selection = t.selection;
        self.visual_anchor = t.visual_anchor;
        self.tree_filter = t.tree_filter;
        self.filter_input = t.filter_input;
        self.filter_pool = t.filter_pool;
        self.preview_search = t.preview_search;
        self.search_input = t.search_input;
        self.search_matches = t.search_matches;
        self.search_idx = t.search_idx;
        // 装飾キャッシュは持ち越さない (decorated_lines が再生成)。
        self.md_cache = None;
        // 画像は重い状態(protocol/元画像/GIFフレーム)を持ち越さず、画像系プレビューなら再読込で復元する。
        self.clear_image();
        if let (Some(kind), Some(path)) = (self.preview_kind.clone(), self.preview_path.clone()) {
            if matches!(
                kind,
                PreviewKind::Image(_)
                    | PreviewKind::Svg(_)
                    | PreviewKind::Video(_)
                    | PreviewKind::Pdf(_)
            ) {
                // SVG/動画サムネ/GIF は別スレッドで読み込み開始(set_* は zoom/center を触らない)。
                // 保存値を即セットしておけば、後から結果が届いても復元したズーム/中心が保たれる。
                // GIF は先頭フレームから再生。
                // PDF は保存ページを start_media_load の前に戻す(その世代でそのページをラスタライズする)。
                self.pdf_page = t.pdf_page.max(1);
                self.pdf_pages = t.pdf_pages;
                self.start_media_load(&kind, &path);
                self.image_zoom = t.image_zoom;
                self.image_center = t.image_center;
                self.image_crop = None;
            }
        }
        // 大きい Code/Text なら ウィンドウ読みリーダを張り直す(byte_top は上で復元済み)。
        self.setup_windowed();
    }

    pub fn tab_count(&self) -> usize {
        self.tabs.len()
    }

    pub fn active_tab_index(&self) -> usize {
        self.active_tab
    }

    /// Display name of tab `i`. While showing Tree, the **root directory name**; while showing Preview/image, etc.,
    /// the **preview target's file name**. The active tab references the latest working state (App fields),
    /// while inactive tabs reference the snapshot (`TabState`) (since saving happens only on switch).
    pub fn tab_label(&self, i: usize) -> String {
        // (mode, root, preview_path) をアクティブ/非アクティブで使い分ける。
        let (mode, root, preview) = if i == self.active_tab {
            (self.mode, self.root.as_path(), self.preview_path.as_deref())
        } else if let Some(t) = self.tabs.get(i) {
            (t.mode, t.root.as_path(), t.preview_path.as_deref())
        } else {
            return String::new();
        };
        let path = match mode {
            Mode::Preview => preview.unwrap_or(root), // 念のため preview 無しは root へ
            Mode::Tree => root,
        };
        path.file_name()
            .map(|n| n.to_string_lossy().into_owned())
            .unwrap_or_else(|| path.display().to_string())
    }

    /// New tab. Create another tree context starting from the current root and switch to it.
    /// The new tab starts in Tree (since it has no preview target). The source tab's preview is
    /// preserved by `save_active`, so it is not lost.
    pub fn tab_new(&mut self) -> Result<()> {
        self.save_active();
        let root = self.root.clone();
        self.open_dir = root.clone();
        self.root = root;
        self.selected = 0;
        self.entries.clear();
        self.rebuild_tree()?;
        // snapshot 前に Tree へリセットする (snapshot がプレビュー状態も取り込むため順序が重要)。
        self.mode = Mode::Tree;
        self.clear_image();
        self.preview_path = None;
        self.preview_kind = None;
        self.preview_scroll = 0;
        self.preview_hscroll = 0;
        self.preview_byte_top = 0;
        self.preview_top_line = 0;
        self.preview_win = None;
        self.win_cache = None;
        self.preview_total_lines = None;
        self.md_cache = None;
        // 新規タブは git オーバーレイ無しの素の Tree から始める(現タブの git 状態は save_active で保持済み)。
        self.git_view = false;
        self.git_view_sel = 0;
        self.git_view_entries.clear();
        self.came_from_git_view = false;
        self.git_log = None;
        self.git_log_sel = 0;
        self.git_detail = None;
        self.git_detail_meta = None;
        self.git_detail_title = None;
        self.git_detail_scroll = 0;
        self.git_detail_hscroll = 0;
        self.git_detail_viewport = 0;
        self.git_detail_total = 0;
        self.git_branches = None;
        self.git_branch_sel = 0;
        self.git_branch_filter.clear();
        self.git_branch_filtering = false;
        self.git_graph = None;
        self.git_graph_sel = 0;
        // 新規タブは選択 / 絞り込み / プレビュー検索を空から始める
        // (現タブのこれらは直前の save_active で TabState に保持済み)。
        self.selection.clear();
        self.visual_anchor = None;
        self.clear_filter_state();
        self.search_clear();
        self.tabs.push(self.snapshot_tab());
        self.active_tab = self.tabs.len() - 1;
        Ok(())
    }

    /// Close the active tab. The last one is not closed.
    pub fn tab_close(&mut self) {
        if self.tabs.len() <= 1 {
            self.flash = Some(tr(self.lang, crate::i18n::Msg::CantCloseLastTab).into());
            return;
        }
        self.tabs.remove(self.active_tab);
        if self.active_tab >= self.tabs.len() {
            self.active_tab = self.tabs.len() - 1;
        }
        self.load_active();
    }

    /// Move tabs relatively (dir: +1=next / -1=previous). Wraps at the ends.
    pub fn tab_cycle(&mut self, dir: i32) {
        if self.tabs.len() <= 1 {
            return;
        }
        self.save_active();
        let n = self.tabs.len() as i32;
        self.active_tab = (self.active_tab as i32 + dir).rem_euclid(n) as usize;
        self.load_active();
    }

    /// Select a tab by number (0-based). Out-of-range or the same tab is ignored.
    pub fn tab_goto(&mut self, i: usize) {
        if i >= self.tabs.len() || i == self.active_tab {
            return;
        }
        self.save_active();
        self.active_tab = i;
        self.load_active();
    }

    /// Format a path into a display string using the current path_style (shared by the tree/preview title).
    pub fn format_path(&self, path: &Path) -> String {
        match self.path_style {
            PathStyle::Full => path.display().to_string(),
            PathStyle::Home => home_relative(path),
            PathStyle::Relative => rel_to_open(&self.open_dir, path),
        }
    }
}

/// Common helper that moves a list cursor by delta and returns it clamped to `[0, len-1]`.
/// Even if the caller (`g`/`G`/Home/End) passes `delta=i32::MIN/MAX`, the computation is done in i64, so it
/// does not panic on overflow (the plain `as i32 + delta` addition used to crash in debug).
/// `len==0` returns 0. The behavior is unchanged from the previous `(cur as i32 + delta).clamp(0, len-1)`.
fn clamp_cursor(cur: usize, delta: i32, len: usize) -> usize {
    if len == 0 {
        return 0;
    }
    let last = len.saturating_sub(1) as i64;
    (cur as i64).saturating_add(delta as i64).clamp(0, last) as usize
}

/// Whether a span is a Markdown link (blue underline). Since konoma's StyleSheet.link()=underline+blue draws them,
/// these two conditions decide it (code/headings/rules have different colors, so no false positives).
fn is_link_span(span: &Span<'static>) -> bool {
    use ratatui::style::{Color, Modifier};
    span.style.add_modifier.contains(Modifier::UNDERLINED) && span.style.fg == Some(Color::Blue)
}

/// Fold the accompanying URL of the "label (URL)" that tui-markdown emits, leaving **only the label** in link style (blue underline,
/// with a leading link icon when `icons=true`). The URLs are collected in order into `targets` and returned (hidden destinations).
/// Pattern: `[label]` `" ("` `[URL(blue underline)]` `")"`. Spans that do not match are passed through unchanged.
fn collapse_links(lines: Vec<Line<'static>>, icons: bool) -> (Vec<Line<'static>>, Vec<String>) {
    use ratatui::style::{Color, Modifier, Style};
    let link_style = Style::new()
        .fg(Color::Blue)
        .add_modifier(Modifier::UNDERLINED);
    let mut out = Vec::with_capacity(lines.len());
    let mut targets = Vec::new();
    for line in lines {
        let style = line.style;
        let spans = line.spans;
        let n = spans.len();
        let mut new: Vec<Span<'static>> = Vec::with_capacity(n);
        let mut i = 0;
        while i < n {
            let is_link_pattern = i + 2 < n
                && spans[i + 1].content.as_ref() == " ("
                && is_link_span(&spans[i + 2])
                && spans.get(i + 3).is_some_and(|s| s.content.starts_with(')'));
            if is_link_pattern {
                let label = spans[i].content.as_ref();
                targets.push(spans[i + 2].content.to_string());
                let text = if icons {
                    format!("{} {label}", crate::ui::icons::link_icon())
                } else {
                    label.to_string()
                };
                new.push(Span::styled(text, link_style));
                // 閉じ括弧 ")" の後ろに続く文字(句読点等)は保持する。
                let closer = spans[i + 3].content.as_ref();
                if closer.len() > 1 {
                    new.push(Span::styled(closer[1..].to_string(), spans[i + 3].style));
                }
                i += 4;
            } else {
                new.push(spans[i].clone());
                i += 1;
            }
        }
        out.push(Line::from(new).style(style));
    }
    (out, targets)
}

/// Within line `line` (multiple colored spans), highlight the parts matching `query` (substring, case-insensitive)
/// in a highlighter style (background color + black text + bold). Even for matches crossing span boundaries, each span is split at the
/// match boundaries and the background is applied (the original fg/bold/italic are kept). If the byte length changes when lowercasing
/// (multibyte), it does nothing to avoid mis-slicing.
/// When `current_occurrence`=Some(occurrence rank within the line, 0-based), **only that one occurrence is orange**, and
/// the others are yellow (vim's CurSearch/Search style; `n`/`N` change the color of only the selected occurrence). None means all yellow.
/// Since occurrences are identified by rank rather than column (byte position), the current match stays stable even if the byte sequence shifts from tab expansion (#14).
fn highlight_query_in_line(
    line: Line<'static>,
    query: &str,
    current_occurrence: Option<usize>,
) -> Line<'static> {
    use ratatui::style::{Color, Modifier};
    if query.is_empty() {
        return line;
    }
    let full: String = line.spans.iter().map(|s| s.content.as_ref()).collect();
    let lower = full.to_lowercase();
    let q = query.to_lowercase();
    if lower.len() != full.len() {
        return line; // 非 ASCII でバイト長が変わる場合は安全側で強調なし
    }
    // 一致バイト範囲を収集。
    let mut ranges: Vec<(usize, usize)> = Vec::new();
    let mut i = 0;
    while let Some(rel) = lower[i..].find(&q) {
        let s = i + rel;
        let e = s + q.len();
        ranges.push((s, e));
        i = e;
    }
    if ranges.is_empty() {
        return line;
    }
    let style = line.style;
    let mut out: Vec<Span<'static>> = Vec::new();
    let mut pos = 0usize; // full 内のバイト位置
    for span in line.spans {
        let text = span.content.into_owned();
        let span_start = pos;
        let span_end = pos + text.len();
        // この span 内の分割点(span 端+一致境界)。
        let mut points = vec![span_start, span_end];
        for (s, e) in &ranges {
            if *s > span_start && *s < span_end {
                points.push(*s);
            }
            if *e > span_start && *e < span_end {
                points.push(*e);
            }
        }
        points.sort_unstable();
        points.dedup();
        for w in points.windows(2) {
            let (a, b) = (w[0], w[1]);
            if let Some(seg) = text.get(a - span_start..b - span_start) {
                if seg.is_empty() {
                    continue;
                }
                // この区間が属する一致範囲の出現順位(あれば)。その順位が current_occurrence
                // なら現在の出現=オレンジ、他の一致は黄色。範囲外は素のまま。
                let hit = ranges.iter().position(|(s, e)| a >= *s && b <= *e);
                let st = if let Some(idx) = hit {
                    let bg = if current_occurrence == Some(idx) {
                        Color::Rgb(0xff, 0x8c, 0x00) // 現在の出現
                    } else {
                        Color::Yellow // 他の出現
                    };
                    span.style
                        .bg(bg)
                        .fg(Color::Black)
                        .add_modifier(Modifier::BOLD)
                } else {
                    span.style
                };
                out.push(Span::styled(seg.to_string(), st));
            }
        }
        pos = span_end;
    }
    Line::from(out).style(style)
}

/// Prepend a line-number gutter (right-aligned + a space) to each line. The first line's number is `top_line+1` (1-based).
/// A dim color (DarkGray) distinguishes it from the body. The original line style (background, etc.) is kept.
fn with_line_numbers(lines: Vec<Line<'static>>, top_line: usize) -> Vec<Line<'static>> {
    use ratatui::style::{Color, Style};
    let last = top_line + lines.len().max(1);
    let width = last.to_string().len().max(3); // 最低 3 桁ぶんの幅を確保
    lines
        .into_iter()
        .enumerate()
        .map(|(i, line)| {
            let n = top_line + i + 1;
            let gutter = Span::styled(format!("{n:>width$} "), Style::new().fg(Color::DarkGray));
            let style = line.style;
            let mut spans = Vec::with_capacity(line.spans.len() + 1);
            spans.push(gutter);
            spans.extend(line.spans);
            Line::from(spans).style(style)
        })
        .collect()
}

/// The rectangle that centers an image of size `cells` (natural size) within `inner` while preserving the aspect ratio.
/// With `allow_upscale=false`, downscale only (scale<=1=fit behavior); with `true`, it may upscale to fill the area.
fn centered_rect(cells: (u16, u16), inner: Rect, allow_upscale: bool) -> Rect {
    let (cw, ch) = cells;
    if cw == 0 || ch == 0 || inner.width == 0 || inner.height == 0 {
        return inner;
    }
    let mut scale = (inner.width as f64 / cw as f64).min(inner.height as f64 / ch as f64);
    if !allow_upscale {
        scale = scale.min(1.0);
    }
    let w = ((cw as f64 * scale).round() as u16).clamp(1, inner.width);
    let h = ((ch as f64 * scale).round() as u16).clamp(1, inner.height);
    let x = inner.x + (inner.width - w) / 2;
    let y = inner.y + (inner.height - h) / 2;
    Rect {
        x,
        y,
        width: w,
        height: h,
    }
}

/// Compute the display layout for an image/GIF frame (a pure function shared by prepare_image / prepare_gif).
/// From (source image src, font_size, zoom, center[0,1], display area inner, render_scale), returns
/// `(target, crop_rect, center, frac)` (None if size 0).
///
/// - `target`  : the render-target rectangle (centered; z=1=fit, grows when zooming, clips when exceeding the viewport)
/// - `crop_rect`: the source-image window of the visible portion (px: x,y,w,h)
/// - `center`  : the center clamped to where the visible window fits within the image [0,1]
/// - `frac`    : the visible fraction per axis (<1=clipped=pan possible)
#[allow(clippy::type_complexity)]
fn image_layout(
    src: &image::DynamicImage,
    font_size: ratatui_image::FontSize,
    zoom: f64,
    center: (f64, f64),
    inner: Rect,
    render_scale: f64,
) -> Option<(Rect, (u32, u32, u32, u32), (f64, f64), (f64, f64))> {
    use image::GenericImageView;
    let (sw, sh) = src.dimensions();
    if sw == 0 || sh == 0 || inner.width == 0 || inner.height == 0 {
        return None;
    }
    // z=1 のフィット表示サイズ(セル, 拡大しない)。
    let natural = Resize::natural_size(src, font_size);
    let base = centered_rect((natural.width, natural.height), inner, false);
    // ズーム後の論理表示サイズ。
    let disp_w = (base.width as f64 * zoom).max(1.0);
    let disp_h = (base.height as f64 * zoom).max(1.0);
    // 画面に出る大きさ = min(表示サイズ, 表示領域)。
    let tw = (disp_w.min(inner.width as f64).round() as u16).max(1);
    let th = (disp_h.min(inner.height as f64).round() as u16).max(1);
    // 各軸の可視率(<1 なら見切れ=パン可能)。
    let fw = (tw as f64 / disp_w).min(1.0);
    let fh = (th as f64 / disp_h).min(1.0);
    // 中心を可視窓が画像内に収まる範囲へクランプ。
    let cx = center.0.clamp(fw / 2.0, 1.0 - fw / 2.0);
    let cy = center.1.clamp(fh / 2.0, 1.0 - fh / 2.0);
    // 元画像から見える窓を切り出す(px)。
    let cw = ((sw as f64 * fw).round() as u32).clamp(1, sw);
    let ch = ((sh as f64 * fh).round() as u32).clamp(1, sh);
    let x0 = ((cx * sw as f64) as i64 - cw as i64 / 2).clamp(0, (sw - cw) as i64) as u32;
    let y0 = ((cy * sh as f64) as i64 - ch as i64 / 2).clamp(0, (sh - ch) as i64) as u32;
    let crop_rect = (x0, y0, cw, ch);
    // 表示矩形(中央寄せ)。任意で render_scale により縮小(転送量=描画待ち削減)。
    let scale = render_scale.clamp(0.1, 1.0);
    let (tw, th) = if scale >= 0.999 {
        (tw, th)
    } else {
        (
            ((tw as f64 * scale).round() as u16).max(1),
            ((th as f64 * scale).round() as u16).max(1),
        )
    };
    let target = Rect {
        x: inner.x + (inner.width - tw.min(inner.width)) / 2,
        y: inner.y + (inner.height - th.min(inner.height)) / 2,
        width: tw.min(inner.width),
        height: th.min(inner.height),
    };
    Some((target, crop_rect, (cx, cy), (fw, fh)))
}

/// The modification time of `path`, or None if it cannot be read. Used by the FS-driven media auto-reload guard.
fn file_mtime(path: &Path) -> Option<std::time::SystemTime> {
    std::fs::metadata(path).and_then(|m| m.modified()).ok()
}

/// Assemble the copy string (a pure function; does not touch the clipboard).
/// `open_dir` is the base for relative paths (the launch directory).
fn copy_text(path: &Path, open_dir: &Path, kind: CopyKind) -> String {
    match kind {
        CopyKind::Name => path
            .file_name()
            .map(|n| n.to_string_lossy().into_owned())
            .unwrap_or_default(),
        CopyKind::Full => path.display().to_string(),
        CopyKind::Parent => path
            .parent()
            .map(|p| p.display().to_string())
            .unwrap_or_default(),
        // 左上のタイトル表示 (format_path の Relative) と完全に同じ基準にする。
        CopyKind::Relative => rel_to_open(open_dir, path),
    }
}

/// A relative display string based on `open_dir` (the launch directory). For paths underneath, it puts the launch directory name first (e.g. `A/sub/x`),
/// and for things outside open_dir (siblings/ancestors) it relativizes with `..` (e.g. `../B/aaa.md`, `..`). If it cannot be relativized, `~/...`.
/// A shared function to guarantee the **same base** for the top-left path display (`format_path`'s Relative) and path copy (`cr`/`yr`).
fn rel_to_open(open_dir: &Path, path: &Path) -> String {
    if path.starts_with(open_dir) {
        // open_dir 配下: 起動ディレクトリ名を先頭に出すため、その親を基準に相対化 (例: A/sub/x)。
        let base = open_dir.parent().unwrap_or(open_dir);
        match path.strip_prefix(base) {
            Ok(rel) if !rel.as_os_str().is_empty() => rel.display().to_string(),
            _ => home_relative(path),
        }
    } else {
        // open_dir の外(兄弟/上位など): open_dir 基準の相対パスを `..` 込みで表示 (例: ../B/aaa.md)。
        // これが無いと兄弟 B のファイルが `B/aaa.md` のように見え、配下にあるかのように誤解される。
        match rel_from(open_dir, path) {
            Some(rel) if !rel.as_os_str().is_empty() => rel.display().to_string(),
            _ => home_relative(path),
        }
    }
}

/// Write to the clipboard. Returns Err on environments where arboard is unavailable (the caller shows a flash).
fn set_clipboard(text: &str) -> Result<()> {
    let mut cb = arboard::Clipboard::new()?;
    cb.set_text(text.to_string())?;
    Ok(())
}

/// `~/...` if under HOME, otherwise the full path.
fn home_relative(path: &Path) -> String {
    if let Some(home) = std::env::var_os("HOME") {
        let home = PathBuf::from(home);
        if let Ok(rel) = path.strip_prefix(&home) {
            if rel.as_os_str().is_empty() {
                return "~".to_string();
            }
            return format!("~/{}", rel.display());
        }
    }
    path.display().to_string()
}

/// Resolve a dropped (=pasted) string into a list of **existing paths**. Terminals (Ghostty, etc.) pass a drop
/// as shell-escaped text (spaces as `\ `; multiple files separated by unescaped spaces).
/// Undo the backslash escapes, split on unescaped whitespace/newlines, and return only the tokens that **exist on disk**
/// (= safely excludes plain text pastes, junk, and control-character mixes).
fn parse_dropped_paths(text: &str) -> Vec<PathBuf> {
    let mut tokens: Vec<String> = Vec::new();
    let mut cur = String::new();
    let mut escaped = false;
    for c in text.chars() {
        if escaped {
            cur.push(c); // 直前が `\` = この文字はリテラル(空白入りパス名等)
            escaped = false;
        } else if c == '\\' {
            escaped = true;
        } else if c.is_whitespace() {
            if !cur.is_empty() {
                tokens.push(std::mem::take(&mut cur));
            }
        } else {
            cur.push(c);
        }
    }
    if !cur.is_empty() {
        tokens.push(cur);
    }
    tokens
        .into_iter()
        .map(PathBuf::from)
        .filter(|p| p.exists()) // 実在パスのみ採用(テキストペースト/不正入力を弾く安全網)
        .collect()
}

/// Build a plan for sequential rename. Number `targets` **in display order** as `{n}`=1,2,…,
/// expand the template, and create each (old, new) path. If the template has no extension, the original extension is kept automatically.
/// **Pre-validates** collisions: an empty name / a `/` mixed in / duplicate final names / a collision with an existing file (not vacated within the batch) is an Err.
fn build_rename_plan(targets: &[PathBuf], template: &str) -> Result<Vec<(PathBuf, PathBuf)>> {
    let mut plan: Vec<(PathBuf, PathBuf)> = Vec::with_capacity(targets.len());
    for (idx, src) in targets.iter().enumerate() {
        let n = idx + 1;
        let stem = src.file_stem().and_then(|s| s.to_str()).unwrap_or("");
        let ext = src.extension().and_then(|s| s.to_str()).unwrap_or("");
        let rendered = crate::fileops::render_rename_template(template, n, stem, ext);
        let rendered = rendered.trim().to_string();
        if rendered.is_empty() {
            anyhow::bail!("空の名前になります (n={n})");
        }
        if rendered.contains('/') {
            anyhow::bail!("名前に / は使えません: {rendered}");
        }
        // 拡張子: テンプレ結果に拡張子が無ければ元拡張子を自動付与(ユーザ決定)。
        let has_ext = Path::new(&rendered)
            .extension()
            .filter(|e| !e.is_empty())
            .is_some();
        let new_name = if !has_ext && !ext.is_empty() {
            format!("{rendered}.{ext}")
        } else {
            rendered
        };
        let dst = src
            .parent()
            .unwrap_or_else(|| Path::new("."))
            .join(&new_name);
        plan.push((src.clone(), dst));
    }
    // 最終名の重複検証。
    let mut seen = BTreeSet::new();
    for (_, dst) in &plan {
        if !seen.insert(dst.clone()) {
            anyhow::bail!("リネーム先が重複: {}", dst.display());
        }
    }
    // 既存ファイルとの衝突検証(バッチ内で「移動して空く」元パスは除外)。
    let vacated: BTreeSet<PathBuf> = plan
        .iter()
        .filter(|(s, d)| s != d)
        .map(|(s, _)| s.clone())
        .collect();
    for (src, dst) in &plan {
        // 名前据え置き(src == dst)は自分自身の存在を衝突と誤検出しないよう除外する(#11)。
        // 真の衝突=別ファイルと被る場合のみ、最終名重複検証(上)で弾く。
        if src == dst {
            continue;
        }
        if dst.exists() && !vacated.contains(dst) {
            anyhow::bail!("既に存在します: {}", dst.display());
        }
    }
    Ok(plan)
}

/// Return the byte position in `s` corresponding to character index `char_idx` (past the end gives `s.len()`).
/// A conversion to safely compute insertion/deletion positions even for multibyte text (e.g. Japanese file names).
fn char_byte(s: &str, char_idx: usize) -> usize {
    s.char_indices()
        .nth(char_idx)
        .map(|(b, _)| b)
        .unwrap_or(s.len())
}

/// Compute the relative path from `base` to `target`, including `..` (equivalent to pathdiff). It removes the common leading components and
/// pushes one `..` for each remaining level on the base side. None if the root kinds (absolute/drive) disagree and it cannot be relativized.
fn rel_from(base: &Path, target: &Path) -> Option<PathBuf> {
    use std::path::Component;
    let bc: Vec<Component> = base.components().collect();
    let tc: Vec<Component> = target.components().collect();
    let mut i = 0;
    while i < bc.len() && i < tc.len() && bc[i] == tc[i] {
        i += 1;
    }
    // 共通成分が無く、かつ一方がルート(絶対/Prefix)で始まる=相対化不能。
    if i == 0 {
        let is_root = |c: Option<&Component>| {
            matches!(c, Some(Component::Prefix(_)) | Some(Component::RootDir))
        };
        if is_root(bc.first()) || is_root(tc.first()) {
            return None;
        }
    }
    let mut rel = PathBuf::new();
    for _ in i..bc.len() {
        rel.push("..");
    }
    for c in &tc[i..] {
        rel.push(c.as_os_str());
    }
    Some(rel)
}

/// Append one directory's worth of entries to out. Recurse into expanded subdirectories.
/// Bundles the decision info for one entry for sorting (stats the metadata only once).
struct ChildMeta {
    path: PathBuf,
    is_dir: bool,
    size: u64,
    mtime: Option<std::time::SystemTime>,
}

fn child_meta(path: PathBuf) -> ChildMeta {
    let md = std::fs::metadata(&path).ok();
    let is_dir = md.as_ref().map(|m| m.is_dir()).unwrap_or(false);
    let size = md.as_ref().map(|m| m.len()).unwrap_or(0);
    let mtime = md.as_ref().and_then(|m| m.modified().ok());
    ChildMeta {
        path,
        is_dir,
        size,
        mtime,
    }
}

/// Lowercase comparison of file names (a case-insensitive ordering).
fn name_cmp(a: &Path, b: &Path) -> std::cmp::Ordering {
    let an = a
        .file_name()
        .map(|s| s.to_string_lossy().to_lowercase())
        .unwrap_or_default();
    let bn = b
        .file_name()
        .map(|s| s.to_string_lossy().to_lowercase())
        .unwrap_or_default();
    an.cmp(&bn)
}

/// The lowercase extension (empty if none).
fn ext_lower(p: &Path) -> String {
    p.extension()
        .and_then(|e| e.to_str())
        .unwrap_or("")
        .to_lowercase()
}

/// Compare two entries according to the settings. dirs_first → key → reverse, finally stabilized by name.
fn sort_cmp(a: &ChildMeta, b: &ChildMeta, sort: Sort) -> std::cmp::Ordering {
    use std::cmp::Ordering;
    if sort.dirs_first {
        let d = b.is_dir.cmp(&a.is_dir); // ディレクトリ(true)を先頭に
        if d != Ordering::Equal {
            return d;
        }
    }
    let mut ord = match sort.key {
        SortKey::Name => name_cmp(&a.path, &b.path),
        SortKey::Size => a.size.cmp(&b.size),
        SortKey::Modified => a.mtime.cmp(&b.mtime),
        SortKey::Ext => ext_lower(&a.path).cmp(&ext_lower(&b.path)),
    };
    if sort.reverse {
        ord = ord.reverse();
    }
    // 同値は名前(昇順)で安定化して並びがブレないようにする。
    ord.then_with(|| name_cmp(&a.path, &b.path))
}

/// Take the title label for the graph base from refs (`%D`). From `(HEAD -> main, origin/main)`, etc.,
/// pick one branch name (strip the HEAD-> and skip tag:). If there is no branch ref, the short hash.
#[cfg_attr(not(feature = "git"), allow(dead_code))]
fn base_label_from(refs: &str, short: &str) -> String {
    for part in refs.split(',').map(str::trim) {
        let p = part.strip_prefix("HEAD -> ").unwrap_or(part);
        if p.is_empty() || p.starts_with("tag:") {
            continue;
        }
        return p.to_string();
    }
    short.to_string()
}

fn build_dir(
    dir: &Path,
    depth: usize,
    expanded_dirs: &[PathBuf],
    show_hidden: bool,
    sort: Sort,
    out: &mut Vec<Entry>,
) -> Result<()> {
    let mut children: Vec<ChildMeta> = std::fs::read_dir(dir)?
        .filter_map(|r| r.ok())
        .map(|e| e.path())
        .filter(|p| {
            if show_hidden {
                return true;
            }
            !p.file_name()
                .and_then(|n| n.to_str())
                .map(|n| n.starts_with('.'))
                .unwrap_or(false)
        })
        .map(child_meta)
        .collect();

    children.sort_by(|a, b| sort_cmp(a, b, sort));

    for c in children {
        let expanded = c.is_dir && expanded_dirs.iter().any(|d| d == &c.path);
        out.push(Entry {
            path: c.path.clone(),
            is_dir: c.is_dir,
            depth,
            expanded,
        });
        if expanded {
            build_dir(&c.path, depth + 1, expanded_dirs, show_hidden, sort, out)?;
        }
    }
    Ok(())
}

/// Recursively collect files/directories under `root` (the population for filtering). Hidden ones are excluded via `show_hidden`,
/// and symlink directories are not descended into (to prevent loops). The scan count is capped as a cost limit.
/// The return value is in ascending path order (grouped per directory). Each Entry is flat with depth=0 and expanded=false.
fn collect_all(root: &Path, show_hidden: bool) -> Vec<Entry> {
    const CAP: usize = 50_000;
    let mut out = Vec::new();
    let mut stack = vec![root.to_path_buf()];
    while let Some(dir) = stack.pop() {
        if out.len() >= CAP {
            break;
        }
        let Ok(rd) = std::fs::read_dir(&dir) else {
            continue;
        };
        for path in rd.filter_map(|r| r.ok()).map(|e| e.path()) {
            if out.len() >= CAP {
                break;
            }
            let hidden = path
                .file_name()
                .and_then(|n| n.to_str())
                .map(|n| n.starts_with('.'))
                .unwrap_or(false);
            if hidden && !show_hidden {
                continue;
            }
            // シンボリックリンクの dir には潜らない(循環回避)。is_dir はリンク先を辿るので別途判定。
            let is_symlink = std::fs::symlink_metadata(&path)
                .map(|m| m.file_type().is_symlink())
                .unwrap_or(false);
            let is_dir = path.is_dir();
            out.push(Entry {
                path: path.clone(),
                is_dir,
                depth: 0,
                expanded: false,
            });
            if is_dir && !is_symlink {
                stack.push(path);
            }
        }
    }
    out.sort_by(|a, b| a.path.cmp(&b.path));
    out
}

#[cfg(test)]
mod tests;