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
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
use super::*;

impl Kuizer {
    pub(super) fn render_overview(&self, cx: &mut Context<Self>) -> AnyElement {
        let Some(report) = self.report() else {
            return div().into_any_element();
        };
        if self.list.map.shown {
            return self.render_map(cx);
        }
        if self.list.projects_view {
            return self.render_projects(cx);
        }
        let figures = &self.session.report_stats;
        let caches = figures.caches.all.bytes;
        let app_caches = figures.app_caches.all.bytes;
        let toolchains = figures.toolchains.all.bytes;
        let containers = figures.docker.all.bytes;
        let trash = figures.trash.all.bytes;
        let system = figures.system.all.bytes;
        let large = figures.big.all.bytes;
        let others = caches + app_caches + toolchains + containers + trash + system + large;
        let space = figures.space();
        let charts = figures.charts(report);
        let categories = &charts.categories;
        let projects = &charts.projects;
        let largest_project = projects.first().map_or(0, |bucket| bucket.bytes);
        let largest_cache = report
            .caches
            .first()
            .map_or(0, |(_, candidate)| candidate.usage.allocated);

        scroll("overview")
            .child(
                div()
                    .flex()
                    .items_center()
                    .gap(unit(space::L))
                    .child(self.overview_switch(cx)),
            )
            .children(overview_disks(report))
            .child(overview_hero(report, figures))
            .children(self.overview_growth(report))
            .child(self.overview_wins(report, cx))
            .child(self.overview_sections(cx))
            .child(
                div()
                    .flex()
                    .gap(unit(space::L))
                    .items_start()
                    .child(
                        ui::card("Where the space is")
                            .flex_1()
                            .children(categories.iter().enumerate().map(|(index, bucket)| {
                                ui::bar_row(
                                    format!(
                                        "{}  {}",
                                        bucket.key.as_str(),
                                        plural(bucket.count, "item")
                                    ),
                                    theme::bytes(bucket.bytes),
                                    theme::share(bucket.bytes, space),
                                    theme::bar(),
                                )
                                .id(("space", index))
                                .tip(tooltip::term(Term::category(bucket.key)))
                            }))
                            .when(
                                report.options.developer || figures.caches.all.count > 0,
                                |this| {
                                    this.child(ui::bar_row(
                                        format!(
                                            "developer caches  {}",
                                            plural(figures.caches.all.count, "cache")
                                        ),
                                        theme::bytes(caches),
                                        theme::share(caches, space),
                                        theme::faint(),
                                    ))
                                },
                            )
                            .child(ui::bar_row(
                                format!(
                                    "app caches  {}",
                                    plural(figures.app_caches.all.count, "cache")
                                ),
                                theme::bytes(app_caches),
                                theme::share(app_caches, space),
                                theme::faint(),
                            ))
                            .when(report.options.trash, |this| {
                                this.child(ui::bar_row(
                                    format!("trash  {}", plural(figures.trash.all.count, "folder")),
                                    theme::bytes(trash),
                                    theme::share(trash, space),
                                    theme::faint(),
                                ))
                            })
                            .when(report.options.system, |this| {
                                this.child(ui::bar_row(
                                    format!(
                                        "system caches  {}",
                                        plural(figures.system.all.count, "cache")
                                    ),
                                    theme::bytes(system),
                                    theme::share(system, space),
                                    theme::faint(),
                                ))
                            })
                            .when(report.options.big, |this| {
                                this.child(ui::bar_row(
                                    format!(
                                        "large items  {}",
                                        plural(figures.big.all.count, "item")
                                    ),
                                    theme::bytes(large),
                                    theme::share(large, space),
                                    theme::faint(),
                                ))
                            })
                            .when(report.options.toolchains, |this| {
                                this.child(ui::bar_row(
                                    format!(
                                        "toolchains  {}",
                                        plural(report.toolchains.len(), "version")
                                    ),
                                    theme::bytes(toolchains),
                                    theme::share(toolchains, space),
                                    theme::faint(),
                                ))
                            })
                            .when(report.options.docker, |this| {
                                this.child(ui::bar_row(
                                    format!("docker  {}", plural(report.docker.len(), "object")),
                                    theme::bytes(containers),
                                    theme::share(containers, space),
                                    theme::faint(),
                                ))
                            })
                            .when(categories.is_empty() && others == 0, |this| {
                                this.child(ui::empty("Nothing to clean up found"))
                            }),
                    )
                    .child(if report.options.developer || !projects.is_empty() {
                        ui::card("Largest projects")
                            .flex_1()
                            .children(projects.iter().take(8).enumerate().map(|(index, bucket)| {
                                ui::bar_row(
                                    model::short_path(&bucket.key, &report.roots),
                                    theme::bytes(bucket.bytes),
                                    theme::share(bucket.bytes, largest_project),
                                    theme::bar(),
                                )
                                .id(("project", index))
                                .tip(tooltip::path(&bucket.key))
                            }))
                            .when(projects.is_empty(), |this| {
                                this.child(ui::empty("No projects with artifacts"))
                            })
                    } else {
                        let mut folders: Vec<(&Path, u64)> = report
                            .usage
                            .as_ref()
                            .map(|tree| {
                                tree.roots
                                    .iter()
                                    .flat_map(|root| root.children.iter())
                                    .filter(|child| child.is_dir && child.allocated > 0)
                                    .map(|child| (child.path.as_path(), child.allocated))
                                    .collect()
                            })
                            .unwrap_or_default();
                        folders.sort_unstable_by_key(|a| std::cmp::Reverse(a.1));
                        let largest_folder = folders.first().map_or(0, |(_, bytes)| *bytes);
                        ui::card("Largest folders")
                            .flex_1()
                            .children(folders.into_iter().take(8).enumerate().map(
                                |(index, (path, bytes))| {
                                    ui::bar_row(
                                        model::short_path(path, &report.roots),
                                        theme::bytes(bytes),
                                        theme::share(bytes, largest_folder),
                                        theme::bar(),
                                    )
                                    .id(("folder", index))
                                    .tip(tooltip::path(path))
                                },
                            ))
                            .when(largest_folder == 0, |this| {
                                this.child(ui::empty("No folders measured"))
                            })
                    })
                    .child(
                        ui::card("Largest caches")
                            .flex_1()
                            .children(report.caches.iter().take(8).map(|(cache, candidate)| {
                                ui::bar_row(
                                    cache_label(cache),
                                    theme::bytes(candidate.usage.allocated),
                                    theme::share(candidate.usage.allocated, largest_cache),
                                    if candidate.rule.safety == Safety::Review {
                                        theme::review()
                                    } else {
                                        theme::bar()
                                    },
                                )
                            }))
                            .when(report.caches.is_empty(), |this| {
                                this.child(ui::empty("No caches found"))
                            }),
                    ),
            )
            .child(overview_trends(figures, charts))
            .child(
                div()
                    .text_size(unit(font::SMALL))
                    .text_color(theme::faint())
                    .child({
                        let throughput = report
                            .walk_diagnostics
                            .as_ref()
                            .filter(|diag| diag.dirs_per_sec() > 0)
                            .map(|diag| {
                                format!(
                                    "  ·  {} dirs/s, {} files/s ({} threads)",
                                    grouped(diag.dirs_per_sec()),
                                    grouped(diag.files_per_sec()),
                                    diag.threads,
                                )
                            })
                            .unwrap_or_default();
                        format!(
                            "Scanned {} folders and {} files in {:.2}s{}{}",
                            grouped(report.summary.progress.dirs),
                            grouped(report.summary.progress.files),
                            report.summary.duration.as_secs_f32(),
                            if report.summary.cancelled {
                                ", cancelled"
                            } else {
                                ""
                            },
                            throughput,
                        )
                    }),
            )
            .into_any_element()
    }

    /// Why the biggest safe wins cannot be selected, or `None` when there are some.
    pub(super) fn wins_blocked(&self) -> Option<&'static str> {
        let report = self.report()?;
        self.session
            .report_stats
            .charts(report)
            .wins
            .0
            .is_empty()
            .then_some("No safe items to select")
    }

    /// Selects the biggest safe wins from every list and opens the list of the largest one,
    /// where Delete removes the whole selection.
    pub(super) fn select_wins(&mut self, cx: &mut Context<Self>) {
        let Some(report) = self.report() else {
            return;
        };
        let keys = self.session.report_stats.charts(report).wins.0.clone();
        let Some(&(source, id)) = keys.first() else {
            return;
        };
        let largest = self.target_tab(&Target::Item(source, id, PathBuf::new()));
        for key in keys {
            self.select(key);
        }
        self.go_to(largest, cx);
        if largest.grades() && self.list.safety == Some(Safety::Review) {
            self.list.safety = None;
            self.filtered();
        }
    }

    /// The first step to take: the largest safe artifacts, one key away from being selected.
    fn overview_wins(&self, report: &Report, cx: &mut Context<Self>) -> Div {
        let (keys, bytes) = &self.session.report_stats.charts(report).wins;
        let card = ui::card("Biggest safe wins").debug_selector(|| "overview-wins".to_owned());
        if keys.is_empty() {
            return card.child(ui::empty(if self.refreshing() {
                "No safe items found yet, the scan is still running"
            } else {
                "No safe items in this scan"
            }));
        }
        let picks: Vec<&Candidate> = keys
            .iter()
            .filter_map(|&key| self.session.index.find(report, key))
            .collect();
        let largest = picks
            .first()
            .map_or(0, |candidate| candidate.usage.allocated);
        let key = self.hint(&Command::SelectWins);
        let button = self
            .button(
                "overview-wins-select",
                format!("Select {}", plural(keys.len(), "item")),
                ButtonKind::Primary,
                self.blocked(&Command::SelectWins).is_none(),
                cx,
                |app, _, cx| app.select_wins(cx),
            )
            .tip(
                Tooltip::new(
                    "Selects them and opens the list of the largest one. Nothing is deleted yet",
                )
                .keys(&[&key])
                .build(),
            );
        card.child(
            div()
                .flex()
                .items_center()
                .gap(unit(space::L))
                .child(
                    div()
                        .flex()
                        .flex_col()
                        .flex_1()
                        .min_w_0()
                        .gap(unit(space::XXS))
                        .child(ui::tabular(
                            div()
                                .text_size(unit(font::HEADING))
                                .font_weight(FontWeight::SEMIBOLD)
                                .child(theme::bytes(*bytes)),
                        ))
                        .child(
                            div()
                                .text_size(unit(font::SMALL))
                                .text_color(theme::faint())
                                .child(format!(
                                    "in the {} largest safe {}. Select them, check the list, then press {} to delete them",
                                    keys.len(),
                                    if keys.len() == 1 { "item" } else { "items" },
                                    self.hint(&Command::Trash),
                                )),
                        ),
                )
                .child(ui::kbd(key))
                .child(button),
        )
        .children(picks.into_iter().take(WIN_ROWS).enumerate().map(|(index, candidate)| {
            ui::bar_row(
                model::short_path(&candidate.path, &report.roots),
                theme::bytes(candidate.usage.allocated),
                theme::share(candidate.usage.allocated, largest),
                theme::bar(),
            )
            .id(("win", index))
            .tip(tooltip::path(&candidate.path))
        }))
    }

    /// What grew since the previous scan of the same folder, grouped per project.
    fn overview_growth(&self, report: &Report) -> Option<Div> {
        let (since, diff) = self.session.growth.as_ref()?;
        let grown: Vec<&scan::ProjectGrowth> = diff.grown_projects().collect();
        if grown.is_empty() {
            return None;
        }
        let added: u64 = grown
            .iter()
            .map(|project| u64::try_from(project.delta_bytes).unwrap_or(0))
            .sum();
        let largest = grown
            .first()
            .and_then(|project| u64::try_from(project.delta_bytes).ok())
            .unwrap_or(0);
        let compared = snapshot::age_label(*since, report.scanned).to_lowercase();
        let net = match diff.delta_bytes {
            delta if delta > 0 && u64::try_from(delta).ok() != Some(added) => {
                format!(" · net +{}", theme::bytes(delta as u64))
            }
            delta if delta < 0 => {
                format!(" · net -{}", theme::bytes(delta.unsigned_abs()))
            }
            _ => String::new(),
        };
        let subtitle = format!(
            "in {} · compared to previous scan ({compared}){net}",
            plural(grown.len(), "project"),
        );
        Some(
            ui::card("Grew since last scan")
                .debug_selector(|| "overview-growth".to_owned())
                .child(
                    div()
                        .flex()
                        .flex_col()
                        .gap(unit(space::XXS))
                        .child(ui::tabular(
                            div()
                                .text_size(unit(font::HEADING))
                                .font_weight(FontWeight::SEMIBOLD)
                                .text_color(theme::review())
                                .child(format!("+{}", theme::bytes(added))),
                        ))
                        .child(
                            div()
                                .text_size(unit(font::SMALL))
                                .text_color(theme::faint())
                                .child(subtitle),
                        ),
                )
                .children(
                    grown
                        .into_iter()
                        .take(8)
                        .enumerate()
                        .map(|(index, project)| {
                            let delta = u64::try_from(project.delta_bytes).unwrap_or(0);
                            let name = model::short_path(&project.project, &report.roots);
                            let mut tip = Tooltip::details(name.clone())
                                .row("Previous", theme::bytes(project.previous_bytes))
                                .row("Now", theme::bytes(project.current_bytes))
                                .row("Grew", format!("+{}", theme::bytes(delta)));
                            for (path, item_delta) in project.grown_paths.iter().take(4) {
                                let item_bytes = u64::try_from(*item_delta).unwrap_or(0);
                                let item_name = path
                                    .strip_prefix(&project.project)
                                    .ok()
                                    .filter(|rel| !rel.as_os_str().is_empty())
                                    .map(|rel| rel.display().to_string())
                                    .unwrap_or_else(|| model::short_path(path, &report.roots));
                                tip = tip.row(item_name, format!("+{}", theme::bytes(item_bytes)));
                            }
                            ui::bar_row(
                                name,
                                format!("+{}", theme::bytes(delta)),
                                theme::share(delta, largest),
                                theme::review(),
                            )
                            .id(("growth", index))
                            .tip(tip.build())
                        }),
                ),
        )
    }

    /// The sections that can free space, largest share first to read, each a way into its list.
    fn overview_sections(&self, cx: &mut Context<Self>) -> Div {
        const SECTIONS: [Tab; 10] = [
            Tab::AppCaches,
            Tab::Trash,
            Tab::System,
            Tab::LargeFiles,
            Tab::Artifacts,
            Tab::Caches,
            Tab::Toolchains,
            Tab::Docker,
            Tab::Repos,
            Tab::Duplicates,
        ];
        let largest = SECTIONS
            .iter()
            .filter_map(|&tab| self.tab_bytes(tab))
            .max()
            .unwrap_or(0);
        let shortcuts = &self.config.route_shortcuts;
        let hints = shortcuts.enabled && shortcuts.hints;
        let rows = SECTIONS.into_iter().enumerate().map(|(index, tab)| {
            let bytes = self.tab_bytes(tab).unwrap_or(0);
            let (one, many) = tab.noun();
            let found = match self.tab_count(tab) {
                Some(1) => format!("1 {one}"),
                Some(count) => format!("{count} {many}"),
                None => "not searched".to_owned(),
            };
            let row = div()
                .id(("overview-section", index))
                .debug_selector(move || format!("overview-section-{index}"))
                .flex()
                .items_center()
                .gap(unit(space::L))
                .h(unit(size::row_tall()))
                .px(unit(space::M))
                .rounded(theme::radius_control())
                .cursor_pointer()
                .hover(|style| style.bg(theme::hover()))
                .tip(tooltip::term(tab.term()))
                .child(icon::view(tab.icon(), theme::muted()))
                .child(
                    div()
                        .w(unit(col::XXL))
                        .flex_none()
                        .truncate()
                        .font_weight(FontWeight::MEDIUM)
                        .child(tab.label()),
                )
                .child(
                    div()
                        .w(unit(col::L))
                        .flex_none()
                        .truncate()
                        .text_size(unit(font::SMALL))
                        .text_color(theme::faint())
                        .child(found),
                )
                .child(
                    div()
                        .flex_1()
                        .min_w_0()
                        .h(unit(size::TRACK))
                        .rounded(theme::radius_bar())
                        .bg(theme::track())
                        .when(bytes > 0, |this| {
                            this.child(
                                div()
                                    .h_full()
                                    .w(gpui::relative(theme::share(bytes, largest)))
                                    .min_w(unit(size::SLIVER))
                                    .rounded(theme::radius_bar())
                                    .bg(theme::bar()),
                            )
                        }),
                )
                .child(
                    ui::figure(theme::bytes(bytes))
                        .w(unit(col::M))
                        .when(bytes == 0, |this| this.text_color(theme::faint())),
                )
                .children(
                    Some(self.hint(&Command::GoTo(tab)))
                        .filter(|key| hints && !key.is_empty())
                        .map(ui::kbd),
                );
            self.control(row, cx, move |app, _, cx| app.go_to(tab, cx))
        });
        div()
            .flex()
            .flex_col()
            .p(unit(space::M))
            .rounded(theme::radius_panel())
            .bg(theme::elevated())
            .border_1()
            .border_color(theme::border())
            .children(rows)
    }
}

/// How many of the picked items the overview lists by name.
const WIN_ROWS: usize = 5;

/// How full a disk is, in hundredths, when its bar turns to the review tint.
const DISK_FILLING: u64 = 80;
/// How full a disk is, in hundredths, when its bar turns to the danger tint.
const DISK_FULL: u64 = 92;

/// @name disk_fill
/// @description The tint of a disk bar for how full the disk is: danger from 92% up, review
/// from 80% up, the plain bar below that.
///
/// @example
/// let fill = disk_fill(used, total);
pub(super) fn disk_fill(used: u64, total: u64) -> gpui::Rgba {
    let percent = percent_full(used, total);
    if percent >= DISK_FULL {
        theme::danger()
    } else if percent >= DISK_FILLING {
        theme::review()
    } else {
        theme::bar()
    }
}

fn percent_full(used: u64, total: u64) -> u64 {
    if total == 0 {
        return 0;
    }
    u64::try_from(u128::from(used) * 100 / u128::from(total)).unwrap_or(100)
}

/// The disks that hold the scanned folders: what is used of each, what is free, and a bar
/// that warns as a disk fills up. Left out when no disk size is known.
pub(super) fn overview_disks(report: &Report) -> Option<Div> {
    let disks: Vec<(u64, u64)> = report
        .disks
        .iter()
        .filter_map(|disk| Some((disk.available?, disk.total?)))
        .filter(|(_, total)| *total > 0)
        .collect();
    if disks.is_empty() {
        return None;
    }
    Some(
        ui::card("Disk usage")
            .debug_selector(|| "overview-disk".to_owned())
            .children(disks.into_iter().enumerate().map(|(index, (free, total))| {
                let used = total.saturating_sub(free);
                ui::bar_row(
                    format!(
                        "{} used of {} · {} free",
                        theme::bytes(used),
                        theme::bytes(total),
                        theme::bytes(free)
                    ),
                    format!("{}% full", percent_full(used, total)),
                    theme::share(used, total),
                    disk_fill(used, total),
                )
                .debug_selector(move || format!("overview-disk-{index}"))
            })),
    )
}

/// One figure of the overview hero, set off from its neighbour by a rule.
fn hero_figure(
    label: &'static str,
    value: String,
    dot: Option<gpui::Rgba>,
    term: Term,
) -> Stateful<Div> {
    div()
        .id(label)
        .flex()
        .flex_col()
        .flex_none()
        .gap(unit(space::XS))
        .pl(unit(space::XL))
        .border_l_1()
        .border_color(theme::border())
        .tip(tooltip::term(term))
        .child(
            div()
                .flex()
                .items_center()
                .gap(unit(space::S))
                .text_size(unit(font::SMALL))
                .text_color(theme::muted())
                .children(dot.map(|fill| {
                    div()
                        .size(unit(size::DOT))
                        .flex_none()
                        .rounded(theme::radius_pill())
                        .bg(fill)
                }))
                .child(label),
        )
        .child(ui::tabular(
            div()
                .text_size(unit(font::HEADING))
                .font_weight(FontWeight::SEMIBOLD)
                .child(value),
        ))
}

pub(super) fn overview_hero(report: &Report, figures: &ReportStats) -> Div {
    let artifact_safe = figures.artifacts.safe.bytes;
    let artifact_review = figures.artifacts.review.bytes;
    let caches = figures.caches.all.bytes + figures.app_caches.all.bytes;
    let trash = figures.trash.all.bytes;
    let system = figures.system.all.bytes;
    let toolchains = figures.toolchains.safe.bytes;
    let containers = figures.docker.safe.bytes;
    let duplicates = report
        .duplicates
        .as_ref()
        .map_or(0, kuizer::dupes::Duplicates::reclaimable);
    let safe = artifact_safe
        + figures.caches.safe.bytes
        + figures.app_caches.safe.bytes
        + figures.trash.safe.bytes
        + figures.system.safe.bytes
        + toolchains
        + containers;
    let review = artifact_review
        + figures.caches.review.bytes
        + figures.app_caches.review.bytes
        + figures.system.review.bytes;
    let reclaimable = artifact_safe
        + artifact_review
        + caches
        + trash
        + system
        + toolchains
        + containers
        + duplicates;
    let mut segments = vec![
        Segment {
            label: "Safe artifacts".into(),
            bytes: artifact_safe,
            fill: theme::bar_strong(),
        },
        Segment {
            label: "Needs review".into(),
            bytes: artifact_review,
            fill: theme::review(),
        },
        Segment {
            label: "Caches".into(),
            bytes: caches,
            fill: theme::bar(),
        },
        Segment {
            label: "Trash".into(),
            bytes: trash,
            fill: theme::ok(),
        },
        Segment {
            label: "System caches".into(),
            bytes: system,
            fill: theme::bar_mid(),
        },
        Segment {
            label: "Unused toolchains".into(),
            bytes: toolchains,
            fill: theme::bar_mid(),
        },
        Segment {
            label: "Docker".into(),
            bytes: containers,
            fill: theme::bar_soft(),
        },
        Segment {
            label: "Duplicates".into(),
            bytes: duplicates,
            fill: theme::bar_soft(),
        },
    ];
    let disk = report
        .disks
        .first()
        .and_then(|disk| Some((disk.available?, disk.total?)));
    let whole = match disk {
        Some((free, size)) => {
            let used = size.saturating_sub(free);
            segments.push(Segment {
                label: "Other files".into(),
                bytes: used.saturating_sub(reclaimable),
                fill: theme::bar_rest(),
            });
            segments.push(Segment {
                label: "Free".into(),
                bytes: free,
                fill: theme::track(),
            });
            size.max(reclaimable)
        }
        None => reclaimable,
    };
    let figures_row =
        div()
            .flex()
            .flex_wrap()
            .items_end()
            .gap_x(unit(space::XXL))
            .gap_y(unit(space::L))
            .child(
                div()
                    .flex()
                    .flex_col()
                    .flex_1()
                    .min_w(unit(size::LABEL))
                    .gap(unit(space::XXS))
                    .child(
                        div()
                            .text_size(unit(font::SMALL))
                            .text_color(theme::muted())
                            .child("Could be reclaimed"),
                    )
                    .child(ui::tabular(
                        div()
                            .text_size(unit(font::DISPLAY))
                            .font_weight(FontWeight::SEMIBOLD)
                            .child(theme::bytes(reclaimable)),
                    ))
                    .children(disk.map(|(_, size)| {
                        div()
                            .text_size(unit(font::SMALL))
                            .text_color(theme::faint())
                            .child(format!("of a {} disk", theme::bytes(size)))
                    })),
            )
            .child(hero_figure(
                "Safe to remove",
                theme::bytes(safe),
                Some(theme::ok()),
                Term::Safe,
            ))
            .child(hero_figure(
                "Needs review",
                theme::bytes(review),
                Some(theme::review()),
                Term::Review,
            ))
            .children(disk.map(|(free, _)| {
                hero_figure("Disk free", theme::bytes(free), None, Term::DiskFree)
            }));
    div()
        .flex()
        .flex_col()
        .gap(unit(space::XL))
        .p(unit(space::XXL))
        .rounded(theme::radius_panel())
        .bg(theme::elevated())
        .border_1()
        .border_color(theme::border())
        .child(figures_row)
        .child(chart::composition("disk", &segments, whole))
}

pub(super) fn overview_trends(figures: &ReportStats, charts: &Charts) -> Div {
    let ages = &charts.ages;
    let sizes = &charts.sizes;
    let ecosystems = &charts.ecosystems;
    let largest = ecosystems.first().map_or(0, |bucket| bucket.bytes);
    let total = figures.artifacts.all.bytes;
    let empty = figures.artifacts.all.count == 0;
    let removed = charts.removed.as_ref();
    div()
        .flex()
        .flex_col()
        .gap(unit(space::L))
        .child(
            div()
                .flex()
                .gap(unit(space::L))
                .items_start()
                .child(
                    ui::card("Idle since")
                        .flex_1()
                        .debug_selector(|| "chart-ages".to_owned())
                        .when(!empty, |this| {
                            this.child(chart::columns("age", ages, Measure::Bytes, "Items"))
                        })
                        .when(empty, |this| {
                            this.child(ui::empty("No project artifacts found"))
                        }),
                )
                .child(
                    ui::card("Artifact sizes")
                        .flex_1()
                        .when(!empty, |this| {
                            this.child(chart::columns("size", sizes, Measure::Count, "Items"))
                        })
                        .when(empty, |this| {
                            this.child(ui::empty("No project artifacts found"))
                        }),
                )
                .child(
                    ui::card("By ecosystem")
                        .flex_1()
                        .children(
                            ecosystems
                                .iter()
                                .take(6)
                                .enumerate()
                                .map(|(index, bucket)| {
                                    ui::bar_row(
                                        format!(
                                            "{}  {}",
                                            bucket.label,
                                            plural(bucket.count, "item")
                                        ),
                                        theme::bytes(bucket.bytes),
                                        theme::share(bucket.bytes, largest),
                                        theme::bar(),
                                    )
                                    .id(("ecosystem", index))
                                    .tip(
                                        Tooltip::details(bucket.label.clone())
                                            .row("Size", theme::bytes(bucket.bytes))
                                            .row("Items", bucket.count.to_string())
                                            .row(
                                                "Share",
                                                chart::percent(theme::share(bucket.bytes, total)),
                                            )
                                            .build(),
                                    )
                                }),
                        )
                        .when(empty, |this| {
                            this.child(ui::empty("No project artifacts found"))
                        }),
                ),
        )
        .children(removed.map(|months| {
            let total: u64 = months.iter().map(|month| month.bytes).sum();
            ui::card(format!(
                "Removed in the last 12 months  {}",
                theme::bytes(total)
            ))
            .child(chart::columns("removed", months, Measure::Bytes, "Items"))
        }))
}

#[cfg(test)]
mod tests {
    use gpui::TestAppContext;
    use kuizer::caches::KnownCache;
    use kuizer::system;

    use super::*;
    use crate::app::tests::{artifact, open};
    use crate::model::Disk;

    #[test]
    fn the_sidebar_lists_general_sections_first() {
        let headed: Vec<(Tab, &str)> = Tab::ALL
            .into_iter()
            .filter_map(|tab| tab.heading().map(|heading| (tab, heading)))
            .collect();
        assert_eq!(
            headed,
            [
                (Tab::DiskUsage, "Clean up"),
                (Tab::Artifacts, "Developer"),
                (Tab::Duplicates, "Files"),
                (Tab::History, "Activity"),
            ]
        );
        assert_eq!(Tab::ALL[0], Tab::Overview);
        assert_eq!(Tab::ALL[5], Tab::LargeFiles);
    }

    #[test]
    fn a_disk_bar_warns_as_the_disk_fills() {
        assert_eq!(disk_fill(50, 100), theme::bar());
        assert_eq!(disk_fill(80, 100), theme::review());
        assert_eq!(disk_fill(92, 100), theme::danger());
        assert_eq!(disk_fill(0, 0), theme::bar());
    }

    #[gpui::test]
    fn biggest_safe_wins_come_from_every_safe_list(cx: &mut TestAppContext) {
        let dir = tempfile::tempdir().unwrap();
        let (view, cx) = open(cx, dir.path().join("recent"));
        let thumbs = KnownCache {
            name: "thumbnails".to_owned(),
            tool: "thumbnails".to_owned(),
            group: kuizer::catalog::Group::Apps,
            category: Category::Cache,
            kind: kuizer::detect::Kind::Dir,
            path: PathBuf::from("/c/thumbnails"),
            safety: Safety::Safe,
            note: String::new(),
            processes: Vec::new(),
        };
        let journal = system::Item {
            manager: system::Manager::Journal,
            id: "journal".to_owned(),
            label: "System journal".to_owned(),
            bytes: 40 * 4096,
            size_known: true,
            safety: Safety::Safe,
            needs_root: true,
            note: String::new(),
        };
        let folder = kuizer::trashcan::Folder {
            path: PathBuf::from("/t/Trash"),
            items: 2,
            layout: kuizer::trashcan::Layout::Freedesktop,
        };
        view.update(cx, |app, cx| {
            let roots = vec![PathBuf::from("/p")];
            let mut report = Report::empty(&roots, &app.session.options);
            report.candidates = vec![artifact(1, Path::new("/p/a/node_modules"))];
            report.caches = vec![(thumbs, artifact(50, Path::new("/c/thumbnails")))];
            report.trash = vec![(folder, artifact(20, Path::new("/t/Trash")))];
            let candidate = journal.candidate(1);
            report.system = vec![(journal, candidate)];
            report.big = vec![artifact(100, Path::new("/p/huge.iso"))];
            report.disks = vec![Disk {
                available: Some(5),
                total: Some(100),
            }];
            app.session.roots = roots;
            app.session.phase = Phase::Ready(Box::new(report));
            app.refresh_stats();
            app.list.tab = Tab::Overview;
            cx.notify();
        });
        cx.update(|window, cx| window.draw(cx).clear());
        assert!(cx.debug_bounds("overview-disk-0").is_some());
        view.update(cx, |app, cx| {
            let report = app.report().unwrap();
            let (keys, _) = &app.session.report_stats.charts(report).wins;
            assert_eq!(
                keys,
                &[
                    (Source::Cache, 50),
                    (Source::System, 1),
                    (Source::Trash, 20),
                    (Source::Artifact, 1),
                ],
                "large files never count as a safe win"
            );
            app.list.safety = Some(Safety::Review);
            app.select_wins(cx);
            assert_eq!(app.list.selection.len(), 4);
            assert_eq!(app.list.tab, Tab::AppCaches, "the largest win's list opens");
            assert_eq!(app.list.safety, None);
        });
    }
}