kuizer-gui 0.3.0

Desktop app for kuizer, a keyboard-driven PC cleaner that also deeply cleans developer artifacts, caches, toolchains, Docker and duplicates, built on GPUI
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
use std::cell::RefCell;
use std::collections::{BTreeMap, HashMap, HashSet};
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, Ordering};
use std::thread;
use std::time::{Duration, Instant, SystemTime};

pub use kuizer::caches::guard_roots as cache_roots;
pub use kuizer::delete::Batch;
pub use kuizer::source::Source;

use kuizer::big::{self, LargeFile};
use kuizer::caches::{self, KnownCache, Locations};
use kuizer::config::{Config, DeleteConfig, DeleteMode, Excludes};
use kuizer::delete::{Executor, Removal, Status};
use kuizer::detect::Category;
use kuizer::docker;
use kuizer::dupes::{self, Duplicates, Options};
use kuizer::history::restore::Status as RestoreStatus;
use kuizer::history::{self, Action, History, TrashSnapshot, TrashView};
use kuizer::platform::{self, display_path};
use kuizer::protect::Protected;
use kuizer::repos::{self, Repository};
use kuizer::scan::{self, Cancel, Candidate, Issue, Progress, SortKey, Summary, sort_candidates};
use kuizer::system;
use kuizer::toolchains::{self, Toolchain};
use kuizer::trashcan;
use kuizer::usage::{self, MeasureConfig, UsageOptions, UsageTree, WalkDiagnostics};

use crate::activity::{self, Found, Step, Tracker, grouped, plural};
use crate::start::ScanOptions;
use crate::stats::HistoryStats;
use crate::theme;

pub const CANCELLED: &str = "cancelled";

/// One section of a scan that arrives on its own: the parts run side by side and each is
/// shown the moment it is done.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub enum Part {
    Artifacts,
    Caches,
    Toolchains,
    Docker,
    Repos,
    Trash,
    System,
    Big,
    Usage,
    History,
}

impl Part {
    /// @name Part::expected
    /// @description The parts a scan with these options delivers. Parts the options turn off
    /// never arrive, so nothing waits for them.
    ///
    /// @example
    /// let pending = Part::expected(&options);
    pub fn expected(options: &ScanOptions) -> HashSet<Part> {
        [
            (true, Self::Artifacts),
            (options.caches, Self::Caches),
            (options.toolchains, Self::Toolchains),
            (options.docker, Self::Docker),
            (options.repos, Self::Repos),
            (options.trash, Self::Trash),
            (options.system, Self::System),
            (options.big, Self::Big),
            (options.usage, Self::Usage),
            (true, Self::History),
        ]
        .into_iter()
        .filter_map(|(on, part)| on.then_some(part))
        .collect()
    }

    pub fn source(self) -> Option<Source> {
        match self {
            Self::Artifacts => Some(Source::Artifact),
            Self::Caches => Some(Source::Cache),
            Self::Toolchains => Some(Source::Toolchain),
            Self::Docker => Some(Source::Docker),
            Self::Trash => Some(Source::Trash),
            Self::Big => Some(Source::Big),
            Self::System => Some(Source::System),
            Self::Repos | Self::Usage | Self::History => None,
        }
    }
}

/// What a running scan hands to the window: a batch of artifacts found so far while the folder
/// walk runs, or a finished part that replaces its section of the report.
pub enum Loaded {
    Found(Vec<Candidate>),
    Artifacts {
        candidates: Vec<Candidate>,
        issues: Vec<Issue>,
        summary: Summary,
        disks: Vec<Disk>,
    },
    ArtifactsDone {
        issues: Vec<Issue>,
        summary: Summary,
        disks: Vec<Disk>,
    },
    Caches(Vec<(KnownCache, Candidate)>),
    Toolchains(Vec<(Toolchain, Candidate)>),
    Docker {
        entries: Vec<(docker::Item, Candidate)>,
        issues: Vec<String>,
    },
    Repos(Vec<Repository>),
    Trash {
        entries: Vec<(trashcan::Folder, Candidate)>,
        issues: Vec<Issue>,
    },
    System {
        entries: Vec<(system::Item, Candidate)>,
        issues: Vec<String>,
    },
    Big(Vec<Candidate>),
    Usage(Option<UsageTree>),
    Diagnostics(WalkDiagnostics),
    History(Result<HistoryView, String>),
}

impl Loaded {
    pub fn part(&self) -> Option<Part> {
        match self {
            Self::Found(_) | Self::Diagnostics(_) => None,
            Self::Artifacts { .. } | Self::ArtifactsDone { .. } => Some(Part::Artifacts),
            Self::Caches(_) => Some(Part::Caches),
            Self::Toolchains(_) => Some(Part::Toolchains),
            Self::Docker { .. } => Some(Part::Docker),
            Self::Repos(_) => Some(Part::Repos),
            Self::Trash { .. } => Some(Part::Trash),
            Self::System { .. } => Some(Part::System),
            Self::Big(_) => Some(Part::Big),
            Self::Usage(_) => Some(Part::Usage),
            Self::History(_) => Some(Part::History),
        }
    }

    /// @name Loaded::without
    /// @description Leaves out the items of this part that sit under an excluded path or were
    /// deleted while the scan ran, so a running scan never brings them back. Filtering each part
    /// as it arrives costs only its own items, not the whole report on every update.
    ///
    /// @example
    /// loaded.without(&excluded, &gone);
    pub fn without(&mut self, excluded: &[PathBuf], gone: &HashMap<Source, HashSet<PathBuf>>) {
        let source = match self {
            Self::Found(_) | Self::Artifacts { .. } | Self::ArtifactsDone { .. } => {
                Some(Source::Artifact)
            }
            Self::Caches(_) => Some(Source::Cache),
            Self::Toolchains(_) => Some(Source::Toolchain),
            Self::Docker { .. } => Some(Source::Docker),
            Self::Trash { .. } => Some(Source::Trash),
            Self::Big(_) => Some(Source::Big),
            Self::System { .. } => Some(Source::System),
            Self::Repos(_) | Self::Usage(_) | Self::Diagnostics(_) | Self::History(_) => None,
        };
        let deleted = source.and_then(|source| gone.get(&source));
        if excluded.is_empty() && deleted.is_none_or(HashSet::is_empty) {
            return;
        }
        let stays = |path: &Path| {
            !deleted.is_some_and(|deleted| deleted.contains(path))
                && !excluded.iter().any(|excluded| path.starts_with(excluded))
        };
        match self {
            Self::Found(candidates) => candidates.retain(|candidate| stays(&candidate.path)),
            Self::Artifacts {
                candidates, issues, ..
            } => {
                candidates.retain(|candidate| stays(&candidate.path));
                issues.retain(|issue| stays(&issue.path));
            }
            Self::ArtifactsDone { issues, .. } => issues.retain(|issue| stays(&issue.path)),
            Self::Caches(caches) => caches.retain(|(_, candidate)| stays(&candidate.path)),
            Self::Toolchains(toolchains) => {
                toolchains.retain(|(_, candidate)| stays(&candidate.path));
            }
            Self::Docker { entries, .. } => entries.retain(|(_, candidate)| {
                !deleted.is_some_and(|deleted| deleted.contains(&candidate.path))
            }),
            Self::Repos(repos) => repos.retain(|repository| stays(&repository.root)),
            Self::Trash { entries, .. } => entries.retain(|(_, candidate)| stays(&candidate.path)),
            Self::Big(candidates) => candidates.retain(|candidate| stays(&candidate.path)),
            Self::System { entries, .. } => entries.retain(|(_, candidate)| {
                !deleted.is_some_and(|deleted| deleted.contains(&candidate.path))
            }),
            Self::Usage(tree) => {
                if let Some(tree) = tree {
                    let mut dropped: HashSet<PathBuf> = gone
                        .values()
                        .flat_map(|paths| paths.iter().cloned())
                        .collect();
                    dropped.extend(excluded.iter().cloned());
                    tree.drop_paths(&dropped);
                }
            }
            Self::Diagnostics(_) | Self::History(_) => {}
        }
    }
}

pub struct Disk {
    pub available: Option<u64>,
    pub total: Option<u64>,
}

pub use kuizer::history::TrashState;

pub struct HistoryView {
    pub history: std::sync::Arc<History>,
    pub trash: TrashSnapshot,
    pub stats: HistoryStats,
}

impl HistoryView {
    /// @name HistoryView::new
    /// @description Holds a history with its trash snapshot and works out the trash states and
    /// totals the history tab shows right away, so a view built on the history thread leaves
    /// nothing for render to compute.
    ///
    /// @example
    /// let view = HistoryView::new(history, TrashSnapshot::read(&history));
    pub fn new(history: History, trash: TrashSnapshot) -> Self {
        let stats = HistoryStats::of(&history, &trash);
        Self {
            history: std::sync::Arc::new(history),
            trash,
            stats,
        }
    }

    pub fn load() -> Result<Self, String> {
        let path = history::default_path().map_err(|error| error.to_string())?;
        let history = history::load(&path).map_err(|error| error.to_string())?;
        let trash = TrashSnapshot::read(&history);
        Ok(Self::new(history, trash))
    }

    pub fn trash_state(&self, run: usize) -> TrashState {
        self.stats
            .trash
            .get(run)
            .copied()
            .unwrap_or(TrashState::NotTrashed)
    }

    pub fn delete_runs(&self) -> impl DoubleEndedIterator<Item = &history::Run> {
        self.history
            .runs
            .iter()
            .filter(|run| run.action == Action::Delete)
    }
}

pub struct Report {
    pub roots: Vec<PathBuf>,
    pub options: ScanOptions,
    pub candidates: Vec<Candidate>,
    pub issues: Vec<Issue>,
    pub summary: Summary,
    pub caches: Vec<(KnownCache, Candidate)>,
    pub toolchains: Vec<(Toolchain, Candidate)>,
    pub docker: Vec<(docker::Item, Candidate)>,
    pub docker_issues: Vec<String>,
    pub repos: Vec<Repository>,
    pub trash: Vec<(trashcan::Folder, Candidate)>,
    pub trash_issues: Vec<Issue>,
    pub system: Vec<(system::Item, Candidate)>,
    pub system_issues: Vec<String>,
    pub big: Vec<Candidate>,
    pub usage: Option<UsageTree>,
    pub walk_diagnostics: Option<WalkDiagnostics>,
    pub duplicates: Option<Duplicates>,
    pub history: Result<HistoryView, String>,
    pub disks: Vec<Disk>,
    pub scanned: SystemTime,
}

pub struct Bucket<K> {
    pub key: K,
    pub bytes: u64,
    pub count: usize,
}

impl Report {
    /// @name Report::empty
    /// @description A report with nothing in it yet, for the parts of a scan to fill in as they
    /// finish.
    ///
    /// @example
    /// let mut report = Report::empty(&roots, &options);
    pub fn empty(roots: &[PathBuf], options: &ScanOptions) -> Self {
        Self {
            roots: roots.to_vec(),
            options: options.clone(),
            candidates: Vec::new(),
            issues: Vec::new(),
            summary: Summary {
                progress: Progress::default(),
                duration: Duration::ZERO,
                cancelled: false,
            },
            caches: Vec::new(),
            toolchains: Vec::new(),
            docker: Vec::new(),
            docker_issues: Vec::new(),
            repos: Vec::new(),
            trash: Vec::new(),
            trash_issues: Vec::new(),
            system: Vec::new(),
            system_issues: Vec::new(),
            big: Vec::new(),
            usage: None,
            walk_diagnostics: None,
            duplicates: None,
            history: Err(String::new()),
            disks: Vec::new(),
            scanned: SystemTime::now(),
        }
    }

    /// @name Report::apply
    /// @description Stores what a scan delivered. A batch of found artifacts joins the list,
    /// largest first; a finished part replaces its section. Returns what the section held
    /// before, so the caller can drop it where it does not hold up the window.
    ///
    /// @example
    /// let old = report.apply(Loaded::Caches(caches));
    pub fn apply(&mut self, loaded: Loaded) -> Loaded {
        match loaded {
            Loaded::Found(batch) => {
                self.candidates.extend(batch);
                Loaded::Found(Vec::new())
            }
            Loaded::Artifacts {
                candidates,
                issues,
                summary,
                disks,
            } => Loaded::Artifacts {
                candidates: std::mem::replace(&mut self.candidates, candidates),
                issues: std::mem::replace(&mut self.issues, issues),
                summary: std::mem::replace(&mut self.summary, summary),
                disks: std::mem::replace(&mut self.disks, disks),
            },
            Loaded::ArtifactsDone {
                issues,
                summary,
                disks,
            } => {
                sort_candidates(&mut self.candidates, SortKey::Size);
                Loaded::Artifacts {
                    candidates: Vec::new(),
                    issues: std::mem::replace(&mut self.issues, issues),
                    summary: std::mem::replace(&mut self.summary, summary),
                    disks: std::mem::replace(&mut self.disks, disks),
                }
            }
            Loaded::Caches(caches) => Loaded::Caches(std::mem::replace(&mut self.caches, caches)),
            Loaded::Toolchains(toolchains) => {
                Loaded::Toolchains(std::mem::replace(&mut self.toolchains, toolchains))
            }
            Loaded::Docker { entries, issues } => Loaded::Docker {
                entries: std::mem::replace(&mut self.docker, entries),
                issues: std::mem::replace(&mut self.docker_issues, issues),
            },
            Loaded::Repos(repos) => Loaded::Repos(std::mem::replace(&mut self.repos, repos)),
            Loaded::Trash { entries, issues } => Loaded::Trash {
                entries: std::mem::replace(&mut self.trash, entries),
                issues: std::mem::replace(&mut self.trash_issues, issues),
            },
            Loaded::System { entries, issues } => Loaded::System {
                entries: std::mem::replace(&mut self.system, entries),
                issues: std::mem::replace(&mut self.system_issues, issues),
            },
            Loaded::Big(big) => Loaded::Big(std::mem::replace(&mut self.big, big)),
            Loaded::Usage(usage) => Loaded::Usage(std::mem::replace(&mut self.usage, usage)),
            Loaded::Diagnostics(diagnostics) => {
                self.walk_diagnostics = Some(diagnostics);
                Loaded::Found(Vec::new())
            }
            Loaded::History(history) => {
                Loaded::History(std::mem::replace(&mut self.history, history))
            }
        }
    }

    /// @name Report::into_parts
    /// @description Splits a report into its sections, so a saved scan can fill in only the
    /// sections a fresh scan has not delivered yet.
    ///
    /// @example
    /// for part in saved.into_parts() { report.apply(part); }
    pub fn into_parts(self) -> Vec<Loaded> {
        vec![
            Loaded::Artifacts {
                candidates: self.candidates,
                issues: self.issues,
                summary: self.summary,
                disks: self.disks,
            },
            Loaded::Caches(self.caches),
            Loaded::Toolchains(self.toolchains),
            Loaded::Docker {
                entries: self.docker,
                issues: self.docker_issues,
            },
            Loaded::Repos(self.repos),
            Loaded::Trash {
                entries: self.trash,
                issues: self.trash_issues,
            },
            Loaded::System {
                entries: self.system,
                issues: self.system_issues,
            },
            Loaded::Big(self.big),
            Loaded::Usage(self.usage),
            Loaded::History(self.history),
        ]
    }

    /// The removable items of one section of the report.
    pub fn section(&self, source: Source) -> Box<dyn Iterator<Item = &Candidate> + '_> {
        match source {
            Source::Artifact => Box::new(self.candidates.iter()),
            Source::Cache => Box::new(self.caches.iter().map(|(_, candidate)| candidate)),
            Source::Toolchain => Box::new(self.toolchains.iter().map(|(_, candidate)| candidate)),
            Source::Docker => Box::new(self.docker.iter().map(|(_, candidate)| candidate)),
            Source::Trash => Box::new(self.trash.iter().map(|(_, candidate)| candidate)),
            Source::Big => Box::new(self.big.iter()),
            Source::System => Box::new(self.system.iter().map(|(_, candidate)| candidate)),
        }
    }

    #[cfg(test)]
    pub fn total(&self, safety: Option<kuizer::detect::Safety>) -> u64 {
        self.candidates
            .iter()
            .filter(|candidate| safety.is_none_or(|safety| candidate.rule.safety == safety))
            .map(|candidate| candidate.usage.allocated)
            .sum()
    }

    pub fn by_category(&self) -> Vec<Bucket<Category>> {
        let mut buckets: Vec<Bucket<Category>> = Category::ALL
            .iter()
            .map(|&key| Bucket {
                key,
                bytes: 0,
                count: 0,
            })
            .collect();
        for candidate in &self.candidates {
            if let Some(bucket) = buckets
                .iter_mut()
                .find(|bucket| bucket.key == candidate.rule.category)
            {
                bucket.bytes += candidate.usage.allocated;
                bucket.count += 1;
            }
        }
        buckets.retain(|bucket| bucket.count > 0);
        buckets.sort_by_key(|bucket| std::cmp::Reverse(bucket.bytes));
        buckets
    }

    /// @name Report::drop_paths
    /// @description Removes everything at or below any of `paths` from every list, the way a
    /// scan with those paths excluded would. Duplicate groups left with a single copy are dropped.
    ///
    /// @example
    /// report.drop_paths(&[PathBuf::from("/p/site/node_modules")]);
    pub fn drop_paths(&mut self, paths: &[PathBuf]) {
        if paths.is_empty() {
            return;
        }
        let gone = |path: &Path| paths.iter().any(|excluded| path.starts_with(excluded));
        self.candidates.retain(|candidate| !gone(&candidate.path));
        self.caches.retain(|(_, candidate)| !gone(&candidate.path));
        self.toolchains
            .retain(|(_, candidate)| !gone(&candidate.path));
        self.repos.retain(|repository| !gone(&repository.root));
        self.trash.retain(|(_, candidate)| !gone(&candidate.path));
        self.big.retain(|candidate| !gone(&candidate.path));
        if let Some(usage) = &mut self.usage {
            usage.drop_paths(&paths.iter().cloned().collect());
        }
        self.issues.retain(|issue| !gone(&issue.path));
        self.trash_issues.retain(|issue| !gone(&issue.path));
        if let Some(duplicates) = &mut self.duplicates {
            drop_duplicate_paths(duplicates, paths);
        }
    }

    /// @name Report::remove
    /// @description Drops the items at these exact paths, per list, as a finished deletion
    /// does to the report on screen.
    ///
    /// @example
    /// report.remove(&HashMap::from([(Source::Artifact, HashSet::from([path]))]));
    pub fn remove(&mut self, gone: &HashMap<Source, HashSet<PathBuf>>) {
        let stays = |source: Source, candidate: &Candidate| {
            !gone
                .get(&source)
                .is_some_and(|paths| paths.contains(&candidate.path))
        };
        if gone.contains_key(&Source::Artifact) {
            self.candidates
                .retain(|candidate| stays(Source::Artifact, candidate));
        }
        self.caches
            .retain(|(_, candidate)| stays(Source::Cache, candidate));
        self.toolchains
            .retain(|(_, candidate)| stays(Source::Toolchain, candidate));
        self.docker
            .retain(|(_, candidate)| stays(Source::Docker, candidate));
        self.trash
            .retain(|(_, candidate)| stays(Source::Trash, candidate));
        self.big.retain(|candidate| stays(Source::Big, candidate));
        self.system
            .retain(|(_, candidate)| stays(Source::System, candidate));
        if let Some(usage) = &mut self.usage {
            let dropped: HashSet<PathBuf> = gone
                .iter()
                .filter(|(source, _)| !matches!(source, Source::Docker | Source::System))
                .flat_map(|(_, paths)| paths.iter().cloned())
                .collect();
            usage.drop_paths(&dropped);
        }
    }

    pub fn by_project(&self) -> Vec<Bucket<PathBuf>> {
        let mut projects: BTreeMap<&Path, (u64, usize)> = BTreeMap::new();
        for candidate in &self.candidates {
            let entry = projects
                .entry(candidate.project.as_deref().unwrap_or(&candidate.path))
                .or_default();
            entry.0 += candidate.usage.allocated;
            entry.1 += 1;
        }
        let mut buckets: Vec<Bucket<PathBuf>> = projects
            .into_iter()
            .map(|(key, (bytes, count))| Bucket {
                key: key.to_path_buf(),
                bytes,
                count,
            })
            .collect();
        buckets.sort_by_key(|bucket| std::cmp::Reverse(bucket.bytes));
        buckets
    }
}

/// @name drop_duplicate_paths
/// @description Removes the copies at or below any of `paths` from a duplicate search result,
/// drops groups left with a single copy and orders the rest by what they free, largest first.
/// Cheap to call with no paths, so a result can be filtered on a worker thread first.
///
/// @example
/// drop_duplicate_paths(&mut found, &[PathBuf::from("/p/site/node_modules")]);
pub fn drop_duplicate_paths(duplicates: &mut Duplicates, paths: &[PathBuf]) {
    if paths.is_empty() {
        return;
    }
    let gone = |path: &Path| paths.iter().any(|excluded| path.starts_with(excluded));
    for group in &mut duplicates.groups {
        group.members.retain(|member| !gone(&member.path));
    }
    duplicates.groups.retain(|group| group.members.len() > 1);
    duplicates
        .groups
        .sort_by_key(|group| std::cmp::Reverse(group.reclaimable()));
}

/// @name short_path
/// @description Shows a path relative to the scan root that holds it, so long roots are not
/// repeated on every row. Paths under the home directory root keep their `~` form.
///
/// @example
/// assert_eq!(short_path(Path::new("/p/a/dist"), &[PathBuf::from("/p")]), "a/dist");
pub fn short_path(path: &Path, roots: &[PathBuf]) -> String {
    let home = platform::home_dir();
    roots
        .iter()
        .filter(|root| Some(root.as_path()) != home.as_deref())
        .find_map(|root| {
            path.strip_prefix(root)
                .ok()
                .filter(|rest| !rest.as_os_str().is_empty())
        })
        .map_or_else(|| display_path(path), display_path)
}

/// @name load
/// @description Gathers everything the dashboard shows: project artifacts, toolchain pins and
/// large files from one folder walk, global caches, installed toolchains, git repositories,
/// Docker objects, the trash, system package caches, old downloads, the cleanup history and free
/// disk space.
/// The start screen's options decide which of these run. History, caches, toolchains, Docker,
/// the trash, system caches and old downloads start with the walk and run beside it;
/// repositories and the large-file search start when it ends, so neither slows the walk, and
/// toolchains wait for its pins before they are delivered, because a pinned version is never
/// safe to remove.
/// Artifacts go to `emit` in batches while the walk runs, and every part goes to `emit` the
/// moment it is done. Progress goes through `tracker`, and the work stops once `cancel` is set.
///
/// @example
/// let tracker = Tracker::new(|_| {});
/// load(&config, &roots, &options, &Cancel::new(), &tracker, &|loaded| show(loaded))?;
pub fn load(
    config: &Config,
    roots: &[PathBuf],
    options: &ScanOptions,
    cancel: &Cancel,
    tracker: &Tracker,
    emit: &(dyn Fn(Loaded) + Sync),
) -> Result<(), String> {
    let config = &options.apply(config);
    let scans_artifacts = options.artifacts;
    let runs_usage_pass = options.usage || options.big;
    let pin_search = scans_artifacts && options.toolchains && config.toolchains.pins;
    let include_dev_caches = options.scans_developer_caches(config);
    let started = Instant::now();
    let artifact_scan = if scans_artifacts {
        Some(
            repos::start_scan(config, roots, cancel.clone(), None, pin_search)
                .map_err(|error| error.to_string())?,
        )
    } else {
        None
    };
    tracker.update_now(|activity| {
        for step in Step::ALL {
            if step.enabled(options) && !matches!(step, Step::Repos) {
                activity.begin(step, None);
            }
        }
    });
    let finished = AtomicBool::new(false);
    let result = thread::scope(|scope| {
        let ticker = spawn_part(scope, "pulse", || {
            while !finished.load(Ordering::Relaxed) {
                thread::park_timeout(Duration::from_millis(100));
                tracker.flush();
            }
        });
        spawn_part(scope, "history", || {
            let history = HistoryView::load();
            tracker.update_now(|activity| {
                activity.finish(
                    Step::History,
                    started.elapsed(),
                    match &history {
                        Ok(view) => plural(view.delete_runs().count(), "cleanup"),
                        Err(_) => "Cannot read it".to_owned(),
                    },
                );
            });
            emit(Loaded::History(history));
        });
        if options.docker {
            spawn_part(scope, "docker", || {
                let listing = docker::list(
                    &config.docker.engines,
                    config.docker.timeout(),
                    config.docker.recent_hours,
                );
                tracker.update_now(|activity| {
                    activity.finish(
                        Step::Docker,
                        started.elapsed(),
                        plural(listing.items.len(), "object"),
                    );
                });
                emit(Loaded::Docker {
                    entries: docker::entries(listing.items),
                    issues: listing.issues,
                });
            });
        }
        if options.caches {
            spawn_part(scope, "caches", || {
                let caches = measure_caches(config, include_dev_caches, cancel, tracker);
                let bytes = caches.iter().map(|(_, c)| c.usage.allocated).sum();
                tracker.update_now(|activity| {
                    activity.finish(
                        Step::Caches,
                        started.elapsed(),
                        format!("{}, {}", plural(caches.len(), "cache"), theme::bytes(bytes)),
                    );
                });
                emit(Loaded::Caches(caches));
            });
        }
        if options.trash {
            spawn_part(scope, "trash", || {
                let (entries, issues) = measure_trash(config, cancel);
                let items = entries.iter().map(|(folder, _)| folder.items).sum();
                let bytes = entries.iter().map(|(_, c)| c.usage.allocated).sum();
                tracker.update_now(|activity| {
                    activity.finish(
                        Step::Trash,
                        started.elapsed(),
                        format!("{}, {}", plural(items, "item"), theme::bytes(bytes)),
                    );
                });
                emit(Loaded::Trash { entries, issues });
            });
        }
        if options.system {
            spawn_part(scope, "system", || {
                let listing = system::for_user(&config.system);
                let entries = system::entries(listing.items);
                let bytes = entries.iter().map(|(_, c)| c.usage.allocated).sum();
                tracker.update_now(|activity| {
                    activity.finish(
                        Step::System,
                        started.elapsed(),
                        format!("{}, {}", plural(entries.len(), "item"), theme::bytes(bytes)),
                    );
                });
                emit(Loaded::System {
                    entries,
                    issues: listing.issues,
                });
            });
        }
        let usage_pass = runs_usage_pass.then(|| {
            spawn_part(scope, "usage", move || {
                let usage_opts = if options.usage {
                    UsageOptions {
                        one_file_system: config.scan.one_file_system,
                        ..UsageOptions::default()
                    }
                } else {
                    UsageOptions {
                        max_depth: config.scan.max_depth.unwrap_or(6),
                        max_children: 32,
                        min_bytes: config.big.min_size.0.min(1_000_000),
                        one_file_system: config.scan.one_file_system,
                    }
                };
                let mut report = usage::measure_report(
                    roots,
                    config,
                    &MeasureConfig {
                        usage: usage_opts,
                        collect_large_files: options.big,
                        collect_large_folders: options.big,
                        large_min_size: config.big.min_size.0,
                        large_limit: config.big.limit,
                    },
                    cancel,
                    |dirs, bytes| {
                        tracker.update(|activity| activity.measured(Step::Usage, dirs, bytes));
                    },
                );
                let issues = if scans_artifacts {
                    Vec::new()
                } else {
                    report.tree.issues.clone()
                };
                let diagnostics = report.diagnostics.clone();
                emit(Loaded::Diagnostics(diagnostics.clone()));
                if options.usage {
                    tracker.update_now(|activity| {
                        activity.finish(
                            Step::Usage,
                            started.elapsed(),
                            format!(
                                "{} in {} folders",
                                theme::bytes(report.tree.total_allocated),
                                grouped(report.tree.total_dirs)
                            ),
                        );
                    });
                    emit(Loaded::Usage(Some(report.tree)));
                }
                (
                    std::mem::take(&mut report.large_files),
                    std::mem::take(&mut report.large_folders),
                    issues,
                    diagnostics,
                )
            })
        });
        let downloads = (options.big && config.big.downloads)
            .then(|| spawn_part(scope, "downloads", || old_downloads(config)));
        let toolchains = options.toolchains.then(|| {
            spawn_part(scope, "toolchains", || {
                measure_toolchains(config, cancel, tracker)
            })
        });

        let (pins, artifact_roots) = if let Some((handle, walked)) = artifact_scan {
            let collected = walk(&handle, tracker, emit);
            let walked = walked.recv();
            if cancel.is_cancelled() {
                finished.store(true, Ordering::Relaxed);
                ticker.thread().unpark();
                return Err(CANCELLED.to_owned());
            }
            let Ok(walked) = walked else {
                finished.store(true, Ordering::Relaxed);
                ticker.thread().unpark();
                return Err("the scan stopped before finishing".to_owned());
            };
            let (pins, found_repos) = (walked.pins, walked.repositories);
            let (issues, summary, found, artifact_bytes, artifact_roots) = collected;
            let dirs = summary.progress.dirs;
            emit(Loaded::ArtifactsDone {
                issues,
                summary,
                disks: disks(roots),
            });
            tracker.update_now(|activity| {
                activity.finish(
                    Step::Folders,
                    started.elapsed(),
                    format!(
                        "{} found, {} in {} folders",
                        plural(found, "item"),
                        theme::bytes(artifact_bytes),
                        grouped(dirs)
                    ),
                );
                if options.repos {
                    activity.begin(Step::Repos, Some(found_repos.len()));
                }
            });

            if options.repos {
                spawn_part(scope, "repos", move || {
                    let checked = found_repos.len();
                    let inspected =
                        repos::inspect_all_collecting(found_repos, &config.git, cancel, |root| {
                            tracker.update(|activity| activity.advance(Step::Repos, root));
                        });
                    let failed = inspected.issues.len();
                    let repos = inspected.repositories;
                    tracker.update_now(|activity| {
                        activity.finish(
                            Step::Repos,
                            started.elapsed(),
                            if failed == 0 {
                                format!(
                                    "{} of {} worth cleaning",
                                    repos.len(),
                                    plural(checked, "repository")
                                )
                            } else {
                                format!(
                                    "{} of {} worth cleaning, {failed} could not be read",
                                    repos.len(),
                                    plural(checked, "repository")
                                )
                            },
                        );
                    });
                    emit(Loaded::Repos(repos));
                });
            }
            (pins, artifact_roots)
        } else {
            (None, Vec::new())
        };

        let usage_result = usage_pass.and_then(|handle| handle.join().ok());
        if cancel.is_cancelled() {
            finished.store(true, Ordering::Relaxed);
            ticker.thread().unpark();
            return Err(CANCELLED.to_owned());
        }

        if options.big {
            let (mut large, mut folders) = usage_result
                .as_ref()
                .map(|(files, folders, _, _)| (files.clone(), folders.clone()))
                .unwrap_or_default();
            if !artifact_roots.is_empty() {
                large.retain(|item| !artifact_roots.iter().any(|art| item.path.starts_with(art)));
                folders.retain(|folder| {
                    !artifact_roots
                        .iter()
                        .any(|art| folder.path.starts_with(art))
                });
            }
            let old = downloads
                .and_then(|downloads| downloads.join().ok())
                .unwrap_or_default();
            let big = big::candidates_with_folders(large, old, folders);
            let bytes = big.iter().map(|c| c.usage.allocated).sum();
            tracker.update_now(|activity| {
                activity.finish(
                    Step::Big,
                    started.elapsed(),
                    format!("{}, {}", plural(big.len(), "item"), theme::bytes(bytes)),
                );
            });
            emit(Loaded::Big(big));
        }

        if !scans_artifacts {
            let (issues, summary) = match usage_result {
                Some((_, _, issues, diag)) => (
                    issues,
                    Summary {
                        progress: Progress {
                            dirs: diag.dirs_visited,
                            files: diag.files_visited,
                            ..Progress::default()
                        },
                        duration: diag.elapsed,
                        cancelled: cancel.is_cancelled(),
                    },
                ),
                None => (
                    Vec::new(),
                    Summary {
                        progress: Progress::default(),
                        duration: started.elapsed(),
                        cancelled: cancel.is_cancelled(),
                    },
                ),
            };
            emit(Loaded::ArtifactsDone {
                issues,
                summary,
                disks: disks(roots),
            });
        }

        if let Some(measured) = toolchains {
            let mut toolchains = measured.join().unwrap_or_default();
            if let Some(pins) = &pins {
                toolchains::apply_pins_measured(&mut toolchains, &pins.pins);
            }
            let bytes = toolchains.iter().map(|(_, c)| c.usage.allocated).sum();
            tracker.update_now(|activity| {
                activity.finish(
                    Step::Toolchains,
                    started.elapsed(),
                    format!(
                        "{}, {}",
                        plural(toolchains.len(), "version"),
                        theme::bytes(bytes)
                    ),
                );
            });
            emit(Loaded::Toolchains(toolchains));
        }
        finished.store(true, Ordering::Relaxed);
        ticker.thread().unpark();
        Ok(())
    });
    if cancel.is_cancelled() {
        return Err(CANCELLED.to_owned());
    }
    result
}

fn spawn_part<'scope, T: Send + 'scope>(
    scope: &'scope thread::Scope<'scope, '_>,
    name: &str,
    work: impl FnOnce() -> T + Send + 'scope,
) -> thread::ScopedJoinHandle<'scope, T> {
    thread::Builder::new()
        .name(format!("kuizer-gui-{name}"))
        .spawn_scoped(scope, work)
        .expect("spawn scan part thread")
}

#[derive(Default)]
struct Streamed {
    batch: Vec<Candidate>,
    artifact_roots: Vec<PathBuf>,
    found: u64,
    bytes: u64,
    total_found: usize,
    total_bytes: u64,
    largest: Vec<Found>,
}

fn walk(
    handle: &scan::Scan,
    tracker: &Tracker,
    emit: &(dyn Fn(Loaded) + Sync),
) -> (Vec<Issue>, Summary, usize, u64, Vec<PathBuf>) {
    let streamed = RefCell::new(Streamed::default());
    let (issues, summary) = scan::collect_streaming(
        handle,
        |progress| {
            let (found, bytes, batch) = {
                let mut streamed = streamed.borrow_mut();
                let (found, bytes) = (streamed.found, streamed.bytes);
                streamed.found = 0;
                streamed.bytes = 0;
                let batch =
                    (!streamed.batch.is_empty()).then(|| std::mem::take(&mut streamed.batch));
                (found, bytes, batch)
            };
            tracker.update(|activity| {
                activity.walked = progress;
                activity.touch(Step::Folders, handle.current());
                activity.merge(found, bytes, &streamed.borrow().largest);
            });
            if let Some(batch) = batch {
                emit(Loaded::Found(batch));
            }
        },
        |candidate| {
            let batch = {
                let mut guard = streamed.borrow_mut();
                let streamed = &mut *guard;
                let bytes = candidate.usage.allocated;
                streamed.artifact_roots.push(candidate.path.clone());
                streamed.batch.push(candidate);
                streamed.found += 1;
                streamed.bytes += bytes;
                streamed.total_found += 1;
                streamed.total_bytes += bytes;
                let candidate = streamed.batch.last().expect("just added");
                if activity::beats(&streamed.largest, bytes) {
                    activity::keep(
                        &mut streamed.largest,
                        Found {
                            path: candidate.path.clone(),
                            name: candidate.rule.name.clone(),
                            bytes,
                        },
                    );
                }
                (streamed.batch.len() >= 256).then(|| std::mem::take(&mut streamed.batch))
            };
            if let Some(batch) = batch {
                emit(Loaded::Found(batch));
            }
        },
    );
    let mut streamed = streamed.into_inner();
    if !streamed.batch.is_empty() {
        emit(Loaded::Found(std::mem::take(&mut streamed.batch)));
    }
    (
        issues,
        summary,
        streamed.total_found,
        streamed.total_bytes,
        streamed.artifact_roots,
    )
}

fn disks(roots: &[PathBuf]) -> Vec<Disk> {
    scan::mount_spaces(roots, &[])
        .into_iter()
        .map(|space| Disk {
            available: Some(space.available),
            total: Some(space.total),
        })
        .collect()
}

fn measure_caches(
    config: &Config,
    include_developer: bool,
    cancel: &Cancel,
    tracker: &Tracker,
) -> Vec<(KnownCache, Candidate)> {
    let found: Vec<KnownCache> = Locations::for_user()
        .map(|locations| {
            caches::find_excluding_with_developer(
                &locations,
                &Protected::for_user(),
                &config.catalog,
                &config.usable_excludes(),
                include_developer,
            )
        })
        .unwrap_or_default();
    tracker.update_now(|activity| activity.begin(Step::Caches, Some(found.len())));
    caches::measure_threaded(found, cancel, scan::size_threads(config), |candidate| {
        tracker.update(|activity| {
            activity.advance(Step::Caches, &candidate.path);
            if candidate.usage.entries > 0 {
                activity.record(
                    &candidate.path,
                    &candidate.rule.name,
                    candidate.usage.allocated,
                );
            }
        });
    })
}

fn measure_trash(
    config: &Config,
    cancel: &Cancel,
) -> (Vec<(trashcan::Folder, Candidate)>, Vec<Issue>) {
    let Some((path, layout)) = trashcan::home_trash() else {
        return (Vec::new(), Vec::new());
    };
    match trashcan::inspect(&path, layout) {
        Ok(Some(folder)) if !excluded(&config.usable_excludes(), &folder.path) => {
            (trashcan::entries(vec![folder], cancel), Vec::new())
        }
        Ok(_) => (Vec::new(), Vec::new()),
        Err(issue) => (Vec::new(), vec![issue]),
    }
}

fn old_downloads(config: &Config) -> Vec<LargeFile> {
    let Some(dir) = big::downloads_dir().filter(|dir| dir.is_dir()) else {
        return Vec::new();
    };
    let mut old = big::old_downloads(
        &dir,
        config.big.downloads_age.0,
        config.big.downloads_min_size.0,
        SystemTime::now(),
        &Protected::for_user(),
    );
    let excludes = config.usable_excludes();
    old.retain(|item| !excluded(&excludes, &item.path));
    old
}

fn excluded(excludes: &Excludes, path: &Path) -> bool {
    path.ancestors().any(|dir| excludes.path(dir))
}

fn measure_toolchains(
    config: &Config,
    cancel: &Cancel,
    tracker: &Tracker,
) -> Vec<(Toolchain, Candidate)> {
    let found: Vec<Toolchain> = toolchains::Locations::for_user()
        .map(|locations| {
            toolchains::find_excluding(
                &locations,
                &config.toolchains.tools,
                &config.usable_excludes(),
            )
        })
        .unwrap_or_default();
    tracker.update_now(|activity| activity.begin(Step::Toolchains, Some(found.len())));
    toolchains::measure_with_threads(found, cancel, scan::size_threads(config), |candidate| {
        tracker.update(|activity| {
            activity.advance(Step::Toolchains, &candidate.path);
            activity.record(
                &candidate.path,
                &candidate.rule.name,
                candidate.usage.allocated,
            );
        });
    })
}

/// @name find_duplicates
/// @description Finds duplicate files under the roots with the start screen's options laid
/// over the config, on request rather than as part of every scan. Groups are the same as a
/// scan that collects files during its walk would find. Setting `cancel` stops the walk and the
/// hashing within one file or one MiB of reading and returns no groups.
///
/// @example
/// let found = find_duplicates(&config, &roots, &options, &cancel, |stage| show(stage))?;
pub fn find_duplicates(
    config: &Config,
    roots: &[PathBuf],
    options: &ScanOptions,
    cancel: &Cancel,
    on_stage: impl FnMut(dupes::Stage),
) -> Result<Duplicates, String> {
    let config = options.apply(config);
    dupes::find_cancellable(
        &config,
        roots,
        Options::from_config(&config),
        cancel,
        on_stage,
    )
    .map_err(|error| error.to_string())
}

/// The rule name `UsageTree::candidate_for` gives the disk explorer's entries.
pub const EXPLORED: &str = "disk-usage";

/// @name explored
/// @description Builds the removal candidate for one disk explorer entry, or `None` when the
/// entry may not be removed: the explorer marks it protected, the protected paths refuse it,
/// or it does not lie strictly inside one of the scanned folders. The candidate keeps the
/// entry's current identity, so a folder swapped for another one before removal is refused.
///
/// @example
/// let candidate = explored(&node, &report.roots, &config.delete.protected, id)?;
pub fn explored(
    node: &kuizer::usage::UsageNode,
    roots: &[PathBuf],
    protected: &[PathBuf],
    id: u64,
) -> Option<(Candidate, PathBuf)> {
    if node.protected
        || Protected::protects_system_path(&node.path)
        || Protected::for_user()
            .with_paths(protected)
            .refuses(&node.path)
    {
        return None;
    }
    let parent = node.path.parent()?;
    if !roots.iter().any(|root| parent.starts_with(root)) {
        return None;
    }
    Some((UsageTree::candidate_for(node, id), parent.to_path_buf()))
}

/// @name refreshed
/// @description Measures disk explorer entries again right before their removal. The large
/// file remover refuses an entry whose size or newest change differs from what was listed, and
/// the explorer's totals come from a measurement that may be minutes old.
///
/// @example
/// let batches = batches.into_iter().map(refreshed).collect();
pub fn refreshed(mut batch: Batch) -> Batch {
    for candidate in &mut batch.candidates {
        if candidate.rule.name == big::LARGE_FOLDER_RULE {
            big::refresh_folder(candidate);
            continue;
        }
        if candidate.rule.name != EXPLORED {
            continue;
        }
        let Ok(metadata) = std::fs::symlink_metadata(&candidate.path) else {
            continue;
        };
        if metadata.is_dir() {
            let measured = scan::measure(&candidate.path, &Cancel::new());
            candidate.usage.apparent = measured.usage.apparent;
            candidate.newest = measured.newest;
        } else {
            candidate.usage.apparent = metadata.len();
            candidate.newest = metadata.modified().ok();
        }
    }
    batch
}

pub struct Outcome {
    pub removals: Vec<(Source, Removal)>,
    pub mode: DeleteMode,
    pub history_error: Option<String>,
}

impl Outcome {
    pub fn removed(&self) -> impl Iterator<Item = &(Source, Removal)> {
        self.removals
            .iter()
            .filter(|(_, removal)| removal.status == Status::Removed)
    }

    pub fn trashed(&self, source: Source) -> bool {
        source.trashed(self.mode)
    }

    pub fn failed(&self) -> impl Iterator<Item = &(Source, Removal)> {
        self.removals
            .iter()
            .filter(|(_, removal)| removal.status == Status::Failed)
    }
}

/// @name clean
/// @description Removes every selected item through the shared executor the way `delete.mode`
/// asks: for good, or with artifacts and caches moved to the trash. Toolchains and Docker objects
/// are always deleted for good. System package caches run their package tool's own cleanup
/// through a second executor, which asks for administrator rights with `pkexec` only, never
/// `sudo`, because the window has no terminal. Each batch is checked against its own guard right
/// before acting, exactly like the CLI. Trashed items are recorded as their own run in the
/// history file, so a restore of that run never lists items that cannot come back.
///
/// The runs the clean recorded are added to `history`, the history and trash snapshot on screen,
/// in memory, and the view it returns is built here, off the UI thread. Without a history on
/// screen, or when the history file could not be written, the history is read again instead.
///
/// @example
/// let (outcome, view) = clean(batches, &config.delete, &config.docker.engines, &config.system, Some((history, trash)));
pub fn clean(
    batches: Vec<Batch>,
    delete: &DeleteConfig,
    engines: &[String],
    system_config: &system::SystemConfig,
    history: Option<(std::sync::Arc<History>, TrashSnapshot)>,
) -> (Outcome, Result<HistoryView, String>) {
    let (system_batches, batches): (Vec<Batch>, Vec<Batch>) = batches
        .into_iter()
        .partition(|batch| batch.source == Source::System);
    let mut roots: Vec<PathBuf> = batches
        .iter()
        .flat_map(|batch| batch.roots.iter().cloned())
        .collect();
    roots.sort();
    roots.dedup();
    let mode = delete.mode.into();
    let mut removals = Vec::new();
    let mut finished = Vec::new();
    if !batches.is_empty() {
        let executor = Executor::new(&roots, delete).with_engines(engines);
        removals.extend(executor.run(batches, mode, |_, _| {}).removals);
        finished.push(executor.finish());
    }
    if !system_batches.is_empty() {
        let system_config = system_config.clone();
        let tools = system::Tools::for_user();
        let session = system::Session::graphical_only();
        let remover: kuizer::delete::Remover = std::sync::Arc::new(move |_, candidate, mode| {
            system::remove_with(candidate, mode, &system_config, &tools, &session)
        });
        let executor = Executor::new(&[], delete).with_remover(remover);
        removals.extend(executor.run(system_batches, mode, |_, _| {}).removals);
        finished.push(executor.finish());
    }
    let finished: Result<Vec<history::Run>, history::HistoryError> =
        finished.into_iter().try_fold(Vec::new(), |mut all, runs| {
            all.extend(runs?);
            Ok(all)
        });
    let (view, history_error) = match (finished, history) {
        (Ok(runs), Some((history, mut trash))) => {
            let mut history = std::sync::Arc::unwrap_or_clone(history);
            for run in runs {
                trash.record(&mut history, run);
            }
            (Ok(HistoryView::new(history, trash)), None)
        }
        (Ok(_), None) => (HistoryView::load(), None),
        (Err(error), _) => (HistoryView::load(), Some(error.to_string())),
    };
    let outcome = Outcome {
        removals,
        mode: delete.mode,
        history_error,
    };
    (outcome, view)
}

#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Restored {
    pub items: usize,
    pub bytes: u64,
    pub problems: Vec<(PathBuf, String)>,
    pub history_error: Option<String>,
}

/// @name restore
/// @description Puts one cleanup run back from the trash, exactly like `kuizer restore s4`, for the
/// items that are still in the trash and not restored yet, and records the restore. Lists the
/// trash once and updates `history` in memory, so the view it returns is current without reading
/// the history file again. The view is `None` when the run or the trash cannot be found.
///
/// @example
/// let (restored, view) = restore(Arc::clone(&view.history), 4);
pub fn restore(
    history: std::sync::Arc<History>,
    session: u64,
) -> (Result<Restored, String>, Option<HistoryView>) {
    let id = format!("s{session}");
    let Some(run) = history.runs.iter().position(|run| run.id == session) else {
        return (Err(format!("the history has no cleanup {id}")), None);
    };
    let mut listing = match TrashView::list() {
        Ok(listing) => listing,
        Err(error) => return (Err(error.to_string()), None),
    };
    let mut history = std::sync::Arc::unwrap_or_clone(history);
    let trash = listing.snapshot(&history);
    let targets = history::restorable(&history, &trash, run);
    if targets.is_empty() {
        let view = HistoryView::new(history, trash);
        return (
            Err(format!("nothing from {id} is still in the trash")),
            Some(view),
        );
    }
    let restore = history::restore::restore_listed(&history, &targets, false, &mut listing);
    let restored = Restored {
        items: restore.count(RestoreStatus::Restored),
        bytes: restore.bytes(RestoreStatus::Restored),
        problems: restore
            .outcomes
            .iter()
            .filter(|outcome| outcome.status != RestoreStatus::Restored)
            .map(|outcome| {
                (
                    outcome.path.clone(),
                    outcome.reason.clone().unwrap_or_default(),
                )
            })
            .collect(),
        history_error: restore
            .record_into(&mut history)
            .err()
            .map(|error| error.to_string()),
    };
    let trash = listing.snapshot(&history);
    (Ok(restored), Some(HistoryView::new(history, trash)))
}

#[cfg(test)]
mod tests {
    use std::sync::Arc;

    use kuizer::detect::{Kind, RuleInfo, Safety};
    use kuizer::scan::Usage;

    use super::*;

    fn candidate(id: u64, path: &str, safety: Safety) -> Candidate {
        Candidate {
            id,
            path: PathBuf::from(path),
            kind: Kind::Dir,
            rule: Arc::new(RuleInfo {
                name: "node_modules".to_owned(),
                category: Category::Dependencies,
                safety,
                ecosystem: "node".to_owned(),
            }),
            project: None,
            usage: Usage {
                allocated: id * 10,
                ..Usage::default()
            },
            newest: None,
            identity: None,
            project_last_active: None,
        }
    }

    #[test]
    fn duplicates_on_request_match_the_ones_a_scan_walk_collects() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path().join("photos");
        for (folder, size) in [
            ("a", 8192),
            ("b", 8192),
            ("c", 9000),
            ("d", 9000),
            ("e", 5000),
        ] {
            std::fs::create_dir_all(root.join(folder)).unwrap();
            std::fs::write(root.join(folder).join("same.bin"), vec![b'z'; size]).unwrap();
        }
        std::fs::create_dir_all(root.join("site/node_modules")).unwrap();
        std::fs::write(root.join("site/package.json"), "{}").unwrap();
        std::fs::write(root.join("site/node_modules/same.bin"), vec![b'z'; 8192]).unwrap();
        let config = Config::default();
        let roots = scan::normalize_roots(&[root]);
        let options = ScanOptions::from_config(&config);
        let groups = |found: Duplicates| -> Vec<Vec<PathBuf>> {
            found
                .groups
                .into_iter()
                .map(|group| {
                    group
                        .members
                        .into_iter()
                        .map(|member| member.path)
                        .collect()
                })
                .collect()
        };

        let lazy =
            groups(find_duplicates(&config, &roots, &options, &Cancel::new(), |_| {}).unwrap());
        let applied = options.apply(&config);
        let duplicate_options = Options::from_config(&applied);
        let (handle, walked) = repos::start_scan(
            &applied,
            &roots,
            Cancel::new(),
            Some(duplicate_options),
            false,
        )
        .unwrap();
        scan::collect(&handle, |_| {});
        let files = walked.recv().unwrap().files.unwrap();
        let walked = groups(dupes::group(files, duplicate_options, |_| {}));
        assert_eq!(lazy.len(), 2);
        assert_eq!(lazy, walked);
    }

    #[test]
    fn streamed_candidates_keep_arrival_order_until_the_scan_finishes() {
        let options = ScanOptions::from_config(&Config::default());
        let mut report = Report::empty(&[], &options);
        report.apply(Loaded::Found(vec![
            candidate(1, "/p/small", Safety::Safe),
            candidate(3, "/p/large", Safety::Safe),
        ]));
        assert_eq!(
            report
                .candidates
                .iter()
                .map(|candidate| candidate.id)
                .collect::<Vec<_>>(),
            [1, 3]
        );

        report.apply(Loaded::ArtifactsDone {
            issues: Vec::new(),
            summary: Summary {
                progress: Progress::default(),
                duration: Duration::ZERO,
                cancelled: false,
            },
            disks: Vec::new(),
        });

        assert_eq!(
            report
                .candidates
                .iter()
                .map(|candidate| candidate.id)
                .collect::<Vec<_>>(),
            [3, 1]
        );
    }

    #[test]
    fn short_path_strips_the_scan_root() {
        let roots = [PathBuf::from("/p")];
        assert_eq!(short_path(Path::new("/p/a/dist"), &roots), "a/dist");
        assert_eq!(short_path(Path::new("/q/b"), &roots), "/q/b");
        assert_eq!(short_path(Path::new("/p"), &roots), "/p");
    }

    #[test]
    fn dropped_paths_leave_every_list() {
        let member = |path: &str| dupes::Member {
            path: PathBuf::from(path),
            links: Vec::new(),
            modified: None,
        };
        let group = |paths: &[&str]| dupes::Group {
            size: 10,
            allocated: 10,
            hash: String::new(),
            verified: true,
            members: paths.iter().map(|path| member(path)).collect(),
        };
        let mut report = Report {
            roots: vec![PathBuf::from("/p")],
            options: ScanOptions::from_config(&Config::default()),
            candidates: vec![
                candidate(1, "/p/a/node_modules", Safety::Safe),
                candidate(2, "/p/b/node_modules", Safety::Safe),
            ],
            issues: vec![Issue {
                path: PathBuf::from("/p/a/node_modules/locked"),
                kind: scan::IssueKind::PermissionDenied,
                message: String::new(),
            }],
            summary: Summary {
                progress: Progress::default(),
                duration: std::time::Duration::ZERO,
                cancelled: false,
            },
            caches: Vec::new(),
            toolchains: Vec::new(),
            docker: Vec::new(),
            docker_issues: Vec::new(),
            repos: Vec::new(),
            trash: Vec::new(),
            trash_issues: Vec::new(),
            system: Vec::new(),
            system_issues: Vec::new(),
            big: Vec::new(),
            usage: None,
            walk_diagnostics: None,
            duplicates: Some(Duplicates {
                groups: vec![
                    group(&["/p/a/node_modules/x", "/p/b/x"]),
                    group(&["/p/a/node_modules/y", "/p/b/y", "/p/c/y"]),
                ],
                issues: Vec::new(),
                files: 5,
                duration: std::time::Duration::ZERO,
            }),
            history: Err(String::new()),
            disks: Vec::new(),
            scanned: SystemTime::now(),
        };
        report.drop_paths(&[PathBuf::from("/p/a/node_modules")]);
        assert_eq!(report.candidates.len(), 1);
        assert_eq!(report.candidates[0].id, 2);
        assert!(report.issues.is_empty());
        let groups = &report.duplicates.as_ref().unwrap().groups;
        assert_eq!(groups.len(), 1);
        assert_eq!(groups[0].members.len(), 2);
    }

    #[test]
    fn report_groups_by_category_and_project() {
        let mut first = candidate(1, "/p/a/node_modules", Safety::Safe);
        first.project = Some(PathBuf::from("/p/a"));
        let mut second = candidate(4, "/p/a/dist", Safety::Review);
        second.project = Some(PathBuf::from("/p/a"));
        let report = Report {
            roots: vec![PathBuf::from("/p")],
            options: ScanOptions::from_config(&Config::default()),
            candidates: vec![first, second],
            issues: Vec::new(),
            summary: Summary {
                progress: Progress::default(),
                duration: std::time::Duration::ZERO,
                cancelled: false,
            },
            caches: Vec::new(),
            toolchains: Vec::new(),
            docker: Vec::new(),
            docker_issues: Vec::new(),
            repos: Vec::new(),
            trash: Vec::new(),
            trash_issues: Vec::new(),
            system: Vec::new(),
            system_issues: Vec::new(),
            big: Vec::new(),
            usage: None,
            walk_diagnostics: None,
            duplicates: None,
            history: Err(String::new()),
            disks: Vec::new(),
            scanned: SystemTime::now(),
        };
        assert_eq!(report.total(None), 50);
        assert_eq!(report.total(Some(Safety::Review)), 40);
        let projects = report.by_project();
        assert_eq!(projects.len(), 1);
        assert_eq!(projects[0].bytes, 50);
        assert_eq!(projects[0].count, 2);
        let categories = report.by_category();
        assert_eq!(categories.len(), 1);
        assert_eq!(categories[0].count, 2);
    }

    #[test]
    #[ignore = "runs inside isolated_deletion_cases"]
    fn the_trash_and_large_files_load_without_excluded_or_deleted_paths_inside() {
        let Some(base) = std::env::var_os("KUIZER_GUI_TEST_BASE").map(PathBuf::from) else {
            return;
        };
        let home = base.join("home");
        let root = base.join("sources");
        let _ = std::fs::remove_dir_all(&home);
        let _ = std::fs::remove_dir_all(&root);
        let trash_files = home.join(".local/share/Trash/files");
        std::fs::create_dir_all(&trash_files).unwrap();
        std::fs::write(trash_files.join("old.txt"), b"gone").unwrap();
        std::fs::create_dir_all(home.join(".config")).unwrap();
        std::fs::write(
            home.join(".config/user-dirs.dirs"),
            "XDG_DOWNLOAD_DIR=\"$HOME/Downloads\"\n",
        )
        .unwrap();
        let downloads = home.join("Downloads");
        std::fs::create_dir_all(&downloads).unwrap();
        let setup = downloads.join("setup.iso");
        std::fs::write(&setup, vec![1u8; 70_000]).unwrap();
        std::fs::File::options()
            .write(true)
            .open(&setup)
            .unwrap()
            .set_modified(SystemTime::now() - Duration::from_secs(200 * 86_400))
            .unwrap();
        std::fs::create_dir_all(&root).unwrap();
        let video = root.join("video.mkv");
        std::fs::write(&video, vec![2u8; 80_000]).unwrap();
        std::fs::write(root.join("notes.txt"), b"small").unwrap();

        let mut config = Config::default();
        config.big.min_size = kuizer::units::ByteSize(65_536);
        config.big.downloads_min_size = kuizer::units::ByteSize(65_536);
        let options = ScanOptions {
            caches: false,
            toolchains: false,
            docker: false,
            repos: false,
            system: false,
            ..ScanOptions::from_config(&config)
        };
        let roots = scan::normalize_roots(&[root]);
        let parts = std::sync::Mutex::new(Vec::new());
        load(
            &config,
            &roots,
            &options,
            &Cancel::new(),
            &Tracker::new(|_| {}),
            &|loaded| {
                if matches!(loaded, Loaded::Trash { .. } | Loaded::Big(_)) {
                    parts.lock().unwrap().push(loaded);
                }
            },
        )
        .unwrap();
        let parts = parts.into_inner().unwrap();
        assert_eq!(parts.len(), 2);

        for mut loaded in parts {
            match &loaded {
                Loaded::Trash { entries, .. } => {
                    assert_eq!(entries.len(), 1);
                    assert_eq!(entries[0].0.items, 1);
                    let trash = entries[0].1.path.clone();
                    let gone = HashMap::from([(Source::Trash, HashSet::from([trash]))]);
                    loaded.without(&[], &gone);
                    assert!(matches!(&loaded, Loaded::Trash { entries, .. } if entries.is_empty()));
                }
                Loaded::Big(big) => {
                    let mut names: Vec<&str> = big
                        .iter()
                        .map(|candidate| candidate.rule.name.as_str())
                        .collect();
                    names.sort_unstable();
                    assert_eq!(names, ["large-file", "old-download"]);
                    loaded.without(std::slice::from_ref(&downloads), &HashMap::new());
                    let Loaded::Big(big) = &loaded else {
                        unreachable!()
                    };
                    assert_eq!(big.len(), 1);
                    assert!(big[0].path.ends_with("video.mkv"));
                    let gone = HashMap::from([(Source::Big, HashSet::from([big[0].path.clone()]))]);
                    loaded.without(&[], &gone);
                    assert!(matches!(&loaded, Loaded::Big(big) if big.is_empty()));
                }
                _ => unreachable!(),
            }
        }
    }
}