oxinav-core 0.5.0

Core logic for OxiNav: file operations, pane state, archives and viewing, with no UI dependency
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
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
use crate::archive::{
    classify_entry_path, detect_format, ArchiveEntry, ArchiveFormat, EntryKind, EntryTarget,
};
use crate::error::OxiNavError;
use crate::pane::matches_filter;
use crate::search::{pattern_error, snippet, SearchEnd, SearchHit, SearchQuery, MAX_HITS};
use std::ops::ControlFlow;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, Ordering};

#[derive(Debug, Clone)]
pub enum Operation {
    Copy {
        src: PathBuf,
        dest: PathBuf,
    },
    Move {
        src: PathBuf,
        dest: PathBuf,
    },
    Rename {
        src: PathBuf,
        dest: PathBuf,
    },
    Delete {
        path: PathBuf,
    },
    CreateDir {
        path: PathBuf,
    },
    CreateFile {
        path: PathBuf,
    },
    CreateSymlink {
        source: PathBuf,
        link: PathBuf,
    },
    ExtractArchive {
        archive: PathBuf,
        dest_dir: PathBuf,
    },
    /// Pack `sources` (and everything under them) into a new `archive`, with
    /// entry names relative to `base_dir`.
    CreateArchive {
        sources: Vec<PathBuf>,
        base_dir: PathBuf,
        archive: PathBuf,
    },
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum OperationStatus {
    Pending,
    InProgress,
    Done,
    Failed(String),
}

/// A snapshot of a batch operation's progress, emitted once per item as the
/// operation runs. `items_total`/`bytes_total` are fixed by a pre-walk before
/// the first item is processed; the `*_done` counts and `current` path advance
/// as work proceeds.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Progress {
    /// The item currently being processed.
    pub current: PathBuf,
    /// Items completed so far (files; directories are structural).
    pub items_done: usize,
    /// Total items to process, known up front.
    pub items_total: usize,
    /// Bytes processed so far.
    pub bytes_done: u64,
    /// Total bytes to process, known up front (0 when unknown).
    pub bytes_total: u64,
}

/// How a progress-aware operation finished.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum OperationOutcome {
    /// Every item was processed.
    Completed,
    /// The cancel signal was set; remaining items were left untouched.
    Cancelled,
}

pub trait Filesystem: Send + Sync {
    fn copy(&self, src: &Path, dest: &Path) -> Result<(), OxiNavError>;
    fn rename(&self, src: &Path, dest: &Path) -> Result<(), OxiNavError>;
    fn delete(&self, path: &Path) -> Result<(), OxiNavError>;
    fn create_dir(&self, path: &Path) -> Result<(), OxiNavError>;
    /// Create an empty file at `path`.
    fn create_file(&self, path: &Path) -> Result<(), OxiNavError>;
    /// Create a symbolic link at `link` pointing at `source`.
    fn create_symlink(&self, source: &Path, link: &Path) -> Result<(), OxiNavError>;
    fn exists(&self, path: &Path) -> bool;
    /// Whether `path` is itself a symbolic link, whatever it points at (or
    /// whether it points anywhere at all).
    fn is_symlink(&self, path: &Path) -> bool;
    /// Whether `path` is a directory. Used to drive recursive walks.
    fn is_dir(&self, path: &Path) -> bool;
    /// The immediate children of a directory (full paths).
    fn read_dir(&self, path: &Path) -> Result<Vec<PathBuf>, OxiNavError>;
    /// Size of a file in bytes; 0 for directories or when unknown.
    fn size(&self, path: &Path) -> u64;
    /// Up to `max` bytes from the start of a file. Reading a prefix rather
    /// than the whole file is what keeps the read-only viewer's memory use
    /// bounded no matter how large the file is.
    fn read_capped(&self, path: &Path, max: usize) -> Result<Vec<u8>, OxiNavError>;
    /// How many entries `archive` holds, so progress totals can be fixed
    /// before extraction begins. For a gzipped tar this means decompressing
    /// once to count and again to extract — the price of totals known up
    /// front, which the progress contract requires.
    fn count_archive_entries(
        &self,
        archive: &Path,
        format: ArchiveFormat,
    ) -> Result<usize, OxiNavError>;
    /// Extract `archive` into `dest_dir`, invoking `on_entry` per entry
    /// written. The format is decided by the caller so that detection stays
    /// a pure, tested function rather than being repeated per backend.
    fn extract_archive(
        &self,
        archive: &Path,
        dest_dir: &Path,
        format: ArchiveFormat,
        on_entry: &mut dyn FnMut(&Path),
    ) -> Result<(), OxiNavError>;
    /// Write `entries`, in order, into a new archive at `archive`, calling
    /// `on_entry` after each one; `Break` from it stops the write. Returns
    /// `Break` when stopped that way. A stopped or failed write leaves
    /// nothing at `archive`.
    fn write_archive(
        &self,
        archive: &Path,
        format: ArchiveFormat,
        entries: &[ArchiveEntry],
        on_entry: &mut dyn FnMut(&Path) -> ControlFlow<()>,
    ) -> Result<ControlFlow<()>, OxiNavError>;
    /// Search the files under `root` for `query`, calling `on_hit` per
    /// matching line in a stable order (by path, then line); `Break` from it
    /// stops the search, as does `cancel` being set, which is checked per
    /// file so a search finding little still stops promptly. Returns `Break`
    /// when stopped either way. Unreadable files are skipped, as `rg` does.
    fn search(
        &self,
        root: &Path,
        query: &SearchQuery,
        cancel: &AtomicBool,
        on_hit: &mut dyn FnMut(SearchHit) -> ControlFlow<()>,
    ) -> Result<ControlFlow<()>, OxiNavError>;
}

pub struct OperationEngine<F: Filesystem> {
    fs: F,
}

#[derive(Debug, Clone, Copy)]
pub struct StdFilesystem;

impl Filesystem for StdFilesystem {
    fn copy(&self, src: &Path, dest: &Path) -> Result<(), OxiNavError> {
        if src.is_dir() {
            copy_dir_recursive(src, dest).map_err(|source| OxiNavError::Io {
                path: dest.to_path_buf(),
                source,
            })
        } else {
            std::fs::copy(src, dest)
                .map(|_| ())
                .map_err(|source| OxiNavError::Io {
                    path: dest.to_path_buf(),
                    source,
                })
        }
    }

    fn rename(&self, src: &Path, dest: &Path) -> Result<(), OxiNavError> {
        std::fs::rename(src, dest).map_err(|source| OxiNavError::Io {
            path: dest.to_path_buf(),
            source,
        })
    }

    fn delete(&self, path: &Path) -> Result<(), OxiNavError> {
        let result = if path.is_dir() {
            std::fs::remove_dir_all(path)
        } else {
            std::fs::remove_file(path)
        };

        result.map_err(|source| OxiNavError::Io {
            path: path.to_path_buf(),
            source,
        })
    }

    fn create_dir(&self, path: &Path) -> Result<(), OxiNavError> {
        std::fs::create_dir(path).map_err(|source| OxiNavError::Io {
            path: path.to_path_buf(),
            source,
        })
    }

    fn create_file(&self, path: &Path) -> Result<(), OxiNavError> {
        // create_new refuses to clobber, so a file appearing between the
        // engine's pre-check and here is still an error rather than data loss.
        std::fs::OpenOptions::new()
            .write(true)
            .create_new(true)
            .open(path)
            .map(|_| ())
            .map_err(|source| OxiNavError::Io {
                path: path.to_path_buf(),
                source,
            })
    }

    fn create_symlink(&self, source: &Path, link: &Path) -> Result<(), OxiNavError> {
        #[cfg(unix)]
        let result = std::os::unix::fs::symlink(source, link);
        // Windows has separate calls for the two kinds of target, and needs
        // Developer Mode or elevation for either; without them the error
        // surfaces like any other I/O failure.
        #[cfg(windows)]
        let result = if source.is_dir() {
            std::os::windows::fs::symlink_dir(source, link)
        } else {
            std::os::windows::fs::symlink_file(source, link)
        };
        result.map_err(|source| OxiNavError::Io {
            path: link.to_path_buf(),
            source,
        })
    }

    fn exists(&self, path: &Path) -> bool {
        path.exists()
    }

    fn is_symlink(&self, path: &Path) -> bool {
        path.is_symlink()
    }

    fn is_dir(&self, path: &Path) -> bool {
        path.is_dir()
    }

    fn read_dir(&self, path: &Path) -> Result<Vec<PathBuf>, OxiNavError> {
        let entries = std::fs::read_dir(path).map_err(|source| OxiNavError::Io {
            path: path.to_path_buf(),
            source,
        })?;
        let mut out = Vec::new();
        for entry in entries {
            let entry = entry.map_err(|source| OxiNavError::Io {
                path: path.to_path_buf(),
                source,
            })?;
            out.push(entry.path());
        }
        Ok(out)
    }

    fn size(&self, path: &Path) -> u64 {
        std::fs::metadata(path).map(|m| m.len()).unwrap_or(0)
    }

    fn read_capped(&self, path: &Path, max: usize) -> Result<Vec<u8>, OxiNavError> {
        use std::io::Read;

        let io_error = |source| OxiNavError::Io {
            path: path.to_path_buf(),
            source,
        };
        let file = std::fs::File::open(path).map_err(io_error)?;
        let mut buffer = Vec::new();
        file.take(max as u64)
            .read_to_end(&mut buffer)
            .map_err(io_error)?;
        Ok(buffer)
    }

    fn count_archive_entries(
        &self,
        archive: &Path,
        format: ArchiveFormat,
    ) -> Result<usize, OxiNavError> {
        let file = open_archive(archive)?;
        match format {
            ArchiveFormat::Zip => {
                let zip = zip::ZipArchive::new(file).map_err(|e| archive_error(archive, e))?;
                Ok(zip.len())
            }
            ArchiveFormat::Tar => {
                let mut tar = tar::Archive::new(file);
                let entries = tar.entries().map_err(|e| archive_error(archive, e))?;
                Ok(entries.count())
            }
            ArchiveFormat::TarGz => {
                let mut tar = tar::Archive::new(flate2::read::GzDecoder::new(file));
                let entries = tar.entries().map_err(|e| archive_error(archive, e))?;
                Ok(entries.count())
            }
        }
    }

    fn extract_archive(
        &self,
        archive: &Path,
        dest_dir: &Path,
        format: ArchiveFormat,
        on_entry: &mut dyn FnMut(&Path),
    ) -> Result<(), OxiNavError> {
        let file = open_archive(archive)?;
        match format {
            ArchiveFormat::Zip => {
                let mut zip = zip::ZipArchive::new(file).map_err(|e| archive_error(archive, e))?;
                for index in 0..zip.len() {
                    let mut entry = zip.by_index(index).map_err(|e| archive_error(archive, e))?;
                    let raw = entry.name().to_string();
                    let Some(target) = resolve_entry(dest_dir, &raw)? else {
                        continue;
                    };

                    if entry.is_dir() {
                        create_dir_all(&target)?;
                    } else {
                        if let Some(parent) = target.parent() {
                            create_dir_all(parent)?;
                        }
                        let mut out =
                            std::fs::File::create(&target).map_err(|source| OxiNavError::Io {
                                path: target.clone(),
                                source,
                            })?;
                        std::io::copy(&mut entry, &mut out).map_err(|source| OxiNavError::Io {
                            path: target.clone(),
                            source,
                        })?;
                    }
                    // Tar's `unpack` restores modes itself; zip leaves it to
                    // us. Only the permission bits are applied, never setuid
                    // and the like from an archive someone else made.
                    #[cfg(unix)]
                    if let Some(mode) = entry.unix_mode() {
                        use std::os::unix::fs::PermissionsExt;
                        let permissions = std::fs::Permissions::from_mode(mode & 0o777);
                        std::fs::set_permissions(&target, permissions).map_err(|source| {
                            OxiNavError::Io {
                                path: target.clone(),
                                source,
                            }
                        })?;
                    }
                    on_entry(&target);
                }
                Ok(())
            }
            ArchiveFormat::Tar => extract_tar(tar::Archive::new(file), archive, dest_dir, on_entry),
            ArchiveFormat::TarGz => extract_tar(
                tar::Archive::new(flate2::read::GzDecoder::new(file)),
                archive,
                dest_dir,
                on_entry,
            ),
        }
    }

    /// Writes to a hidden sibling, `.<name>.oxinav-partial`, and renames it
    /// onto `archive` only once complete and synced, so the real name never
    /// holds a half-written archive, even if OxiNav is killed mid-write.
    fn write_archive(
        &self,
        archive: &Path,
        format: ArchiveFormat,
        entries: &[ArchiveEntry],
        on_entry: &mut dyn FnMut(&Path) -> ControlFlow<()>,
    ) -> Result<ControlFlow<()>, OxiNavError> {
        let name = archive.file_name().unwrap_or_default().to_string_lossy();
        let temp = archive.with_file_name(format!(".{name}.oxinav-partial"));
        let io_error = |path: &Path| {
            let path = path.to_path_buf();
            move |source| OxiNavError::Io { path, source }
        };

        let written = (|| {
            let file = std::fs::OpenOptions::new()
                .write(true)
                .create_new(true)
                .open(&temp)
                .map_err(io_error(&temp))?;
            let file = match format {
                ArchiveFormat::Zip => write_zip(file, archive, entries, on_entry)?,
                ArchiveFormat::Tar => write_tar(file, archive, entries, on_entry)?,
                ArchiveFormat::TarGz => {
                    let encoder =
                        flate2::write::GzEncoder::new(file, flate2::Compression::default());
                    match write_tar(encoder, archive, entries, on_entry)? {
                        Some(encoder) => Some(encoder.finish().map_err(io_error(&temp))?),
                        None => None,
                    }
                }
            };
            let Some(file) = file else {
                return Ok(ControlFlow::Break(()));
            };
            file.sync_all().map_err(io_error(&temp))?;
            std::fs::rename(&temp, archive).map_err(io_error(archive))?;
            Ok(ControlFlow::Continue(()))
        })();

        if !matches!(written, Ok(ControlFlow::Continue(()))) {
            let _ = std::fs::remove_file(&temp);
        }
        written
    }

    /// ripgrep's engine with ripgrep's defaults: ignore files honoured (as
    /// `rg` does, `.gitignore` only inside a git repository), binary files
    /// skipped at the first NUL. The walk is serial and sorted by name, so
    /// results arrive in a stable order rather than as threads finish.
    fn search(
        &self,
        root: &Path,
        query: &SearchQuery,
        cancel: &AtomicBool,
        on_hit: &mut dyn FnMut(SearchHit) -> ControlFlow<()>,
    ) -> Result<ControlFlow<()>, OxiNavError> {
        use grep_regex::RegexMatcherBuilder;
        use grep_searcher::{sinks::Lossy, BinaryDetection, SearcherBuilder};

        let matcher = RegexMatcherBuilder::new()
            .case_insensitive(query.case_insensitive)
            // Line-oriented: a match never spans a line break.
            .line_terminator(Some(b'\n'))
            .build(&query.pattern)
            .map_err(|error| OxiNavError::InvalidPattern(pattern_error(&error.to_string())))?;
        let mut searcher = SearcherBuilder::new()
            .binary_detection(BinaryDetection::quit(b'\0'))
            .line_number(true)
            .build();
        let walker = ignore::WalkBuilder::new(root)
            .hidden(!query.include_hidden)
            .sort_by_file_name(|a, b| a.cmp(b))
            .build();

        for entry in walker {
            if cancel.load(Ordering::Relaxed) {
                return Ok(ControlFlow::Break(()));
            }
            let Ok(entry) = entry else { continue };
            if !entry.file_type().is_some_and(|kind| kind.is_file()) {
                continue;
            }
            if let Some(glob) = &query.name_glob {
                let name = entry.file_name().to_string_lossy();
                if !matches_filter(&name, glob) {
                    continue;
                }
            }

            let mut flow = ControlFlow::Continue(());
            let path = entry.path();
            // A file that cannot be read is skipped, not fatal.
            let _ = searcher.search_path(
                &matcher,
                path,
                Lossy(|line, text| {
                    flow = on_hit(SearchHit {
                        path: path.to_path_buf(),
                        line,
                        text: snippet(text),
                    });
                    Ok(flow.is_continue())
                }),
            );
            if flow.is_break() {
                return Ok(ControlFlow::Break(()));
            }
        }
        Ok(ControlFlow::Continue(()))
    }
}

/// The name an entry gets inside a zip: UTF-8 with `/` separators, as the
/// format requires. A name that is not UTF-8 fails rather than being mangled.
fn zip_entry_name(entry: &ArchiveEntry) -> Result<String, OxiNavError> {
    let parts: Option<Vec<&str>> = entry
        .name
        .components()
        .map(|part| part.as_os_str().to_str())
        .collect();
    parts
        .map(|parts| parts.join("/"))
        .ok_or_else(|| OxiNavError::Io {
            path: entry.source.clone(),
            source: std::io::Error::other("zip entry names must be UTF-8"),
        })
}

/// Permission bits to record for `path`, where the platform has them.
fn unix_mode(path: &Path) -> Option<u32> {
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        std::fs::symlink_metadata(path)
            .ok()
            .map(|metadata| metadata.permissions().mode() & 0o7777)
    }
    #[cfg(not(unix))]
    {
        let _ = path;
        None
    }
}

/// `path`'s modification time as a zip timestamp. Zip stores local time
/// with no zone, which is what every unzip tool expects to find. Without
/// this the zip crate writes its 1980 epoch for every entry.
fn zip_time(path: &Path) -> Option<zip::DateTime> {
    use chrono::{Datelike, Timelike};
    let modified = std::fs::symlink_metadata(path).ok()?.modified().ok()?;
    let local: chrono::DateTime<chrono::Local> = modified.into();
    zip::DateTime::from_date_and_time(
        u16::try_from(local.year()).ok()?,
        local.month() as u8,
        local.day() as u8,
        local.hour() as u8,
        local.minute() as u8,
        local.second() as u8,
    )
    .ok()
}

/// Write `entries` as a zip. `None` means `on_entry` asked to stop.
fn write_zip(
    file: std::fs::File,
    archive: &Path,
    entries: &[ArchiveEntry],
    on_entry: &mut dyn FnMut(&Path) -> ControlFlow<()>,
) -> Result<Option<std::fs::File>, OxiNavError> {
    use zip::write::SimpleFileOptions;

    let mut zip = zip::ZipWriter::new(file);
    for entry in entries {
        let name = zip_entry_name(entry)?;
        let source_error = |source| OxiNavError::Io {
            path: entry.source.clone(),
            source,
        };
        let mut options =
            SimpleFileOptions::default().compression_method(zip::CompressionMethod::Deflated);
        if let Some(mode) = unix_mode(&entry.source) {
            options = options.unix_permissions(mode);
        }
        if let Some(time) = zip_time(&entry.source) {
            options = options.last_modified_time(time);
        }
        match entry.kind {
            EntryKind::Dir => zip
                .add_directory(name, options)
                .map_err(|e| archive_error(archive, e))?,
            EntryKind::Symlink => {
                let target = std::fs::read_link(&entry.source).map_err(source_error)?;
                zip.add_symlink(name, target.to_string_lossy(), options)
                    .map_err(|e| archive_error(archive, e))?;
            }
            EntryKind::File => {
                let mut source = std::fs::File::open(&entry.source).map_err(source_error)?;
                let len = source.metadata().map_err(source_error)?.len();
                // Zip64 only where it is needed, so ordinary archives stay
                // readable by the oldest tools.
                let options = options.large_file(len >= u64::from(u32::MAX));
                zip.start_file(name, options)
                    .map_err(|e| archive_error(archive, e))?;
                std::io::copy(&mut source, &mut zip).map_err(source_error)?;
            }
        }
        if on_entry(&entry.source).is_break() {
            return Ok(None);
        }
    }
    zip.finish()
        .map(Some)
        .map_err(|e| archive_error(archive, e))
}

/// Write `entries` as a tar into `writer`, keeping links as links and taking
/// modes from each entry's metadata. `None` means `on_entry` asked to stop.
fn write_tar<W: std::io::Write>(
    writer: W,
    archive: &Path,
    entries: &[ArchiveEntry],
    on_entry: &mut dyn FnMut(&Path) -> ControlFlow<()>,
) -> Result<Option<W>, OxiNavError> {
    let mut builder = tar::Builder::new(writer);
    builder.follow_symlinks(false);
    for entry in entries {
        builder
            .append_path_with_name(&entry.source, &entry.name)
            .map_err(|source| OxiNavError::Io {
                path: entry.source.clone(),
                source,
            })?;
        if on_entry(&entry.source).is_break() {
            return Ok(None);
        }
    }
    // Finished explicitly so a failure surfaces instead of being lost in Drop.
    builder
        .into_inner()
        .map(Some)
        .map_err(|source| OxiNavError::Io {
            path: archive.to_path_buf(),
            source,
        })
}

/// Expand a leading `~` (alone or as `~/rest`) to `home`. A `~` anywhere
/// else is an ordinary character and is left alone.
fn expand_home(input: &str, home: &Path) -> PathBuf {
    match input.strip_prefix('~') {
        Some("") => home.to_path_buf(),
        Some(rest) => match rest.strip_prefix('/') {
            Some(relative) => home.join(relative),
            // `~foo` names another user's home, which we do not resolve.
            None => PathBuf::from(input),
        },
        None => PathBuf::from(input),
    }
}

fn open_archive(archive: &Path) -> Result<std::fs::File, OxiNavError> {
    std::fs::File::open(archive).map_err(|source| OxiNavError::Io {
        path: archive.to_path_buf(),
        source,
    })
}

/// Wrap a decoder error as I/O against the archive, so callers see one error
/// type regardless of which backend produced it.
fn archive_error<E: std::fmt::Display>(archive: &Path, error: E) -> OxiNavError {
    OxiNavError::Io {
        path: archive.to_path_buf(),
        source: std::io::Error::other(error.to_string()),
    }
}

fn create_dir_all(path: &Path) -> Result<(), OxiNavError> {
    std::fs::create_dir_all(path).map_err(|source| OxiNavError::Io {
        path: path.to_path_buf(),
        source,
    })
}

/// Join a raw archive entry name onto `dest_dir`. `Ok(None)` means the entry
/// names the destination itself and has nothing to write; an escaping entry
/// is an error.
fn resolve_entry(dest_dir: &Path, raw: &str) -> Result<Option<PathBuf>, OxiNavError> {
    match classify_entry_path(Path::new(raw)) {
        EntryTarget::Within(relative) => Ok(Some(dest_dir.join(relative))),
        EntryTarget::ArchiveRoot => Ok(None),
        EntryTarget::Escaping => Err(OxiNavError::UnsafeArchiveEntry(raw.to_string())),
    }
}

fn extract_tar<R: std::io::Read>(
    mut tar: tar::Archive<R>,
    archive: &Path,
    dest_dir: &Path,
    on_entry: &mut dyn FnMut(&Path),
) -> Result<(), OxiNavError> {
    let entries = tar.entries().map_err(|e| archive_error(archive, e))?;
    for entry in entries {
        let mut entry = entry.map_err(|e| archive_error(archive, e))?;
        let raw = entry
            .path()
            .map_err(|e| archive_error(archive, e))?
            .to_string_lossy()
            .into_owned();
        let Some(target) = resolve_entry(dest_dir, &raw)? else {
            continue;
        };

        if entry.header().entry_type().is_dir() {
            create_dir_all(&target)?;
        } else {
            if let Some(parent) = target.parent() {
                create_dir_all(parent)?;
            }
            // unpack rather than a manual copy so tar's own mode/mtime
            // handling still applies.
            entry
                .unpack(&target)
                .map_err(|e| archive_error(archive, e))?;
        }
        on_entry(&target);
    }
    Ok(())
}

impl<F: Filesystem> OperationEngine<F> {
    pub fn new(fs: F) -> Self {
        Self { fs }
    }

    pub fn exists(&self, path: &Path) -> bool {
        self.fs.exists(path)
    }

    /// Read at most `max` bytes from the start of `path`, for read-only
    /// viewing. Like the mutating operations, the path is checked before the
    /// filesystem is touched.
    /// Resolve a user-typed directory path for a jump: expand a leading `~`
    /// against `home`, then require that it exists and is a directory.
    ///
    /// Lives on the engine rather than in `pane` because the checks go
    /// through the `Filesystem` trait, which is what makes them testable
    /// without a real directory to point at.
    pub fn resolve_directory(&self, input: &str, home: &Path) -> Result<PathBuf, OxiNavError> {
        let trimmed = input.trim();
        if trimmed.is_empty() {
            return Err(OxiNavError::SourceNotFound(PathBuf::from(trimmed)));
        }

        let expanded = expand_home(trimmed, home);

        if !self.fs.exists(&expanded) {
            return Err(OxiNavError::SourceNotFound(expanded));
        }
        if !self.fs.is_dir(&expanded) {
            return Err(OxiNavError::NotADirectory(expanded));
        }
        Ok(expanded)
    }

    /// Pre-flight for extraction: the archive must exist, be a format we
    /// decode, and have a directory to land in. Checked before any decoding
    /// so an unsupported archive leaves nothing behind.
    fn check_extractable(
        &self,
        archive: &Path,
        dest_dir: &Path,
    ) -> Result<ArchiveFormat, OxiNavError> {
        if !self.fs.exists(archive) {
            return Err(OxiNavError::SourceNotFound(archive.to_path_buf()));
        }
        if !self.fs.exists(dest_dir) {
            return Err(OxiNavError::SourceNotFound(dest_dir.to_path_buf()));
        }
        detect_format(archive).ok_or_else(|| OxiNavError::UnsupportedArchive(archive.to_path_buf()))
    }

    /// Pre-flight for packing, before anything is written: a supported
    /// format by name, a destination that does not exist yet, and sources
    /// that do (a dangling symlink still counts — it is packed as a link).
    fn check_packable(
        &self,
        sources: &[PathBuf],
        archive: &Path,
    ) -> Result<ArchiveFormat, OxiNavError> {
        let format = detect_format(archive)
            .ok_or_else(|| OxiNavError::UnsupportedArchive(archive.to_path_buf()))?;
        if self.fs.exists(archive) || self.fs.is_symlink(archive) {
            return Err(OxiNavError::DestinationExists(archive.to_path_buf()));
        }
        if let Some(missing) = sources
            .iter()
            .find(|source| !self.fs.exists(source) && !self.fs.is_symlink(source))
        {
            return Err(OxiNavError::SourceNotFound(missing.clone()));
        }
        Ok(format)
    }

    /// Everything to pack, depth-first with each directory before its
    /// contents, named relative to `base_dir`. Links are listed, never
    /// entered. Children are sorted so the archive's order is stable.
    fn archive_entries(
        &self,
        sources: &[PathBuf],
        base_dir: &Path,
    ) -> Result<Vec<ArchiveEntry>, OxiNavError> {
        let mut entries = Vec::new();
        for source in sources {
            self.collect_entries(source, base_dir, &mut entries)?;
        }
        Ok(entries)
    }

    fn collect_entries(
        &self,
        path: &Path,
        base_dir: &Path,
        entries: &mut Vec<ArchiveEntry>,
    ) -> Result<(), OxiNavError> {
        let name = match path.strip_prefix(base_dir) {
            Ok(relative) => relative.to_path_buf(),
            // Not under the base: keep at least its own name rather than
            // its absolute path.
            Err(_) => PathBuf::from(path.file_name().unwrap_or_default()),
        };
        let kind = if self.fs.is_symlink(path) {
            EntryKind::Symlink
        } else if self.fs.is_dir(path) {
            EntryKind::Dir
        } else {
            EntryKind::File
        };
        entries.push(ArchiveEntry {
            source: path.to_path_buf(),
            name,
            kind,
        });
        if kind == EntryKind::Dir {
            let mut children = self.fs.read_dir(path)?;
            children.sort();
            for child in children {
                self.collect_entries(&child, base_dir, entries)?;
            }
        }
        Ok(())
    }

    /// Search under `root`, passing each hit to `on_hit`, and stop past
    /// [`MAX_HITS`]: the hit beyond the cap is what tells "capped" apart from
    /// "exactly that many", and it is not passed on.
    pub fn search(
        &self,
        root: &Path,
        query: &SearchQuery,
        cancel: &AtomicBool,
        on_hit: &mut dyn FnMut(SearchHit),
    ) -> Result<SearchEnd, OxiNavError> {
        let mut count = 0;
        let mut capped = false;
        let flow = self.fs.search(root, query, cancel, &mut |hit| {
            if count == MAX_HITS {
                capped = true;
                return ControlFlow::Break(());
            }
            count += 1;
            on_hit(hit);
            ControlFlow::Continue(())
        })?;
        Ok(if capped {
            SearchEnd::Capped
        } else if flow.is_break() {
            SearchEnd::Stopped
        } else {
            SearchEnd::Finished
        })
    }

    pub fn read_capped(&self, path: &Path, max: usize) -> Result<Vec<u8>, OxiNavError> {
        if !self.fs.exists(path) {
            return Err(OxiNavError::SourceNotFound(path.to_path_buf()));
        }
        self.fs.read_capped(path, max)
    }

    pub fn execute(&self, op: &Operation) -> Result<(), OxiNavError> {
        match op {
            Operation::Copy { src, dest } => {
                if !self.fs.exists(src) {
                    return Err(OxiNavError::SourceNotFound(src.clone()));
                }
                if self.fs.exists(dest) {
                    return Err(OxiNavError::DestinationExists(dest.clone()));
                }
                self.fs.copy(src, dest)
            }
            Operation::Move { src, dest } => {
                if !self.fs.exists(src) {
                    return Err(OxiNavError::SourceNotFound(src.clone()));
                }
                if self.fs.exists(dest) {
                    return Err(OxiNavError::DestinationExists(dest.clone()));
                }
                // Fall back to copy+delete for cross-device moves
                match self.fs.rename(src, dest) {
                    Ok(()) => Ok(()),
                    Err(_) => {
                        self.fs.copy(src, dest)?;
                        self.fs.delete(src)
                    }
                }
            }
            Operation::Rename { src, dest } => {
                if !self.fs.exists(src) {
                    return Err(OxiNavError::SourceNotFound(src.clone()));
                }
                if self.fs.exists(dest) {
                    return Err(OxiNavError::DestinationExists(dest.clone()));
                }
                self.fs.rename(src, dest)
            }
            Operation::Delete { path } => {
                if !self.fs.exists(path) {
                    return Err(OxiNavError::SourceNotFound(path.clone()));
                }
                self.fs.delete(path)
            }
            Operation::CreateDir { path } => {
                if self.fs.exists(path) {
                    return Err(OxiNavError::DestinationExists(path.clone()));
                }
                self.fs.create_dir(path)
            }
            Operation::CreateFile { path } => {
                if self.fs.exists(path) {
                    return Err(OxiNavError::DestinationExists(path.clone()));
                }
                self.fs.create_file(path)
            }
            Operation::CreateSymlink { source, link } => {
                if !self.fs.exists(source) {
                    return Err(OxiNavError::SourceNotFound(source.clone()));
                }
                if self.fs.exists(link) {
                    return Err(OxiNavError::DestinationExists(link.clone()));
                }
                self.fs.create_symlink(source, link)
            }
            Operation::ExtractArchive { archive, dest_dir } => {
                let format = self.check_extractable(archive, dest_dir)?;
                self.fs
                    .extract_archive(archive, dest_dir, format, &mut |_| {})
            }
            Operation::CreateArchive { .. } => self
                .execute_with_progress(op, &AtomicBool::new(false), &mut |_| {})
                .map(|_| ()),
        }
    }

    /// Execute an operation while reporting incremental progress and honoring
    /// a cooperative cancel flag.
    ///
    /// For batch operations (Copy/Move/Delete over a directory) the engine
    /// drives the recursive walk itself, emitting one [`Progress`] per file
    /// and polling `cancel` before each not-yet-started item. Totals are fixed
    /// by a pre-walk before the first item is processed. Rename, CreateDir,
    /// CreateFile and CreateSymlink are instantaneous, so they delegate to
    /// [`execute`](Self::execute) and emit a single final tick.
    ///
    /// On cancellation the already-processed items are left in place (no
    /// rollback) and [`OperationOutcome::Cancelled`] is returned.
    pub fn execute_with_progress(
        &self,
        op: &Operation,
        cancel: &AtomicBool,
        on_progress: &mut dyn FnMut(Progress),
    ) -> Result<OperationOutcome, OxiNavError> {
        match op {
            Operation::Copy { src, dest } => {
                if !self.fs.exists(src) {
                    return Err(OxiNavError::SourceNotFound(src.clone()));
                }
                if self.fs.exists(dest) {
                    return Err(OxiNavError::DestinationExists(dest.clone()));
                }
                let (items_total, bytes_total) = self.walk_totals(src);
                let mut state = ProgressState::new(items_total, bytes_total);
                self.copy_recursive(src, dest, cancel, &mut state, on_progress)?;
                Ok(outcome(cancel))
            }
            Operation::Delete { path } => {
                if !self.fs.exists(path) {
                    return Err(OxiNavError::SourceNotFound(path.clone()));
                }
                let (items_total, bytes_total) = self.walk_totals(path);
                let mut state = ProgressState::new(items_total, bytes_total);
                self.delete_recursive(path, cancel, &mut state, on_progress)?;
                Ok(outcome(cancel))
            }
            Operation::Move { src, dest } => {
                if !self.fs.exists(src) {
                    return Err(OxiNavError::SourceNotFound(src.clone()));
                }
                if self.fs.exists(dest) {
                    return Err(OxiNavError::DestinationExists(dest.clone()));
                }
                let (items_total, bytes_total) = self.walk_totals(src);
                // Same-device rename is atomic — a single tick.
                if self.fs.rename(src, dest).is_ok() {
                    on_progress(Progress {
                        current: src.clone(),
                        items_done: items_total,
                        items_total,
                        bytes_done: bytes_total,
                        bytes_total,
                    });
                    return Ok(OperationOutcome::Completed);
                }
                // Cross-device fallback: copy tree (with progress), then delete source.
                let mut state = ProgressState::new(items_total, bytes_total);
                self.copy_recursive(src, dest, cancel, &mut state, on_progress)?;
                if cancel.load(Ordering::Relaxed) {
                    return Ok(OperationOutcome::Cancelled);
                }
                self.fs.delete(src)?;
                Ok(OperationOutcome::Completed)
            }
            // Instantaneous single-item ops: reuse the synchronous path.
            Operation::Rename { dest, .. } => {
                self.execute(op)?;
                on_progress(single_tick(dest.clone()));
                Ok(OperationOutcome::Completed)
            }
            Operation::CreateSymlink { link, .. } => {
                self.execute(op)?;
                on_progress(single_tick(link.clone()));
                Ok(OperationOutcome::Completed)
            }
            // The one operation here that is neither instantaneous nor a
            // filesystem walk: totals come from counting the archive first.
            Operation::ExtractArchive { archive, dest_dir } => {
                let format = self.check_extractable(archive, dest_dir)?;
                let items_total = self.fs.count_archive_entries(archive, format)?;
                let mut items_done = 0;

                self.fs
                    .extract_archive(archive, dest_dir, format, &mut |written| {
                        items_done += 1;
                        on_progress(Progress {
                            current: written.to_path_buf(),
                            items_done,
                            items_total,
                            bytes_done: 0,
                            bytes_total: 0,
                        });
                    })?;

                Ok(OperationOutcome::Completed)
            }
            Operation::CreateDir { path } | Operation::CreateFile { path } => {
                self.execute(op)?;
                on_progress(single_tick(path.clone()));
                Ok(OperationOutcome::Completed)
            }
            // Walked in full first, so the total is known before the first
            // entry is written; cancelling stops the backend mid-archive,
            // and it removes what it had written.
            Operation::CreateArchive {
                sources,
                base_dir,
                archive,
            } => {
                let format = self.check_packable(sources, archive)?;
                let entries = self.archive_entries(sources, base_dir)?;
                let sizes: Vec<u64> = entries
                    .iter()
                    .map(|entry| match entry.kind {
                        EntryKind::File => self.fs.size(&entry.source),
                        EntryKind::Dir | EntryKind::Symlink => 0,
                    })
                    .collect();
                let mut state = ProgressState::new(entries.len(), sizes.iter().sum());
                if cancel.load(Ordering::Relaxed) {
                    return Ok(OperationOutcome::Cancelled);
                }

                let flow = self
                    .fs
                    .write_archive(archive, format, &entries, &mut |written| {
                        state.advance(sizes[state.items_done]);
                        on_progress(state.snapshot(written));
                        if cancel.load(Ordering::Relaxed) {
                            ControlFlow::Break(())
                        } else {
                            ControlFlow::Continue(())
                        }
                    })?;
                Ok(if flow.is_break() {
                    OperationOutcome::Cancelled
                } else {
                    OperationOutcome::Completed
                })
            }
        }
    }

    /// Estimate the `(items, bytes)` an operation will process, matching what
    /// [`execute_with_progress`](Self::execute_with_progress) counts. Lets a
    /// caller pre-sum batch-wide totals before starting work.
    pub fn estimate_totals(&self, op: &Operation) -> (usize, u64) {
        match op {
            Operation::Copy { src, .. } | Operation::Move { src, .. } => self.walk_totals(src),
            Operation::Delete { path } => self.walk_totals(path),
            Operation::Rename { .. }
            | Operation::CreateDir { .. }
            | Operation::CreateFile { .. }
            | Operation::CreateSymlink { .. } => (1, 0),
            // Counting can fail (missing or undecodable archive); execution
            // will report that properly, so fall back to a single item here
            // rather than surfacing an error from an estimate.
            Operation::ExtractArchive { archive, dest_dir } => self
                .check_extractable(archive, dest_dir)
                .and_then(|format| self.fs.count_archive_entries(archive, format))
                .map(|items| (items, 0))
                .unwrap_or((1, 0)),
            Operation::CreateArchive {
                sources, base_dir, ..
            } => self
                .archive_entries(sources, base_dir)
                .map(|entries| {
                    let bytes = entries
                        .iter()
                        .filter(|entry| entry.kind == EntryKind::File)
                        .map(|entry| self.fs.size(&entry.source))
                        .sum();
                    (entries.len(), bytes)
                })
                .unwrap_or((1, 0)),
        }
    }

    /// Count files (as items) and sum their sizes under `path`, recursively.
    /// A file is one item; a directory contributes its descendant files.
    fn walk_totals(&self, path: &Path) -> (usize, u64) {
        if self.fs.is_dir(path) {
            let mut items = 0;
            let mut bytes = 0;
            if let Ok(children) = self.fs.read_dir(path) {
                for child in &children {
                    let (i, b) = self.walk_totals(child);
                    items += i;
                    bytes += b;
                }
            }
            (items, bytes)
        } else {
            (1, self.fs.size(path))
        }
    }

    fn copy_recursive(
        &self,
        src: &Path,
        dest: &Path,
        cancel: &AtomicBool,
        state: &mut ProgressState,
        on_progress: &mut dyn FnMut(Progress),
    ) -> Result<(), OxiNavError> {
        if cancel.load(Ordering::Relaxed) {
            return Ok(());
        }
        if self.fs.is_dir(src) {
            self.fs.create_dir(dest)?;
            for child in self.fs.read_dir(src)? {
                if cancel.load(Ordering::Relaxed) {
                    return Ok(());
                }
                let child_dest = match child.file_name() {
                    Some(name) => dest.join(name),
                    None => dest.to_path_buf(),
                };
                self.copy_recursive(&child, &child_dest, cancel, state, on_progress)?;
            }
        } else {
            self.fs.copy(src, dest)?;
            state.advance(self.fs.size(src));
            on_progress(state.snapshot(src));
        }
        Ok(())
    }

    fn delete_recursive(
        &self,
        path: &Path,
        cancel: &AtomicBool,
        state: &mut ProgressState,
        on_progress: &mut dyn FnMut(Progress),
    ) -> Result<(), OxiNavError> {
        if cancel.load(Ordering::Relaxed) {
            return Ok(());
        }
        if self.fs.is_dir(path) {
            for child in self.fs.read_dir(path)? {
                if cancel.load(Ordering::Relaxed) {
                    return Ok(());
                }
                self.delete_recursive(&child, cancel, state, on_progress)?;
            }
            if cancel.load(Ordering::Relaxed) {
                return Ok(());
            }
            // Children are gone; remove the now-empty directory (structural).
            self.fs.delete(path)?;
        } else {
            let bytes = self.fs.size(path);
            self.fs.delete(path)?;
            state.advance(bytes);
            on_progress(state.snapshot(path));
        }
        Ok(())
    }
}

/// Mutable accumulator threaded through a recursive walk to build each
/// [`Progress`] snapshot.
struct ProgressState {
    items_done: usize,
    items_total: usize,
    bytes_done: u64,
    bytes_total: u64,
}

impl ProgressState {
    fn new(items_total: usize, bytes_total: u64) -> Self {
        Self {
            items_done: 0,
            items_total,
            bytes_done: 0,
            bytes_total,
        }
    }

    fn advance(&mut self, bytes: u64) {
        self.items_done += 1;
        self.bytes_done += bytes;
    }

    fn snapshot(&self, current: &Path) -> Progress {
        Progress {
            current: current.to_path_buf(),
            items_done: self.items_done,
            items_total: self.items_total,
            bytes_done: self.bytes_done,
            bytes_total: self.bytes_total,
        }
    }
}

fn outcome(cancel: &AtomicBool) -> OperationOutcome {
    if cancel.load(Ordering::Relaxed) {
        OperationOutcome::Cancelled
    } else {
        OperationOutcome::Completed
    }
}

fn single_tick(current: PathBuf) -> Progress {
    Progress {
        current,
        items_done: 1,
        items_total: 1,
        bytes_done: 0,
        bytes_total: 0,
    }
}

fn copy_dir_recursive(src: &Path, dest: &Path) -> std::io::Result<()> {
    std::fs::create_dir_all(dest)?;
    for entry in std::fs::read_dir(src)? {
        let entry = entry?;
        let dest_path = dest.join(entry.file_name());
        if entry.file_type()?.is_dir() {
            copy_dir_recursive(&entry.path(), &dest_path)?;
        } else {
            std::fs::copy(entry.path(), &dest_path)?;
        }
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::collections::{HashMap, HashSet};
    use std::sync::{Arc, Mutex};

    /// In-memory filesystem. Each path maps to `Some(size)` for a file or
    /// `None` for a directory, so the mock can model a tree for recursive
    /// walks without touching disk.
    #[derive(Clone)]
    struct MockFs {
        nodes: Arc<Mutex<HashMap<PathBuf, Option<u64>>>>,
        /// Entry names each archive path "contains", standing in for a real
        /// decoder so extraction is testable without a file on disk.
        archives: Arc<Mutex<HashMap<PathBuf, Vec<String>>>>,
        /// Paths that are symbolic links (to whatever their node says).
        links: Arc<Mutex<HashSet<PathBuf>>>,
        /// Paths whose reading fails while being packed.
        unreadable: Arc<Mutex<HashSet<PathBuf>>>,
        /// The entries written into each archive, as `(name, kind)`.
        packed: Arc<Mutex<PackedArchives>>,
        /// File contents, for searching.
        contents: Arc<Mutex<HashMap<PathBuf, String>>>,
    }

    type PackedArchives = HashMap<PathBuf, Vec<(PathBuf, EntryKind)>>;

    impl MockFs {
        /// Build from a flat list of files (each 0 bytes).
        fn with(paths: &[&str]) -> Self {
            Self {
                nodes: Arc::new(Mutex::new(
                    paths.iter().map(|p| (PathBuf::from(p), Some(0))).collect(),
                )),
                archives: Arc::new(Mutex::new(HashMap::new())),
                links: Arc::default(),
                unreadable: Arc::default(),
                packed: Arc::default(),
                contents: Arc::default(),
            }
        }

        /// Register `entries` as the contents of the archive at `path`.
        fn with_archive(self, path: &str, entries: &[&str]) -> Self {
            self.nodes
                .lock()
                .unwrap()
                .insert(PathBuf::from(path), Some(0));
            self.archives.lock().unwrap().insert(
                PathBuf::from(path),
                entries.iter().map(|e| e.to_string()).collect(),
            );
            self
        }

        /// Add a file holding `text`, creating its parent directories.
        fn with_content(self, path: &str, text: &str) -> Self {
            {
                let mut nodes = self.nodes.lock().unwrap();
                let path = PathBuf::from(path);
                let mut parent = path.parent();
                while let Some(dir) = parent {
                    nodes.entry(dir.to_path_buf()).or_insert(None);
                    parent = dir.parent();
                }
                nodes.insert(path.clone(), Some(text.len() as u64));
                self.contents.lock().unwrap().insert(path, text.to_string());
            }
            self
        }

        fn with_link(self, path: &str) -> Self {
            self.links.lock().unwrap().insert(PathBuf::from(path));
            self
        }

        fn with_unreadable(self, path: &str) -> Self {
            self.unreadable.lock().unwrap().insert(PathBuf::from(path));
            self
        }

        fn packed(&self, archive: &str) -> Vec<(String, EntryKind)> {
            self.packed
                .lock()
                .unwrap()
                .get(Path::new(archive))
                .map(|entries| {
                    entries
                        .iter()
                        .map(|(name, kind)| (name.display().to_string(), *kind))
                        .collect()
                })
                .unwrap_or_default()
        }

        fn archive_entries(&self, archive: &Path) -> Vec<String> {
            self.archives
                .lock()
                .unwrap()
                .get(archive)
                .cloned()
                .unwrap_or_default()
        }

        /// Build a tree: `None` marks a directory, `Some(size)` a file.
        fn tree(entries: &[(&str, Option<u64>)]) -> Self {
            Self {
                nodes: Arc::new(Mutex::new(
                    entries
                        .iter()
                        .map(|(p, size)| (PathBuf::from(p), *size))
                        .collect(),
                )),
                archives: Arc::new(Mutex::new(HashMap::new())),
                links: Arc::default(),
                unreadable: Arc::default(),
                packed: Arc::default(),
                contents: Arc::default(),
            }
        }
    }

    impl Filesystem for MockFs {
        fn copy(&self, src: &Path, dest: &Path) -> Result<(), OxiNavError> {
            let mut nodes = self.nodes.lock().unwrap();
            let value = nodes.get(src).copied().unwrap_or(Some(0));
            nodes.insert(dest.to_path_buf(), value);
            Ok(())
        }
        fn rename(&self, src: &Path, dest: &Path) -> Result<(), OxiNavError> {
            let mut nodes = self.nodes.lock().unwrap();
            let value = nodes.remove(src).unwrap_or(Some(0));
            nodes.insert(dest.to_path_buf(), value);
            Ok(())
        }
        fn delete(&self, path: &Path) -> Result<(), OxiNavError> {
            let mut nodes = self.nodes.lock().unwrap();
            nodes.remove(path);
            // Remove descendants too, matching remove_dir_all semantics.
            let prefix = format!("{}/", path.display());
            nodes.retain(|p, _| !p.display().to_string().starts_with(&prefix));
            Ok(())
        }
        fn create_dir(&self, path: &Path) -> Result<(), OxiNavError> {
            self.nodes.lock().unwrap().insert(path.to_path_buf(), None);
            Ok(())
        }
        fn create_file(&self, path: &Path) -> Result<(), OxiNavError> {
            self.nodes
                .lock()
                .unwrap()
                .insert(path.to_path_buf(), Some(0));
            Ok(())
        }
        fn create_symlink(&self, source: &Path, link: &Path) -> Result<(), OxiNavError> {
            // Records the link as an entry mirroring its target's kind, which
            // is all the listing-level assertions here need.
            let mut nodes = self.nodes.lock().unwrap();
            let value = nodes.get(source).copied().unwrap_or(Some(0));
            nodes.insert(link.to_path_buf(), value);
            Ok(())
        }
        fn exists(&self, path: &Path) -> bool {
            self.nodes.lock().unwrap().contains_key(path)
        }
        fn is_symlink(&self, path: &Path) -> bool {
            self.links.lock().unwrap().contains(path)
        }
        fn is_dir(&self, path: &Path) -> bool {
            matches!(self.nodes.lock().unwrap().get(path), Some(None))
        }
        fn read_dir(&self, path: &Path) -> Result<Vec<PathBuf>, OxiNavError> {
            let nodes = self.nodes.lock().unwrap();
            Ok(nodes
                .keys()
                .filter(|p| p.parent() == Some(path))
                .cloned()
                .collect())
        }
        fn size(&self, path: &Path) -> u64 {
            match self.nodes.lock().unwrap().get(path) {
                Some(Some(size)) => *size,
                _ => 0,
            }
        }
        /// Files hold no real bytes here, so a read yields filler of the
        /// recorded size — enough to exercise the cap, which is the only
        /// behaviour of this method worth asserting on.
        fn read_capped(&self, path: &Path, max: usize) -> Result<Vec<u8>, OxiNavError> {
            let len = (self.size(path) as usize).min(max);
            Ok(vec![b'a'; len])
        }
        fn count_archive_entries(
            &self,
            archive: &Path,
            _format: ArchiveFormat,
        ) -> Result<usize, OxiNavError> {
            Ok(self.archive_entries(archive).len())
        }
        /// Stands in for a decoder: the "contents" of an archive are the
        /// entry names registered with `with_archive`, run through the same
        /// `safe_entry_path` guard the real backends use.
        fn extract_archive(
            &self,
            archive: &Path,
            dest_dir: &Path,
            _format: ArchiveFormat,
            on_entry: &mut dyn FnMut(&Path),
        ) -> Result<(), OxiNavError> {
            for raw in self.archive_entries(archive) {
                let Some(target) = resolve_entry(dest_dir, &raw)? else {
                    continue;
                };
                self.nodes.lock().unwrap().insert(target.clone(), Some(0));
                on_entry(&target);
            }
            Ok(())
        }
        /// Records the entries instead of encoding them, and like the real
        /// backend only creates `archive` once every entry is through.
        fn write_archive(
            &self,
            archive: &Path,
            _format: ArchiveFormat,
            entries: &[ArchiveEntry],
            on_entry: &mut dyn FnMut(&Path) -> ControlFlow<()>,
        ) -> Result<ControlFlow<()>, OxiNavError> {
            let mut written = Vec::new();
            for entry in entries {
                if self.unreadable.lock().unwrap().contains(&entry.source) {
                    return Err(OxiNavError::Io {
                        path: entry.source.clone(),
                        source: std::io::Error::from(std::io::ErrorKind::PermissionDenied),
                    });
                }
                written.push((entry.name.clone(), entry.kind));
                if on_entry(&entry.source).is_break() {
                    return Ok(ControlFlow::Break(()));
                }
            }
            self.nodes
                .lock()
                .unwrap()
                .insert(archive.to_path_buf(), Some(0));
            self.packed
                .lock()
                .unwrap()
                .insert(archive.to_path_buf(), written);
            Ok(ControlFlow::Continue(()))
        }
        /// A naive stand-in for ripgrep: substring matching, files in path
        /// order, and the same hidden and name-filter rules.
        fn search(
            &self,
            root: &Path,
            query: &SearchQuery,
            cancel: &AtomicBool,
            on_hit: &mut dyn FnMut(SearchHit) -> ControlFlow<()>,
        ) -> Result<ControlFlow<()>, OxiNavError> {
            let fold = |text: &str| {
                if query.case_insensitive {
                    text.to_lowercase()
                } else {
                    text.to_string()
                }
            };
            let needle = fold(&query.pattern);
            let mut files: Vec<(PathBuf, String)> = self
                .contents
                .lock()
                .unwrap()
                .iter()
                .map(|(path, text)| (path.clone(), text.clone()))
                .collect();
            files.sort();
            for (path, text) in files {
                if cancel.load(Ordering::Relaxed) {
                    return Ok(ControlFlow::Break(()));
                }
                let Ok(relative) = path.strip_prefix(root) else {
                    continue;
                };
                let hidden = relative
                    .components()
                    .any(|part| part.as_os_str().to_string_lossy().starts_with('.'));
                if hidden && !query.include_hidden {
                    continue;
                }
                let name = path.file_name().unwrap_or_default().to_string_lossy();
                if let Some(glob) = &query.name_glob {
                    if !matches_filter(&name, glob) {
                        continue;
                    }
                }
                for (index, line) in text.lines().enumerate() {
                    if fold(line).contains(&needle) {
                        let hit = SearchHit {
                            path: path.clone(),
                            line: index as u64 + 1,
                            text: snippet(line),
                        };
                        if on_hit(hit).is_break() {
                            return Ok(ControlFlow::Break(()));
                        }
                    }
                }
            }
            Ok(ControlFlow::Continue(()))
        }
    }

    fn query(pattern: &str, include_hidden: bool, name_glob: Option<&str>) -> SearchQuery {
        let mut pane = crate::pane::Pane::new(PathBuf::from("/"));
        pane.show_hidden = include_hidden;
        pane.filter = name_glob.map(str::to_string);
        SearchQuery::new(pattern, &pane).unwrap()
    }

    fn search_all(
        engine: &OperationEngine<MockFs>,
        query: &SearchQuery,
    ) -> (Vec<String>, SearchEnd) {
        let mut hits = Vec::new();
        let end = engine
            .search(
                Path::new("/proj"),
                query,
                &AtomicBool::new(false),
                &mut |hit| {
                    hits.push(format!("{}:{}:{}", hit.path.display(), hit.line, hit.text));
                },
            )
            .unwrap();
        (hits, end)
    }

    #[test]
    fn search_finds_matches_recursively_in_order() {
        let fs = MockFs::with(&[])
            .with_content("/proj/src/b.rs", "x\nfn main() {}\n")
            .with_content("/proj/a.rs", "fn main()")
            .with_content("/elsewhere/c.rs", "fn main()");
        let engine = OperationEngine::new(fs);

        let (hits, end) = search_all(&engine, &query("fn main", false, None));

        assert_eq!(
            hits,
            vec!["/proj/a.rs:1:fn main()", "/proj/src/b.rs:2:fn main() {}"]
        );
        assert_eq!(end, SearchEnd::Finished);
    }

    #[test]
    fn search_skips_hidden_files_unless_the_pane_shows_them() {
        let fs = MockFs::with(&[])
            .with_content("/proj/.env", "token")
            .with_content("/proj/.git/config", "token")
            .with_content("/proj/a.txt", "token");
        let engine = OperationEngine::new(fs);

        assert_eq!(search_all(&engine, &query("token", false, None)).0.len(), 1);
        assert_eq!(search_all(&engine, &query("token", true, None)).0.len(), 3);
    }

    #[test]
    fn search_follows_the_pane_name_filter() {
        let fs = MockFs::with(&[])
            .with_content("/proj/a.rs", "needle")
            .with_content("/proj/a.md", "needle");
        let engine = OperationEngine::new(fs);

        let (hits, _) = search_all(&engine, &query("needle", false, Some("*.rs")));
        assert_eq!(hits, vec!["/proj/a.rs:1:needle"]);
    }

    #[test]
    fn search_stops_at_the_cap() {
        let text = "hit\n".repeat(MAX_HITS + 5);
        let fs = MockFs::with(&[]).with_content("/proj/many.txt", &text);
        let engine = OperationEngine::new(fs);

        let (hits, end) = search_all(&engine, &query("hit", false, None));
        assert_eq!(hits.len(), MAX_HITS);
        assert_eq!(end, SearchEnd::Capped);
    }

    #[test]
    fn exactly_the_cap_is_not_capped() {
        let text = "hit\n".repeat(MAX_HITS);
        let fs = MockFs::with(&[]).with_content("/proj/many.txt", &text);
        let engine = OperationEngine::new(fs);

        let (hits, end) = search_all(&engine, &query("hit", false, None));
        assert_eq!(hits.len(), MAX_HITS);
        assert_eq!(end, SearchEnd::Finished);
    }

    #[test]
    fn cancelling_a_search_stops_it() {
        let fs = MockFs::with(&[])
            .with_content("/proj/a.txt", "hit")
            .with_content("/proj/b.txt", "hit");
        let engine = OperationEngine::new(fs);
        let cancel = AtomicBool::new(false);
        let mut hits = 0;

        let end = engine
            .search(
                Path::new("/proj"),
                &query("hit", false, None),
                &cancel,
                &mut |_| {
                    hits += 1;
                    cancel.store(true, Ordering::Relaxed);
                },
            )
            .unwrap();

        assert_eq!(hits, 1);
        assert_eq!(end, SearchEnd::Stopped);
    }

    #[test]
    fn mock_search_applies_smart_case() {
        let fs = MockFs::with(&[]).with_content("/proj/a.txt", "TODO\nTodo\ntodo");
        let engine = OperationEngine::new(fs);

        assert_eq!(search_all(&engine, &query("todo", false, None)).0.len(), 3);
        assert_eq!(search_all(&engine, &query("Todo", false, None)).0.len(), 1);
    }

    fn pack(sources: &[&str], base_dir: &str, archive: &str) -> Operation {
        Operation::CreateArchive {
            sources: sources.iter().map(PathBuf::from).collect(),
            base_dir: PathBuf::from(base_dir),
            archive: PathBuf::from(archive),
        }
    }

    /// The tree most packing tests use: a directory with a nested file, an
    /// empty directory, and a loose file.
    fn packing_tree() -> MockFs {
        MockFs::tree(&[
            ("/w", None),
            ("/w/src", None),
            ("/w/src/main.rs", Some(10)),
            ("/w/src/lib.rs", Some(20)),
            ("/w/src/empty", None),
            ("/w/notes.txt", Some(5)),
            ("/out", None),
        ])
    }

    #[test]
    fn packing_names_entries_relative_to_the_base_directory() {
        let fs = packing_tree();
        let engine = OperationEngine::new(fs.clone());

        engine
            .execute(&pack(&["/w/src", "/w/notes.txt"], "/w", "/out/a.zip"))
            .unwrap();

        assert_eq!(
            fs.packed("/out/a.zip"),
            vec![
                ("src".to_string(), EntryKind::Dir),
                ("src/empty".to_string(), EntryKind::Dir),
                ("src/lib.rs".to_string(), EntryKind::File),
                ("src/main.rs".to_string(), EntryKind::File),
                ("notes.txt".to_string(), EntryKind::File),
            ]
        );
    }

    #[test]
    fn packing_does_not_follow_symlinks() {
        let fs = MockFs::tree(&[
            ("/w", None),
            ("/w/big", None),
            ("/w/big/huge.bin", Some(1_000)),
            ("/w/link", None),
            ("/w/link/huge.bin", Some(1_000)),
            ("/out", None),
        ])
        .with_link("/w/link");
        let engine = OperationEngine::new(fs.clone());

        engine
            .execute(&pack(&["/w/link"], "/w", "/out/a.tar"))
            .unwrap();

        assert_eq!(
            fs.packed("/out/a.tar"),
            vec![("link".to_string(), EntryKind::Symlink)]
        );
    }

    #[test]
    fn packing_reports_progress_against_a_known_total() {
        let fs = packing_tree();
        let engine = OperationEngine::new(fs);
        let mut ticks = Vec::new();

        let outcome = engine
            .execute_with_progress(
                &pack(&["/w/src"], "/w", "/out/a.tar.gz"),
                &AtomicBool::new(false),
                &mut |p| ticks.push(p),
            )
            .unwrap();

        assert_eq!(outcome, OperationOutcome::Completed);
        assert_eq!(ticks.len(), 4);
        assert!(ticks
            .iter()
            .all(|p| p.items_total == 4 && p.bytes_total == 30));
        assert_eq!(ticks.last().unwrap().items_done, 4);
        assert_eq!(ticks.last().unwrap().bytes_done, 30);
        assert_eq!(
            engine.estimate_totals(&pack(&["/w/src"], "/w", "/out/a.tar.gz")),
            (4, 30)
        );
    }

    #[test]
    fn packing_refuses_an_existing_destination() {
        let fs = packing_tree();
        fs.nodes
            .lock()
            .unwrap()
            .insert(PathBuf::from("/out/a.zip"), Some(7));
        let engine = OperationEngine::new(fs.clone());

        let result = engine.execute(&pack(&["/w/notes.txt"], "/w", "/out/a.zip"));

        assert!(matches!(result, Err(OxiNavError::DestinationExists(_))));
        assert!(fs.packed("/out/a.zip").is_empty());
        assert_eq!(fs.size(Path::new("/out/a.zip")), 7);
    }

    #[test]
    fn packing_refuses_an_unsupported_extension() {
        let fs = packing_tree();
        let engine = OperationEngine::new(fs.clone());

        let result = engine.execute(&pack(&["/w/notes.txt"], "/w", "/out/a.rar"));

        assert!(matches!(result, Err(OxiNavError::UnsupportedArchive(_))));
        assert!(!fs.exists(Path::new("/out/a.rar")));
    }

    #[test]
    fn packing_refuses_a_missing_source() {
        let engine = OperationEngine::new(packing_tree());

        let result = engine.execute(&pack(&["/w/gone.txt"], "/w", "/out/a.zip"));

        assert!(matches!(result, Err(OxiNavError::SourceNotFound(_))));
    }

    #[test]
    fn cancelling_packing_leaves_no_archive() {
        let fs = packing_tree();
        let engine = OperationEngine::new(fs.clone());
        let cancel = AtomicBool::new(false);
        let mut ticks = 0;

        let outcome = engine
            .execute_with_progress(&pack(&["/w/src"], "/w", "/out/a.zip"), &cancel, &mut |_| {
                ticks += 1;
                cancel.store(true, Ordering::Relaxed);
            })
            .unwrap();

        assert_eq!(outcome, OperationOutcome::Cancelled);
        assert_eq!(ticks, 1);
        assert!(!fs.exists(Path::new("/out/a.zip")));
    }

    #[test]
    fn an_unreadable_file_fails_packing_and_names_it() {
        let fs = packing_tree().with_unreadable("/w/src/main.rs");
        let engine = OperationEngine::new(fs.clone());

        let result = engine.execute(&pack(&["/w/src"], "/w", "/out/a.zip"));

        match result {
            Err(OxiNavError::Io { path, .. }) => assert_eq!(path, PathBuf::from("/w/src/main.rs")),
            other => panic!("expected an I/O error naming the file, got {other:?}"),
        }
        assert!(!fs.exists(Path::new("/out/a.zip")));
    }

    /// A fresh, empty directory on real disk for one test.
    fn scratch_dir(test: &str) -> PathBuf {
        let dir = std::env::temp_dir().join(format!("oxinav_{test}_{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&dir);
        std::fs::create_dir_all(&dir).unwrap();
        dir
    }

    /// `relative path -> contents` for every file and empty directory under
    /// `root` (directories as `"<dir>"`), for comparing two trees.
    fn snapshot(root: &Path) -> Vec<(String, String)> {
        fn walk(root: &Path, dir: &Path, out: &mut Vec<(String, String)>) {
            let mut children: Vec<_> = std::fs::read_dir(dir)
                .unwrap()
                .map(|e| e.unwrap().path())
                .collect();
            children.sort();
            for child in children {
                let name = child.strip_prefix(root).unwrap().display().to_string();
                if child.is_symlink() {
                    let target = std::fs::read_link(&child).unwrap();
                    out.push((name, format!("<link {}>", target.display())));
                } else if child.is_dir() {
                    out.push((name, "<dir>".to_string()));
                    walk(root, &child, out);
                } else {
                    out.push((name, std::fs::read_to_string(&child).unwrap()));
                }
            }
        }
        let mut out = Vec::new();
        walk(root, root, &mut out);
        out
    }

    /// Pack `work/tree` into `name` with the real backend, extract it into an
    /// empty directory with OxiNav's own extractor, and return both sides.
    fn round_trip(test: &str, name: &str) -> (PathBuf, PathBuf, PathBuf) {
        let work = scratch_dir(test);
        let tree = work.join("tree");
        std::fs::create_dir_all(tree.join("sub/empty")).unwrap();
        std::fs::write(tree.join("a.txt"), "alpha").unwrap();
        std::fs::write(tree.join("sub/b.txt"), "beta").unwrap();
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            std::fs::set_permissions(
                tree.join("sub/b.txt"),
                std::fs::Permissions::from_mode(0o750),
            )
            .unwrap();
        }

        let engine = OperationEngine::new(StdFilesystem);
        let archive = work.join(name);
        engine
            .execute(&Operation::CreateArchive {
                sources: vec![tree.clone()],
                base_dir: work.clone(),
                archive: archive.clone(),
            })
            .unwrap();
        let out = work.join("out");
        std::fs::create_dir(&out).unwrap();
        engine
            .execute(&Operation::ExtractArchive {
                archive: archive.clone(),
                dest_dir: out.clone(),
            })
            .unwrap();
        (work, archive, out)
    }

    #[cfg(unix)]
    fn mode(path: &Path) -> u32 {
        use std::os::unix::fs::PermissionsExt;
        std::fs::metadata(path).unwrap().permissions().mode() & 0o777
    }

    #[test]
    fn every_format_round_trips_through_extraction() {
        for (test, name) in [
            ("rt_zip", "x.zip"),
            ("rt_tar", "x.tar"),
            ("rt_tgz", "x.tar.gz"),
        ] {
            let (work, _, out) = round_trip(test, name);
            assert_eq!(
                snapshot(&out.join("tree")),
                snapshot(&work.join("tree")),
                "{name}"
            );
            #[cfg(unix)]
            assert_eq!(mode(&out.join("tree/sub/b.txt")), 0o750, "{name}");
            std::fs::remove_dir_all(&work).unwrap();
        }
    }

    #[test]
    fn zip_entries_keep_their_modification_date() {
        let (work, archive, _) = round_trip("zip_time", "t.zip");
        let mut zip = zip::ZipArchive::new(std::fs::File::open(&archive).unwrap()).unwrap();
        let entry = zip.by_name("tree/a.txt").unwrap();
        let year = entry.last_modified().map(|time| time.year());
        assert!(year.is_some_and(|year| year > 2000), "{year:?}");
        std::fs::remove_dir_all(&work).unwrap();
    }

    #[cfg(unix)]
    #[test]
    fn symlinks_are_packed_as_links() {
        let work = scratch_dir("pack_links");
        let outside = work.join("outside");
        std::fs::create_dir(&outside).unwrap();
        std::fs::write(outside.join("big.bin"), "lots").unwrap();
        std::os::unix::fs::symlink(&outside, work.join("link")).unwrap();
        let engine = OperationEngine::new(StdFilesystem);

        for name in ["l.tar", "l.zip"] {
            engine
                .execute(&Operation::CreateArchive {
                    sources: vec![work.join("link")],
                    base_dir: work.clone(),
                    archive: work.join(name),
                })
                .unwrap();
        }

        let tar_entries: Vec<_> =
            tar::Archive::new(std::fs::File::open(work.join("l.tar")).unwrap())
                .entries()
                .unwrap()
                .map(|e| e.unwrap().header().entry_type())
                .collect();
        assert_eq!(tar_entries, vec![tar::EntryType::Symlink]);

        let mut zip =
            zip::ZipArchive::new(std::fs::File::open(work.join("l.zip")).unwrap()).unwrap();
        assert_eq!(zip.len(), 1);
        assert!(zip.by_index(0).unwrap().is_symlink());
        std::fs::remove_dir_all(&work).unwrap();
    }

    #[test]
    fn cancelled_packing_leaves_neither_archive_nor_temp_file() {
        let work = scratch_dir("pack_cancel");
        for i in 0..5 {
            std::fs::write(work.join(format!("f{i}.txt")), "x").unwrap();
        }
        let engine = OperationEngine::new(StdFilesystem);
        let cancel = AtomicBool::new(false);
        let archive = work.join("out.tar.gz");
        let sources = (0..5).map(|i| work.join(format!("f{i}.txt"))).collect();

        let outcome = engine
            .execute_with_progress(
                &Operation::CreateArchive {
                    sources,
                    base_dir: work.clone(),
                    archive: archive.clone(),
                },
                &cancel,
                &mut |_| cancel.store(true, Ordering::Relaxed),
            )
            .unwrap();

        assert_eq!(outcome, OperationOutcome::Cancelled);
        assert!(!archive.exists());
        assert!(!work.join(".out.tar.gz.oxinav-partial").exists());
        std::fs::remove_dir_all(&work).unwrap();
    }

    /// A small project on real disk for the ripgrep backend: a git repo
    /// (so `.gitignore` applies, as in `rg`), an ignored build directory, a
    /// binary file and a hidden file.
    fn search_tree(test: &str) -> PathBuf {
        let root = scratch_dir(test);
        std::fs::create_dir_all(root.join(".git")).unwrap();
        std::fs::create_dir_all(root.join("src")).unwrap();
        std::fs::create_dir_all(root.join("target")).unwrap();
        std::fs::write(root.join(".gitignore"), "target/\n").unwrap();
        std::fs::write(root.join("src/b.rs"), "// TODO later\nfn main() {}\n").unwrap();
        std::fs::write(root.join("a.md"), "todo: write docs\nTodo list\n").unwrap();
        std::fs::write(root.join("target/out.rs"), "fn main() {}\n").unwrap();
        std::fs::write(root.join("blob.bin"), b"fn main\0\x01\x02").unwrap();
        std::fs::write(root.join(".env"), "fn main\n").unwrap();
        root
    }

    fn std_search(root: &Path, pattern: &str) -> Result<Vec<String>, OxiNavError> {
        let engine = OperationEngine::new(StdFilesystem);
        let query = query(pattern, false, None);
        let mut hits = Vec::new();
        engine.search(root, &query, &AtomicBool::new(false), &mut |hit| {
            let name = hit
                .path
                .strip_prefix(root)
                .unwrap()
                .to_string_lossy()
                .replace('\\', "/");
            hits.push(format!("{name}:{}:{}", hit.line, hit.text));
        })?;
        Ok(hits)
    }

    #[test]
    fn ripgrep_backend_skips_ignored_binary_and_hidden_files() {
        let root = search_tree("rg_scope");
        assert_eq!(
            std_search(&root, r"fn\s+main").unwrap(),
            vec!["src/b.rs:2:fn main() {}"]
        );
        std::fs::remove_dir_all(&root).unwrap();
    }

    #[test]
    fn ripgrep_backend_applies_smart_case_in_a_stable_order() {
        let root = search_tree("rg_case");
        assert_eq!(
            std_search(&root, "todo").unwrap(),
            vec![
                "a.md:1:todo: write docs",
                "a.md:2:Todo list",
                "src/b.rs:1:// TODO later",
            ]
        );
        assert_eq!(std_search(&root, "Todo").unwrap(), vec!["a.md:2:Todo list"]);
        std::fs::remove_dir_all(&root).unwrap();
    }

    #[test]
    fn ripgrep_backend_rejects_an_invalid_regex() {
        let root = search_tree("rg_invalid");
        assert!(matches!(
            std_search(&root, "foo("),
            Err(OxiNavError::InvalidPattern(_))
        ));
        std::fs::remove_dir_all(&root).unwrap();
    }

    #[test]
    fn create_file_creates_an_empty_file() {
        let fs = MockFs::with(&[]);
        let engine = OperationEngine::new(fs);

        engine
            .execute(&Operation::CreateFile {
                path: "/new.txt".into(),
            })
            .unwrap();

        assert!(engine.exists(Path::new("/new.txt")));
    }

    #[test]
    fn create_file_rejects_an_existing_name() {
        let engine = OperationEngine::new(MockFs::with(&["/taken.txt"]));

        let result = engine.execute(&Operation::CreateFile {
            path: "/taken.txt".into(),
        });

        assert!(matches!(result, Err(OxiNavError::DestinationExists(_))));
    }

    #[test]
    fn create_file_rejects_an_existing_directory_name() {
        let engine = OperationEngine::new(MockFs::tree(&[("/dir", None)]));

        let result = engine.execute(&Operation::CreateFile {
            path: "/dir".into(),
        });

        assert!(matches!(result, Err(OxiNavError::DestinationExists(_))));
    }

    #[test]
    fn create_symlink_creates_a_link_at_the_target_path() {
        let engine = OperationEngine::new(MockFs::with(&["/src.txt"]));

        engine
            .execute(&Operation::CreateSymlink {
                source: "/src.txt".into(),
                link: "/other/link.txt".into(),
            })
            .unwrap();

        assert!(engine.exists(Path::new("/other/link.txt")));
        // The source is linked, not moved.
        assert!(engine.exists(Path::new("/src.txt")));
    }

    #[test]
    fn create_symlink_rejects_a_missing_source() {
        let engine = OperationEngine::new(MockFs::with(&[]));

        let result = engine.execute(&Operation::CreateSymlink {
            source: "/gone.txt".into(),
            link: "/link.txt".into(),
        });

        assert!(matches!(result, Err(OxiNavError::SourceNotFound(_))));
        assert!(!engine.exists(Path::new("/link.txt")));
    }

    #[test]
    fn create_symlink_rejects_an_existing_link_path() {
        let engine = OperationEngine::new(MockFs::with(&["/src.txt", "/link.txt"]));

        let result = engine.execute(&Operation::CreateSymlink {
            source: "/src.txt".into(),
            link: "/link.txt".into(),
        });

        assert!(matches!(result, Err(OxiNavError::DestinationExists(_))));
    }

    #[test]
    fn new_single_item_ops_estimate_one_item() {
        let engine = OperationEngine::new(MockFs::with(&["/src.txt"]));

        assert_eq!(
            engine.estimate_totals(&Operation::CreateFile {
                path: "/new.txt".into()
            }),
            (1, 0)
        );
        assert_eq!(
            engine.estimate_totals(&Operation::CreateSymlink {
                source: "/src.txt".into(),
                link: "/link.txt".into(),
            }),
            (1, 0)
        );
    }

    fn extract(archive: &str, dest: &str) -> Operation {
        Operation::ExtractArchive {
            archive: archive.into(),
            dest_dir: dest.into(),
        }
    }

    #[test]
    fn extract_writes_entries_under_the_destination() {
        let fs =
            MockFs::tree(&[("/dest", None)]).with_archive("/a.zip", &["one.txt", "nested/two.txt"]);
        let engine = OperationEngine::new(fs);

        engine.execute(&extract("/a.zip", "/dest")).unwrap();

        assert!(engine.exists(Path::new("/dest/one.txt")));
        assert!(engine.exists(Path::new("/dest/nested/two.txt")));
    }

    #[test]
    fn extract_rejects_an_unsupported_format_without_writing_anything() {
        let fs = MockFs::tree(&[("/dest", None)]).with_archive("/a.rar", &["one.txt"]);
        let engine = OperationEngine::new(fs);

        let result = engine.execute(&extract("/a.rar", "/dest"));

        assert!(matches!(result, Err(OxiNavError::UnsupportedArchive(_))));
        // The format is checked before decoding, so nothing was extracted.
        assert!(!engine.exists(Path::new("/dest/one.txt")));
    }

    #[test]
    fn extract_rejects_a_missing_archive() {
        let engine = OperationEngine::new(MockFs::tree(&[("/dest", None)]));

        let result = engine.execute(&extract("/gone.zip", "/dest"));

        assert!(matches!(result, Err(OxiNavError::SourceNotFound(_))));
    }

    #[test]
    fn extract_rejects_a_missing_destination() {
        let fs = MockFs::with(&[]).with_archive("/a.zip", &["one.txt"]);
        let engine = OperationEngine::new(fs);

        let result = engine.execute(&extract("/a.zip", "/nope"));

        assert!(matches!(result, Err(OxiNavError::SourceNotFound(_))));
    }

    #[test]
    fn extract_refuses_an_entry_escaping_the_destination() {
        let fs = MockFs::tree(&[("/dest", None)]).with_archive("/evil.zip", &["../../etc/passwd"]);
        let engine = OperationEngine::new(fs);

        let result = engine.execute(&extract("/evil.zip", "/dest"));

        assert!(matches!(result, Err(OxiNavError::UnsafeArchiveEntry(_))));
        assert!(!engine.exists(Path::new("/etc/passwd")));
    }

    #[test]
    fn extract_reports_progress_per_entry_against_a_total_known_up_front() {
        let fs = MockFs::tree(&[("/dest", None)])
            .with_archive("/a.tar.gz", &["one.txt", "two.txt", "three.txt"]);
        let engine = OperationEngine::new(fs);
        let cancel = AtomicBool::new(false);
        let mut seen: Vec<Progress> = Vec::new();

        let outcome = engine
            .execute_with_progress(&extract("/a.tar.gz", "/dest"), &cancel, &mut |p| {
                seen.push(p)
            })
            .unwrap();

        assert_eq!(outcome, OperationOutcome::Completed);
        assert_eq!(seen.len(), 3);
        // Totals fixed before the first entry, counts advancing to N of N.
        assert!(seen.iter().all(|p| p.items_total == 3));
        assert_eq!(
            seen.iter().map(|p| p.items_done).collect::<Vec<_>>(),
            vec![1, 2, 3]
        );
    }

    #[test]
    fn extract_estimates_the_archive_entry_count() {
        let fs = MockFs::tree(&[("/dest", None)]).with_archive("/a.zip", &["one.txt", "two.txt"]);
        let engine = OperationEngine::new(fs);

        assert_eq!(engine.estimate_totals(&extract("/a.zip", "/dest")), (2, 0));
    }

    #[test]
    fn extract_estimate_falls_back_to_one_item_when_unreadable() {
        let engine = OperationEngine::new(MockFs::tree(&[("/dest", None)]));

        assert_eq!(
            engine.estimate_totals(&extract("/gone.zip", "/dest")),
            (1, 0)
        );
    }

    /// A scratch directory under the system temp dir, emptied first.
    fn scratch(name: &str) -> PathBuf {
        let dir = std::env::temp_dir().join(name);
        std::fs::remove_dir_all(&dir).ok();
        std::fs::create_dir_all(&dir).unwrap();
        dir
    }

    fn write_zip(path: &Path, entries: &[(&str, &[u8])]) {
        use std::io::Write;
        let file = std::fs::File::create(path).unwrap();
        let mut zip = zip::ZipWriter::new(file);
        for (name, body) in entries {
            zip.start_file(*name, zip::write::SimpleFileOptions::default())
                .unwrap();
            zip.write_all(body).unwrap();
        }
        zip.finish().unwrap();
    }

    fn write_tar_gz(path: &Path, entries: &[(&str, &[u8])]) {
        let file = std::fs::File::create(path).unwrap();
        let encoder = flate2::write::GzEncoder::new(file, flate2::Compression::default());
        let mut builder = tar::Builder::new(encoder);
        for (name, body) in entries {
            let mut header = tar::Header::new_gnu();
            header.set_size(body.len() as u64);
            header.set_mode(0o644);
            header.set_cksum();
            builder.append_data(&mut header, name, *body).unwrap();
        }
        builder.into_inner().unwrap().finish().unwrap();
    }

    #[test]
    fn real_zip_is_extracted_with_its_contents_and_nesting() {
        let dir = scratch("oxinav_test_extract_zip");
        let archive = dir.join("bundle.zip");
        write_zip(
            &archive,
            &[("top.txt", b"one"), ("nested/deep.txt", b"two")],
        );
        let dest = dir.join("out");
        std::fs::create_dir_all(&dest).unwrap();

        let engine = OperationEngine::new(StdFilesystem);
        engine
            .execute(&Operation::ExtractArchive {
                archive,
                dest_dir: dest.clone(),
            })
            .unwrap();

        assert_eq!(std::fs::read(dest.join("top.txt")).unwrap(), b"one");
        assert_eq!(std::fs::read(dest.join("nested/deep.txt")).unwrap(), b"two");

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

    #[test]
    fn real_tar_gz_is_extracted_with_its_contents() {
        let dir = scratch("oxinav_test_extract_targz");
        let archive = dir.join("bundle.tar.gz");
        write_tar_gz(&archive, &[("a.txt", b"alpha"), ("sub/b.txt", b"beta")]);
        let dest = dir.join("out");
        std::fs::create_dir_all(&dest).unwrap();

        let engine = OperationEngine::new(StdFilesystem);
        engine
            .execute(&Operation::ExtractArchive {
                archive,
                dest_dir: dest.clone(),
            })
            .unwrap();

        assert_eq!(std::fs::read(dest.join("a.txt")).unwrap(), b"alpha");
        assert_eq!(std::fs::read(dest.join("sub/b.txt")).unwrap(), b"beta");

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

    #[test]
    fn real_tar_gz_with_a_dot_root_entry_still_extracts() {
        // `tar czf x.tar.gz -C dir .` makes `./` the first entry. Treating it
        // as an escape aborted the whole archive on entry one; only a
        // GNU-tar-built fixture caught it, since tar::Builder emits no root.
        let dir = scratch("oxinav_test_extract_dot_root");
        let archive = dir.join("rooted.tar.gz");
        write_tar_gz(
            &archive,
            &[
                ("./", b""),
                ("./top.txt", b"one"),
                ("./sub/deep.txt", b"two"),
            ],
        );
        let dest = dir.join("out");
        std::fs::create_dir_all(&dest).unwrap();

        let engine = OperationEngine::new(StdFilesystem);
        engine
            .execute(&Operation::ExtractArchive {
                archive,
                dest_dir: dest.clone(),
            })
            .unwrap();

        assert_eq!(std::fs::read(dest.join("top.txt")).unwrap(), b"one");
        assert_eq!(std::fs::read(dest.join("sub/deep.txt")).unwrap(), b"two");

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

    #[test]
    fn real_zip_slip_entry_never_escapes_the_destination() {
        let dir = scratch("oxinav_test_extract_zipslip");
        let archive = dir.join("evil.zip");
        // A genuine zip-slip payload: the entry name climbs out of dest.
        write_zip(&archive, &[("../escaped.txt", b"pwned")]);
        let dest = dir.join("out");
        std::fs::create_dir_all(&dest).unwrap();

        let engine = OperationEngine::new(StdFilesystem);
        let result = engine.execute(&Operation::ExtractArchive {
            archive,
            dest_dir: dest.clone(),
        });

        assert!(matches!(result, Err(OxiNavError::UnsafeArchiveEntry(_))));
        assert!(!dir.join("escaped.txt").exists());

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

    #[test]
    fn real_entry_count_matches_the_archive() {
        let dir = scratch("oxinav_test_extract_count");
        let zip_path = dir.join("z.zip");
        write_zip(&zip_path, &[("a", b"1"), ("b", b"2"), ("c", b"3")]);
        let tgz_path = dir.join("t.tar.gz");
        write_tar_gz(&tgz_path, &[("a", b"1"), ("b", b"2")]);

        let fs = StdFilesystem;
        assert_eq!(
            fs.count_archive_entries(&zip_path, ArchiveFormat::Zip)
                .unwrap(),
            3
        );
        assert_eq!(
            fs.count_archive_entries(&tgz_path, ArchiveFormat::TarGz)
                .unwrap(),
            2
        );

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

    #[test]
    fn resolve_directory_accepts_an_existing_directory() {
        let engine = OperationEngine::new(MockFs::tree(&[("/home/me/code", None)]));

        let target = engine
            .resolve_directory("/home/me/code", Path::new("/home/me"))
            .unwrap();

        assert_eq!(target, PathBuf::from("/home/me/code"));
    }

    #[test]
    fn resolve_directory_expands_a_leading_tilde() {
        let engine =
            OperationEngine::new(MockFs::tree(&[("/home/me", None), ("/home/me/code", None)]));
        let home = Path::new("/home/me");

        assert_eq!(
            engine.resolve_directory("~/code", home).unwrap(),
            PathBuf::from("/home/me/code")
        );
        // `~` alone is the home directory itself.
        assert_eq!(
            engine.resolve_directory("~", home).unwrap(),
            PathBuf::from("/home/me")
        );
    }

    #[test]
    fn resolve_directory_leaves_an_interior_tilde_alone() {
        let engine = OperationEngine::new(MockFs::tree(&[("/data/back~up", None)]));

        assert_eq!(
            engine
                .resolve_directory("/data/back~up", Path::new("/home/me"))
                .unwrap(),
            PathBuf::from("/data/back~up")
        );
    }

    #[test]
    fn resolve_directory_rejects_a_missing_path() {
        let engine = OperationEngine::new(MockFs::tree(&[]));

        let result = engine.resolve_directory("/nope", Path::new("/home/me"));

        assert!(matches!(result, Err(OxiNavError::SourceNotFound(_))));
    }

    #[test]
    fn resolve_directory_rejects_a_file() {
        let engine = OperationEngine::new(MockFs::with(&["/home/me/notes.txt"]));

        let result = engine.resolve_directory("/home/me/notes.txt", Path::new("/home/me"));

        assert!(matches!(result, Err(OxiNavError::NotADirectory(_))));
    }

    #[test]
    fn resolve_directory_rejects_a_blank_input() {
        let engine = OperationEngine::new(MockFs::tree(&[("/home/me", None)]));

        assert!(engine
            .resolve_directory("   ", Path::new("/home/me"))
            .is_err());
    }

    #[test]
    fn resolve_directory_trims_surrounding_whitespace() {
        let engine = OperationEngine::new(MockFs::tree(&[("/home/me/code", None)]));

        assert_eq!(
            engine
                .resolve_directory("  /home/me/code  ", Path::new("/home/me"))
                .unwrap(),
            PathBuf::from("/home/me/code")
        );
    }

    #[test]
    fn read_capped_stops_at_the_cap() {
        let engine = OperationEngine::new(MockFs::tree(&[("/big", Some(4096))]));

        let bytes = engine.read_capped(Path::new("/big"), 100).unwrap();

        assert_eq!(bytes.len(), 100);
    }

    #[test]
    fn read_capped_missing_source_errors() {
        let engine = OperationEngine::new(MockFs::with(&[]));

        let result = engine.read_capped(Path::new("/gone"), 100);

        assert!(matches!(result, Err(OxiNavError::SourceNotFound(_))));
    }

    #[test]
    fn copy_missing_source_errors() {
        let engine = OperationEngine::new(MockFs::with(&[]));
        let result = engine.execute(&Operation::Copy {
            src: "/a".into(),
            dest: "/b".into(),
        });
        assert!(matches!(result, Err(OxiNavError::SourceNotFound(_))));
    }

    #[test]
    fn copy_existing_dest_errors() {
        let engine = OperationEngine::new(MockFs::with(&["/a", "/b"]));
        let result = engine.execute(&Operation::Copy {
            src: "/a".into(),
            dest: "/b".into(),
        });
        assert!(matches!(result, Err(OxiNavError::DestinationExists(_))));
    }

    #[test]
    fn delete_missing_source_errors() {
        let engine = OperationEngine::new(MockFs::with(&[]));
        let result = engine.execute(&Operation::Delete { path: "/a".into() });
        assert!(matches!(result, Err(OxiNavError::SourceNotFound(_))));
    }

    #[test]
    fn create_dir_existing_errors() {
        let engine = OperationEngine::new(MockFs::with(&["/dir"]));
        let result = engine.execute(&Operation::CreateDir {
            path: "/dir".into(),
        });
        assert!(matches!(result, Err(OxiNavError::DestinationExists(_))));
    }

    #[test]
    fn exists_reports_true_for_present_path() {
        let engine = OperationEngine::new(MockFs::with(&["/a"]));
        assert!(engine.exists(Path::new("/a")));
    }

    #[test]
    fn exists_reports_false_for_missing_path() {
        let engine = OperationEngine::new(MockFs::with(&["/a"]));
        assert!(!engine.exists(Path::new("/b")));
    }

    #[test]
    fn recursive_copy_emits_progress_per_file() {
        // /src holds 3 files (one nested); totals: 3 items, 60 bytes.
        let engine = OperationEngine::new(MockFs::tree(&[
            ("/src", None),
            ("/src/a.txt", Some(10)),
            ("/src/b.txt", Some(20)),
            ("/src/sub", None),
            ("/src/sub/c.txt", Some(30)),
        ]));
        let cancel = AtomicBool::new(false);
        let mut ticks = Vec::new();
        let outcome = engine
            .execute_with_progress(
                &Operation::Copy {
                    src: "/src".into(),
                    dest: "/dst".into(),
                },
                &cancel,
                &mut |p| ticks.push(p),
            )
            .unwrap();

        assert_eq!(outcome, OperationOutcome::Completed);
        // One tick per file, in item order regardless of walk order.
        assert_eq!(
            ticks.iter().map(|p| p.items_done).collect::<Vec<_>>(),
            vec![1, 2, 3]
        );
        // Totals are fixed up front on every tick.
        assert!(ticks
            .iter()
            .all(|p| p.items_total == 3 && p.bytes_total == 60));
        // bytes_done accumulates monotonically to the total.
        assert!(ticks.windows(2).all(|w| w[0].bytes_done <= w[1].bytes_done));
        assert_eq!(ticks.last().unwrap().bytes_done, 60);
        // Every file landed under the destination.
        assert!(engine.exists(Path::new("/dst/a.txt")));
        assert!(engine.exists(Path::new("/dst/b.txt")));
        assert!(engine.exists(Path::new("/dst/sub/c.txt")));
    }

    #[test]
    fn estimate_totals_counts_files_and_bytes() {
        let engine = OperationEngine::new(MockFs::tree(&[
            ("/src", None),
            ("/src/a.txt", Some(10)),
            ("/src/sub", None),
            ("/src/sub/b.txt", Some(30)),
        ]));
        // A directory: descendant files and their summed bytes.
        assert_eq!(
            engine.estimate_totals(&Operation::Copy {
                src: "/src".into(),
                dest: "/dst".into(),
            }),
            (2, 40)
        );
        // A single file: one item, its own size.
        assert_eq!(
            engine.estimate_totals(&Operation::Delete {
                path: "/src/a.txt".into(),
            }),
            (1, 10)
        );
    }

    #[test]
    fn cancel_stops_before_next_item() {
        let engine = OperationEngine::new(MockFs::tree(&[
            ("/src", None),
            ("/src/a", Some(1)),
            ("/src/b", Some(1)),
            ("/src/c", Some(1)),
        ]));
        let cancel = Arc::new(AtomicBool::new(false));
        let flag = cancel.clone();
        let mut ticks = 0usize;
        let outcome = engine
            .execute_with_progress(
                &Operation::Copy {
                    src: "/src".into(),
                    dest: "/dst".into(),
                },
                &cancel,
                // Cancel right after the first item completes.
                &mut |_| {
                    ticks += 1;
                    flag.store(true, Ordering::Relaxed);
                },
            )
            .unwrap();

        assert_eq!(outcome, OperationOutcome::Cancelled);
        // Stopped before starting the second item.
        assert_eq!(ticks, 1);
        // Exactly one of the three files was copied; the rest were left alone.
        let copied = ["/dst/a", "/dst/b", "/dst/c"]
            .iter()
            .filter(|p| engine.exists(&PathBuf::from(*p)))
            .count();
        assert_eq!(copied, 1);
    }
}