kuizer-gui 0.3.1

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
//! Figures the views show, computed once when the report or the selection changes instead of on
//! every frame: report totals and charts, an id lookup into the report, and running selection
//! totals.

use std::cell::OnceCell;
use std::collections::{HashMap, HashSet};
use std::path::PathBuf;
use std::time::SystemTime;

use kuizer::caches::KnownCache;
use kuizer::catalog::Group;
use kuizer::detect::{Category, Safety};
use kuizer::history::{self, History, TrashSnapshot};
use kuizer::scan::Candidate;

use crate::model::{Bucket, Report, Source, TrashState};

/// One selectable item: the list it is in and its candidate id.
pub type Key = (Source, u64);

const PROJECTS: usize = 8;

fn slot(source: Source) -> usize {
    match source {
        Source::Artifact => 0,
        Source::Cache => 1,
        Source::Toolchain => 2,
        Source::Docker => 3,
        Source::Trash => 4,
        Source::Big => 5,
        Source::System => 6,
    }
}

#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
pub struct Tally {
    pub count: usize,
    pub bytes: u64,
}

impl Tally {
    fn add(&mut self, bytes: u64) {
        self.count += 1;
        self.bytes += bytes;
    }

    fn sub(&mut self, bytes: u64) {
        self.count -= 1;
        self.bytes -= bytes;
    }

    fn plus(self, other: Self) -> Self {
        Self {
            count: self.count + other.count,
            bytes: self.bytes + other.bytes,
        }
    }
}

/// Items and bytes of a group of candidates, in all and split by safety.
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
pub struct Totals {
    pub all: Tally,
    pub safe: Tally,
    pub review: Tally,
}

impl Totals {
    fn add(&mut self, bytes: u64, safety: Safety) {
        self.all.add(bytes);
        match safety {
            Safety::Safe => self.safe.add(bytes),
            Safety::Review => self.review.add(bytes),
        }
    }

    fn sub(&mut self, bytes: u64, safety: Safety) {
        self.all.sub(bytes);
        match safety {
            Safety::Safe => self.safe.sub(bytes),
            Safety::Review => self.review.sub(bytes),
        }
    }

    fn of<'a>(candidates: impl Iterator<Item = &'a Candidate>) -> Self {
        let mut totals = Self::default();
        for candidate in candidates {
            totals.add(candidate.usage.allocated, candidate.rule.safety);
        }
        totals
    }

    fn plus(self, other: Self) -> Self {
        Self {
            all: self.all.plus(other.all),
            safe: self.safe.plus(other.safe),
            review: self.review.plus(other.review),
        }
    }
}

/// Totals of a set of selected items, per list.
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
pub struct SelectionStats {
    sources: [Totals; Source::ALL.len()],
}

impl SelectionStats {
    /// @name SelectionStats::of
    /// @description Counts a list of items from scratch.
    ///
    /// @example
    /// let stats = SelectionStats::of(app.selected().into_iter());
    #[cfg(test)]
    pub fn of<'a>(items: impl Iterator<Item = (Source, &'a Candidate)>) -> Self {
        let mut stats = Self::default();
        for (source, candidate) in items {
            stats.sources[slot(source)].add(candidate.usage.allocated, candidate.rule.safety);
        }
        stats
    }

    pub fn source(&self, source: Source) -> Totals {
        self.sources[slot(source)]
    }

    pub fn total(&self) -> Totals {
        self.sources
            .iter()
            .fold(Totals::default(), |sum, totals| sum.plus(*totals))
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct Weight {
    bytes: u64,
    safety: Safety,
}

/// @name Selection
/// @description The selected items with running totals, so the summary bar and the views
/// read their figures without walking the report. Every change goes through a method that keeps
/// the totals in step.
///
/// @example
/// selection.insert((Source::Artifact, candidate.id), candidate);
/// let bytes = selection.stats().total().all.bytes;
#[derive(Debug, Default)]
pub struct Selection {
    keys: HashMap<Key, Weight>,
    stats: SelectionStats,
    generation: u64,
}

impl Selection {
    /// Keys carried over from an earlier report. They count for nothing until `reweigh` runs
    /// against the report they belong to.
    pub fn pending(keys: impl IntoIterator<Item = Key>) -> Self {
        let unweighed = Weight {
            bytes: 0,
            safety: Safety::Safe,
        };
        Self {
            keys: keys.into_iter().map(|key| (key, unweighed)).collect(),
            stats: SelectionStats::default(),
            generation: 0,
        }
    }

    pub fn stats(&self) -> SelectionStats {
        self.stats
    }

    /// Changes whenever the selection does, so views can cache what they derive from it.
    pub fn generation(&self) -> u64 {
        self.generation
    }

    pub fn contains(&self, key: &Key) -> bool {
        self.keys.contains_key(key)
    }

    #[cfg(test)]
    pub fn len(&self) -> usize {
        self.keys.len()
    }

    pub fn is_empty(&self) -> bool {
        self.keys.is_empty()
    }

    pub fn keys(&self) -> impl Iterator<Item = &Key> {
        self.keys.keys()
    }

    /// Adds an item, and says whether it was not selected before.
    pub fn insert(&mut self, key: Key, candidate: &Candidate) -> bool {
        if self.keys.contains_key(&key) {
            return false;
        }
        let weight = Weight {
            bytes: candidate.usage.allocated,
            safety: candidate.rule.safety,
        };
        self.stats.sources[slot(key.0)].add(weight.bytes, weight.safety);
        self.keys.insert(key, weight);
        self.generation += 1;
        true
    }

    /// Drops an item, and says whether it was selected.
    pub fn remove(&mut self, key: &Key) -> bool {
        let Some(weight) = self.keys.remove(key) else {
            return false;
        };
        self.stats.sources[slot(key.0)].sub(weight.bytes, weight.safety);
        self.generation += 1;
        true
    }

    pub fn clear(&mut self) {
        self.keys.clear();
        self.stats = SelectionStats::default();
        self.generation += 1;
    }

    /// @name Selection::reset
    /// @description Replaces the selection with `keys`, keeping only those `find` knows and
    /// weighing each by its current candidate. Used whenever the report changes.
    ///
    /// @example
    /// selection.reset(keys, |key| index.find(report, key));
    pub fn reset<'a>(
        &mut self,
        keys: impl IntoIterator<Item = Key>,
        find: impl Fn(Key) -> Option<&'a Candidate>,
    ) {
        self.clear();
        for key in keys {
            if let Some(candidate) = find(key) {
                self.insert(key, candidate);
            }
        }
    }

    /// Weighs the selection again against the report, forgetting items it no longer has.
    pub fn reweigh<'a>(&mut self, find: impl Fn(Key) -> Option<&'a Candidate>) {
        let keys: Vec<Key> = self.keys.keys().copied().collect();
        self.reset(keys, find);
    }
}

impl PartialEq<HashSet<Key>> for Selection {
    fn eq(&self, other: &HashSet<Key>) -> bool {
        self.keys.len() == other.len() && other.iter().all(|key| self.keys.contains_key(key))
    }
}

/// @name Index
/// @description Finds a candidate of the report by list and id without a linear search. Built
/// on first use after each report change; a stale entry falls back to a search, never to a
/// wrong item.
///
/// @example
/// let index = Index::default();
/// let candidate = index.find(&report, (Source::Cache, id));
#[derive(Debug, Default)]
pub struct Index(OnceCell<HashMap<Key, usize>>);

impl Index {
    fn map(&self, report: &Report) -> &HashMap<Key, usize> {
        self.0.get_or_init(|| {
            Source::ALL
                .into_iter()
                .flat_map(|source| {
                    report
                        .section(source)
                        .enumerate()
                        .map(move |(position, candidate)| ((source, candidate.id), position))
                })
                .collect()
        })
    }

    pub fn find<'a>(&self, report: &'a Report, key: Key) -> Option<&'a Candidate> {
        self.locate(report, key).map(|(_, candidate)| candidate)
    }

    /// Where an item sits in its list of the report, and the item.
    pub fn locate<'a>(&self, report: &'a Report, key: Key) -> Option<(usize, &'a Candidate)> {
        if let Some(&position) = self.map(report).get(&key)
            && let Some(candidate) = at(report, key.0, position).filter(|c| c.id == key.1)
        {
            return Some((position, candidate));
        }
        (0..count(report, key.0)).find_map(|position| {
            at(report, key.0, position)
                .filter(|candidate| candidate.id == key.1)
                .map(|candidate| (position, candidate))
        })
    }
}

fn count(report: &Report, source: Source) -> usize {
    match source {
        Source::Artifact => report.candidates.len(),
        Source::Cache => report.caches.len(),
        Source::Toolchain => report.toolchains.len(),
        Source::Docker => report.docker.len(),
        Source::Trash => report.trash.len(),
        Source::Big => report.big.len(),
        Source::System => report.system.len(),
    }
}

/// @name developer
/// @description Whether a cache belongs to Developer caches rather than App caches: the ones
/// package managers and build tools keep, as opposed to apps, browsers and the desktop.
///
/// @example
/// let developer = report.caches.iter().filter(|(cache, _)| stats::developer(cache)).count();
pub fn developer(cache: &KnownCache) -> bool {
    cache.group == Group::Developer
}

fn by_category(candidates: &[Candidate]) -> Vec<(Category, u64)> {
    let mut bytes: Vec<(Category, u64)> = Category::ALL.into_iter().map(|key| (key, 0)).collect();
    for candidate in candidates {
        if let Some(slot) = bytes
            .iter_mut()
            .find(|(key, _)| *key == candidate.rule.category)
        {
            slot.1 += candidate.usage.allocated;
        }
    }
    bytes.sort_by_key(|(_, bytes)| std::cmp::Reverse(*bytes));
    bytes
}

fn at(report: &Report, source: Source, position: usize) -> Option<&Candidate> {
    match source {
        Source::Artifact => report.candidates.get(position),
        Source::Cache => report.caches.get(position).map(|(_, candidate)| candidate),
        Source::Toolchain => report
            .toolchains
            .get(position)
            .map(|(_, candidate)| candidate),
        Source::Docker => report.docker.get(position).map(|(_, candidate)| candidate),
        Source::Trash => report.trash.get(position).map(|(_, candidate)| candidate),
        Source::Big => report.big.get(position),
        Source::System => report.system.get(position).map(|(_, candidate)| candidate),
    }
}

/// What the history tab shows about past cleanups.
#[derive(Debug, Default)]
pub struct HistoryStats {
    pub trash: Vec<TrashState>,
    pub freed: u64,
    pub in_trash: u64,
}

impl HistoryStats {
    pub fn of(history: &History, trash: &TrashSnapshot) -> Self {
        Self {
            trash: trash.states(history),
            freed: history::freed_bytes(history, trash),
            in_trash: trash.in_trash(history).bytes,
        }
    }
}

/// The overview charts, added up the first time the overview shows a report.
pub struct Charts {
    pub categories: Vec<Bucket<Category>>,
    pub projects: Vec<Bucket<PathBuf>>,
    pub ages: Vec<kuizer::stats::Bucket>,
    pub sizes: Vec<kuizer::stats::Bucket>,
    pub ecosystems: Vec<kuizer::stats::Bucket>,
    pub removed: Option<Vec<kuizer::stats::Bucket>>,
    pub wins: (Vec<Key>, u64),
}

/// The lists the biggest safe wins come from. Large files are personal files and always need
/// review, so they never count as a win.
const WIN_SOURCES: [Source; 4] = [
    Source::Trash,
    Source::Cache,
    Source::System,
    Source::Artifact,
];

/// @name biggest_wins
/// @description The largest safe items across the trash, every cache, system package caches
/// and project artifacts, largest first, capped at `cap`, with their total size.
///
/// @example
/// let (keys, bytes) = biggest_wins(&report, kuizer::stats::WINS);
pub fn biggest_wins(report: &Report, cap: usize) -> (Vec<Key>, u64) {
    let mut safe: Vec<(Source, &Candidate)> = WIN_SOURCES
        .into_iter()
        .flat_map(|source| {
            report
                .section(source)
                .filter(|candidate| {
                    candidate.rule.safety == Safety::Safe && candidate.usage.allocated > 0
                })
                .map(move |candidate| (source, candidate))
        })
        .collect();
    let largest = |a: &(Source, &Candidate), b: &(Source, &Candidate)| {
        b.1.usage
            .allocated
            .cmp(&a.1.usage.allocated)
            .then_with(|| a.1.path.cmp(&b.1.path))
    };
    if safe.len() > cap && cap > 0 {
        safe.select_nth_unstable_by(cap - 1, largest);
    }
    safe.truncate(cap);
    safe.sort_unstable_by(largest);
    let bytes = safe
        .iter()
        .map(|(_, candidate)| candidate.usage.allocated)
        .sum();
    (
        safe.into_iter()
            .map(|(source, candidate)| (source, candidate.id))
            .collect(),
        bytes,
    )
}

/// @name ReportStats
/// @description What the sidebar, the status line, the overview and the history tab add up from
/// the report. Totals are counted when the report changes and charts the first time a view asks
/// for them, so a streaming scan only pays for what is on screen. Trash states come with the
/// history view, which works them out on the history thread.
///
/// @example
/// let stats = ReportStats::new(&report);
/// let safe = stats.artifacts.safe.bytes;
#[derive(Default)]
pub struct ReportStats {
    pub artifacts: Totals,
    pub caches: Totals,
    pub app_caches: Totals,
    pub toolchains: Totals,
    pub docker: Totals,
    pub trash: Totals,
    pub system: Totals,
    pub big: Totals,
    /// Bytes of the project artifacts per category, largest first.
    pub categories: Vec<(Category, u64)>,
    charts: OnceCell<Charts>,
}

impl ReportStats {
    pub fn new(report: &Report) -> Self {
        Self {
            artifacts: Totals::of(report.section(Source::Artifact)),
            caches: Totals::of(
                report
                    .caches
                    .iter()
                    .filter(|(cache, _)| developer(cache))
                    .map(|(_, candidate)| candidate),
            ),
            app_caches: Totals::of(
                report
                    .caches
                    .iter()
                    .filter(|(cache, _)| !developer(cache))
                    .map(|(_, candidate)| candidate),
            ),
            toolchains: Totals::of(report.section(Source::Toolchain)),
            docker: Totals::of(report.section(Source::Docker)),
            trash: Totals::of(report.section(Source::Trash)),
            system: Totals::of(report.system.iter().map(|(_, candidate)| candidate)),
            big: Totals::of(report.section(Source::Big)),
            categories: by_category(&report.candidates),
            charts: OnceCell::new(),
        }
    }

    /// Everything the space bar and the stat cards count as removable.
    pub fn space(&self) -> u64 {
        self.artifacts.all.bytes
            + self.caches.all.bytes
            + self.app_caches.all.bytes
            + self.toolchains.all.bytes
            + self.docker.all.bytes
            + self.trash.all.bytes
            + self.system.all.bytes
            + self.big.all.bytes
    }

    pub fn charts(&self, report: &Report) -> &Charts {
        self.charts.get_or_init(|| {
            let mut projects = report.by_project();
            projects.truncate(PROJECTS);
            Charts {
                categories: report.by_category(),
                projects,
                ages: kuizer::stats::by_age(&report.candidates, SystemTime::now()),
                sizes: kuizer::stats::by_size(&report.candidates),
                ecosystems: kuizer::stats::by_ecosystem(&report.candidates),
                wins: biggest_wins(report, kuizer::stats::WINS),
                removed: report.history.as_ref().ok().map(|view| {
                    kuizer::stats::removed_by_month(&view.history, &kuizer::history::now(), 12)
                }),
            }
        })
    }
}

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

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

    use super::*;

    fn candidate(id: u64, bytes: u64, safety: Safety) -> Candidate {
        Candidate {
            id,
            path: PathBuf::from(format!("/p/{id}")),
            kind: Kind::Dir,
            rule: Arc::new(RuleInfo {
                name: "x".to_owned(),
                category: Category::ALL[0],
                safety,
                ecosystem: "x".to_owned(),
            }),
            project: None,
            usage: Usage {
                allocated: bytes,
                apparent: bytes,
                entries: 1,
                partial: false,
            },
            newest: None,
            identity: None,
            project_last_active: None,
        }
    }

    #[test]
    fn running_totals_match_a_recount() {
        let sources = [
            Source::Artifact,
            Source::Cache,
            Source::Toolchain,
            Source::Docker,
        ];
        let items: Vec<(Source, Candidate)> = (0..64)
            .map(|id| {
                let safety = if id % 3 == 0 {
                    Safety::Review
                } else {
                    Safety::Safe
                };
                (sources[id as usize % 4], candidate(id, id * 97 + 1, safety))
            })
            .collect();
        let mut selection = Selection::default();
        let mut seed: u64 = 0x2545_f491_4f6c_dd1d;
        for round in 0..2000 {
            seed ^= seed << 13;
            seed ^= seed >> 7;
            seed ^= seed << 17;
            let (source, candidate) = &items[(seed % items.len() as u64) as usize];
            let key = (*source, candidate.id);
            match seed % 7 {
                0..=2 => {
                    selection.insert(key, candidate);
                }
                3..=5 => {
                    selection.remove(&key);
                }
                _ if round % 50 == 0 => selection.clear(),
                _ => selection.reweigh(|key| {
                    items
                        .iter()
                        .find(|(source, candidate)| (*source, candidate.id) == key)
                        .filter(|_| key.1 % 5 != 0)
                        .map(|(_, candidate)| candidate)
                }),
            }
            let recount = SelectionStats::of(
                items
                    .iter()
                    .filter(|(source, candidate)| selection.contains(&(*source, candidate.id)))
                    .map(|(source, candidate)| (*source, candidate)),
            );
            assert_eq!(selection.stats(), recount, "round {round}");
        }
    }
}