tree-space 0.1.0

A dockable, keyboard-first file manager panel for Wayland/Hyprland
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
//! Configuration and XDG persistence.
//!
//! This module owns two concerns:
//!
//! * **`Config`** — the user-facing TOML file at
//!   `$XDG_CONFIG_HOME/tree-space/config.toml` (`~/.config/tree-space/config.toml`).
//!   Every field has a sane default via `#[serde(default)]`, so a minimal file
//!   (or none at all) is valid. Those defaults are not written here: they are
//!   parsed from the shipped `default-config.toml` (see [`builtin`]), which is
//!   the single source of truth for every default value.
//! * **`SessionState`** — small runtime state (last opened root) kept in
//!   `$XDG_STATE_HOME/tree-space/state.toml`. Kept separate from the config so
//!   that re-exporting the config as a "default" for users stays clean.
//!
//! The XDG resolution helpers are pure functions over environment-style inputs
//! so they can be tested without mutating process-global environment variables.

use std::env;
use std::path::{Path, PathBuf};
use std::sync::OnceLock;

use regex::Regex;
use serde::{Deserialize, Serialize};

/// The directory name used below all XDG base dirs.
pub const APP_DIR: &str = "tree-space";
/// Name of the config file inside [`APP_DIR`].
pub const CONFIG_FILE: &str = "config.toml";
/// Name of the state file inside [`APP_DIR`].
pub const STATE_FILE: &str = "state.toml";
/// Name of the user stylesheet inside [`APP_DIR`].
pub const STYLE_FILE: &str = "main.css";

/// The shipping default config, written out on first launch. This is the
/// **single source of truth** for every default value: [`Config::default`] and
/// each section's `Default` are parsed from it (see [`builtin`]). It is kept as
/// a real file (rather than generated by serialization) so it can be commented
/// and laid out for humans.
const DEFAULT_CONFIG: &str = include_str!("../default-config.toml");

/// The shipped default stylesheet, written out beside the config on first
/// launch and used as a fallback when the user's own is missing or unreadable.
pub const DEFAULT_STYLESHEET: &str = include_str!("../style/main.css");

/// The parsed `default-config.toml`, built once. Every `Default` impl delegates
/// here so the file, not this module, decides the defaults.
///
/// Parsing uses [`ShippedRaw`], whose section fields are `Option`s with
/// *(field-level)* `#[serde(default)]`. That keeps the parse free of any call
/// back into a section's own `Default` — and therefore out of [`builtin`]
/// itself — because the shipped file always populates every section. A missing
/// section (or scalar) falls back to the literal schema default on its type,
/// which likewise never re-enters [`builtin`].
fn builtin() -> &'static Config {
    static ONCE: OnceLock<Config> = OnceLock::new();
    ONCE.get_or_init(|| {
        let raw: ShippedRaw = toml::from_str(DEFAULT_CONFIG)
            .expect("default-config.toml must be valid TOML");
        Config {
            panel: raw.panel.unwrap_or_default(),
            tree: raw.tree.unwrap_or_default(),
            startup: raw.startup.unwrap_or_default(),
            context_menu: raw.context_menu.unwrap_or_default(),
            pane_menu: raw.pane_menu.unwrap_or_default(),
        }
    })
}

/// A recursion-free view of `default-config.toml`: every section is optional
/// and defaults to `None`, so deserializing the shipped file never touches a
/// section's `Default` (which would re-enter [`builtin`]).
#[derive(Deserialize)]
struct ShippedRaw {
    #[serde(default)]
    panel: Option<PanelConfig>,
    #[serde(default)]
    tree: Option<TreeConfig>,
    #[serde(default)]
    startup: Option<StartupRoot>,
    #[serde(default)]
    context_menu: Option<ContextMenu>,
    #[serde(default)]
    pane_menu: Option<PaneMenu>,
}

// ---------------------------------------------------------------------------
// XDG path resolution
// ---------------------------------------------------------------------------

/// Resolve `$XDG_CONFIG_HOME` / `$HOME/.config` from explicit inputs.
///
/// `xdg` is the value of `XDG_CONFIG_HOME`, `home` the value of `HOME`. When
/// neither is present the XDG spec mandates falling back to `~/.config`.
fn xdg_config_home(xdg: Option<&str>, home: Option<&str>) -> PathBuf {
    match xdg.filter(|s| !s.is_empty()) {
        Some(dir) => PathBuf::from(dir),
        None => home.map(PathBuf::from).unwrap_or_else(|| PathBuf::from("/")).join(".config"),
    }
}

/// Resolve `$XDG_STATE_HOME` / `$HOME/.local/state` from explicit inputs.
fn xdg_state_home(xdg: Option<&str>, home: Option<&str>) -> PathBuf {
    match xdg.filter(|s| !s.is_empty()) {
        Some(dir) => PathBuf::from(dir),
        None => home.map(PathBuf::from).unwrap_or_else(|| PathBuf::from("/")).join(".local/state"),
    }
}

/// Path of `<app dir>/<file>` below an XDG base directory.
fn app_path(base: &Path, file: &str) -> PathBuf {
    base.join(APP_DIR).join(file)
}

/// Read `XDG_CONFIG_HOME`/`HOME` from the environment. Replaced by
/// [`xdg_config_home`] in tests where determinism matters.
fn config_home_from_env() -> PathBuf {
    let xdg = env::var_os("XDG_CONFIG_HOME").map(|v| v.to_string_lossy().into_owned());
    let home = env::var_os("HOME").map(|v| v.to_string_lossy().into_owned());
    xdg_config_home(xdg.as_deref(), home.as_deref())
}

/// Read `XDG_STATE_HOME`/`HOME` from the environment.
fn state_home_from_env() -> PathBuf {
    let xdg = env::var_os("XDG_STATE_HOME").map(|v| v.to_string_lossy().into_owned());
    let home = env::var_os("HOME").map(|v| v.to_string_lossy().into_owned());
    xdg_state_home(xdg.as_deref(), home.as_deref())
}

/// Absolute path of the config file for the current environment.
pub fn config_file() -> PathBuf {
    app_path(&config_home_from_env(), CONFIG_FILE)
}

/// Absolute path of the state file for the current environment.
pub fn state_file() -> PathBuf {
    app_path(&state_home_from_env(), STATE_FILE)
}

/// Absolute path of the user stylesheet for the current environment.
pub fn style_file() -> PathBuf {
    app_path(&config_home_from_env(), STYLE_FILE)
}

// ---------------------------------------------------------------------------
// Config values
// ---------------------------------------------------------------------------

/// Which edge of the screen the panel docks to.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, Default)]
#[serde(rename_all = "lowercase")]
pub enum PanelSide {
    #[default]
    Left,
    Right,
}

impl PanelSide {
    /// Both sides, left then right.
    pub const ALL: [PanelSide; 2] = [PanelSide::Left, PanelSide::Right];

    /// The other side ("right" for left, and vice versa).
    pub fn opposite(&self) -> PanelSide {
        match self {
            PanelSide::Left => PanelSide::Right,
            PanelSide::Right => PanelSide::Left,
        }
    }

    /// The lowercase word used in user-facing labels ("left" / "right").
    pub fn name(&self) -> &'static str {
        match self {
            PanelSide::Left => "left",
            PanelSide::Right => "right",
        }
    }
}

/// The wlr-layer-shell layer the panel lives in. `Bottom` keeps it behind
/// normal windows (the Ormachy/Hyprland "stays out of the way" mode).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "lowercase")]
pub enum PanelLayer {
    Background,
    #[default]
    Bottom,
    Top,
    Overlay,
}

/// Smallest allowed panel width, in pixels.
pub const PANEL_MIN_WIDTH: u32 = 160;
/// Largest allowed panel width, in pixels.
pub const PANEL_MAX_WIDTH: u32 = 2000;

// Field-level serde defaults. These run only for a field omitted from a
// *user's* partial table (the shipped file lists every field, so they are never
// reached while [`builtin`] is being initialized). Each returns the shipped
// value, so an omitted key still matches `default-config.toml`.
fn default_panel_side() -> PanelSide {
    builtin().panel.side
}
fn default_panel_layer() -> PanelLayer {
    builtin().panel.layer
}
fn default_panel_width() -> u32 {
    builtin().panel.width
}
fn default_dirs_first() -> bool {
    builtin().tree.dirs_first
}
fn default_sort_key() -> String {
    builtin().tree.sort_key.clone()
}
fn default_sort_ascending() -> bool {
    builtin().tree.sort_ascending
}
fn default_font_size() -> u32 {
    builtin().tree.font_size
}
fn default_icon_size() -> u32 {
    builtin().tree.icon_size
}
fn default_confirm_drop_move() -> bool {
    builtin().tree.confirm_drop_move
}

/// Dock/panel configuration. Field-level serde defaults keep a partially
/// written `[panel]` table valid without consulting `Self::default()` (which
/// parses the shipped file — see [`builtin`]).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub struct PanelConfig {
    #[serde(default = "default_panel_side")]
    pub side: PanelSide,
    #[serde(default = "default_panel_layer")]
    pub layer: PanelLayer,
    /// Panel width in pixels.
    #[serde(default = "default_panel_width")]
    pub width: u32,
    /// Pixel margin around the panel within the screen edge.
    #[serde(default)]
    pub margin: u32,
}

impl Default for PanelConfig {
    fn default() -> Self {
        builtin().panel
    }
}

/// Sorting and visibility rules for the tree.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct TreeConfig {
    /// When true, directories are listed before files; otherwise everything is
    /// interleaved and only alphabetically sorted. Names are always sorted
    /// alphabetically (case-insensitively).
    #[serde(default = "default_dirs_first")]
    pub dirs_first: bool,
    /// Primary sort key: `name`, `size`, `modified`, or `type`.
    #[serde(default = "default_sort_key")]
    pub sort_key: String,
    /// Sort ascending (A→Z, smallest first) when true; descending otherwise.
    #[serde(default = "default_sort_ascending")]
    pub sort_ascending: bool,
    /// Show dotfiles. When false, hidden entries are never read into the model.
    #[serde(default)]
    pub show_hidden: bool,
    /// Base font size in px applied to the tree.
    #[serde(default = "default_font_size")]
    pub font_size: u32,
    /// Pixel size of file/directory icons in the tree.
    #[serde(default = "default_icon_size")]
    pub icon_size: u32,
    /// When true, dropping a dragged selection onto a directory asks for
    /// confirmation before moving; when false (the default) the move happens
    /// immediately. Copying (Ctrl+drag) never asks.
    #[serde(default = "default_confirm_drop_move")]
    pub confirm_drop_move: bool,
}

impl Default for TreeConfig {
    fn default() -> Self {
        builtin().tree.clone()
    }
}

impl TreeConfig {
    /// Translate the configured sort fields into a [`SortOptions`]. Unknown
    /// `sort_key` values fall back to name.
    pub fn sort_options(&self) -> crate::fs::SortOptions {
        crate::fs::SortOptions {
            dirs_first: self.dirs_first,
            key: crate::fs::SortKey::parse(&self.sort_key).unwrap_or(crate::fs::SortKey::Name),
            ascending: self.sort_ascending,
        }
    }
}

/// Where the panel opens when launched without an explicit path argument.
///
/// In TOML this is a single `root` value: `"home"` (the default), `"last"`, or
/// a table naming a fixed directory — `{ path = "/some/dir" }`. A leading `~` in
/// the path expands to `$HOME`.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub enum StartupRoot {
    /// Always open the user's home directory.
    #[default]
    Home,
    /// Reopen the most recently used directory (persisted between launches).
    Last,
    /// Always open the named directory.
    Path(String),
}

impl StartupRoot {
    /// Resolve the directory to open, given the last-used directory from session
    /// state. `None` means "fall back to home" (unknown/unusable path).
    pub fn resolve(&self, last: Option<PathBuf>) -> Option<PathBuf> {
        match self {
            StartupRoot::Last => last,
            StartupRoot::Home => None,
            StartupRoot::Path(path) => expand_tilde(path),
        }
    }
}

impl Serialize for StartupRoot {
    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        use serde::ser::SerializeMap;
        match self {
            StartupRoot::Last => serializer.serialize_str("last"),
            StartupRoot::Home => serializer.serialize_str("home"),
            StartupRoot::Path(path) => {
                let mut map = serializer.serialize_map(Some(1))?;
                map.serialize_entry("path", path)?;
                map.end()
            }
        }
    }
}

impl<'de> Deserialize<'de> for StartupRoot {
    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        use serde::de::Error as _;

        #[derive(Deserialize)]
        #[serde(untagged)]
        enum Repr {
            Keyword(String),
            Path { path: String },
        }

        match Repr::deserialize(deserializer)? {
            Repr::Keyword(word) => match word.to_ascii_lowercase().as_str() {
                "last" => Ok(StartupRoot::Last),
                "home" => Ok(StartupRoot::Home),
                other => Err(D::Error::custom(format!(
                    "unknown startup root {other:?} (expected \"last\", \"home\", or {{ path = \"...\" }})"
                ))),
            },
            Repr::Path { path } => Ok(StartupRoot::Path(path)),
        }
    }
}

/// Expand a leading `~` in `path` to `$HOME`. An empty string stays empty.
pub fn expand_tilde(path: &str) -> Option<PathBuf> {
    if path.is_empty() {
        return None;
    }
    match path.strip_prefix('~') {
        Some(rest) => std::env::var_os("HOME").map(|home| {
            let mut p = PathBuf::from(home);
            p.push(rest.strip_prefix('/').unwrap_or(rest));
            p
        }),
        // A relative configured path is resolved against the working directory
        // (matching how CLI arguments are normalized), so the pane and its path
        // entry never show a bare relative spelling.
        None => {
            let path = PathBuf::from(path);
            Some(std::path::absolute(&path).unwrap_or(path))
        }
    }
}

/// Which rows a context-menu rule applies to. Checked in order of rule
/// precedence: [`Dir`](ContextMatch::Dir) first, then extension, then
/// no-extension, then [`Regex`](ContextMatch::Regex) / [`Fallback`](ContextMatch::Fallback)
/// for anything else.
#[derive(Debug, Clone)]
pub enum ContextMatch {
    /// A directory.
    Dir,
    /// A file with no extension (the name has no `.` after the last path
    /// separator).
    NoExt,
    /// Every path that was not claimed by a more specific rule.
    Fallback,
    /// A multi-row selection (more than one row selected). Not a property of a
    /// single path, so [`Self::matches`] always returns false for it; it only
    /// participates in [`ContextMenu::actions_for_selection`].
    Multi,
    /// A file whose *name* ends with the extension, case-insensitively:
    /// `Ext("py")` matches both `x.py` and `x.tar.gz` (multi-part suffixes are
    /// matched from the end, so more specific rules should come first).
    Ext(String),
    /// The full row path matched against a regex. Applies to files and
    /// directories alike; case-sensitive unless the pattern opts out with
    /// `(?i)`. Matched against the whole path, so name-only patterns should
    /// anchor with `.*\.NAME$`.
    Regex(Regex),
}

impl ContextMatch {
    /// The canonical configuration spelling.
    pub fn as_str(&self) -> String {
        match self {
            ContextMatch::Dir => "dir".to_owned(),
            ContextMatch::NoExt => "noext".to_owned(),
            ContextMatch::Fallback => "fallback".to_owned(),
            ContextMatch::Multi => "multi".to_owned(),
            ContextMatch::Ext(ext) => format!("ext:{ext}"),
            ContextMatch::Regex(re) => format!("regex:{}", re.as_str()),
        }
    }

    /// Parse a config spelling. `"*"` is an alias for `"fallback"`.
    pub fn parse(value: &str) -> Result<Self, String> {
        let value = value.trim();
        match value {
            "dir" | "directory" => Ok(ContextMatch::Dir),
            "noext" => Ok(ContextMatch::NoExt),
            "fallback" | "*" | "all" => Ok(ContextMatch::Fallback),
            "multi" | "multi-select" | "selection" => Ok(ContextMatch::Multi),
            _ => {
                if let Some(ext) = value.strip_prefix("ext:") {
                    return Ok(ContextMatch::Ext(ext.to_owned()));
                }
                if let Some(pattern) = value.strip_prefix("regex:") {
                    return Regex::new(pattern)
                        .map(ContextMatch::Regex)
                        .map_err(|err| {
                            format!(
                                "invalid regex {pattern:?} in context menu matcher {value:?}: {err}"
                            )
                        });
                }
                Err(format!("unknown context menu matcher {value:?}"))
            }
        }
    }

    /// Whether `path` is claimed by this matcher. Extension and no-extention
    /// matchers only ever claim files.
    pub fn matches(&self, path: &Path) -> bool {
        match self {
            ContextMatch::Dir => path.is_dir(),
            ContextMatch::NoExt => {
                let Some(name) = path.file_name() else {
                    return false;
                };
                let name = name.to_string_lossy();
                !path.is_dir() && !name.ends_with('.') && {
                    // No dot past the last path separators that isn't the
                    // leading dot of a hidden file name.
                    let after_sep = name.rsplit(['/', '\\']).next().unwrap_or("");
                    !after_sep[1..].contains('.')
                }
            }
            ContextMatch::Fallback => true,
            // Selection-level, never a property of one path.
            ContextMatch::Multi => false,
            ContextMatch::Ext(ext) => {
                if path.is_dir() || ext.is_empty() {
                    return false;
                }
                let Some(name) = path.file_name() else {
                    return false;
                };
                let name = name.to_string_lossy().to_lowercase();
                name.trim_start_matches('.').ends_with(&format!(".{}", ext.trim().to_lowercase()))
            }
            ContextMatch::Regex(re) => re.is_match(&path.to_string_lossy()),
        }
    }
}

impl PartialEq for ContextMatch {
    fn eq(&self, other: &Self) -> bool {
        match (self, other) {
            (ContextMatch::Dir, ContextMatch::Dir) => true,
            (ContextMatch::NoExt, ContextMatch::NoExt) => true,
            (ContextMatch::Fallback, ContextMatch::Fallback) => true,
            (ContextMatch::Multi, ContextMatch::Multi) => true,
            (ContextMatch::Ext(a), ContextMatch::Ext(b)) => a == b,
            (ContextMatch::Regex(a), ContextMatch::Regex(b)) => a.as_str() == b.as_str(),
            _ => false,
        }
    }
}

impl Eq for ContextMatch {}

impl Serialize for ContextMatch {
    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        serializer.serialize_str(&self.as_str())
    }
}

impl<'de> Deserialize<'de> for ContextMatch {
    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        let raw = String::deserialize(deserializer)?;
        ContextMatch::parse(&raw).map_err(serde::de::Error::custom)
    }
}

/// A built-in context-menu action: everything the panel can do to a row that
/// is not a custom command. A [`Separator`](BuiltinAction::Separator) is only a
/// menu divider; it has no action.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BuiltinAction {
    /// Open: expand/collapse a directory, or open a file in its default app.
    Open,
    /// Open the directory as a new split pane *in the current dock*.
    OpenSplit,
    /// Open the directory as a new pane in the *same* panel (like a split view).
    InNewPanel,
    /// Open the directory in the *opposite* panel (the dock on the other side
    /// of the screen). The menu label names that side: "In right panel".
    InOppositePanel,
    /// Pick an application for the row and open it with that app.
    OpenWith,
    /// Open a file with its default application (a sibling of
    /// [`Self::Open`]; the label shows the default app's name).
    OpenWithDefault,
    /// Show or hide an inline thumbnail preview: below an image row, or below
    /// every image inside a directory. Purely visual and non-persistent.
    ViewThumbnail,
    /// Create a new file in the row's target directory.
    NewFile,
    /// Create a new folder in the row's target directory.
    NewFolder,
    /// Inline-rename the row.
    Rename,
    /// Duplicate the row.
    Duplicate,
    /// Copy the row's absolute path.
    CopyPath,
    /// Copy the row's path relative to the tree root.
    CopyRelativePath,
    /// Cut the selection (moved on the next paste).
    Cut,
    /// Copy the selection (duplicated on the next paste).
    Copy,
    /// Paste the clipboard into the row's directory (the row itself for a
    /// directory, its parent for a file).
    Paste,
    /// Create a symlink to the row next to it.
    CreateLink,
    /// Show the row's properties.
    Properties,
    /// Move the row to the trash.
    Trash,
    /// Permanently delete the row.
    DeletePermanently,
    /// Toggle visibility of dotfiles in the current tree.
    ToggleHidden,
    /// Sort entries by name.
    SortByName,
    /// Sort entries by size.
    SortBySize,
    /// Sort entries by modification time.
    SortByModified,
    /// Sort entries by type/extension.
    SortByType,
    /// Flip ascending/descending order.
    ToggleSortAscending,
    /// Pane-level: pick a folder to browse (the hamburger menu).
    OpenFolder,
    /// Pane-level: open the filter bar.
    Filter,
    /// Pane-level: split the pane.
    SplitView,
    /// Pane-level: open the current directory's parent (the enclosing folder).
    Up,
    /// Pane-level: go back to the previously shown directory in this pane.
    Back,
    /// Pane-level: go forward again after going back.
    Forward,
    /// Pane-level: hide this pane's whole side.
    Collapse,
    /// Pane-level: close this pane.
    ClosePane,
    /// A menu divider; never does anything.
    Separator,
}

impl BuiltinAction {
    /// The configuration string identifying this action (also its menu label,
    /// unless the menu uses a dynamic label).
    pub fn as_str(&self) -> &'static str {
        match self {
            BuiltinAction::Open => "Open",
            BuiltinAction::OpenSplit => "Open in Split View",
            BuiltinAction::InNewPanel => "In new panel",
            BuiltinAction::InOppositePanel => "In opposite panel",
            BuiltinAction::OpenWith => "Open With...",
            BuiltinAction::OpenWithDefault => "Open With Default",
            BuiltinAction::ViewThumbnail => "View Thumbnail",
            BuiltinAction::NewFile => "New File",
            BuiltinAction::NewFolder => "New Folder",
            BuiltinAction::Rename => "Rename",
            BuiltinAction::Duplicate => "Duplicate",
            BuiltinAction::CopyPath => "Copy Path",
            BuiltinAction::CopyRelativePath => "Copy Relative Path",
            BuiltinAction::Cut => "Cut",
            BuiltinAction::Copy => "Copy",
            BuiltinAction::Paste => "Paste",
            BuiltinAction::CreateLink => "Create Link",
            BuiltinAction::Properties => "Properties",
            BuiltinAction::Trash => "Move to Trash",
            BuiltinAction::DeletePermanently => "Delete Permanently",
            BuiltinAction::ToggleHidden => "Toggle Hidden Files",
            BuiltinAction::SortByName => "Sort by Name",
            BuiltinAction::SortBySize => "Sort by Size",
            BuiltinAction::SortByModified => "Sort by Modified",
            BuiltinAction::SortByType => "Sort by Type",
            BuiltinAction::ToggleSortAscending => "Reverse Sort Order",
            BuiltinAction::OpenFolder => "Open Folder...",
            BuiltinAction::Filter => "Filter...",
            BuiltinAction::SplitView => "Split View",
            BuiltinAction::Up => "Up One Level",
            BuiltinAction::Back => "Back",
            BuiltinAction::Forward => "Forward",
            BuiltinAction::Collapse => "Collapse",
            BuiltinAction::ClosePane => "Close Pane",
            BuiltinAction::Separator => "---",
        }
    }

    /// The shortcut that a bare string item implies, when the user does not
    /// spell one out. `None` for actions without a default key.
    pub fn default_shortcut(&self) -> Option<&'static str> {
        match self {
            BuiltinAction::Cut => Some("Ctrl+x"),
            BuiltinAction::Copy => Some("Ctrl+c"),
            BuiltinAction::Paste => Some("Ctrl+v"),
            BuiltinAction::Rename => Some("F2"),
            BuiltinAction::Duplicate => Some("Ctrl+d"),
            BuiltinAction::NewFile => Some("Ctrl+n"),
            BuiltinAction::NewFolder => Some("Ctrl+Shift+n"),
            BuiltinAction::CreateLink => Some("Ctrl+Shift+m"),
            BuiltinAction::Trash => Some("Delete"),
            BuiltinAction::DeletePermanently => Some("Shift+Delete"),
            BuiltinAction::ViewThumbnail => Some("Ctrl+t"),
            BuiltinAction::ToggleHidden => Some("Ctrl+h"),
            BuiltinAction::SortByName => Some("Ctrl+1"),
            BuiltinAction::SortBySize => Some("Ctrl+2"),
            BuiltinAction::SortByModified => Some("Ctrl+3"),
            BuiltinAction::SortByType => Some("Ctrl+4"),
            BuiltinAction::ToggleSortAscending => Some("Ctrl+Shift+r"),
            BuiltinAction::SplitView => Some("Ctrl+s"),
            BuiltinAction::Up => Some("Alt+Up"),
            BuiltinAction::Back => Some("Alt+Left"),
            BuiltinAction::Forward => Some("Alt+Right"),
            BuiltinAction::ClosePane => Some("Ctrl+w"),
            _ => None,
        }
    }

    /// Whether this action operates on a single row only, and so should be
    /// hidden from a context menu opened over a multi-row selection. Actions
    /// that fan out over the selection (trash, delete, copy, cut, properties,
    /// copy path) are not listed here.
    pub fn is_single_row_only(&self) -> bool {
        matches!(
            self,
            BuiltinAction::Open
                | BuiltinAction::OpenSplit
                | BuiltinAction::InNewPanel
                | BuiltinAction::InOppositePanel
                | BuiltinAction::OpenWith
                | BuiltinAction::OpenWithDefault
                | BuiltinAction::ViewThumbnail
                | BuiltinAction::NewFile
                | BuiltinAction::NewFolder
                | BuiltinAction::Rename
                | BuiltinAction::Duplicate
                | BuiltinAction::CreateLink
        )
    }

    /// Whether this action only makes sense for directories (the menu drops
    /// it from file rows).
    pub fn is_directory_only(&self) -> bool {
        matches!(self, BuiltinAction::OpenSplit | BuiltinAction::InNewPanel | BuiltinAction::InOppositePanel)
    }

    /// Whether this is a pane-level action (open a folder, filter, split,
    /// collapse, close) that the app, not a tree, must perform. Pane actions
    /// belong in the hamburger menu; a shortcut bound to one is routed upward.
    pub fn is_pane_action(&self) -> bool {
        matches!(
            self,
            BuiltinAction::OpenFolder
                | BuiltinAction::Filter
                | BuiltinAction::SplitView
                | BuiltinAction::Up
                | BuiltinAction::Back
                | BuiltinAction::Forward
                | BuiltinAction::Collapse
                | BuiltinAction::ClosePane
        )
    }

    /// Parse a configuration string, case-insensitively. `"---"` and
    /// `"separator"` both spell a menu divider.
    ///
    /// The typographic ellipsis (`…`, U+2026) is accepted as a synonym for
    /// three ASCII dots (`...`) in labels, so configs written before the switch
    /// to plain ASCII still load.
    pub fn parse(name: &str) -> Option<Self> {
        let name = name.trim();
        let name = if name.contains('\u{2026}') {
            name.replace('\u{2026}', "...")
        } else {
            name.to_owned()
        };
        let name = name.as_str();
        [
            Self::Open,
            Self::OpenSplit,
            Self::InNewPanel,
            Self::InOppositePanel,
            Self::OpenWith,
            Self::OpenWithDefault,
            Self::ViewThumbnail,
            Self::NewFile,
            Self::NewFolder,
            Self::Rename,
            Self::Duplicate,
            Self::CopyPath,
            Self::CopyRelativePath,
            Self::Cut,
            Self::Copy,
            Self::Paste,
            Self::CreateLink,
            Self::Properties,
            Self::Trash,
            Self::DeletePermanently,
            Self::ToggleHidden,
            Self::SortByName,
            Self::SortBySize,
            Self::SortByModified,
            Self::SortByType,
            Self::ToggleSortAscending,
            Self::OpenFolder,
            Self::Filter,
            Self::SplitView,
            Self::Up,
            Self::Back,
            Self::Forward,
            Self::Collapse,
            Self::ClosePane,
            Self::Separator,
        ]
        .into_iter()
        .find(|a| {
            a.as_str().eq_ignore_ascii_case(name)
                || (matches!(a, Self::Separator) && name.eq_ignore_ascii_case("separator"))
        })
    }
}

impl Serialize for BuiltinAction {
    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        serializer.serialize_str(self.as_str())
    }
}

impl<'de> Deserialize<'de> for BuiltinAction {
    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        let raw = String::deserialize(deserializer)?;
        BuiltinAction::parse(&raw).ok_or_else(|| {
            serde::de::Error::custom(format!("unknown context menu builtin action {raw:?}"))
        })
    }
}

/// A custom command run with the row's path. The `{path}` marker is replaced
/// with the row's full path; `{dir}` with the directory itself for a directory
/// row or its parent for a file. With no marker, the path is appended as the
/// final argument.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct CommandAction {
    pub command: String,
    /// Optional menu label; defaults to the command text.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub label: Option<String>,
    /// Optional accelerator (GTK syntax: `"Ctrl+Shift+m"`, `"F2"`, `"Delete"`).
    /// While the tree is focused, the key fires this command against the row
    /// under the keyboard cursor.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub shortcut: Option<String>,
    /// Hide this item from the rendered menu while keeping its shortcut live —
    /// a way to bind a key without cluttering the menu.
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    pub hidden: bool,
}

/// A builtin menu item written out in table form, so a label override and/or a
/// shortcut can be attached to it: `{ action = "Cut", shortcut = "Ctrl+x" }`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct BuiltinEntry {
    pub action: BuiltinAction,
    /// Optional menu label override; defaults to the action's name.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub label: Option<String>,
    /// Optional accelerator override; defaults to the action's default
    /// shortcut (see [`BuiltinAction::default_shortcut`]).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub shortcut: Option<String>,
    /// Hide this item from the rendered menu while keeping its shortcut live.
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    pub hidden: bool,
}

/// A nested submenu: a labelled row that opens a child menu of its own items.
/// The items may be anything a top-level menu item can be, including further
/// submenus.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Submenu {
    /// The row's label.
    pub label: String,
    /// The child menu's items, in order.
    pub items: Vec<ContextAction>,
    /// Hide this submenu from the rendered menu while keeping the shortcuts of
    /// its children live.
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    pub hidden: bool,
}

impl Submenu {
    /// Wrap `items` in a submenu with the given `label`.
    pub fn new(label: impl Into<String>, items: Vec<ContextAction>) -> Self {
        Self { label: label.into(), items, hidden: false }
    }
}

/// One entry in a context-menu rule:
///   * a builtin action, written as a plain string (`"Cut"`), which gets its
///     action's default shortcut;
///   * a builtin in table form (`{ action = "Cut", shortcut = "Ctrl+x" }`);
///   * a custom command (`{ command = "...", label = "...", shortcut = "..." }`);
///   * a submenu (`{ label = "More", items = [ ... ] }`).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(untagged)]
pub enum ContextAction {
    Builtin(BuiltinAction),
    Entry(BuiltinEntry),
    Command(CommandAction),
    Submenu(Submenu),
}

/// The action bound by a shortcut: a builtin, or a custom command that is run
/// against the current row.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(untagged)]
pub enum ShortcutTarget {
    Builtin(BuiltinAction),
    Command(CommandAction),
}

impl ShortcutTarget {
    /// Resolve a menu item to the target a shortcut would invoke. Submenus have
    /// no action of their own, so they yield `None`.
    pub fn from_action(action: &ContextAction) -> Option<Self> {
        Some(match action {
            ContextAction::Builtin(a) => ShortcutTarget::Builtin(*a),
            ContextAction::Entry(e) => ShortcutTarget::Builtin(e.action),
            ContextAction::Command(cmd) => ShortcutTarget::Command(cmd.clone()),
            ContextAction::Submenu(_) => return None,
        })
    }
}

impl ContextAction {
    /// The menu item's label (the *base* label; a few actions use a dynamic
    /// label that depends on the row, resolved in the UI layer).
    pub fn label(&self) -> String {
        match self {
            ContextAction::Builtin(action) => action.as_str().to_owned(),
            ContextAction::Entry(entry) => {
                entry.label.clone().unwrap_or_else(|| entry.action.as_str().to_owned())
            }
            ContextAction::Command(cmd) => cmd.label.clone().unwrap_or_else(|| cmd.command.clone()),
            ContextAction::Submenu(sub) => sub.label.clone(),
        }
    }

    /// Whether this item opens a submenu rather than dispatching an action.
    pub fn is_submenu(&self) -> bool {
        matches!(self, ContextAction::Submenu(_))
    }

    /// Whether this item is hidden from the rendered menu. A hidden item keeps
    /// its shortcut live; only its row is skipped. A plain-string builtin
    /// cannot be hidden (write it as a table with `hidden = true` instead).
    pub fn is_hidden(&self) -> bool {
        match self {
            ContextAction::Builtin(_) => false,
            ContextAction::Entry(entry) => entry.hidden,
            ContextAction::Command(cmd) => cmd.hidden,
            ContextAction::Submenu(sub) => sub.hidden,
        }
    }

    /// The child items when this is a submenu.
    pub fn submenu_items(&self) -> Option<&[ContextAction]> {
        match self {
            ContextAction::Submenu(sub) => Some(&sub.items),
            _ => None,
        }
    }

    /// The shortcut attached to this item, if any: an explicit override when
    /// written in table form, otherwise the builtin's default shortcut.
    pub fn shortcut(&self) -> Option<String> {
        match self {
            ContextAction::Builtin(action) => action
                .default_shortcut()
                .map(str::to_owned),
            ContextAction::Entry(entry) => entry
                .shortcut
                .clone()
                .or_else(|| entry.action.default_shortcut().map(str::to_owned)),
            ContextAction::Command(cmd) => cmd.shortcut.clone(),
            ContextAction::Submenu(_) => None,
        }
    }
}

/// A context-menu rule: rows claimed by any `matches` entry get exactly
/// `items`. Rules are evaluated top-down; the first match wins.
///
/// A rule may instead be an **include**: `include = "rules.d"` (no `matches`)
/// pulls in the `[[context_menu.rules]]` of every `*.toml` file in that
/// directory, spliced in at the include's position. This lets specific rules
/// live in their own files yet still be checked *before* a later catch-all
/// `fallback` rule. See [`expand_includes`].
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ContextRule {
    #[serde(default)]
    pub matches: Vec<ContextMatch>,
    #[serde(default)]
    pub items: Vec<ContextAction>,
    /// Directory (relative to the config file, or absolute) whose `*.toml`
    /// files supply rules to splice in here. Mutually exclusive with `matches`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub include: Option<PathBuf>,
}

impl ContextRule {
    /// A plain matching rule.
    pub fn rule(matches: Vec<ContextMatch>, items: Vec<ContextAction>) -> Self {
        ContextRule { matches, items, include: None }
    }

    /// An include placeholder.
    pub fn include(path: PathBuf) -> Self {
        ContextRule { matches: Vec::new(), items: Vec::new(), include: Some(path) }
    }
}

/// Configurable per-row context menus.
///
/// With no configuration the built-in rules produce the classic menu; the
/// built-in defaults are listed below so users can copy and adapt them.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ContextMenu {
    pub rules: Vec<ContextRule>,
}

#[cfg(test)]
macro_rules! builtin_items {
    ($($name:ident),* $(,)?) => {
        vec![
            $(ContextAction::Builtin(BuiltinAction::$name),)*
        ]
    };
}

impl ContextMenu {
    /// The menu for a row no rule claims. Sourced from the first `dir`/`fallback`
    /// rule of the shipped default (so `default-config.toml` also decides the
    /// fallback); an empty menu when neither is present.
    pub fn fallback_actions(path: &Path) -> Vec<ContextAction> {
        let wanted = if path.is_dir() { ContextMatch::Dir } else { ContextMatch::Fallback };
        builtin()
            .context_menu
            .rules
            .iter()
            .find(|rule| rule.matches.contains(&wanted))
            .map(|rule| rule.items.clone())
            .unwrap_or_default()
    }

    /// The menu actions for `path`, in display order.
    ///
    /// Resolution is top-down over [`Self::rules`]; the first rule with at
    /// least one claimed matcher provides the whole menu. Rows no rule claims
    /// get [`Self::fallback_actions`].
    pub fn actions_for(&self, path: &Path) -> Vec<ContextAction> {
        for rule in &self.rules {
            if rule.matches.iter().any(|m| m.matches(path)) {
                return rule.items.clone();
            }
        }
        Self::fallback_actions(path)
    }

    /// The menu actions for a context menu opened over the given selection.
    ///
    /// When more than one row is selected the first rule carrying the
    /// [`Multi`](ContextMatch::Multi) matcher provides the whole menu (so a
    /// `multi` rule takes precedence over the per-path rules). For a single
    /// selection this is exactly [`Self::actions_for`].
    pub fn actions_for_selection(&self, path: &Path, selection_len: usize) -> Vec<ContextAction> {
        if selection_len > 1 {
            for rule in &self.rules {
                if rule.matches.contains(&ContextMatch::Multi) {
                    return rule.items.clone();
                }
            }
        }
        self.actions_for(path)
    }

    /// Every configured shortcut, in rule order, deduplicated (first wins).
    ///
    /// These drive the tree's keyboard handling: while the tree is focused, a
    /// pressed key fires the bound action against the row under the cursor.
    /// Shortcuts are collected from *all* rules (not just the one that claims
    /// the current row), so a shortcut stays live wherever its action is
    /// reachable in some menu.
    pub fn shortcuts(&self) -> Vec<(String, ShortcutTarget)> {
        let mut seen = std::collections::HashSet::new();
        let mut out = Vec::new();
        for rule in &self.rules {
            collect_shortcuts(&rule.items, &mut seen, &mut out);
        }
        out
    }
}

/// Recursively collect shortcuts from `actions`, descending into submenus.
/// `seen` deduplicates by accelerator so the first binding wins.
fn collect_shortcuts(
    actions: &[ContextAction],
    seen: &mut std::collections::HashSet<String>,
    out: &mut Vec<(String, ShortcutTarget)>,
) {
    for action in actions {
        if let Some(items) = action.submenu_items() {
            collect_shortcuts(items, seen, out);
            continue;
        }
        let Some(shortcut) = action.shortcut() else {
            continue;
        };
        if !seen.insert(shortcut.clone()) {
            continue;
        }
        if let Some(target) = ShortcutTarget::from_action(action) {
            out.push((shortcut, target));
        }
    }
}

impl Default for ContextMenu {
    fn default() -> Self {
        builtin().context_menu.clone()
    }
}

/// The configurable hamburger ("pane") menu that opens from the toolbar.
///
/// Unlike the per-row [`ContextMenu`] there are no match rules — the pane menu
/// is one flat list of items that apply to the whole pane (open a folder, toggle
/// hidden files, change the sort order, close the pane, ...). Items reuse the same
/// [`ContextAction`] vocabulary as the context menu, so builtins, table entries
/// with a shortcut, and custom commands all work here too.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct PaneMenu {
    pub items: Vec<ContextAction>,
}

impl PaneMenu {
    /// The label for each item, in display order (used by tests and the UI).
    pub fn labels(&self) -> Vec<String> {
        self.items.iter().map(ContextAction::label).collect()
    }

    /// Every shortcut attached to a pane-menu item, in order, deduplicated
    /// (first wins). Merged with the context-menu shortcuts so pane actions
    /// (`Ctrl+h`, `Ctrl+1`...) work while the tree is focused.
    pub fn shortcuts(&self) -> Vec<(String, ShortcutTarget)> {
        let mut seen = std::collections::HashSet::new();
        let mut out = Vec::new();
        collect_shortcuts(&self.items, &mut seen, &mut out);
        out
    }
}

impl Default for PaneMenu {
    fn default() -> Self {
        builtin().pane_menu.clone()
    }
}

/// Top-level configuration.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(default)]
pub struct Config {
    pub panel: PanelConfig,
    pub tree: TreeConfig,
    pub startup: StartupRoot,
    pub context_menu: ContextMenu,
    pub pane_menu: PaneMenu,
}

impl Default for Config {
    /// The shipped defaults, parsed from `default-config.toml` (see [`builtin`]).
    /// `#[serde(default)]` above uses this to fill any section a user's file
    /// omits, so editing `default-config.toml` changes both.
    fn default() -> Self {
        builtin().clone()
    }
}

impl Config {
    /// Load the config file for the current environment.
    ///
    /// On first launch — when neither the config file nor its `tree-space`
    /// directory exists — the default config is written out to disk first, so
    /// the user always has a file to edit afterwards.
    ///
    /// Unparsable files fall back to defaults with an error report (a broken
    /// dotfile cannot take down the panel, and is never clobbered).
    pub fn load() -> LoadResult {
        Self::load_and_ensure(&config_file())
    }

    /// [`Self::load`] against an explicit path (tests).
    fn load_and_ensure(path: &Path) -> LoadResult {
        let result = Self::load_from_path(path);
        if result.problem.is_none()
            && !path.exists()
            && let Err(problem) = Self::ensure_default_file(path)
        {
            return LoadResult { config: result.config, problem: Some(problem) };
        }
        result
    }

    /// Write the default config to `<path>`, creating parent directories. Used
    /// on first launch so a config file always exists. Best-effort: failures
    /// are reported but never prevent startup.
    ///
    /// Skips the attempt entirely when neither the config directory nor the
    /// file exists *and* the parent directory is not writable: a read-only
    /// `$XDG_CONFIG_HOME` then produces no error on every launch (the panel
    /// simply uses defaults).
    fn ensure_default_file(path: &Path) -> Result<(), LoadProblem> {
        let Some(parent) = path.parent() else {
            return Err(LoadProblem::Io(path.to_path_buf(), std::io::ErrorKind::NotFound));
        };
        if !parent.exists()
            && let Err(err) = std::fs::create_dir_all(parent)
        {
            return Err(LoadProblem::Io(parent.to_path_buf(), err.kind()));
        }
        // A read-only directory is a normal, expected setup (e.g. a Nix or
        // immutable-home install); treat it as "no config to write" rather
        // than an error.
        if let Ok(metadata) = std::fs::metadata(parent)
            && metadata.permissions().readonly()
        {
            return Ok(());
        }
        std::fs::write(path, DEFAULT_CONFIG)
            .map_err(|err| LoadProblem::Io(path.to_path_buf(), err.kind()))
    }

    /// Parse a config from a file, returning any problem encountered.
    pub fn load_from_path(path: &Path) -> LoadResult {
        let raw = match std::fs::read_to_string(path) {
            Ok(raw) => raw,
            Err(err) if err.kind() == std::io::ErrorKind::NotFound => {
                return LoadResult {
                    config: Config::default(),
                    problem: None,
                };
            }
            Err(err) => {
                return LoadResult {
                    config: Config::default(),
                    problem: Some(LoadProblem::Io(path.to_path_buf(), err.kind())),
                };
            }
        };
        Self::parse(&raw, path)
    }

    /// Validate and normalize a parsed config.
    fn normalize(mut self) -> Self {
        self.panel.width = self
            .panel
            .width
            .clamp(PANEL_MIN_WIDTH, PANEL_MAX_WIDTH);
        self.panel.margin = self.panel.margin.clamp(0, 200);
        self.tree.font_size = self.tree.font_size.clamp(6, 40);
        self.tree.icon_size = self.tree.icon_size.clamp(12, 128);
        self
    }
}

/// Why a config could not be loaded cleanly. Absence of a problem (/ defaults
/// used because the file doesn't exist) is not reported.
#[derive(Debug, Clone)]
pub enum LoadProblem {
    Io(PathBuf, std::io::ErrorKind),
    Parse(PathBuf, toml::de::Error),
}

/// The outcome of loading a config: always a usable config plus an optional
/// problem description for the status bar.
#[derive(Debug, Clone)]
pub struct LoadResult {
    pub config: Config,
    pub problem: Option<LoadProblem>,
}

/// The outcome of loading the user stylesheet.
#[derive(Debug, Clone)]
pub struct Stylesheet {
    /// The CSS to apply: the user's file when present and readable, otherwise
    /// the shipped default.
    pub css: String,
    /// Where the CSS came from, for a status message or diagnostics.
    pub source: StyleSource,
    /// A read problem, when the file existed but could not be read. The `css`
    /// then falls back to the shipped default.
    pub problem: Option<LoadProblem>,
}

/// Which stylesheet [`load_stylesheet`] actually returned.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum StyleSource {
    /// The user's `main.css`.
    User,
    /// The compiled-in default (no user file, or it could not be read).
    Builtin,
}

/// Load the user stylesheet for the current environment.
///
/// Prefers `$XDG_CONFIG_HOME/tree-space/main.css`; when that is missing the
/// shipped default is used. On first launch the default is written out first
/// (see [`ensure_default_stylesheet`]) so a file always exists to edit.
pub fn load_stylesheet() -> Stylesheet {
    let path = style_file();
    // Materialize the default on first launch, mirroring the config file, so
    // there is always something to edit.
    let _ = ensure_default_stylesheet(&path);
    load_stylesheet_from_path(&path)
}

/// Read the stylesheet at `path`, falling back to the built-in default when it
/// is missing or unreadable.
fn load_stylesheet_from_path(path: &Path) -> Stylesheet {
    match std::fs::read_to_string(path) {
        Ok(css) => Stylesheet {
            css,
            source: StyleSource::User,
            problem: None,
        },
        Err(err) if err.kind() == std::io::ErrorKind::NotFound => Stylesheet {
            css: DEFAULT_STYLESHEET.to_owned(),
            source: StyleSource::Builtin,
            problem: None,
        },
        Err(err) => Stylesheet {
            css: DEFAULT_STYLESHEET.to_owned(),
            source: StyleSource::Builtin,
            problem: Some(LoadProblem::Io(path.to_path_buf(), err.kind())),
        },
    }
}

/// Write the shipped stylesheet to `path` when it does not exist yet, creating
/// parent directories. Best-effort, like [`Config::ensure_default_file`]:
/// a read-only config directory simply means "no file to write", not an error.
fn ensure_default_stylesheet(path: &Path) -> Result<(), LoadProblem> {
    if path.exists() {
        return Ok(());
    }
    let Some(parent) = path.parent() else {
        return Err(LoadProblem::Io(path.to_path_buf(), std::io::ErrorKind::NotFound));
    };
    if !parent.exists()
        && let Err(err) = std::fs::create_dir_all(parent)
    {
        return Err(LoadProblem::Io(parent.to_path_buf(), err.kind()));
    }
    if let Ok(metadata) = std::fs::metadata(parent)
        && metadata.permissions().readonly()
    {
        return Ok(());
    }
    std::fs::write(path, DEFAULT_STYLESHEET)
        .map_err(|err| LoadProblem::Io(path.to_path_buf(), err.kind()))
}

impl Config {
    /// Parse TOML text, reporting parse problems without aborting.
    fn parse(raw: &str, path: &Path) -> LoadResult {
        match toml::from_str::<Config>(raw) {
            Ok(mut config) => {
                // Resolve `include = "..."` rules relative to the config file.
                let base = path.parent().unwrap_or_else(|| Path::new("."));
                let mut problems = Vec::new();
                config.context_menu.rules =
                    expand_includes(&config.context_menu.rules, base, 0, &mut problems);
                let config = config.normalize();
                LoadResult {
                    config,
                    // Only the first problem is surfaced, matching the single
                    // status-line slot; the config is still fully usable.
                    problem: problems.into_iter().next(),
                }
            }
            Err(err) => LoadResult {
                config: Config::default(),
                problem: Some(LoadProblem::Parse(path.to_path_buf(), err)),
            },
        }
    }
}

/// Maximum include nesting, so a cycle (`a.toml` inside the directory it
/// includes) cannot recurse forever.
const MAX_INCLUDE_DEPTH: usize = 8;

/// The shape of a drop-in file pulled in by an include rule: the same
/// `[[context_menu.rules]]` table as the main config, nothing else.
#[derive(Deserialize)]
struct IncludedRules {
    #[serde(default)]
    context_menu: ContextMenu,
}

/// Replace every include rule in `rules` with the rules of the `*.toml` files
/// in its directory, spliced in at the include's position.
///
/// The directory is resolved relative to `base` (the containing config file's
/// directory). Files are read in filename order (so `10-a.toml` sorts before
/// `20-b.toml`), and each file's `[[context_menu.rules]]` are expanded
/// recursively. A missing directory contributes nothing; an unreadable or
/// unparsable file is added to `problems` and skipped, so one bad drop-in never
/// breaks the rest of the menu.
fn expand_includes(
    rules: &[ContextRule],
    base: &Path,
    depth: usize,
    problems: &mut Vec<LoadProblem>,
) -> Vec<ContextRule> {
    let mut out = Vec::new();
    for rule in rules {
        let Some(include) = &rule.include else {
            out.push(rule.clone());
            continue;
        };
        if depth >= MAX_INCLUDE_DEPTH {
            continue;
        }
        let dir = if include.is_absolute() {
            include.clone()
        } else {
            base.join(include)
        };
        for file in toml_files_in(&dir, problems) {
            // Nested includes resolve relative to *this* file's directory.
            let nested_base = file.parent().unwrap_or(base);
            match std::fs::read_to_string(&file) {
                Ok(text) => match toml::from_str::<IncludedRules>(&text) {
                    Ok(included) => {
                        out.extend(expand_includes(
                            &included.context_menu.rules,
                            nested_base,
                            depth + 1,
                            problems,
                        ));
                    }
                    Err(err) => problems.push(LoadProblem::Parse(file.clone(), err)),
                },
                Err(err) => problems.push(LoadProblem::Io(file.clone(), err.kind())),
            }
        }
    }
    out
}

/// The `*.toml` files directly inside `dir`, sorted by filename. A missing
/// directory (or one that cannot be read) yields an empty list.
fn toml_files_in(dir: &Path, problems: &mut Vec<LoadProblem>) -> Vec<PathBuf> {
    let entries = match std::fs::read_dir(dir) {
        Ok(entries) => entries,
        // A missing include directory is normal: contribute nothing.
        Err(err) if err.kind() == std::io::ErrorKind::NotFound => return Vec::new(),
        Err(err) => {
            problems.push(LoadProblem::Io(dir.to_path_buf(), err.kind()));
            return Vec::new();
        }
    };
    let mut files: Vec<PathBuf> = entries
        .filter_map(Result::ok)
        .map(|entry| entry.path())
        .filter(|path| {
            path.is_file()
                && path
                    .extension()
                    .is_some_and(|ext| ext.eq_ignore_ascii_case("toml"))
        })
        .collect();
    files.sort();
    files
}

// ---------------------------------------------------------------------------
// Session state
// ---------------------------------------------------------------------------

/// Small runtime state persisted between launches.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct SessionState {
    /// The most recently opened root directory, if any.
    pub last_root: Option<PathBuf>,
    /// Left dock width from the last interactive resize, if any. Overrides the
    /// configured `[panel] width` on the next launch.
    pub left_width: Option<u32>,
    /// Right dock width from the last interactive resize, if any.
    pub right_width: Option<u32>,
}

impl SessionState {
    /// Load state from the environment's state file. Missing or broken files
    /// yield an empty default.
    pub fn load() -> Self {
        Self::load_from_path(&state_file())
    }

    /// Load state from an explicit path.
    pub fn load_from_path(path: &Path) -> Self {
        match std::fs::read_to_string(path) {
            Ok(raw) => toml::from_str(&raw).unwrap_or_default(),
            Err(_) => Self::default(),
        }
    }

    /// Persist state to the environment's state file, creating directories.
    pub fn save(&self) -> std::io::Result<()> {
        Self::save_to_path(&state_file(), self)
    }

    /// Persist state to an explicit path, creating parent directories.
    ///
    /// Atomic: the serialized bytes are written to a sibling temp file first and
    /// then `rename`d over the target, so a crash mid-write can never leave a
    /// truncated `state.toml` behind (the old file stays intact until the swap).
    pub fn save_to_path(path: &Path, state: &Self) -> std::io::Result<()> {
        if let Some(parent) = path.parent() {
            std::fs::create_dir_all(parent)?;
        }
        let body = toml::to_string(state).map_err(|e| {
            std::io::Error::new(std::io::ErrorKind::InvalidData, e.to_string())
        })?;
        let tmp = path.with_extension("toml.tmp");
        std::fs::write(&tmp, body)?;
        std::fs::rename(&tmp, path)
    }
}

/// Build a command line for a custom context-menu action on `path`.
///
/// The template is tokenized on whitespace.
/// Literal `{path}` is replaced with the row's full path and `{dir}` with the
/// directory row itself (or, for a file row, its parent). When the template has
/// neither marker, the row's path is appended as the trailing argument.
pub fn action_command(template: &str, path: &Path) -> Vec<String> {
    let path_s = path.to_string_lossy();
    let dir = if path.is_dir() {
        path.to_string_lossy()
    } else {
        path.parent().unwrap_or(path).to_string_lossy()
    };
    let has_path = template.contains("{path}");
    let has_dir = template.contains("{dir}");
    let mut tokens: Vec<String> = template
        .split_whitespace()
        .map(|t| t.replace("{path}", &path_s).replace("{dir}", &dir))
        .filter(|t| !t.is_empty())
        .collect();
    if !has_path && !has_dir {
        tokens.push(path_s.into_owned());
    }
    tokens
}

#[cfg(test)]
mod tests {
    use super::*;

    fn parse(raw: &str) -> Config {
        Config::parse(raw, Path::new("test.toml")).config
    }

    #[test]
    fn defaults_are_sane() {
        // Values themselves live in `default-config.toml` (the single source of
        // truth); this only checks they are structurally usable, so it does not
        // become a second copy of the defaults.
        let config = Config::default();
        assert!((PANEL_MIN_WIDTH..=PANEL_MAX_WIDTH).contains(&config.panel.width));
        assert!(config.tree.icon_size > 0);
        assert!(config.tree.font_size > 0);
        assert!(!config.context_menu.rules.is_empty());
        assert!(!config.pane_menu.items.is_empty());
    }

    #[test]
    fn shipping_default_file_parses_and_is_current() {
        // `default-config.toml` is the single source of truth; `Config::default`
        // parses it. This guards that the embedded copy still parses cleanly and
        // matches the file on disk (so an un-rebuilt stale include is caught).
        assert_eq!(parse(DEFAULT_CONFIG), Config::default());

        let written = std::fs::read_to_string(concat!(
            env!("CARGO_MANIFEST_DIR"),
            "/default-config.toml"
        ))
        .unwrap();
        assert_eq!(DEFAULT_CONFIG, written);
    }

    #[test]
    fn empty_document_uses_defaults() {
        let config = parse("");
        assert_eq!(config, Config::default());
    }

    #[test]
    fn full_document_round_trips() {
        let raw = r#"
[panel]
side = "right"
layer = "top"
width = 420
margin = 8

[tree]
dirs_first = false
show_hidden = true
font_size = 14
icon_size = 20
"#;
        let config = parse(raw);
        assert_eq!(config.panel.side, PanelSide::Right);
        assert_eq!(config.panel.layer, PanelLayer::Top);
        assert_eq!(config.panel.width, 420);
        assert!(!config.tree.dirs_first);
        assert!(config.tree.show_hidden);

        // Round-trip through TOML serialization.
        let reparsed = toml::from_str::<Config>(&toml::to_string(&config).unwrap()).unwrap();
        assert_eq!(config, reparsed);
    }

    #[test]
    fn partial_document_is_merged_with_defaults() {
        let config = parse("[panel]\nside = \"right\"\n");
        assert_eq!(config.panel.side, PanelSide::Right);
        assert_eq!(config.panel.width, Config::default().panel.width);
        assert_eq!(config.tree, Config::default().tree);
    }

    #[test]
    fn defaults_come_from_the_shipped_file() {
        // Every section's default (not just the whole config) must be the value
        // parsed from `default-config.toml`, so editing that file is sufficient.
        let shipped = parse(DEFAULT_CONFIG);
        assert_eq!(Config::default(), shipped);
        assert_eq!(PanelConfig::default(), shipped.panel);
        assert_eq!(TreeConfig::default(), shipped.tree);
        assert_eq!(ContextMenu::default(), shipped.context_menu);
        assert_eq!(PaneMenu::default(), shipped.pane_menu);
        // A partial *section* falls back to the shipped value of the missing key.
        let partial = parse("[tree]\nfont_size = 21\n");
        assert_eq!(partial.tree.font_size, 21);
        assert_eq!(partial.tree.icon_size, shipped.tree.icon_size);
        assert_eq!(partial.tree.sort_key, shipped.tree.sort_key);
        assert_eq!(partial.tree.confirm_drop_move, shipped.tree.confirm_drop_move);
        // Drop-to-move is immediate by default; confirmation is opt-in.
        assert!(!shipped.tree.confirm_drop_move);
    }

    #[test]
    fn out_of_range_values_are_clamped() {
        let config = parse(
            "[panel]\nwidth = 100000\nmargin = 9000\n\n[tree]\nfont_size = 2\nicon_size = 2\n",
        );
        assert_eq!(config.panel.width, 2000);
        assert_eq!(config.panel.margin, 200);
        assert_eq!(config.tree.font_size, 6);
        assert_eq!(config.tree.icon_size, 12);
    }

    #[test]
    fn invalid_toml_falls_back_to_defaults_with_problem() {
        let result = Config::parse("panel = ", Path::new("broken.toml"));
        assert_eq!(result.config, Config::default());
        assert!(matches!(result.problem, Some(LoadProblem::Parse(..))));
    }

    #[test]
    fn missing_file_yields_defaults_without_problem() {
        let result = Config::load_from_path(Path::new("/definitely/not/here/config.toml"));
        assert_eq!(result.config, Config::default());
        assert!(result.problem.is_none());
    }

    #[test]
    fn first_launch_materializes_default_config_file() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("tree-space/config.toml");
        assert!(!path.exists());

        let result = Config::load_and_ensure(&path);
        assert_eq!(result.config, Config::default());
        assert!(result.problem.is_none());

        // The directory and file were created with the shipped template.
        let written = std::fs::read_to_string(&path).unwrap();
        assert_eq!(written, DEFAULT_CONFIG);

        // A second load reads it back cleanly.
        let reloaded = Config::load_and_ensure(&path);
        assert_eq!(reloaded.config, Config::default());
        assert!(reloaded.problem.is_none());
    }

    #[test]
    fn existing_file_is_never_overwritten() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("tree-space/config.toml");
        std::fs::create_dir_all(path.parent().unwrap()).unwrap();
        std::fs::write(&path, "[panel]\nwidth = 500\n").unwrap();

        let result = Config::load_and_ensure(&path);
        assert_eq!(result.config.panel.width, 500);
        assert!(result.problem.is_none());
        assert_eq!(std::fs::read_to_string(&path).unwrap(), "[panel]\nwidth = 500\n");
    }

    #[test]
    fn xdg_config_resolution_follows_spec() {
        // Explicit override wins.
        assert_eq!(
            xdg_config_home(Some("/opt/cfg"), Some("/home/u")),
            PathBuf::from("/opt/cfg")
        );
        // Falls back below HOME.
        assert_eq!(
            xdg_config_home(None, Some("/home/u")),
            PathBuf::from("/home/u/.config")
        );
        assert_eq!(
            xdg_state_home(None, Some("/home/u")),
            PathBuf::from("/home/u/.local/state")
        );
        // Empty XDG values are ignored per the spec.
        assert_eq!(xdg_config_home(Some(""), Some("/h")), PathBuf::from("/h/.config"));
    }

    #[test]
    fn app_path_joins_app_dir() {
        assert_eq!(
            app_path(&PathBuf::from("/cfg"), STATE_FILE),
            PathBuf::from("/cfg/tree-space/state.toml")
        );
    }

    #[test]
    fn session_state_round_trips_through_disk() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("state.toml");
        let state = SessionState {
            last_root: Some(PathBuf::from("/home/user/projects/foo")),
            left_width: Some(420),
            right_width: None,
        };
        SessionState::save_to_path(&path, &state).unwrap();
        assert_eq!(SessionState::load_from_path(&path), state);
    }

    #[test]
    fn missing_or_broken_state_defaults() {
        let dir = tempfile::tempdir().unwrap();
        let broken = dir.path().join("broken.toml");
        std::fs::write(&broken, "not [ valid").unwrap();
        assert_eq!(SessionState::load_from_path(&broken), SessionState::default());
        assert_eq!(
            SessionState::load_from_path(&dir.path().join("missing.toml")),
            SessionState::default()
        );
    }

    /// Flatten every label in a menu, descending into submenus, so tests can
    /// assert against items regardless of nesting.
    fn all_labels(actions: &[ContextAction]) -> Vec<String> {
        let mut out = Vec::new();
        for action in actions {
            match action.submenu_items() {
                Some(items) => out.extend(all_labels(items)),
                None => out.push(action.label()),
            }
        }
        out
    }

    #[test]
    fn default_context_menu_reproduces_classic_items() {
        let menu = ContextMenu::default();
        let dir = tempfile::tempdir().unwrap();
        let file = dir.path().join("notes.txt");
        std::fs::write(&file, "").unwrap();
        std::fs::write(dir.path().join("photo.jpg"), "").unwrap();

        let dir_labels = all_labels(&menu.actions_for(dir.path()));
        // Classic items still present (now reachable through the "Open"/"New"
        // submenus)...
        for classic in [
            "In same panel",
            "In split view",
            "Folder",
            "File",
            "Copy Path",
            "Move to Trash",
            "Delete Permanently",
        ] {
            assert!(dir_labels.contains(&classic.to_owned()), "missing {classic}: {dir_labels:?}");
        }
        // ...plus the file-manager parity additions.
        for parity in ["In opposite panel", "With...", "Cut", "Copy", "Paste", "Create Link", "Rename", "Properties"] {
            assert!(
                dir_labels.contains(&parity.to_owned()),
                "missing {parity}: {dir_labels:?}"
            );
        }

        let file_labels = all_labels(&menu.actions_for(&file));
        // Directory-only items are dropped for files.
        for dropped in ["In split view", "In opposite panel"] {
            assert!(!file_labels.contains(&dropped.to_owned()), "{dropped} present: {file_labels:?}");
        }
        // The file "Open" submenu offers both the default app and "With...".
        assert!(file_labels.contains(&"With Default".to_owned()));
        assert!(file_labels.contains(&"With...".to_owned()));
        assert!(file_labels.len() > 15);

        // Shortcuts are spelled out on the default actions (submenu items too).
        let menus = menu.actions_for(dir.path());
        let cut = menus
            .iter()
            .flat_map(flatten_actions)
            .find(|a| a.label() == "Cut")
            .expect("Cut present");
        assert_eq!(cut.shortcut().as_deref(), Some("Ctrl+x"));
        let trash = menus
            .iter()
            .flat_map(flatten_actions)
            .find(|a| a.label() == "Move to Trash")
            .expect("Trash present");
        assert_eq!(trash.shortcut().as_deref(), Some("Delete"));
    }

    /// Borrow every leaf action in a menu, descending into submenus.
    fn flatten_actions(action: &ContextAction) -> Vec<&ContextAction> {
        match action.submenu_items() {
            Some(items) => items.iter().flat_map(flatten_actions).collect(),
            None => vec![action],
        }
    }

    #[test]
    fn default_shortcuts_follow_conventions() {
        assert_eq!(BuiltinAction::Cut.default_shortcut(), Some("Ctrl+x"));
        assert_eq!(BuiltinAction::Copy.default_shortcut(), Some("Ctrl+c"));
        assert_eq!(BuiltinAction::Rename.default_shortcut(), Some("F2"));
        assert_eq!(BuiltinAction::CreateLink.default_shortcut(), Some("Ctrl+Shift+m"));
        assert_eq!(BuiltinAction::Trash.default_shortcut(), Some("Delete"));
        assert_eq!(BuiltinAction::DeletePermanently.default_shortcut(), Some("Shift+Delete"));
        assert_eq!(BuiltinAction::ViewThumbnail.default_shortcut(), Some("Ctrl+t"));
        assert_eq!(BuiltinAction::Open.default_shortcut(), None);
        assert_eq!(BuiltinAction::Separator.default_shortcut(), None);
    }

    #[test]
    fn shortcuts_are_collected_top_down_and_deduplicated() {
        let menu = ContextMenu {
            rules: vec![
                ContextRule::rule(
                    vec![ContextMatch::Dir],
                    vec![
                        ContextAction::Builtin(BuiltinAction::Open),
                        ContextAction::Entry(BuiltinEntry {
                            action: BuiltinAction::Rename,
                            label: None,
                            shortcut: Some("F2".into()),
                            hidden: false,
                        }),
                        ContextAction::Command(CommandAction {
                            command: "code {path}".into(),
                            label: None,
                            shortcut: Some("Ctrl+Shift+e".into()),
                            hidden: false,
                        }),
                    ],
                ),
                ContextRule::rule(
                    vec![ContextMatch::Fallback],
                    vec![ContextAction::Builtin(BuiltinAction::Trash)],
                ),
            ],
        };
        let shortcuts = menu.shortcuts();
        // Open has no shortcut; separators would contribute none either.
        assert_eq!(
            shortcuts,
            vec![
                ("F2".to_owned(), ShortcutTarget::Builtin(BuiltinAction::Rename)),
                ("Ctrl+Shift+e".to_owned(), ShortcutTarget::Command(CommandAction {
                    command: "code {path}".into(),
                    label: None,
                    shortcut: Some("Ctrl+Shift+e".into()),
                    hidden: false,
                })),
                ("Delete".to_owned(), ShortcutTarget::Builtin(BuiltinAction::Trash)),
            ]
        );
    }

    #[test]
    fn table_form_spells_out_shortcuts_and_labels() {
        let raw = r#"
[[context_menu.rules]]
matches = ["fallback"]
items = [
    { action = "Cut", shortcut = "Ctrl+Alt+x", label = "Cut here" },
    { command = "sh {path}", shortcut = "Ctrl+Alt+s" },
    "---",
]
"#;
        let config = parse(raw);
        let actions = &config.context_menu.rules[0].items;
        assert_eq!(actions.len(), 3);

        match &actions[0] {
            ContextAction::Entry(entry) => {
                assert_eq!(entry.action, BuiltinAction::Cut);
                assert_eq!(entry.shortcut.as_deref(), Some("Ctrl+Alt+x"));
                assert_eq!(entry.label.as_deref(), Some("Cut here"));
                assert_eq!(actions[0].label(), "Cut here");
                assert_eq!(actions[0].shortcut().as_deref(), Some("Ctrl+Alt+x"));
            }
            other => panic!("expected Entry, got {other:?}"),
        }
        match &actions[1] {
            ContextAction::Command(cmd) => {
                assert_eq!(cmd.shortcut.as_deref(), Some("Ctrl+Alt+s"));
            }
            other => panic!("expected Command, got {other:?}"),
        }
        match &actions[2] {
            ContextAction::Builtin(BuiltinAction::Separator) => {}
            other => panic!("expected Separator, got {other:?}"),
        }

        let reparsed = toml::from_str::<Config>(&toml::to_string(&config).unwrap()).unwrap();
        assert_eq!(config, reparsed);
    }

    #[test]
    fn pane_actions_are_classified() {
        for action in [
            BuiltinAction::OpenFolder,
            BuiltinAction::Filter,
            BuiltinAction::SplitView,
            BuiltinAction::Collapse,
            BuiltinAction::ClosePane,
        ] {
            assert!(action.is_pane_action(), "{action:?} should be a pane action");
        }
        for action in [
            BuiltinAction::Open,
            BuiltinAction::OpenSplit,
            BuiltinAction::ToggleHidden,
            BuiltinAction::SortByName,
            BuiltinAction::Separator,
        ] {
            assert!(!action.is_pane_action(), "{action:?} is not a pane action");
        }
    }

    #[test]
    fn separator_matches_both_spellings() {
        assert_eq!(BuiltinAction::parse("---"), Some(BuiltinAction::Separator));
        assert_eq!(BuiltinAction::parse("separator"), Some(BuiltinAction::Separator));
        assert_eq!(BuiltinAction::parse("SEPARATOR"), Some(BuiltinAction::Separator));
        assert_eq!(BuiltinAction::Separator.as_str(), "---");
    }

    #[test]
    fn ellipsis_labels_use_ascii_and_accept_the_typographic_form() {
        // The canonical spellings are plain ASCII, so users can type them.
        assert_eq!(BuiltinAction::OpenWith.as_str(), "Open With...");
        assert_eq!(BuiltinAction::OpenFolder.as_str(), "Open Folder...");
        assert_eq!(BuiltinAction::Filter.as_str(), "Filter...");
        // The typographic ellipsis is still accepted as a synonym.
        assert_eq!(BuiltinAction::parse("Open With…"), Some(BuiltinAction::OpenWith));
        assert_eq!(BuiltinAction::parse("Open Folder…"), Some(BuiltinAction::OpenFolder));
        assert_eq!(BuiltinAction::parse("Filter…"), Some(BuiltinAction::Filter));
        // And the ASCII form parses too.
        assert_eq!(BuiltinAction::parse("open folder..."), Some(BuiltinAction::OpenFolder));
    }

    #[test]
    fn pane_menu_defaults_include_view_and_pane_actions() {
        let menu = PaneMenu::default();
        let labels = menu.labels();
        assert!(labels.contains(&"Open Folder...".to_owned()));
        assert!(labels.contains(&"Split View".to_owned()));
        assert!(labels.contains(&"Close Pane".to_owned()));
        assert!(labels.contains(&"Toggle Hidden Files".to_owned()));
        assert!(labels.contains(&"Sort by Size".to_owned()));
        // The view actions are NOT in the row context menus.
        let dir_menu = ContextMenu::default();
        let dir_labels: Vec<String> = dir_menu
            .rules
            .iter()
            .flat_map(|rule| rule.items.iter())
            .map(ContextAction::label)
            .collect();
        assert!(!dir_labels.contains(&"Toggle Hidden Files".to_owned()));
    }

    #[test]
    fn pane_menu_shortcuts_are_collected() {
        let menu = PaneMenu::default();
        let shortcuts = menu.shortcuts();
        assert!(shortcuts.iter().any(|(k, _)| k == "Ctrl+h"));
        assert!(shortcuts.iter().any(|(k, _)| k == "Ctrl+1"));
        // Separators and shortcut-less pane actions contribute nothing.
        assert!(shortcuts.iter().all(|(k, _)| !k.is_empty()));
    }

    #[test]
    fn pane_menu_parses_custom_commands() {
        let toml = r#"
            items = [
                "Split View",
                "---",
                { command = "echo hi", label = "Say hi" },
            ]
        "#;
        let menu: PaneMenu = toml::from_str(toml).unwrap();
        assert_eq!(menu.labels(), vec!["Split View", "---", "Say hi"]);
    }

    #[test]
    fn navigation_builtins_round_trip_and_are_pane_actions() {
        for action in [BuiltinAction::Up, BuiltinAction::Back, BuiltinAction::Forward] {
            let s = action.as_str();
            assert_eq!(BuiltinAction::parse(s), Some(action), "{s} should parse");
            assert!(action.is_pane_action(), "{s} should be a pane action");
            assert!(action.default_shortcut().is_some(), "{s} needs a default key");
        }
        assert_eq!(BuiltinAction::Up.default_shortcut(), Some("Alt+Up"));
        assert_eq!(BuiltinAction::Back.default_shortcut(), Some("Alt+Left"));
        assert_eq!(BuiltinAction::Forward.default_shortcut(), Some("Alt+Right"));
    }

    #[test]
    fn hidden_items_parse_and_keep_their_shortcut() {
        let toml = r#"
            items = [
                { action = "Up One Level", hidden = true },
                { command = "echo hi", label = "Say hi", shortcut = "Ctrl+g", hidden = true },
                { label = "More", hidden = true, items = [ "Copy Path" ] },
                "Open",
            ]
        "#;
        let menu: PaneMenu = toml::from_str(toml).unwrap();
        assert!(menu.items[0].is_hidden());
        assert!(menu.items[1].is_hidden());
        assert!(menu.items[2].is_hidden());
        assert!(!menu.items[3].is_hidden());
        // Hidden items are still parsed with their labels and shortcuts.
        assert_eq!(menu.items[0].label(), "Up One Level");
        assert_eq!(menu.items[1].shortcut().as_deref(), Some("Ctrl+g"));
        // And hidden items contribute their shortcuts exactly like visible ones.
        let shortcuts = menu.shortcuts();
        assert!(shortcuts.iter().any(|(k, _)| k == "Alt+Up"));
        assert!(shortcuts.iter().any(|(k, _)| k == "Ctrl+g"));
    }

    #[test]
    fn hidden_submenu_children_keep_their_shortcuts() {
        let toml = r#"
            items = [
                { label = "More", hidden = true, items = [
                    { action = "Rename", shortcut = "Ctrl+Shift+r" },
                ] },
            ]
        "#;
        let menu: PaneMenu = toml::from_str(toml).unwrap();
        assert!(menu.items[0].is_hidden());
        assert!(menu.shortcuts().iter().any(|(k, _)| k == "Ctrl+Shift+r"));
    }

    #[test]
    fn hidden_defaults_to_false_and_is_not_serialized() {
        #[derive(serde::Deserialize)]
        struct One {
            item: ContextAction,
        }
        let visible: One = toml::from_str(r#"item = { action = "Cut", shortcut = "Ctrl+x" }"#).unwrap();
        assert!(!visible.item.is_hidden());
        // A plain-string builtin can never be hidden.
        let plain: One = toml::from_str(r#"item = "Cut""#).unwrap();
        assert!(!plain.item.is_hidden());
        // Round-trips omit the flag when it is false.
        #[derive(serde::Serialize)]
        struct OneOut {
            item: ContextAction,
        }
        let encoded = toml::to_string(&OneOut { item: visible.item }).unwrap();
        assert!(!encoded.contains("hidden"), "{encoded}");
    }

    #[test]
    fn menu_items_parse_submenus_recursively() {
        let toml = r#"
            items = [
                "Open",
                { label = "More", items = [
                    { action = "Copy Path", shortcut = "Ctrl+Shift+c" },
                    { label = "Deeper", items = [ { command = "echo hi", label = "Hi" } ] },
                ] },
            ]
        "#;
        let menu: PaneMenu = toml::from_str(toml).unwrap();
        assert_eq!(menu.labels(), vec!["Open", "More"]);
        // A submenu reports its children and no shortcut of its own.
        let sub = &menu.items[1];
        assert!(sub.is_submenu());
        assert!(sub.shortcut().is_none());
        let children = sub.submenu_items().unwrap();
        assert_eq!(children.len(), 2);
        assert_eq!(children[0].label(), "Copy Path");
        assert!(children[1].is_submenu());
        // Shortcuts inside submenus (at any depth) stay live.
        let shortcuts = menu.shortcuts();
        assert!(shortcuts.iter().any(|(k, _)| k == "Ctrl+Shift+c"));
    }

    #[test]
    fn context_menu_collects_nested_shortcuts() {
        let raw = r#"
            [[context_menu.rules]]
            matches = ["dir"]
            items = [
                "Open",
                { label = "More", items = [
                    { action = "Copy Path", shortcut = "Ctrl+Shift+c" },
                ] },
            ]
            [[context_menu.rules]]
            matches = ["fallback"]
            items = ["Open"]
        "#;
        let config = parse(raw);
        let shortcuts = config.context_menu.shortcuts();
        assert!(shortcuts.iter().any(|(k, _)| k == "Ctrl+Shift+c"));
    }

    #[test]
    fn startup_last_uses_session_root() {
        let root = StartupRoot::Last;
        let last = Some(PathBuf::from("/tmp/last"));
        assert_eq!(root.resolve(last.clone()), last);
        assert_eq!(root.resolve(None), None);
    }

    #[test]
    fn startup_home_ignores_session_root() {
        let root = StartupRoot::Home;
        assert_eq!(root.resolve(Some(PathBuf::from("/tmp/last"))), None);
    }

    #[test]
    fn startup_path_uses_configured_directory() {
        let root = StartupRoot::Path("/tmp/fixed".to_owned());
        assert_eq!(
            root.resolve(Some(PathBuf::from("/tmp/last"))),
            Some(PathBuf::from("/tmp/fixed"))
        );
        // An empty path resolves to nothing, so callers fall back to home.
        assert_eq!(StartupRoot::Path(String::new()).resolve(None), None);
    }

    #[test]
    fn startup_tilde_expands_to_home() {
        // SAFETY: single-threaded test setup; HOME is read-only here.
        unsafe { std::env::set_var("HOME", "/home/tester") };
        let root = StartupRoot::Path("~/notes".to_owned());
        assert_eq!(root.resolve(None), Some(PathBuf::from("/home/tester/notes")));
        assert_eq!(expand_tilde("~"), Some(PathBuf::from("/home/tester")));
        assert_eq!(expand_tilde("/abs/path"), Some(PathBuf::from("/abs/path")));
        assert_eq!(expand_tilde(""), None);
        // A relative configured path is made absolute (against the cwd), so it
        // never surfaces as a bare relative spelling in the UI.
        let rel = expand_tilde("some/relative/dir").unwrap();
        assert!(rel.is_absolute(), "{rel:?} should be absolute");
        assert!(rel.ends_with("some/relative/dir"), "{rel:?}");
    }

    #[test]
    fn startup_parses_from_toml() {
        assert_eq!(parse("startup = \"home\"\n").startup, StartupRoot::Home);
        assert_eq!(parse("startup = \"last\"\n").startup, StartupRoot::Last);
        assert_eq!(
            parse("startup = { path = \"/srv\" }\n").startup,
            StartupRoot::Path("/srv".to_owned())
        );
        // Default is "home".
        assert_eq!(Config::default().startup, StartupRoot::Home);
        // An unknown keyword is rejected (whole config falls back to defaults).
        assert!(
            Config::parse("startup = \"bogus\"\n", Path::new("test.toml"))
                .problem
                .is_some()
        );
        // Round-trips through serialization.
        let cfg = Config { startup: StartupRoot::Path("/srv".to_owned()), ..Config::default() };
        let text = toml::to_string(&cfg).unwrap();
        assert_eq!(toml::from_str::<Config>(&text).unwrap().startup, cfg.startup);
    }

    #[test]
    fn context_matches_classify_rows() {
        let dir = tempfile::tempdir().unwrap();
        let file = dir.path().join("report.md");
        std::fs::write(&file, "").unwrap();
        let noext = dir.path().join("Makefile");
        std::fs::write(&noext, "").unwrap();
        let tarball = dir.path().join("app.tar.gz");
        std::fs::write(&tarball, "").unwrap();

        assert!(ContextMatch::parse("dir").unwrap().matches(dir.path()));
        assert!(!ContextMatch::parse("dir").unwrap().matches(&file));
        assert!(ContextMatch::parse("noext").unwrap().matches(&noext));
        assert!(!ContextMatch::parse("noext").unwrap().matches(&file));
        assert!(ContextMatch::parse("ext:md").unwrap().matches(&file));
        assert!(ContextMatch::parse("ext:MD").unwrap().matches(&file));
        assert!(ContextMatch::parse("ext:gz").unwrap().matches(&tarball));
        assert!(!ContextMatch::parse("ext:md").unwrap().matches(dir.path()));
        assert_eq!(ContextMatch::parse("directory"), Ok(ContextMatch::Dir));
        assert_eq!(ContextMatch::parse("*"), Ok(ContextMatch::Fallback));
        assert!(ContextMatch::parse("bogus").is_err());
    }

    #[test]
    fn regex_matcher_matches_the_full_path() {
        let dir = tempfile::tempdir().unwrap();
        let md = dir.path().join("guide.md");
        std::fs::write(&md, "").unwrap();

        // Anchored at the end of the full path.
        assert!(ContextMatch::parse(r"regex:\.md$").unwrap().matches(&md));
        assert!(!ContextMatch::parse(r"regex:\.rs$").unwrap().matches(&md));

        // Matching the directory path itself (regexes claim directories too).
        let exact = format!("regex:^{}$", regex::escape(dir.path().to_str().unwrap()));
        assert!(ContextMatch::parse(&exact).unwrap().matches(dir.path()));

        // Spelling round-trips through serialization.
        let parsed = ContextMatch::parse(r"regex:\.rs$").unwrap();
        assert_eq!(parsed.as_str(), r"regex:\.rs$");
        let reparsed = ContextMatch::parse(&parsed.as_str()).unwrap();
        assert_eq!(parsed, reparsed);
    }

    #[test]
    fn invalid_regex_is_a_parse_error() {
        let err = ContextMatch::parse("regex:(").unwrap_err();
        assert!(err.contains("invalid regex"), "got: {err}");
    }

    #[test]
    fn stylesheet_prefers_the_user_file_and_materializes_a_default() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("tree-space/main.css");

        // No file yet: the built-in default is returned (and no problem).
        let first = load_stylesheet_from_path(&path);
        assert_eq!(first.source, StyleSource::Builtin);
        assert!(first.problem.is_none());
        assert_eq!(first.css, DEFAULT_STYLESHEET);

        // Materializing writes the shipped default to the path.
        ensure_default_stylesheet(&path).unwrap();
        assert_eq!(std::fs::read_to_string(&path).unwrap(), DEFAULT_STYLESHEET);

        // A user edit is then picked up verbatim.
        std::fs::write(&path, ".tree-row { color: red; }").unwrap();
        let user = load_stylesheet_from_path(&path);
        assert_eq!(user.source, StyleSource::User);
        assert!(user.problem.is_none());
        assert_eq!(user.css, ".tree-row { color: red; }");
    }

    #[test]
    fn materialize_never_overwrites_an_existing_stylesheet() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("tree-space/main.css");
        std::fs::create_dir_all(path.parent().unwrap()).unwrap();
        std::fs::write(&path, "/* mine */").unwrap();

        ensure_default_stylesheet(&path).unwrap();
        assert_eq!(std::fs::read_to_string(&path).unwrap(), "/* mine */");
    }

    #[test]
    fn unreadable_stylesheet_falls_back_to_builtin_with_a_problem() {
        let dir = tempfile::tempdir().unwrap();
        // A directory where a file is expected: `read_to_string` fails with a
        // non-NotFound error, so we fall back and report it.
        let path = dir.path().join("main.css");
        std::fs::create_dir(&path).unwrap();

        let stylesheet = load_stylesheet_from_path(&path);
        assert_eq!(stylesheet.source, StyleSource::Builtin);
        assert_eq!(stylesheet.css, DEFAULT_STYLESHEET);
        assert!(matches!(stylesheet.problem, Some(LoadProblem::Io(..))));
    }

    #[test]
    fn include_rule_splices_files_in_place_and_name_sorted() {        let dir = tempfile::tempdir().unwrap();
        let rules_dir = dir.path().join("rules.d");
        std::fs::create_dir_all(&rules_dir).unwrap();
        // Two drop-ins, deliberately named so name-sort decides their order.
        std::fs::write(
            rules_dir.join("20-second.toml"),
            "[[context_menu.rules]]\nmatches = [\"ext:b\"]\nitems = [\"Properties\"]\n",
        )
        .unwrap();
        std::fs::write(
            rules_dir.join("10-first.toml"),
            "[[context_menu.rules]]\nmatches = [\"ext:a\"]\nitems = [\"Properties\", \"Copy Path\"]\n",
        )
        .unwrap();
        // A non-TOML file in the directory is ignored.
        std::fs::write(rules_dir.join("README.md"), "not config").unwrap();

        let main = dir.path().join("config.toml");
        std::fs::write(
            &main,
            r#"
[[context_menu.rules]]
matches = ["dir"]
items = ["Open"]

[[context_menu.rules]]
include = "rules.d"

[[context_menu.rules]]
matches = ["fallback"]
items = ["Move to Trash"]
"#,
        )
        .unwrap();

        let config = Config::load_from_path(&main);
        assert!(config.problem.is_none(), "{:?}", config.problem);
        let rules = &config.config.context_menu.rules;
        // dir, 10-first, 20-second, fallback — included rules land in place.
        assert_eq!(rules.len(), 4);
        assert_eq!(rules[0].matches, vec![ContextMatch::Dir]);
        assert_eq!(rules[1].matches, vec![ContextMatch::Ext("a".to_owned())]);
        assert_eq!(rules[2].matches, vec![ContextMatch::Ext("b".to_owned())]);
        assert_eq!(rules[3].matches, vec![ContextMatch::Fallback]);
        // The include placeholder itself is gone.
        assert!(rules.iter().all(|r| r.include.is_none()));
    }

    #[test]
    fn include_of_a_missing_directory_contributes_nothing() {
        let dir = tempfile::tempdir().unwrap();
        let main = dir.path().join("config.toml");
        std::fs::write(
            &main,
            "[[context_menu.rules]]\ninclude = \"nope.d\"\n\n[[context_menu.rules]]\nmatches = [\"fallback\"]\nitems = [\"Move to Trash\"]\n",
        )
        .unwrap();
        let result = Config::load_from_path(&main);
        // A missing include directory is not an error.
        assert!(result.problem.is_none(), "{:?}", result.problem);
        assert_eq!(result.config.context_menu.rules.len(), 1);
        assert_eq!(result.config.context_menu.rules[0].matches, vec![ContextMatch::Fallback]);
    }

    #[test]
    fn include_of_an_invalid_file_is_reported_but_others_still_load() {
        let dir = tempfile::tempdir().unwrap();
        let rules_dir = dir.path().join("rules.d");
        std::fs::create_dir_all(&rules_dir).unwrap();
        std::fs::write(rules_dir.join("10-good.toml"), "[[context_menu.rules]]\nmatches = [\"dir\"]\nitems = [\"Open\"]\n").unwrap();
        std::fs::write(rules_dir.join("20-bad.toml"), "this is not = valid toml [").unwrap();

        let main = dir.path().join("config.toml");
        std::fs::write(
            &main,
            "[[context_menu.rules]]\ninclude = \"rules.d\"\n",
        )
        .unwrap();

        let result = Config::load_from_path(&main);
        // The bad file is reported...
        assert!(matches!(result.problem, Some(LoadProblem::Parse(..))), "{:?}", result.problem);
        // ...but the good file's rule still made it in.
        assert_eq!(result.config.context_menu.rules.len(), 1);
        assert_eq!(result.config.context_menu.rules[0].matches, vec![ContextMatch::Dir]);
    }

    #[test]
    fn included_rules_are_expanded_recursively() {
        let dir = tempfile::tempdir().unwrap();
        let outer = dir.path().join("outer.d");
        let inner = outer.join("inner.d");
        std::fs::create_dir_all(&inner).unwrap();
        std::fs::write(inner.join("nested.toml"), "[[context_menu.rules]]\nmatches = [\"dir\"]\nitems = [\"Open\"]\n").unwrap();
        std::fs::write(
            outer.join("mid.toml"),
            "[[context_menu.rules]]\ninclude = \"inner.d\"\n",
        )
        .unwrap();

        let main = dir.path().join("config.toml");
        std::fs::write(&main, "[[context_menu.rules]]\ninclude = \"outer.d\"\n").unwrap();

        let result = Config::load_from_path(&main);
        assert!(result.problem.is_none(), "{:?}", result.problem);
        assert_eq!(result.config.context_menu.rules.len(), 1);
        assert_eq!(result.config.context_menu.rules[0].matches, vec![ContextMatch::Dir]);
    }

    #[test]
    fn first_matching_rule_wins() {
        let menu = ContextMenu {
            rules: vec![
                ContextRule::rule(
                    vec![ContextMatch::Ext("md".to_owned())],
                    builtin_items![CopyPath],
                ),
                ContextRule::rule(vec![ContextMatch::Fallback], builtin_items![Open]),
            ],
        };
        let dir = tempfile::tempdir().unwrap();
        let md = dir.path().join("a.md");
        std::fs::write(&md, "").unwrap();
        let txt = dir.path().join("a.txt");
        std::fs::write(&txt, "").unwrap();

        assert_eq!(menu.actions_for(&md), builtin_items![CopyPath]);
        // txt matches the second (fallback) rule, so it gets that rule's menu.
        assert_eq!(menu.actions_for(&txt), builtin_items![Open]);
    }

    #[test]
    fn multi_matcher_parses_and_never_matches_a_single_path() {
        assert_eq!(ContextMatch::parse("multi").unwrap(), ContextMatch::Multi);
        assert_eq!(ContextMatch::parse("multi-select").unwrap(), ContextMatch::Multi);
        assert_eq!(ContextMatch::Multi.as_str(), "multi");
        // A selection-level matcher is never true for one path.
        let dir = tempfile::tempdir().unwrap();
        assert!(!ContextMatch::Multi.matches(dir.path()));
    }

    #[test]
    fn multi_rule_wins_for_a_multi_selection_only() {
        let menu = ContextMenu {
            rules: vec![
                ContextRule::rule(vec![ContextMatch::Multi], builtin_items![Trash, CopyPath]),
                ContextRule::rule(vec![ContextMatch::Dir], builtin_items![Open]),
                ContextRule::rule(vec![ContextMatch::Fallback], builtin_items![Open]),
            ],
        };
        let dir = tempfile::tempdir().unwrap();

        // One selected path: the per-path rule applies.
        assert_eq!(menu.actions_for_selection(dir.path(), 1), builtin_items![Open]);
        // Two or more: the multi rule applies instead.
        assert_eq!(
            menu.actions_for_selection(dir.path(), 2),
            builtin_items![Trash, CopyPath]
        );
        assert_eq!(
            menu.actions_for_selection(dir.path(), 7),
            builtin_items![Trash, CopyPath]
        );
    }

    #[test]
    fn shipped_multi_rule_offers_selection_actions() {
        let menu = ContextMenu::default();
        let dir = tempfile::tempdir().unwrap();
        let file = dir.path().join("a.txt");
        std::fs::write(&file, "").unwrap();

        // One row: the multi rule does not intervene.
        let single = menu.actions_for_selection(&file, 1);
        assert_eq!(single, menu.actions_for(&file));

        // Two or more rows: the shipped `multi` rule supplies the menu, with the
        // fan-out actions present and single-row actions absent.
        let labels = all_labels(&menu.actions_for_selection(&file, 3));
        assert!(labels.contains(&"Move to Trash".to_owned()), "{labels:?}");
        assert!(labels.contains(&"Copy Path".to_owned()), "{labels:?}");
        assert!(labels.contains(&"Properties".to_owned()), "{labels:?}");
        assert!(!labels.contains(&"Rename".to_owned()), "{labels:?}");
        assert!(!labels.contains(&"Duplicate".to_owned()), "{labels:?}");
        assert!(!labels.contains(&"With...".to_owned()), "{labels:?}");
    }

    #[test]
    fn single_row_only_actions_are_classified() {
        assert!(BuiltinAction::Rename.is_single_row_only());
        assert!(BuiltinAction::Open.is_single_row_only());
        assert!(BuiltinAction::Duplicate.is_single_row_only());
        assert!(!BuiltinAction::Trash.is_single_row_only());
        assert!(!BuiltinAction::DeletePermanently.is_single_row_only());
        assert!(!BuiltinAction::Copy.is_single_row_only());
        assert!(!BuiltinAction::Cut.is_single_row_only());
        assert!(!BuiltinAction::Properties.is_single_row_only());
        assert!(!BuiltinAction::CopyPath.is_single_row_only());
    }

    #[test]
    fn empty_rule_list_falls_back_to_classic_menu() {
        let menu = ContextMenu { rules: Vec::new() };
        let dir = tempfile::tempdir().unwrap();
        assert_eq!(menu.actions_for(dir.path()), ContextMenu::fallback_actions(dir.path()));
    }

    #[test]
    fn custom_context_menu_round_trips() {
        let raw = r#"
[[context_menu.rules]]
matches = ["ext:rs", "ext:toml"]
items = ["Open", { command = "cargo fmt", label = "Fmt" }]

[[context_menu.rules]]
matches = ["dir"]
items = [{ command = "foot -D {dir}", label = "Open in Terminal" }, "New Folder"]

[[context_menu.rules]]
matches = ["noext"]
items = [{ command = "sh {path}" }]

[[context_menu.rules]]
matches = ['regex:.*\.lock$']
items = ["Open", { command = "rm {path}", label = "Discard lock" }]
"#;
        let config = parse(raw);
        assert_eq!(config.context_menu.rules.len(), 4);

        let first = &config.context_menu.rules[0];
        assert_eq!(
            first.matches,
            vec![ContextMatch::Ext("rs".to_owned()), ContextMatch::Ext("toml".to_owned())]
        );
        assert!(matches!(first.items[0], ContextAction::Builtin(BuiltinAction::Open)));
        assert!(matches!(
            &first.items[1],
            ContextAction::Command(cmd) if cmd.command == "cargo fmt" && cmd.label.as_deref() == Some("Fmt")
        ));

        let last = &config.context_menu.rules[3];
        assert_eq!(
            last.matches,
            vec![ContextMatch::parse(r"regex:.*\.lock$").unwrap()]
        );

        let reparsed = toml::from_str::<Config>(&toml::to_string(&config).unwrap()).unwrap();
        assert_eq!(config, reparsed);
    }

    #[test]
    fn unknown_builtin_action_is_a_parse_problem() {
        let result = Config::parse(
            "[[context_menu.rules]]\nmatches = [\"dir\"]\nitems = [\"Frobnicate\"]\n",
            Path::new("bad-menu.toml"),
        );
        assert!(matches!(result.problem, Some(LoadProblem::Parse(..))));
        assert_eq!(result.config, Config::default());
    }

    #[test]
    fn unknown_context_matcher_is_a_parse_problem() {
        let result = Config::parse(
            "[[context_menu.rules]]\nmatches = [\"gibberish\"]\nitems = [\"Open\"]\n",
            Path::new("bad-matcher.toml"),
        );
        assert!(matches!(result.problem, Some(LoadProblem::Parse(..))));
        assert_eq!(result.config, Config::default());
    }

    #[test]
    fn action_command_substitutes_markers() {
        let dir = tempfile::tempdir().unwrap();
        let dir_s = dir.path().to_string_lossy().into_owned();
        assert_eq!(
            action_command("code {path}", dir.path()),
            vec!["code".to_owned(), dir_s.clone()]
        );
        assert_eq!(
            action_command("code {dir}", &dir.path().join("x.rs")),
            vec!["code".to_owned(), dir_s]
        );
    }

    #[test]
    fn action_command_appends_path_without_marker() {
        assert_eq!(
            action_command("sh", Path::new("/tmp/s.sh")),
            vec!["sh".to_owned(), "/tmp/s.sh".to_owned()]
        );
    }
}