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
//! File-explorer as a real read-only buffer window (#55) — Neovim neo-tree/oil style.
//!
//! The tree **model** (`ExplorerTree`: root, expanded set, flat node list) is
//! kept from the previous implementation. `render_text` produces the buffer
//! text and a line→node map. Everything else (custom render, key handler,
//! focus flag, scroll, selection, mouse zone) is gone — the engine provides
//! those for free because the explorer is now a real left window in the layout
//! tree.
use std::collections::{HashMap, HashSet};
use std::path::{Path, PathBuf};
use std::thread;
use std::time::Instant;
use crossbeam_channel::{Receiver, Sender};
// ── Prompt / confirm / clipboard state ────────────────────────────────────────
/// Kind of explorer prompt currently open.
#[derive(Debug, Clone)]
pub(crate) enum ExplorerPromptKind {
/// `a` — create a new file or directory.
Create,
/// `r` — rename the node under cursor.
Rename {
/// The path being renamed.
from: PathBuf,
},
}
/// An active explorer text prompt (create / rename).
pub(crate) struct ExplorerPrompt {
pub kind: ExplorerPromptKind,
pub field: hjkl_form::TextFieldEditor,
/// Directory under which the new name will be placed.
pub base: PathBuf,
}
/// Pending delete confirmation.
#[derive(Debug, Clone)]
pub(crate) struct ExplorerConfirm {
/// Path to delete.
pub path: PathBuf,
pub is_dir: bool,
}
/// Clipboard entry for copy (`y`) / cut (`x`) operations.
#[derive(Debug, Clone)]
pub(crate) struct ExplorerClip {
pub path: PathBuf,
/// `true` → move (cut); `false` → copy.
pub cut: bool,
}
// ── Tree model ─────────────────────────────────────────────────────────────────
/// One visible row in the flattened tree.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct ExplorerNode {
pub path: PathBuf,
/// Nesting depth: root is depth 0, its children depth 1, …
pub depth: usize,
pub is_dir: bool,
/// True when this node is the last child of its parent (`└╴` vs `├╴`).
pub is_last: bool,
/// For each ancestor level above this node (excluding the root): whether
/// that ancestor has a following sibling (draw a `│` in that column).
/// Length `depth - 1` for `depth >= 1`; empty for the root.
pub branches: Vec<bool>,
}
/// Pure tree model. Owned by `ExplorerPane` on `App`.
#[derive(Debug, Clone)]
pub(crate) struct ExplorerTree {
/// Root of the tree (cwd when the explorer was opened).
pub(crate) root: PathBuf,
/// Directories the user has expanded (absolute paths).
expanded: HashSet<PathBuf>,
/// Flattened depth-first list of currently visible rows.
/// Indexed 1:1 with buffer lines after `render_text`.
pub(crate) nodes: Vec<ExplorerNode>,
/// When `false`, entries whose name starts with `.` are hidden. Defaults to
/// `true` (dotfiles shown). `H` toggles this. The `.git` dir is always
/// skipped regardless.
pub(crate) show_hidden: bool,
/// When `true` (default), entries matched by the repo's git ignore rules
/// (`.gitignore`, `.git/info/exclude`, core.excludesfile) are hidden — this
/// also prunes ignored dirs (e.g. `target/`, `node_modules/`) from the fuzzy
/// search walk, keeping it fast. `I` toggles this. No effect outside a repo.
pub(crate) respect_gitignore: bool,
/// Active fuzzy filter query. `None` = unfiltered (normal expansion mode).
/// When `Some`, `rebuild` performs a full recursive walk and only shows
/// files that fuzzy-match the query, plus their ancestor dirs.
pub(crate) filter: Option<String>,
/// Number of files that matched the last filtered rebuild. 0 when unfiltered.
pub(crate) match_count: usize,
/// Total number of files visited during the last filtered rebuild. 0 when
/// unfiltered.
pub(crate) total_count: usize,
/// Row (index into `nodes`) of the highest-scoring matched file after the
/// last filtered rebuild, so the search can focus the BEST match rather than
/// the first in tree order. `None` when unfiltered or no match.
pub(crate) best_match_row: Option<usize>,
}
impl ExplorerTree {
/// Create a fresh tree rooted at `root`. The root starts expanded so its
/// children are visible immediately. Dotfiles are shown by default;
/// git-ignored entries are hidden by default.
pub(crate) fn new(root: PathBuf) -> Self {
let mut expanded = HashSet::new();
expanded.insert(root.clone());
let mut tree = Self {
root,
expanded,
nodes: Vec::new(),
show_hidden: true,
respect_gitignore: true,
filter: None,
match_count: 0,
total_count: 0,
best_match_row: None,
};
tree.rebuild();
tree
}
/// Read one directory's children, sorted directories-first then by
/// case-insensitive name. The `.git` dir is always skipped; dotfiles are
/// filtered unless `show_hidden`; git-ignored entries are filtered when
/// `respect_gitignore` and a repo is available (`repo`).
fn read_children(&self, dir: &Path, repo: Option<&git2::Repository>) -> Vec<(PathBuf, bool)> {
let mut entries: Vec<(PathBuf, bool)> = match std::fs::read_dir(dir) {
Ok(rd) => rd
.filter_map(|e| e.ok())
.filter_map(|e| {
let p = e.path();
let name = p.file_name().map(|n| n.to_string_lossy().into_owned());
// Never show the repo internals dir.
if name.as_deref() == Some(".git") {
return None;
}
// Skip dotfiles unless show_hidden.
if !self.show_hidden && name.as_deref().is_some_and(|n| n.starts_with('.')) {
return None;
}
// Skip git-ignored entries (prunes ignored dirs from the walk).
if self.respect_gitignore
&& let Some(r) = repo
&& r.is_path_ignored(&p).unwrap_or(false)
{
return None;
}
let is_dir = e.file_type().map(|t| t.is_dir()).unwrap_or(false);
Some((p, is_dir))
})
.collect(),
Err(_) => Vec::new(),
};
entries.sort_by(|(a, a_dir), (b, b_dir)| {
b_dir.cmp(a_dir).then_with(|| {
let an = a.file_name().map(|n| n.to_string_lossy().to_lowercase());
let bn = b.file_name().map(|n| n.to_string_lossy().to_lowercase());
an.cmp(&bn)
})
});
entries
}
/// Open the git repo enclosing `root` for ignore checks. `None` when not in
/// a repo or when ignore-honoring is disabled.
fn open_repo(&self) -> Option<git2::Repository> {
if !self.respect_gitignore {
return None;
}
git2::Repository::discover(&self.root).ok()
}
/// Recursively append `dir`'s expanded children to `out`.
fn push_children(
&self,
dir: &Path,
depth: usize,
prefix: &[bool],
out: &mut Vec<ExplorerNode>,
repo: Option<&git2::Repository>,
) {
let children = self.read_children(dir, repo);
let n = children.len();
for (i, (path, is_dir)) in children.into_iter().enumerate() {
let is_last = i + 1 == n;
out.push(ExplorerNode {
path: path.clone(),
depth,
is_dir,
is_last,
branches: prefix.to_vec(),
});
if is_dir && self.expanded.contains(&path) {
let mut child_prefix = prefix.to_vec();
child_prefix.push(!is_last);
self.push_children(&path, depth + 1, &child_prefix, out, repo);
}
}
}
/// Rebuild the flattened node list from the current expansion state.
///
/// When `self.filter` is `Some(q)`, performs a full bounded recursive walk
/// of the filesystem under `root`, scores each file with `hjkl_fuzzy::score`,
/// and builds a force-expanded filtered view. Otherwise falls back to the
/// lazy expansion-set walk.
pub(crate) fn rebuild(&mut self) {
if let Some(ref q) = self.filter.clone() {
self.rebuild_filtered(q);
} else {
self.rebuild_unfiltered();
}
}
fn rebuild_unfiltered(&mut self) {
let mut out = Vec::new();
let root = self.root.clone();
out.push(ExplorerNode {
path: root.clone(),
depth: 0,
is_dir: true,
is_last: true,
branches: Vec::new(),
});
if self.expanded.contains(&root) {
let repo = self.open_repo();
self.push_children(&root, 1, &[], &mut out, repo.as_ref());
}
self.nodes = out;
self.match_count = 0;
self.total_count = 0;
self.best_match_row = None;
}
/// Full recursive fs walk under `root`, filtered to fuzzy-matching files.
/// Cap total entries visited at 20_000 to bound scan time on huge trees.
fn rebuild_filtered(&mut self, query: &str) {
// Walk the entire tree under root, collecting matching files.
const CAP: usize = 20_000;
let root = self.root.clone();
let root_str = root.to_string_lossy().to_string();
let root_str_len = root_str.len();
// Open the repo once for the whole walk so ignored dirs (target/,
// node_modules/, …) are pruned and never descended into.
let repo = self.open_repo();
let mut visited: usize = 0;
let mut truncated = false;
// file_path → score (only files that matched)
let mut scored: HashMap<PathBuf, i64> = HashMap::new();
let mut total: usize = 0;
// Iterative DFS using a stack of dirs to visit.
let mut dir_stack: Vec<PathBuf> = vec![root.clone()];
while let Some(dir) = dir_stack.pop() {
if visited >= CAP {
truncated = true;
break;
}
let children = self.read_children(&dir, repo.as_ref());
for (path, is_dir) in children {
visited += 1;
if visited > CAP {
truncated = true;
break;
}
if is_dir {
dir_stack.push(path);
} else {
total += 1;
// Score relative path so matches feel project-relative.
let full = path.to_string_lossy();
let rel = if full.starts_with(&root_str) {
let stripped = &full[root_str_len..];
stripped.trim_start_matches(std::path::MAIN_SEPARATOR)
} else {
full.as_ref()
};
if let Some((s, _)) = hjkl_fuzzy::score(rel, query) {
scored.insert(path, s);
}
}
}
}
if truncated {
tracing::debug!(
cap = CAP,
"explorer filter walk capped at {CAP} entries; tree may be incomplete"
);
}
self.match_count = scored.len();
self.total_count = total;
// Build the ancestor set: every dir from a matched file up to root.
let mut show: HashSet<PathBuf> = HashSet::new();
show.insert(root.clone());
for path in scored.keys() {
let mut cur = path.parent();
while let Some(p) = cur {
show.insert(p.to_path_buf());
if p == root {
break;
}
cur = p.parent();
}
}
// Also insert matched files themselves into show.
for path in scored.keys() {
show.insert(path.clone());
}
// DFS to build nodes — force-expanded, include only `show` members.
let mut out = Vec::new();
out.push(ExplorerNode {
path: root.clone(),
depth: 0,
is_dir: true,
is_last: true,
branches: Vec::new(),
});
self.push_children_filtered(&root, 1, &[], &show, &mut out, repo.as_ref());
self.nodes = out;
// Focus the highest-scoring match (not the first in tree order). Pick
// the matched file with the max score, then its row in `nodes`.
self.best_match_row = scored
.iter()
.max_by_key(|(_, s)| **s)
.map(|(p, _)| p.clone())
.and_then(|best| self.nodes.iter().position(|n| n.path == best));
}
/// Recursive helper for filtered rebuild — mirrors `push_children` but
/// limits children to those in `show` and always recurses into dirs
/// (force-expanded).
fn push_children_filtered(
&self,
dir: &Path,
depth: usize,
prefix: &[bool],
show: &HashSet<PathBuf>,
out: &mut Vec<ExplorerNode>,
repo: Option<&git2::Repository>,
) {
let children = self.read_children(dir, repo);
// Keep only children that are in the show set.
let visible: Vec<(PathBuf, bool)> = children
.into_iter()
.filter(|(p, _)| show.contains(p))
.collect();
let n = visible.len();
for (i, (path, is_dir)) in visible.into_iter().enumerate() {
let is_last = i + 1 == n;
out.push(ExplorerNode {
path: path.clone(),
depth,
is_dir,
is_last,
branches: prefix.to_vec(),
});
if is_dir {
let mut child_prefix = prefix.to_vec();
child_prefix.push(!is_last);
self.push_children_filtered(&path, depth + 1, &child_prefix, show, out, repo);
}
}
}
/// Apply a fuzzy filter query. Empty string → clears the filter.
/// Triggers a `rebuild`.
pub(crate) fn apply_filter(&mut self, query: &str) {
let q = query.trim();
if q.is_empty() {
self.filter = None;
} else {
self.filter = Some(q.to_string());
}
self.rebuild();
}
/// Clear the active filter and rebuild.
pub(crate) fn clear_filter(&mut self) {
self.filter = None;
self.rebuild();
}
/// Build a filtered tree for a worker thread search. Constructs the struct
/// directly (no unfiltered `new()` rebuild), sets `filter = Some(query)`,
/// and calls `rebuild()` to run the filtered walk. The `git2::Repository`
/// opened inside `rebuild()` stays on the calling (worker) thread — never
/// send a `Repository` across a channel.
pub(crate) fn for_search(
root: PathBuf,
show_hidden: bool,
respect_gitignore: bool,
query: String,
) -> Self {
// Build the struct directly without running the unfiltered walk.
let mut expanded = HashSet::new();
expanded.insert(root.clone());
let mut tree = Self {
root,
expanded,
nodes: Vec::new(),
show_hidden,
respect_gitignore,
filter: Some(query),
match_count: 0,
total_count: 0,
best_match_row: None,
};
tree.rebuild();
tree
}
/// Install a worker result onto the tree without running a filesystem walk.
/// Called from the main thread when a worker result arrives.
pub(crate) fn apply_search_result(
&mut self,
query: String,
nodes: Vec<ExplorerNode>,
match_count: usize,
total_count: usize,
best_match_row: Option<usize>,
) {
self.filter = Some(query);
self.nodes = nodes;
self.match_count = match_count;
self.total_count = total_count;
self.best_match_row = best_match_row;
}
/// Toggle the expansion of the directory at `path`. Returns `true` if the
/// tree changed (caller should rebuild + set_content the buffer).
pub(crate) fn toggle(&mut self, path: &Path) -> bool {
if self.expanded.contains(path) {
self.expanded.remove(path);
} else {
self.expanded.insert(path.to_path_buf());
}
self.rebuild();
true
}
/// Collapse the directory at `path` (no-op if not expanded).
pub(crate) fn collapse(&mut self, path: &Path) {
self.expanded.remove(path);
self.rebuild();
}
pub(crate) fn is_expanded(&self, path: &Path) -> bool {
self.expanded.contains(path)
}
/// Flip `show_hidden` and rebuild.
pub(crate) fn toggle_hidden(&mut self) {
self.show_hidden = !self.show_hidden;
self.rebuild();
}
/// Flip `respect_gitignore` (show/hide git-ignored entries) and rebuild.
pub(crate) fn toggle_gitignore(&mut self) {
self.respect_gitignore = !self.respect_gitignore;
self.rebuild();
}
/// Re-root the tree at `new_root`, preserving the existing `expanded` set.
/// The new root is automatically added to `expanded`.
pub(crate) fn set_root(&mut self, new_root: PathBuf) {
self.root = new_root.clone();
self.expanded.insert(new_root);
self.rebuild();
}
/// Expand all ancestor dirs of `path` and return its row in `self.nodes`,
/// or `None` if `path` is not under the root.
///
/// Robust to path-form differences (relative vs absolute, symlinked cwd):
/// the path is reduced to components relative to the root — trying a plain
/// `strip_prefix` first, then a canonicalized one — and the node path is
/// reconstructed as `root.join(rel)` so it matches how the tree builds node
/// paths (`read_dir` → `dir.join(name)`).
pub(crate) fn reveal(&mut self, path: &Path) -> Option<usize> {
// Determine `path` relative to root, tolerating canonicalization diffs.
let rel = path
.strip_prefix(&self.root)
.ok()
.map(|p| p.to_path_buf())
.or_else(|| {
let rc = std::fs::canonicalize(&self.root).ok()?;
let pc = std::fs::canonicalize(path).ok()?;
pc.strip_prefix(&rc).ok().map(|p| p.to_path_buf())
})?;
// Reconstruct the node path from the root + relative components, and
// expand every ancestor directory down to (and including) the root.
let mut target = self.root.clone();
for comp in rel.components() {
target = target.join(comp);
}
self.expanded.insert(self.root.clone());
let mut anc = target.parent();
while let Some(p) = anc {
self.expanded.insert(p.to_path_buf());
if p == self.root {
break;
}
anc = p.parent();
}
self.rebuild();
self.nodes.iter().position(|n| n.path == target)
}
/// Build the buffer text and line→node map for the current tree state.
///
/// Each line in the returned `String` corresponds to `nodes[i]`, so
/// `cursor_row` in the editor maps directly to `nodes[cursor_row]`.
pub(crate) fn render_text(&self, icons: hjkl_icons::IconMode) -> String {
let mut out = String::new();
for (i, node) in self.nodes.iter().enumerate() {
if i > 0 {
out.push('\n');
}
if node.depth == 0 {
// Root line: just the directory path (or name).
let name = node
.path
.file_name()
.map(|n| n.to_string_lossy().into_owned())
.unwrap_or_else(|| node.path.to_string_lossy().into_owned());
out.push(hjkl_icons::dir_icon_for_path(
&node.path,
self.is_expanded(&node.path),
icons,
));
out.push(' ');
out.push_str(&name);
} else {
// Guide columns for each ancestor level.
for &b in &node.branches {
out.push(if b { '│' } else { ' ' });
out.push(' ');
}
// Connector glyph.
out.push(if node.is_last { '└' } else { '├' });
out.push('╴');
// Icon + space + name.
let icon = if node.is_dir {
hjkl_icons::dir_icon_for_path(&node.path, self.is_expanded(&node.path), icons)
} else {
hjkl_icons::file_icon_for_path(&node.path, icons)
};
out.push(icon);
out.push(' ');
let name = node
.path
.file_name()
.map(|n| n.to_string_lossy().into_owned())
.unwrap_or_default();
out.push_str(&name);
}
}
out
}
}
// ── App-level explorer state ───────────────────────────────────────────────────
/// Tracks the open explorer window + slot so `toggle_explorer` can close it.
#[derive(Debug, Clone)]
pub(crate) struct ExplorerPane {
/// WindowId of the explorer window in the active tab's layout.
pub win_id: super::window::WindowId,
/// The tree model.
pub tree: ExplorerTree,
}
// ── Explorer search worker ─────────────────────────────────────────────────────
/// Job submitted to the explorer search worker.
pub(crate) struct ExplorerSearchJob {
/// Monotonic generation counter — used by the main thread to discard stale
/// results (only results whose `generation == explorer_search_gen` are applied).
pub generation: u64,
pub root: PathBuf,
pub query: String,
pub show_hidden: bool,
pub respect_gitignore: bool,
}
/// Result produced by the explorer search worker.
pub(crate) struct ExplorerSearchResult {
pub generation: u64,
pub query: String,
pub nodes: Vec<ExplorerNode>,
pub match_count: usize,
pub total_count: usize,
pub best_match_row: Option<usize>,
}
/// Background worker that runs the filtered fs walk off the UI thread.
///
/// One background thread services all submitted jobs. Jobs are coalesced
/// by processing only the **last** job in a drained batch (queries are
/// strictly latest-wins — no per-key map needed because there is only one
/// explorer search at a time). Results are sent back on an unbounded channel.
///
/// `Drop` closes the job channel (dropping `tx`) and then **joins** the
/// thread — this prevents teardown races with `libgit2`'s OpenSSL cleanup
/// (same rationale as `BlameWorker`).
pub(crate) struct ExplorerSearchWorker {
tx: Option<Sender<ExplorerSearchJob>>,
rx: Receiver<ExplorerSearchResult>,
join: Option<thread::JoinHandle<()>>,
}
impl ExplorerSearchWorker {
/// Spawn the worker thread. Returns immediately.
pub(crate) fn new() -> Self {
let (job_tx, job_rx) = crossbeam_channel::unbounded::<ExplorerSearchJob>();
let (res_tx, res_rx) = crossbeam_channel::unbounded::<ExplorerSearchResult>();
let handle = thread::Builder::new()
.name("hjkl-explorer-search".into())
.spawn(move || explorer_search_worker_loop(job_rx, res_tx))
.expect("spawn explorer-search worker");
Self {
tx: Some(job_tx),
rx: res_rx,
join: Some(handle),
}
}
/// Submit a search job. Non-blocking.
pub(crate) fn submit(&self, job: ExplorerSearchJob) {
if let Some(tx) = self.tx.as_ref() {
let _ = tx.send(job);
}
}
/// Non-blocking drain. Returns the next completed result, if any.
pub(crate) fn try_recv(&self) -> Option<ExplorerSearchResult> {
self.rx.try_recv().ok()
}
}
impl Drop for ExplorerSearchWorker {
fn drop(&mut self) {
// Close the sender first — the worker's `recv()` will return `Err`
// and the loop will exit cleanly.
drop(self.tx.take());
if let Some(h) = self.join.take() {
let _ = h.join();
}
}
}
impl Default for ExplorerSearchWorker {
fn default() -> Self {
Self::new()
}
}
/// Main loop executed on the worker thread.
///
/// Blocks on `recv()` until a job arrives, then drains all
/// immediately-available additional jobs with `try_recv()` and
/// **processes only the last one** (highest index — pure coalesce; earlier
/// queries are stale). Builds the filtered tree via
/// `ExplorerTree::for_search`, which creates the `git2::Repository` on
/// this thread (never sent across a channel). Loops until the sender is
/// dropped.
fn explorer_search_worker_loop(
job_rx: Receiver<ExplorerSearchJob>,
res_tx: Sender<ExplorerSearchResult>,
) {
loop {
// Block until at least one job arrives (or channel closes).
let first = match job_rx.recv() {
Ok(j) => j,
Err(_) => return, // sender dropped → exit
};
// Drain all immediately-available additional jobs without blocking,
// then keep only the last one (latest-wins coalescing).
let mut last = first;
while let Ok(j) = job_rx.try_recv() {
last = j;
}
// Run the filtered fs walk on the worker thread.
let tree = ExplorerTree::for_search(
last.root,
last.show_hidden,
last.respect_gitignore,
last.query.clone(),
);
let result = ExplorerSearchResult {
generation: last.generation,
query: last.query,
match_count: tree.match_count,
total_count: tree.total_count,
best_match_row: tree.best_match_row,
nodes: tree.nodes,
};
if res_tx.send(result).is_err() {
// Receiver dropped → UI is gone. Exit.
return;
}
}
}
// ── App methods ────────────────────────────────────────────────────────────────
use hjkl_engine::Host;
impl super::App {
/// `true` when the focused window's slot is the explorer buffer.
pub(crate) fn explorer_buf_focused(&self) -> bool {
let fw = self.focused_window();
self.windows
.get(fw)
.and_then(|w| w.as_ref())
.map(|w| self.slots.get(w.slot).is_some_and(|s| s.is_explorer))
.unwrap_or(false)
}
/// `<leader>e` toggle: closed → open + focus; open → close.
pub(crate) fn toggle_explorer(&mut self) {
if self.explorer.is_some() {
self.close_explorer();
} else {
self.open_explorer();
}
}
/// Open the explorer window (left vertical split of the current tab).
fn open_explorer(&mut self) {
use super::STATUS_LINE_HEIGHT;
use super::window::{LayoutTree, SplitDir, Window};
use crate::host::TuiHost;
use hjkl_buffer::Buffer;
use hjkl_engine::{BufferEdit, Editor, Host, Options};
use std::time::Instant;
// Capture the file the user was editing so we can reveal it.
let active_file = self.active().filename.clone();
let cwd = std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."));
let mut tree = ExplorerTree::new(cwd.clone());
// Reveal the active file's path before rendering, so the initial
// cursor lands on it.
let reveal_row: Option<usize> = active_file.as_deref().and_then(|p| {
// Only reveal when the file is under cwd.
if p.starts_with(&cwd) {
tree.reveal(p)
} else {
None
}
});
let text = tree.render_text(self.icon_mode);
// Nodes are rebuilt by new() above; no extra rebuild needed.
let buffer_id = self.next_buffer_id;
self.next_buffer_id += 1;
let host = TuiHost::new();
let mut editor = Editor::new(
Buffer::new(),
host,
Options {
readonly: true,
..Options::default()
},
);
if let Ok(size) = crossterm::terminal::size() {
let h = size.1.saturating_sub(STATUS_LINE_HEIGHT);
let vp = editor.host_mut().viewport_mut();
vp.width = super::explorer::EXPLORER_WINDOW_WIDTH;
vp.height = h;
}
editor.set_current_buffer_id(buffer_id);
if !text.is_empty() {
BufferEdit::replace_all(editor.buffer_mut(), &text);
}
editor.set_filetype("explorer");
// Settings for the explorer: no line numbers, no sign column, cursorline on.
{
let s = editor.settings_mut();
s.number = false;
s.relativenumber = false;
s.signcolumn = hjkl_engine::types::SignColumnMode::No;
s.cursorline = true;
s.foldcolumn = 0;
}
let _ = editor.take_content_edits();
let _ = editor.take_content_reset();
let slot = super::BufferSlot {
buffer_id,
is_explorer: true,
features: super::BufferFeatures {
syntax: false,
lsp: false,
hover: false,
end_of_buffer: false,
},
editor,
filename: None,
dirty: false,
is_new_file: false,
is_untracked: false,
diag_signs: Vec::new(),
diag_signs_lsp: Vec::new(),
lsp_diags: Vec::new(),
last_lsp_dirty_gen: None,
git_signs: Vec::new(),
last_git_dirty_gen: None,
last_git_refresh_at: Instant::now(),
blame: Vec::new(),
last_blame_dirty_gen: None,
last_blame_refresh_at: Instant::now(),
saved_hash: 0,
saved_len: 0,
signature_cache: None,
disk_mtime: None,
disk_len: None,
disk_state: super::DiskState::Synced,
swap_path: None,
last_swap_dirty_gen: None,
last_fold_dirty_gen: None,
};
self.slots.push(slot);
let slot_idx = self.slots.len() - 1;
let new_win_id = self.next_window_id;
self.next_window_id += 1;
self.windows.push(Some(Window::new(slot_idx)));
// Splice a left vertical split: new explorer window on the left,
// existing layout on the right.
let total_w = crossterm::terminal::size()
.map(|(w, _)| w as usize)
.unwrap_or(80);
let ratio_a = (EXPLORER_WINDOW_WIDTH as f32 / total_w as f32).clamp(0.05, 0.45);
let ratio_b = 1.0 - ratio_a;
let _ = ratio_b; // ratio_a is the left side
// Save the outgoing window's cursor/scroll before changing the layout.
self.sync_viewport_from_editor();
let old_layout = self.take_layout();
let new_layout = LayoutTree::Split {
dir: SplitDir::Vertical,
ratio: ratio_a,
a: Box::new(LayoutTree::Leaf(new_win_id)),
b: Box::new(old_layout),
last_rect: None,
};
self.restore_layout(new_layout);
// Focus the new explorer window.
self.set_focused_window(new_win_id);
self.sync_viewport_to_editor();
self.explorer = Some(ExplorerPane {
win_id: new_win_id,
tree,
});
// Apply the reveal cursor position if we found the active file.
if let Some(row) = reveal_row {
if let Some(Some(win)) = self.windows.get_mut(new_win_id) {
win.cursor_row = row;
win.cursor_col = 0;
}
self.sync_viewport_to_explorer_editor();
}
}
/// Current slot index of the explorer's scratch buffer, found by its
/// `is_explorer` flag (robust to slot re-indexing from `:bd`/`:bn`).
fn explorer_slot_idx(&self) -> Option<usize> {
self.slots.iter().position(|s| s.is_explorer)
}
/// Close the explorer window and remove its slot.
fn close_explorer(&mut self) {
let Some(ep) = self.explorer.take() else {
return;
};
let new_focus = match self.layout_mut().remove_leaf(ep.win_id) {
Ok(f) => f,
Err(_) => return,
};
self.windows[ep.win_id] = None;
if let Some(slot_idx) = self.explorer_slot_idx() {
self.slots.remove(slot_idx);
let slot_count = self.slots.len();
for win in self.windows.iter_mut().flatten() {
if win.slot == slot_idx {
win.slot = 0;
} else if win.slot > slot_idx {
win.slot -= 1;
}
win.slot = win.slot.min(slot_count.saturating_sub(1));
}
}
self.set_focused_window(new_focus);
self.sync_viewport_to_editor();
}
/// Rebuild the explorer buffer text (after expand/collapse). Keeps the
/// cursor row on the same path when possible.
pub(crate) fn explorer_rebuild_buffer(&mut self) {
let Some(slot_idx) = self.explorer_slot_idx() else {
return;
};
let icons = self.icon_mode;
let (text, win_id) = match self.explorer.as_ref() {
Some(ep) => (ep.tree.render_text(icons), ep.win_id),
None => return,
};
// Stash the path currently under cursor before we rebuild.
let prev_row = self
.windows
.get(win_id)
.and_then(|w| w.as_ref())
.map(|w| w.cursor_row)
.unwrap_or(0);
let prev_path = self
.explorer
.as_ref()
.and_then(|ep| ep.tree.nodes.get(prev_row))
.map(|n| n.path.clone());
// Write new content directly (bypasses readonly guard intentionally).
self.slots[slot_idx].editor.set_content(&text);
let _ = self.slots[slot_idx].editor.take_content_edits();
let _ = self.slots[slot_idx].editor.take_content_reset();
// Try to keep cursor on the same path.
let new_row = if let Some(ref p) = prev_path {
self.explorer
.as_ref()
.and_then(|ep| ep.tree.nodes.iter().position(|n| &n.path == p))
.unwrap_or(prev_row)
} else {
prev_row
};
if let Some(Some(win)) = self.windows.get_mut(win_id) {
win.cursor_row = new_row.min(
self.explorer
.as_ref()
.map(|ep| ep.tree.nodes.len().saturating_sub(1))
.unwrap_or(0),
);
win.cursor_col = 0;
}
// Sync the editor cursor to match the window snapshot.
let fw = self.focused_window();
if fw == win_id {
self.sync_viewport_to_explorer_editor();
}
}
/// Sync the explorer editor's cursor from the explorer window's snapshot.
/// Like `sync_viewport_to_editor` but only for the explorer slot.
pub(crate) fn sync_viewport_to_explorer_editor(&mut self) {
let Some(ref ep) = self.explorer else { return };
let win_id = ep.win_id;
let Some(slot_idx) = self.slots.iter().position(|s| s.is_explorer) else {
return;
};
let (row, col, top) = {
let win = self.windows.get(win_id).and_then(|w| w.as_ref());
match win {
Some(w) => (w.cursor_row, w.cursor_col, w.top_row),
None => return,
}
};
let editor = &mut self.slots[slot_idx].editor;
editor.jump_cursor(row, col);
let vp = editor.host_mut().viewport_mut();
vp.top_row = top;
}
/// "Follow" the active buffer in the explorer: when the explorer is open,
/// reveal the active buffer's file (expand its ancestors) and move the
/// explorer's selection to it — so the buffer you're editing is the
/// highlighted row in the tree. Does NOT change window focus. No-op for
/// scratch buffers or files outside the tree root.
pub(crate) fn explorer_reveal_active(&mut self) {
if self.explorer.is_none() {
return;
}
let Some(fname) = self.active().filename.clone() else {
return;
};
// Tree nodes are absolute (root = cwd); the active filename may be cwd-
// relative. Resolve to absolute before matching.
let abs = if fname.is_absolute() {
fname
} else {
std::env::current_dir()
.map(|c| c.join(&fname))
.unwrap_or(fname)
};
let win_id;
let row;
{
let Some(ep) = self.explorer.as_mut() else {
return;
};
if !abs.starts_with(&ep.tree.root) {
return; // file isn't under the explorer's root
}
win_id = ep.win_id;
row = ep.tree.reveal(&abs);
}
self.explorer_rebuild_buffer();
if let Some(r) = row {
if let Some(Some(win)) = self.windows.get_mut(win_id) {
win.cursor_row = r;
win.cursor_col = 0;
// Scroll the explorer window so the revealed row stays in
// view. The window's per-window `top_row` is independent of
// any other window on the same buffer, so this only moves
// the explorer's viewport — a second window showing the same
// slot is unaffected. Without this the cursor can land off
// the bottom/top of the pane after a buffer switch.
let height = win.last_rect.map(|rc| rc.h as usize).unwrap_or(0);
if height > 0 {
if r < win.top_row {
win.top_row = r;
} else if r >= win.top_row + height {
win.top_row = r + 1 - height;
}
}
}
// Sync the explorer editor cursor so the (usually unfocused)
// cursorline highlights the revealed row.
self.sync_viewport_to_explorer_editor();
}
}
/// Enter/l/o on the explorer: toggle dir or open file.
pub(crate) fn explorer_activate(&mut self) {
// Determine the cursor row in the explorer window.
let cursor_row = {
let ep = self.explorer.as_ref().unwrap();
let win = self.windows.get(ep.win_id).and_then(|w| w.as_ref());
win.map(|w| w.cursor_row).unwrap_or(0)
};
// Get the node at cursor.
let node = self
.explorer
.as_ref()
.and_then(|ep| ep.tree.nodes.get(cursor_row))
.cloned();
let Some(node) = node else { return };
if node.is_dir {
// Toggle dir expansion and rebuild buffer.
let path = node.path.clone();
if let Some(ref mut ep) = self.explorer {
ep.tree.toggle(&path);
}
self.explorer_rebuild_buffer();
} else {
// File: open in the nearest non-explorer window.
let target_win = self.nearest_non_explorer_window();
if let Some(win_id) = target_win {
self.switch_focus(win_id);
}
let s = Self::explorer_open_arg(&node.path);
self.dispatch_ex(&format!("edit {s}"));
}
}
/// h/Left: collapse expanded dir or move to parent line.
pub(crate) fn explorer_collapse(&mut self) {
let cursor_row = {
let ep = self.explorer.as_ref().unwrap();
let win = self.windows.get(ep.win_id).and_then(|w| w.as_ref());
win.map(|w| w.cursor_row).unwrap_or(0)
};
let node = self
.explorer
.as_ref()
.and_then(|ep| ep.tree.nodes.get(cursor_row))
.cloned();
let Some(node) = node else { return };
if node.is_dir
&& let Some(ref ep) = self.explorer
&& ep.tree.is_expanded(&node.path)
{
let path = node.path.clone();
if let Some(ref mut ep) = self.explorer {
ep.tree.collapse(&path);
}
self.explorer_rebuild_buffer();
return;
}
// Move cursor to the parent row.
if node.depth == 0 {
return;
}
let target_depth = node.depth - 1;
let parent_row = self.explorer.as_ref().and_then(|ep| {
ep.tree.nodes[..cursor_row]
.iter()
.rposition(|n| n.depth == target_depth)
});
if let Some(row) = parent_row {
let ep = self.explorer.as_ref().unwrap();
let win_id = ep.win_id;
if let Some(Some(win)) = self.windows.get_mut(win_id) {
win.cursor_row = row;
win.cursor_col = 0;
}
let fw = self.focused_window();
if fw == win_id {
self.sync_viewport_to_explorer_editor();
}
}
}
/// Find the nearest non-explorer window in the active tab's layout.
pub(crate) fn nearest_non_explorer_window(&self) -> Option<super::window::WindowId> {
let leaves = self.layout().leaves();
let explorer_win = self.explorer.as_ref().map(|ep| ep.win_id);
// Prefer the currently focused non-explorer window.
let fw = self.focused_window();
if Some(fw) != explorer_win {
return Some(fw);
}
// Fall back to the first non-explorer leaf.
leaves
.into_iter()
.find(|&win_id| Some(win_id) != explorer_win)
}
// ── Cursor-node helpers ───────────────────────────────────────────────────
/// Return the node currently under the explorer cursor.
fn explorer_cursor_node(&self) -> Option<ExplorerNode> {
let ep = self.explorer.as_ref()?;
let win = self.windows.get(ep.win_id)?.as_ref()?;
ep.tree.nodes.get(win.cursor_row).cloned()
}
/// Path string for an `:edit`/`:split`/… open command. Relative to the cwd
/// when the file is under it (so buffer names match normally-opened files
/// instead of showing absolute paths in the picker / buffer line), else
/// absolute.
fn explorer_open_arg(path: &Path) -> String {
if let Ok(cwd) = std::env::current_dir()
&& let Ok(rel) = path.strip_prefix(&cwd)
{
return rel.to_string_lossy().into_owned();
}
path.to_string_lossy().into_owned()
}
/// Resolve the "target directory" for create / paste from the cursor node:
/// - dir node → that directory
/// - file node → parent of file
/// - root node with no parent → root
fn explorer_target_dir(node: &ExplorerNode) -> PathBuf {
if node.is_dir {
node.path.clone()
} else {
node.path
.parent()
.map(|p| p.to_path_buf())
.unwrap_or_else(|| node.path.clone())
}
}
// ── Refresh / hidden / root ───────────────────────────────────────────────
/// Re-read the filesystem and rebuild the buffer (preserves cursor path).
pub(crate) fn explorer_refresh(&mut self) {
if let Some(ref mut ep) = self.explorer {
ep.tree.rebuild();
}
self.explorer_rebuild_buffer();
}
/// Toggle dotfile visibility and rebuild.
pub(crate) fn explorer_toggle_hidden(&mut self) {
if let Some(ref mut ep) = self.explorer {
ep.tree.toggle_hidden();
}
self.explorer_rebuild_buffer();
}
/// Toggle git-ignore honoring (show/hide ignored entries) and rebuild.
pub(crate) fn explorer_toggle_gitignore(&mut self) {
if let Some(ref mut ep) = self.explorer {
ep.tree.toggle_gitignore();
}
self.explorer_rebuild_buffer();
}
/// Move the tree root up to its parent directory.
pub(crate) fn explorer_root_up(&mut self) {
let parent = self
.explorer
.as_ref()
.and_then(|ep| ep.tree.root.parent().map(|p| p.to_path_buf()));
if let Some(parent) = parent {
if let Some(ref mut ep) = self.explorer {
ep.tree.set_root(parent);
}
self.explorer_rebuild_buffer();
}
}
// ── Open modes ───────────────────────────────────────────────────────────
/// Open the file under cursor in a horizontal split.
pub(crate) fn explorer_open_split(&mut self) {
let node = match self.explorer_cursor_node() {
Some(n) if !n.is_dir => n,
_ => return,
};
if let Some(win_id) = self.nearest_non_explorer_window() {
self.switch_focus(win_id);
}
let s = Self::explorer_open_arg(&node.path);
self.dispatch_ex(&format!("split {s}"));
}
/// Open the file under cursor in a vertical split.
pub(crate) fn explorer_open_vsplit(&mut self) {
let node = match self.explorer_cursor_node() {
Some(n) if !n.is_dir => n,
_ => return,
};
if let Some(win_id) = self.nearest_non_explorer_window() {
self.switch_focus(win_id);
}
let s = Self::explorer_open_arg(&node.path);
self.dispatch_ex(&format!("vsplit {s}"));
}
/// Open the file under cursor in a new tab.
pub(crate) fn explorer_open_tab(&mut self) {
let node = match self.explorer_cursor_node() {
Some(n) if !n.is_dir => n,
_ => return,
};
let s = Self::explorer_open_arg(&node.path);
self.dispatch_ex(&format!("tabnew {s}"));
}
// ── File operations ───────────────────────────────────────────────────────
/// `a` — open a create prompt. Name ending with `/` creates a directory.
pub(crate) fn explorer_create(&mut self) {
let node = match self.explorer_cursor_node() {
Some(n) => n,
None => return,
};
let base = Self::explorer_target_dir(&node);
let mut field = hjkl_form::TextFieldEditor::new(true);
field.enter_insert_at_end();
self.explorer_prompt = Some(ExplorerPrompt {
kind: ExplorerPromptKind::Create,
field,
base,
});
}
/// `r` — open a rename prompt prefilled with the current filename.
pub(crate) fn explorer_rename(&mut self) {
let node = match self.explorer_cursor_node() {
Some(n) => n,
None => return,
};
if node.depth == 0 {
return; // Don't rename the root.
}
let from = node.path.clone();
let base = from
.parent()
.map(|p| p.to_path_buf())
.unwrap_or_else(|| from.clone());
let prefill = from
.file_name()
.map(|n| n.to_string_lossy().into_owned())
.unwrap_or_default();
let mut field = hjkl_form::TextFieldEditor::new(true);
field.enter_insert_at_end();
// Seed the field with the current filename.
for c in prefill.chars() {
let input = hjkl_engine::Input {
key: hjkl_engine::Key::Char(c),
ctrl: false,
alt: false,
shift: false,
};
field.handle_input(input);
}
self.explorer_prompt = Some(ExplorerPrompt {
kind: ExplorerPromptKind::Rename { from },
field,
base,
});
}
/// `d` — open a delete confirmation prompt.
pub(crate) fn explorer_delete(&mut self) {
let node = match self.explorer_cursor_node() {
Some(n) => n,
None => return,
};
if node.depth == 0 {
return; // Refuse to delete the root.
}
self.explorer_confirm = Some(ExplorerConfirm {
path: node.path,
is_dir: node.is_dir,
});
}
/// `y` — copy the node under cursor to the clipboard.
pub(crate) fn explorer_copy(&mut self) {
let node = match self.explorer_cursor_node() {
Some(n) => n,
None => return,
};
if node.depth == 0 {
return;
}
let name = node
.path
.file_name()
.map(|n| n.to_string_lossy().into_owned())
.unwrap_or_default();
self.bus.info(format!("Copied: {name}"));
self.explorer_clip = Some(ExplorerClip {
path: node.path,
cut: false,
});
}
/// `x` — cut the node under cursor (move on paste).
pub(crate) fn explorer_cut(&mut self) {
let node = match self.explorer_cursor_node() {
Some(n) => n,
None => return,
};
if node.depth == 0 {
return;
}
let name = node
.path
.file_name()
.map(|n| n.to_string_lossy().into_owned())
.unwrap_or_default();
self.bus.info(format!("Cut: {name}"));
self.explorer_clip = Some(ExplorerClip {
path: node.path,
cut: true,
});
}
/// `p` — paste from clipboard into the target directory.
pub(crate) fn explorer_paste(&mut self) {
let clip = match self.explorer_clip.clone() {
Some(c) => c,
None => {
self.bus.info("Nothing to paste");
return;
}
};
let node = match self.explorer_cursor_node() {
Some(n) => n,
None => return,
};
let dest_dir = Self::explorer_target_dir(&node);
let file_name = match clip.path.file_name() {
Some(n) => n,
None => {
self.bus.error("Cannot paste: source has no filename");
return;
}
};
let dest = dest_dir.join(file_name);
if clip.cut {
// Move: try rename first (same device), fall back to copy+remove.
if let Err(e) = std::fs::rename(&clip.path, &dest) {
// Cross-device: copy then remove.
if copy_recursive(&clip.path, &dest).is_err() {
self.bus.error(format!("Paste failed: {e}"));
return;
}
let _ = if clip.path.is_dir() {
std::fs::remove_dir_all(&clip.path)
} else {
std::fs::remove_file(&clip.path)
};
}
// Clear clip after cut-paste.
self.explorer_clip = None;
} else {
// Copy.
if let Err(e) = copy_recursive(&clip.path, &dest) {
self.bus.error(format!("Copy failed: {e}"));
return;
}
}
self.explorer_refresh();
// Reveal the destination.
if let Some(ref mut ep) = self.explorer {
let row = ep.tree.reveal(&dest);
let win_id = ep.win_id;
if let (Some(row), Some(Some(win))) = (row, self.windows.get_mut(win_id)) {
win.cursor_row = row;
win.cursor_col = 0;
}
}
self.explorer_rebuild_buffer();
}
// ── Prompt commit helpers ─────────────────────────────────────────────────
/// Called when the user presses Enter in a Create prompt.
pub(crate) fn explorer_commit_create(&mut self, name: String) {
let base = match self.explorer_prompt.as_ref() {
Some(ep) => ep.base.clone(),
None => return,
};
self.explorer_prompt = None;
let new_path = base.join(&name);
let result = if name.ends_with('/') {
std::fs::create_dir_all(&new_path)
} else {
// Ensure parent dirs exist, then create the file.
if let Some(parent) = new_path.parent()
&& let Err(e) = std::fs::create_dir_all(parent)
{
self.bus.error(format!("Create failed: {e}"));
return;
}
std::fs::File::create(&new_path).map(|_| ())
};
match result {
Ok(()) => {
self.explorer_refresh();
// Expand the base dir and reveal the new path.
if let Some(ref mut ep) = self.explorer {
ep.tree.expanded.insert(base.clone());
let row = ep.tree.reveal(&new_path);
let win_id = ep.win_id;
if let (Some(row), Some(Some(win))) = (row, self.windows.get_mut(win_id)) {
win.cursor_row = row;
win.cursor_col = 0;
}
}
self.explorer_rebuild_buffer();
}
Err(e) => {
self.bus.error(format!("Create failed: {e}"));
}
}
}
/// Called when the user presses Enter in a Rename prompt.
pub(crate) fn explorer_commit_rename(&mut self, new_name: String) {
let (from, base) = match self.explorer_prompt.as_ref() {
Some(ep) => match &ep.kind {
ExplorerPromptKind::Rename { from } => (from.clone(), ep.base.clone()),
_ => return,
},
None => return,
};
self.explorer_prompt = None;
let dest = base.join(&new_name);
match std::fs::rename(&from, &dest) {
Ok(()) => {
self.explorer_refresh();
if let Some(ref mut ep) = self.explorer {
let row = ep.tree.reveal(&dest);
let win_id = ep.win_id;
if let (Some(row), Some(Some(win))) = (row, self.windows.get_mut(win_id)) {
win.cursor_row = row;
win.cursor_col = 0;
}
}
self.explorer_rebuild_buffer();
}
Err(e) => {
self.bus.error(format!("Rename failed: {e}"));
}
}
}
/// Called when the user confirms deletion with `y`.
pub(crate) fn explorer_commit_delete(&mut self) {
let confirm = match self.explorer_confirm.take() {
Some(c) => c,
None => return,
};
let result = if confirm.is_dir {
std::fs::remove_dir_all(&confirm.path)
} else {
std::fs::remove_file(&confirm.path)
};
match result {
Ok(()) => {
self.explorer_refresh();
}
Err(e) => {
self.bus.error(format!("Delete failed: {e}"));
}
}
}
// ── Prompt / confirm key handlers ─────────────────────────────────────────
/// Route a key when `explorer_prompt` is active.
pub(crate) fn handle_explorer_prompt_key(&mut self, key: crossterm::event::KeyEvent) {
use crossterm::event::KeyCode;
match key.code {
KeyCode::Esc => {
self.explorer_prompt = None;
}
KeyCode::Enter => {
let (kind, name) = match self.explorer_prompt.as_ref() {
Some(ep) => {
let name = ep.field.text();
(ep.kind.clone(), name)
}
None => return,
};
match kind {
ExplorerPromptKind::Create => {
self.explorer_commit_create(name);
}
ExplorerPromptKind::Rename { .. } => {
self.explorer_commit_rename(name);
}
}
}
_ => {
// Forward to the text field.
let input = hjkl_engine_tui::crossterm_to_input(key);
if let Some(ref mut ep) = self.explorer_prompt {
ep.field.handle_input(input);
}
}
}
}
/// Route a key when `explorer_confirm` (delete) is active.
pub(crate) fn handle_explorer_confirm_key(&mut self, key: crossterm::event::KeyEvent) {
use crossterm::event::KeyCode;
match key.code {
// Accept either case regardless of whether SHIFT is reported.
KeyCode::Char('y') | KeyCode::Char('Y') => {
self.explorer_commit_delete();
}
KeyCode::Char('n') | KeyCode::Char('N') | KeyCode::Esc => {
self.explorer_confirm = None;
}
_ => {} // consume but do nothing
}
}
// ── Explorer search (fuzzy filter) ────────────────────────────────────────
/// Open the explorer's vim-editable fuzzy-filter field. The field is seeded
/// with any committed filter query so re-focusing keeps the current search
/// visible (Enter commits without clearing; only Esc cancels). `insert`
/// picks the starting mode: `true` (via `/` or click) drops straight into
/// insert; `false` (via `k` from the top row) lands in normal mode so `j`
/// moves back down into the tree.
pub(crate) fn open_explorer_search(&mut self, insert: bool) {
// Seed from the committed filter so the box keeps showing it.
let seed = self
.explorer
.as_ref()
.and_then(|ep| ep.tree.filter.clone())
.unwrap_or_default();
let mut field = hjkl_form::TextFieldEditor::new(true);
field.enter_insert_at_end();
for c in seed.chars() {
field.handle_input(hjkl_engine::Input {
key: hjkl_engine::Key::Char(c),
ctrl: false,
alt: false,
shift: false,
});
}
if !insert {
field.enter_normal();
}
self.explorer_search = Some(field);
}
/// Re-filter the tree from the current field text and move cursor to the
/// first matched file row.
#[allow(dead_code)]
/// Move the explorer cursor to the highest-scoring match
/// (`tree.best_match_row`), falling back to the first matched file row.
pub(crate) fn explorer_cursor_to_best_match(&mut self) {
let target = self.explorer.as_ref().and_then(|ep| {
ep.tree
.best_match_row
.or_else(|| ep.tree.nodes.iter().position(|n| !n.is_dir))
});
let win_id = self.explorer.as_ref().map(|ep| ep.win_id);
if let (Some(row), Some(win_id)) = (target, win_id) {
if let Some(Some(win)) = self.windows.get_mut(win_id) {
win.cursor_row = row;
win.cursor_col = 0;
}
let fw = self.focused_window();
if fw == win_id {
self.sync_viewport_to_explorer_editor();
}
}
}
/// Key handler while `explorer_search` is active — mirrors
/// `handle_search_field_key` minus history / `<C-f>`.
pub(crate) fn handle_explorer_search_key(&mut self, key: crossterm::event::KeyEvent) {
use hjkl_engine::{Key as EngineKey, VimMode};
let input = hjkl_engine_tui::crossterm_to_input(key);
// Enter → commit (close the field, keep filter). Clear the pending
// debounce and bump gen so any in-flight worker result is dropped —
// the committed filter is already installed from the last applied result.
if input.key == EngineKey::Enter {
// If a debounce was still pending (typed fast, then Enter before it
// fired), apply the final query synchronously so the committed
// filter reflects exactly what was typed.
if let Some(q) = self.explorer_search_pending_query.take() {
if let Some(ref mut ep) = self.explorer {
ep.tree.apply_filter(&q);
}
self.explorer_rebuild_buffer();
self.explorer_cursor_to_best_match();
}
self.explorer_search = None;
self.explorer_search_dirty_at = None;
self.explorer_search_pending_query = None;
self.explorer_search_gen = self.explorer_search_gen.wrapping_add(1);
return;
}
// Esc logic:
// - empty field → cancel (clear filter + close)
// - Insert mode → enter Normal mode
// - Normal mode, non-empty → cancel (clear filter + close)
if input.key == EngineKey::Esc {
let (is_empty, is_insert) = match self.explorer_search.as_ref() {
Some(f) => (f.text().is_empty(), f.vim_mode() == VimMode::Insert),
None => return,
};
if is_empty || !is_insert {
// Cancel: close + clear filter + clear pending debounce.
self.explorer_search = None;
self.explorer_search_dirty_at = None;
self.explorer_search_pending_query = None;
self.explorer_search_gen = self.explorer_search_gen.wrapping_add(1);
if let Some(ref mut ep) = self.explorer {
ep.tree.clear_filter();
}
self.explorer_rebuild_buffer();
} else {
// Insert → Normal.
if let Some(ref mut f) = self.explorer_search {
f.enter_normal();
}
}
return;
}
// In NORMAL mode, `j`/Down returns focus to the tree (keeps the
// committed filter — this is navigation, not a cancel).
{
use crossterm::event::KeyCode;
let in_normal = self
.explorer_search
.as_ref()
.map(|f| f.vim_mode() == VimMode::Normal)
.unwrap_or(false);
if in_normal && matches!(key.code, KeyCode::Char('j') | KeyCode::Down) {
self.explorer_search = None;
self.explorer_search_dirty_at = None;
self.explorer_search_pending_query = None;
self.explorer_search_gen = self.explorer_search_gen.wrapping_add(1);
return;
}
}
// Backspace on empty prompt → cancel.
if input.key == EngineKey::Backspace {
let is_empty = self
.explorer_search
.as_ref()
.map(|f| f.text().is_empty())
.unwrap_or(true);
if is_empty {
self.explorer_search = None;
self.explorer_search_dirty_at = None;
self.explorer_search_pending_query = None;
self.explorer_search_gen = self.explorer_search_gen.wrapping_add(1);
if let Some(ref mut ep) = self.explorer {
ep.tree.clear_filter();
}
self.explorer_rebuild_buffer();
return;
}
}
// Forward the key to the field; if content changed, schedule a
// debounced worker submission rather than filtering synchronously.
let dirty = match self.explorer_search.as_mut() {
Some(f) => f.handle_input(input),
None => return,
};
if dirty {
let text = self
.explorer_search
.as_ref()
.map(|f| f.text())
.unwrap_or_default();
self.explorer_search_pending_query = Some(text);
self.explorer_search_dirty_at = Some(Instant::now());
}
}
}
/// Width of the explorer window in columns.
pub(crate) const EXPLORER_WINDOW_WIDTH: u16 = 36;
/// Recursively copy `src` to `dst`. `src` may be a file or directory.
fn copy_recursive(src: &Path, dst: &Path) -> std::io::Result<()> {
if src.is_dir() {
std::fs::create_dir_all(dst)?;
for entry in std::fs::read_dir(src)? {
let entry = entry?;
let ty = entry.file_type()?;
let child_dst = dst.join(entry.file_name());
if ty.is_dir() {
copy_recursive(&entry.path(), &child_dst)?;
} else {
std::fs::copy(entry.path(), child_dst)?;
}
}
Ok(())
} else {
std::fs::copy(src, dst).map(|_| ())
}
}
// ── Tests ──────────────────────────────────────────────────────────────────────
#[cfg(test)]
mod tests {
use super::*;
use std::fs;
/// Build a unique temp dir tree:
/// root/{ a_dir/{ inner.txt }, b_dir/, m_file.txt, z_file.txt }
fn make_tree() -> PathBuf {
let base = std::env::temp_dir().join(format!("hjkl_explorer_test_{}", std::process::id()));
let _ = fs::remove_dir_all(&base);
fs::create_dir_all(base.join("a_dir")).unwrap();
fs::create_dir_all(base.join("b_dir")).unwrap();
fs::write(base.join("a_dir").join("inner.txt"), "x").unwrap();
fs::write(base.join("m_file.txt"), "x").unwrap();
fs::write(base.join("z_file.txt"), "x").unwrap();
base
}
/// Names of the non-root nodes.
fn child_names(tree: &ExplorerTree) -> Vec<String> {
tree.nodes[1..]
.iter()
.map(|n| n.path.file_name().unwrap().to_string_lossy().into_owned())
.collect()
}
/// End-to-end: `/` in the focused explorer opens the fuzzy-search field via
/// `handle_keypress`, typing applies a tree filter, and Esc cancels +
/// restores the unfiltered tree. Guards the full key path (not just the
/// `ExplorerTree::apply_filter` unit).
#[test]
fn slash_opens_search_typing_filters_esc_cancels() {
use crate::keymap_actions::AppAction;
use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
let mut app = super::super::App::new(None, false, None, None).unwrap();
app.dispatch_action(AppAction::ToggleExplorer, 1);
assert!(app.explorer.is_some(), "explorer should be open");
assert!(app.explorer_buf_focused(), "explorer should be focused");
// `/` opens the search field.
app.handle_keypress(KeyEvent::new(KeyCode::Char('/'), KeyModifiers::NONE));
assert!(
app.explorer_search.is_some(),
"`/` must open the explorer fuzzy-search field"
);
// Typing routes to the field and SCHEDULES a debounce (not synchronous
// filter) — the worker fires after EXPLORER_SEARCH_DEBOUNCE elapses.
app.handle_keypress(KeyEvent::new(KeyCode::Char('z'), KeyModifiers::NONE));
assert_eq!(
app.explorer_search_pending_query.as_deref(),
Some("z"),
"typing must schedule a debounce with the query"
);
assert!(
app.explorer_search_dirty_at.is_some(),
"typing must arm the debounce timer"
);
// Esc: insert→normal, then normal(non-empty)→cancel (close + clear).
// Cancel must also clear the pending debounce state.
app.handle_keypress(KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE));
app.handle_keypress(KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE));
assert!(
app.explorer_search.is_none(),
"Esc must close the search field"
);
assert!(
app.explorer_search_pending_query.is_none(),
"Esc must clear the pending query"
);
assert!(
app.explorer_search_dirty_at.is_none(),
"Esc must clear the debounce timer"
);
let filter2 = app.explorer.as_ref().and_then(|ep| ep.tree.filter.clone());
assert_eq!(filter2, None, "cancel must restore the unfiltered tree");
}
/// `ExplorerTree::for_search` constructs and walks a filtered tree without
/// spinning up a worker thread — exactly the code path the worker uses.
/// Query "buf" on the make_filter_tree fixture must yield 2 matches
/// (buffer_ops.rs, buffer_test.rs) plus their ancestor dirs.
#[test]
fn for_search_returns_filtered_tree() {
let root = make_filter_tree();
let tree = ExplorerTree::for_search(root.clone(), true, false, "buf".to_string());
let paths: Vec<String> = tree
.nodes
.iter()
.filter_map(|n| n.path.file_name().map(|f| f.to_string_lossy().into_owned()))
.collect();
assert_eq!(tree.match_count, 2, "match_count must be 2 (buf query)");
assert!(
paths.contains(&"buffer_ops.rs".to_string()),
"buffer_ops.rs must be present: {paths:?}"
);
assert!(
paths.contains(&"buffer_test.rs".to_string()),
"buffer_test.rs must be present: {paths:?}"
);
// Ancestor dirs must be included.
assert!(
paths.contains(&"src".to_string()),
"src dir must be present as ancestor: {paths:?}"
);
assert!(
paths.contains(&"tests".to_string()),
"tests dir must be present as ancestor: {paths:?}"
);
// Non-matching files must be absent.
assert!(
!paths.contains(&"main.rs".to_string()),
"main.rs must NOT be present: {paths:?}"
);
assert!(
!paths.contains(&"readme.md".to_string()),
"readme.md must NOT be present: {paths:?}"
);
let _ = fs::remove_dir_all(&root);
}
#[test]
fn root_first_then_dirs_first_then_name() {
let root = make_tree();
let tree = ExplorerTree::new(root.clone());
assert_eq!(tree.nodes[0].path, root);
assert!(tree.nodes[0].is_dir && tree.nodes[0].depth == 0);
assert_eq!(
child_names(&tree),
vec!["a_dir", "b_dir", "m_file.txt", "z_file.txt"]
);
let _ = fs::remove_dir_all(&root);
}
#[test]
fn expand_inserts_children_at_depth_with_guide() {
let root = make_tree();
let mut tree = ExplorerTree::new(root.clone());
let a_dir_path = tree.nodes[1].path.clone(); // a_dir
tree.toggle(&a_dir_path);
assert_eq!(
child_names(&tree),
vec!["a_dir", "inner.txt", "b_dir", "m_file.txt", "z_file.txt"]
);
let inner = &tree.nodes[2]; // root, a_dir, inner.txt
assert_eq!(inner.depth, 2);
assert!(!inner.is_dir);
assert_eq!(inner.branches, vec![true]);
let _ = fs::remove_dir_all(&root);
}
#[test]
fn last_child_flag() {
let root = make_tree();
let tree = ExplorerTree::new(root.clone());
assert!(!tree.nodes[1].is_last); // a_dir
let z = tree.nodes.last().unwrap();
assert_eq!(z.path.file_name().unwrap(), "z_file.txt");
assert!(z.is_last);
let _ = fs::remove_dir_all(&root);
}
#[test]
fn collapse_removes_subtree() {
let root = make_tree();
let mut tree = ExplorerTree::new(root.clone());
let a_dir_path = tree.nodes[1].path.clone();
tree.toggle(&a_dir_path); // expand
assert_eq!(tree.nodes.len(), 6); // root + 4 + inner
tree.collapse(&a_dir_path);
assert_eq!(
child_names(&tree),
vec!["a_dir", "b_dir", "m_file.txt", "z_file.txt"]
);
let _ = fs::remove_dir_all(&root);
}
#[test]
fn render_text_line_count_matches_nodes() {
let root = make_tree();
let tree = ExplorerTree::new(root.clone());
let text = tree.render_text(hjkl_icons::IconMode::Nerd);
let line_count = text.lines().count();
assert_eq!(
line_count,
tree.nodes.len(),
"render_text line count must equal node count"
);
let _ = fs::remove_dir_all(&root);
}
#[test]
fn render_text_line_count_after_expand() {
let root = make_tree();
let mut tree = ExplorerTree::new(root.clone());
let a_dir_path = tree.nodes[1].path.clone();
tree.toggle(&a_dir_path);
let text = tree.render_text(hjkl_icons::IconMode::Nerd);
let line_count = text.lines().count();
assert_eq!(line_count, tree.nodes.len());
let _ = fs::remove_dir_all(&root);
}
#[test]
fn toggle_explorer_creates_window_and_is_explorer_slot() {
use crate::keymap_actions::AppAction;
let mut app = super::super::App::new(None, false, None, None).unwrap();
assert!(app.explorer.is_none());
// Open explorer.
app.dispatch_action(AppAction::ToggleExplorer, 1);
assert!(app.explorer.is_some(), "explorer should be open");
assert!(
app.slots.iter().any(|s| s.is_explorer),
"explorer slot must have is_explorer = true"
);
// Close explorer.
app.dispatch_action(AppAction::ToggleExplorer, 1);
assert!(app.explorer.is_none(), "explorer should be closed");
}
#[test]
fn buffer_line_click_maps_past_interleaved_explorer_slot() {
use crate::app::mouse::{Zone, buffer_line_x_ranges, hit_test_zone};
use crate::keymap_actions::AppAction;
let pid = std::process::id();
let f0 = std::env::temp_dir().join(format!("hjkl_bl_a_{pid}.txt"));
let f1 = std::env::temp_dir().join(format!("hjkl_bl_b_{pid}.txt"));
std::fs::write(&f0, "a").unwrap();
std::fs::write(&f1, "b").unwrap();
let mut app = super::super::App::new(Some(f0.clone()), false, None, None).unwrap();
// Open the explorer so its slot lands BETWEEN the two file slots.
app.dispatch_action(AppAction::ToggleExplorer, 1); // slot 1 = explorer
app.dispatch_action(AppAction::FocusRight, 1); // focus the editor window
app.dispatch_ex(&format!("edit {}", f1.display())); // slot 2 = f1
// Buffer line shows f0, f1 (explorer skipped). Clicking the LAST entry
// must resolve to f1's real slot — NOT the interleaved explorer slot.
let ranges = buffer_line_x_ranges(&app, 80);
assert!(ranges.len() >= 2, "expected >=2 entries, got {ranges:?}");
let col = ranges[ranges.len() - 1].0;
match hit_test_zone(&app, col, 0) {
Zone::BufferLine { slot_idx } => {
assert!(
!app.slots[slot_idx].is_explorer,
"buffer-line click must not map to the explorer slot"
);
assert_eq!(
app.slots[slot_idx].filename.as_deref(),
Some(f1.as_path()),
"last buffer-line entry must map to f1"
);
}
other => panic!("expected BufferLine zone, got {other:?}"),
}
let _ = std::fs::remove_file(&f0);
let _ = std::fs::remove_file(&f1);
}
#[test]
fn switch_to_never_targets_the_explorer_window() {
use crate::keymap_actions::AppAction;
let f1 = std::env::temp_dir().join(format!("hjkl_exp_st_{}.txt", std::process::id()));
std::fs::write(&f1, "hello").unwrap();
let mut app = super::super::App::new(Some(f1.clone()), false, None, None).unwrap();
// Open the explorer — it gets focused.
app.dispatch_action(AppAction::ToggleExplorer, 1);
assert!(app.explorer_buf_focused(), "explorer should be focused");
// Switching to the real buffer while the explorer is focused must NOT
// clobber the explorer pane — it redirects to a non-explorer window.
let real_idx = app.slots.iter().position(|s| !s.is_explorer).unwrap();
app.switch_to(real_idx);
assert!(
!app.explorer_buf_focused(),
"switch_to must move focus off the explorer window"
);
assert!(
!app.active().is_explorer,
"active buffer must be the real one"
);
let ep_win = app.explorer.as_ref().unwrap().win_id;
let ep_slot = app.windows[ep_win].as_ref().unwrap().slot;
assert!(
app.slots[ep_slot].is_explorer,
"the explorer window must still display the explorer buffer"
);
let _ = std::fs::remove_file(&f1);
}
#[test]
fn buffer_next_skips_explorer_slot() {
use crate::keymap_actions::AppAction;
// Create two real files so buffer_next has something to cycle through.
let f1 = std::env::temp_dir().join(format!("hjkl_exp_bn_a_{}.txt", std::process::id()));
let f2 = std::env::temp_dir().join(format!("hjkl_exp_bn_b_{}.txt", std::process::id()));
std::fs::write(&f1, "hello").unwrap();
std::fs::write(&f2, "world").unwrap();
let mut app = super::super::App::new(Some(f1.clone()), false, None, None).unwrap();
// Open a second real buffer.
app.dispatch_ex(&format!("edit {}", f2.display()));
// Open the explorer (it gets focused).
app.dispatch_action(AppAction::ToggleExplorer, 1);
assert!(app.explorer.is_some());
// Focus the right (editor) window so buffer_next operates on a real slot.
app.dispatch_action(AppAction::FocusRight, 1);
assert!(!app.active().is_explorer, "should be on a real slot now");
// buffer_next should never land on the explorer slot.
for _ in 0..10 {
app.buffer_next();
assert!(
!app.active().is_explorer,
"buffer_next must skip is_explorer slots"
);
}
let _ = std::fs::remove_file(&f1);
let _ = std::fs::remove_file(&f2);
}
// ── New tests for plan features ────────────────────────────────────────
/// Build a unique temp dir with dotfiles:
/// root/{ .hidden_dir/, .hidden_file, visible.txt }
fn make_dotfile_tree() -> PathBuf {
let base =
std::env::temp_dir().join(format!("hjkl_explorer_dot_test_{}", std::process::id()));
let _ = fs::remove_dir_all(&base);
fs::create_dir_all(base.join(".hidden_dir")).unwrap();
fs::write(base.join(".hidden_file"), "x").unwrap();
fs::write(base.join("visible.txt"), "x").unwrap();
base
}
#[test]
fn read_children_shows_dotfiles_by_default() {
let root = make_dotfile_tree();
let tree = ExplorerTree::new(root.clone());
// Dotfiles are shown by default now; `.git` would still be skipped.
let names = child_names(&tree);
assert!(
names.iter().any(|n| n.starts_with('.')),
"dotfiles should be shown by default, got: {names:?}"
);
assert!(
names.contains(&"visible.txt".to_string()),
"visible.txt should be present"
);
let _ = fs::remove_dir_all(&root);
}
#[test]
fn toggle_hidden_hides_then_shows_dotfiles() {
let root = make_dotfile_tree();
let mut tree = ExplorerTree::new(root.clone());
assert!(
child_names(&tree).iter().any(|n| n.starts_with('.')),
"dotfiles should be shown before toggle"
);
tree.toggle_hidden();
let names = child_names(&tree);
assert!(
!names.iter().any(|n| n.starts_with('.')),
"dotfiles should be hidden after toggle_hidden, got: {names:?}"
);
// Toggle back.
tree.toggle_hidden();
assert!(
child_names(&tree).iter().any(|n| n.starts_with('.')),
"dotfiles should be shown again after second toggle"
);
let _ = fs::remove_dir_all(&root);
}
#[test]
fn reveal_expands_ancestors_and_returns_row() {
let root = make_tree();
// Build a fresh tree (root expanded by default, a_dir is NOT expanded).
let mut tree = ExplorerTree::new(root.clone());
let inner = root.join("a_dir").join("inner.txt");
// inner.txt is two levels deep; reveal should expand a_dir.
let row = tree.reveal(&inner);
assert!(
row.is_some(),
"reveal should return a row for an existing path"
);
let row = row.unwrap();
assert_eq!(
tree.nodes[row].path, inner,
"node at returned row should be inner.txt"
);
assert!(
tree.is_expanded(&root.join("a_dir")),
"a_dir should be expanded after reveal"
);
let _ = fs::remove_dir_all(&root);
}
#[test]
fn set_root_re_roots_to_parent() {
let root = make_tree();
let mut tree = ExplorerTree::new(root.join("a_dir"));
// a_dir is the root; set_root to root's parent brings us up.
tree.set_root(root.clone());
// Now root should be the root and a_dir visible as a child.
assert_eq!(tree.root, root);
let names = child_names(&tree);
assert!(
names.contains(&"a_dir".to_string()),
"a_dir should be a visible child after set_root: {names:?}"
);
let _ = fs::remove_dir_all(&root);
}
#[test]
fn target_dir_resolver_dir_node_returns_itself() {
let root = make_tree();
let tree = ExplorerTree::new(root.clone());
// nodes[1] is a_dir (a directory).
let node = tree.nodes[1].clone();
assert!(node.is_dir, "test prerequisite: nodes[1] is a_dir");
let target = super::super::App::explorer_target_dir(&node);
assert_eq!(target, node.path, "dir node → that dir");
let _ = fs::remove_dir_all(&root);
}
#[test]
fn target_dir_resolver_file_node_returns_parent() {
let root = make_tree();
let tree = ExplorerTree::new(root.clone());
// Find m_file.txt (a file node).
let node = tree
.nodes
.iter()
.find(|n| {
n.path
.file_name()
.map(|f| f == "m_file.txt")
.unwrap_or(false)
})
.cloned()
.expect("m_file.txt should exist");
assert!(!node.is_dir, "test prerequisite: m_file.txt is not a dir");
let target = super::super::App::explorer_target_dir(&node);
assert_eq!(
target,
node.path.parent().unwrap().to_path_buf(),
"file node → parent dir"
);
let _ = fs::remove_dir_all(&root);
}
#[test]
fn commit_create_file_creates_on_disk() {
let root = make_tree();
let mut app = super::super::App::new(None, false, None, None).unwrap();
// Manually set up explorer_prompt state as if `a` was pressed.
let mut field = hjkl_form::TextFieldEditor::new(true);
field.enter_insert_at_end();
app.explorer_prompt = Some(super::ExplorerPrompt {
kind: super::ExplorerPromptKind::Create,
field,
base: root.clone(),
});
// Commit creation of a plain file.
app.explorer_commit_create("new_file.txt".to_string());
assert!(
root.join("new_file.txt").exists(),
"new_file.txt should be created on disk"
);
let _ = fs::remove_dir_all(&root);
}
#[test]
fn commit_create_dir_trailing_slash_creates_dir() {
let root = make_tree();
let mut app = super::super::App::new(None, false, None, None).unwrap();
let mut field = hjkl_form::TextFieldEditor::new(true);
field.enter_insert_at_end();
app.explorer_prompt = Some(super::ExplorerPrompt {
kind: super::ExplorerPromptKind::Create,
field,
base: root.clone(),
});
app.explorer_commit_create("new_dir/".to_string());
assert!(
root.join("new_dir").is_dir(),
"new_dir/ should create a directory"
);
let _ = fs::remove_dir_all(&root);
}
#[test]
fn commit_rename_moves_file() {
let root = make_tree();
let from = root.join("m_file.txt");
let expected = root.join("renamed.txt");
let mut app = super::super::App::new(None, false, None, None).unwrap();
let mut field = hjkl_form::TextFieldEditor::new(true);
field.enter_insert_at_end();
app.explorer_prompt = Some(super::ExplorerPrompt {
kind: super::ExplorerPromptKind::Rename { from: from.clone() },
field,
base: root.clone(),
});
app.explorer_commit_rename("renamed.txt".to_string());
assert!(!from.exists(), "original file should be gone after rename");
assert!(expected.exists(), "renamed file should exist");
let _ = fs::remove_dir_all(&root);
}
#[test]
fn commit_delete_removes_file() {
let root = make_tree();
let path = root.join("m_file.txt");
assert!(path.exists(), "test prerequisite: m_file.txt exists");
let mut app = super::super::App::new(None, false, None, None).unwrap();
app.explorer_confirm = Some(super::ExplorerConfirm {
path: path.clone(),
is_dir: false,
});
app.explorer_commit_delete();
assert!(!path.exists(), "m_file.txt should be deleted");
let _ = fs::remove_dir_all(&root);
}
#[test]
fn commit_delete_removes_dir() {
let root = make_tree();
let path = root.join("b_dir");
assert!(path.is_dir(), "test prerequisite: b_dir exists");
let mut app = super::super::App::new(None, false, None, None).unwrap();
app.explorer_confirm = Some(super::ExplorerConfirm {
path: path.clone(),
is_dir: true,
});
app.explorer_commit_delete();
assert!(!path.exists(), "b_dir should be deleted");
let _ = fs::remove_dir_all(&root);
}
// ── Plan Verification: fuzzy filter tests ──────────────────────────────
/// Tree fixture for filter tests:
/// root/{ src/{ buffer_ops.rs, main.rs }, tests/{ buffer_test.rs }, readme.md }
fn make_filter_tree() -> PathBuf {
let base = std::env::temp_dir().join(format!("hjkl_filter_test_{}", std::process::id()));
let _ = fs::remove_dir_all(&base);
fs::create_dir_all(base.join("src")).unwrap();
fs::create_dir_all(base.join("tests")).unwrap();
fs::write(base.join("src").join("buffer_ops.rs"), "x").unwrap();
fs::write(base.join("src").join("main.rs"), "x").unwrap();
fs::write(base.join("tests").join("buffer_test.rs"), "x").unwrap();
fs::write(base.join("readme.md"), "x").unwrap();
base
}
#[test]
fn filter_best_match_row_points_at_highest_scorer() {
let root = make_filter_tree();
let mut tree = ExplorerTree::new(root.clone());
// "main" matches only src/main.rs in this fixture; best_match_row must
// point at that node (a file, not a dir).
tree.apply_filter("main");
let row = tree.best_match_row.expect("best_match_row should be set");
let node = &tree.nodes[row];
assert!(!node.is_dir, "best match must be a file");
assert_eq!(
node.path.file_name().unwrap(),
"main.rs",
"best match should be main.rs, got {:?}",
node.path
);
// Unfiltered → cleared.
tree.clear_filter();
assert!(tree.best_match_row.is_none());
let _ = fs::remove_dir_all(&root);
}
#[test]
fn filter_keeps_matching_files_and_ancestors() {
let root = make_filter_tree();
let mut tree = ExplorerTree::new(root.clone());
tree.apply_filter("buf");
// buffer_ops.rs and buffer_test.rs should match; main.rs and readme.md
// should be absent.
let paths: Vec<String> = tree
.nodes
.iter()
.filter_map(|n| n.path.file_name().map(|f| f.to_string_lossy().into_owned()))
.collect();
assert!(
paths.contains(&"buffer_ops.rs".to_string()),
"buffer_ops.rs must be present: {paths:?}"
);
assert!(
paths.contains(&"buffer_test.rs".to_string()),
"buffer_test.rs must be present: {paths:?}"
);
// Ancestor dirs must appear too.
assert!(
paths.contains(&"src".to_string()),
"src dir must be present as ancestor: {paths:?}"
);
assert!(
paths.contains(&"tests".to_string()),
"tests dir must be present as ancestor: {paths:?}"
);
// Non-matching files must be absent.
assert!(
!paths.contains(&"main.rs".to_string()),
"main.rs must NOT be present: {paths:?}"
);
assert!(
!paths.contains(&"readme.md".to_string()),
"readme.md must NOT be present: {paths:?}"
);
// match_count must equal 2 (buffer_ops.rs + buffer_test.rs).
assert_eq!(
tree.match_count, 2,
"match_count should be 2, got {}",
tree.match_count
);
let _ = fs::remove_dir_all(&root);
}
#[test]
fn filter_empty_query_equals_full_tree() {
let root = make_filter_tree();
let mut tree = ExplorerTree::new(root.clone());
// Count nodes with no filter (default: root + dirs only at top level,
// since a_dir etc. are collapsed). We expand everything manually.
for entry in fs::read_dir(&root).unwrap().flatten() {
let p = entry.path();
if p.is_dir() {
tree.expanded.insert(p);
}
}
tree.rebuild();
let unfiltered_count = tree.nodes.len();
// Apply and then clear the filter.
tree.apply_filter("buf");
assert!(
tree.nodes.len() < unfiltered_count,
"filtered should be shorter"
);
tree.apply_filter(""); // empty → clear
assert_eq!(
tree.nodes.len(),
unfiltered_count,
"after clearing filter, node count must equal unfiltered count"
);
assert!(
tree.filter.is_none(),
"filter should be None after empty apply"
);
let _ = fs::remove_dir_all(&root);
}
#[test]
fn filter_nodes_have_no_orphans() {
let root = make_filter_tree();
let mut tree = ExplorerTree::new(root.clone());
tree.apply_filter("buf");
// Every non-root node's parent path must appear in the node list.
let node_paths: HashSet<PathBuf> = tree.nodes.iter().map(|n| n.path.clone()).collect();
for node in &tree.nodes {
if node.depth == 0 {
continue;
}
let parent = node.path.parent().map(|p| p.to_path_buf());
if let Some(p) = parent {
assert!(
node_paths.contains(&p),
"node {:?} has no parent in the node list (orphan)",
node.path
);
}
}
let _ = fs::remove_dir_all(&root);
}
#[test]
fn filter_no_match_yields_only_root() {
let root = make_filter_tree();
let mut tree = ExplorerTree::new(root.clone());
tree.apply_filter("xyzzy_no_match_possible");
assert_eq!(
tree.nodes.len(),
1,
"a query matching nothing should yield only the root node"
);
assert_eq!(tree.nodes[0].path, root, "the sole node should be the root");
assert_eq!(tree.match_count, 0, "match_count must be 0");
let _ = fs::remove_dir_all(&root);
}
#[test]
fn explorer_slot_features_disabled_normal_slot_features_enabled() {
use crate::keymap_actions::AppAction;
// Open the app with an unnamed scratch buffer (slot 0 = normal).
let mut app = super::super::App::new(None, false, None, None).unwrap();
// Normal slot must have all features on.
let normal = &app.slots[0];
assert!(
normal.features.syntax,
"normal slot: syntax should be enabled"
);
assert!(normal.features.lsp, "normal slot: lsp should be enabled");
assert!(
normal.features.hover,
"normal slot: hover should be enabled"
);
// Open the explorer — its slot is pushed after the normal slot.
app.dispatch_action(AppAction::ToggleExplorer, 1);
let explorer_idx = app
.slots
.iter()
.position(|s| s.is_explorer)
.expect("explorer slot must exist after ToggleExplorer");
let exp = &app.slots[explorer_idx];
assert!(
!exp.features.syntax,
"explorer slot: syntax should be disabled"
);
assert!(!exp.features.lsp, "explorer slot: lsp should be disabled");
assert!(
!exp.features.hover,
"explorer slot: hover should be disabled"
);
}
}