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
use gpui::BoxShadow;

use super::*;

impl Kuizer {
    pub(super) fn restore(&mut self, session: u64, cx: &mut Context<Self>) {
        if !self.can_restore() {
            return;
        }
        let Some(history) = self
            .report()
            .and_then(|report| report.history.as_ref().ok())
            .map(|view| view.history.clone())
        else {
            return;
        };
        let spawned = spawn_worker("kuizer-gui-restore", move || {
            model::restore(history, session)
        });
        let receiver = match spawned {
            Ok(receiver) => receiver,
            Err(error) => {
                self.show_toast(Notice::Failed(format!("Could not restore: {error}")), cx);
                return;
            }
        };
        self.show_toast(Notice::Restoring { session }, cx);
        self.session.restore_task = Some(cx.spawn(async move |this, cx| {
            let message = receiver.await.ok();
            let _ = this.update(cx, |app, cx| app.restored(message, cx));
        }));
    }

    pub(super) fn restored(
        &mut self,
        message: Option<(Result<Restored, String>, Option<HistoryView>)>,
        cx: &mut Context<Self>,
    ) {
        let Some((restored, history)) = message else {
            self.show_toast(
                Notice::Failed("Could not restore: the restore stopped unexpectedly".to_owned()),
                cx,
            );
            return;
        };
        if let Phase::Ready(report) = &mut self.session.phase
            && let Some(history) = history
        {
            report.history = Ok(history);
        }
        self.refresh_stats();
        let notice = match restored {
            Ok(restored) => {
                if restored.items > 0 && matches!(self.session.phase, Phase::Ready(_)) {
                    self.rescan(cx);
                }
                Notice::Restored(restored)
            }
            Err(error) => Notice::Failed(format!("Could not restore: {error}")),
        };
        self.show_toast(notice, cx);
    }

    pub(super) fn trash(&mut self, cx: &mut Context<Self>) {
        if !self.list.selection.is_empty() {
            self.delete(None, cx);
        }
    }

    /// Starts deleting the selection, or one item when `only` is set, unless something stands
    /// in the way.
    pub(super) fn delete(&mut self, only: Option<(Source, u64)>, cx: &mut Context<Self>) {
        match only {
            Some(key) => self.delete_keys(&[key], cx),
            None => {
                let keys: Vec<(Source, u64)> = self
                    .selected()
                    .into_iter()
                    .map(|(source, candidate)| (source, candidate.id))
                    .collect();
                self.delete_keys(&keys, cx);
            }
        }
    }

    /// Starts deleting the specified `(Source, id)` items unless something stands in the way.
    /// Emptying the trash and moving large files away wait for the inline confirmation first.
    pub(super) fn delete_keys(&mut self, keys: &[(Source, u64)], cx: &mut Context<Self>) {
        if !self.removable(keys) {
            return;
        }
        if keys.iter().any(|(source, _)| confirm::asks(*source)) {
            self.ask_remove(keys, cx);
        } else {
            self.clean_keys(keys, cx);
        }
    }

    /// Whether these items can be removed right now: they are in the report and nothing runs
    /// that their removal would have to wait for.
    pub(super) fn removable(&self, keys: &[(Source, u64)]) -> bool {
        let items: Vec<(Source, &Candidate)> =
            keys.iter().filter_map(|&key| self.item(key)).collect();
        let locked = self
            .locked(items.iter().map(|(source, _)| *source))
            .is_some();
        !items.is_empty() && !self.busy() && !locked && !self.saving_protected_paths()
    }

    /// Removes the items through the shared executor, one batch per source with its own guard.
    pub(super) fn clean_keys(&mut self, keys: &[(Source, u64)], cx: &mut Context<Self>) {
        if !self.removable(keys) {
            return;
        }
        let Some(report) = self.report() else {
            return;
        };
        let items: Vec<(Source, &Candidate)> =
            keys.iter().filter_map(|&key| self.item(key)).collect();
        let mut paths: HashMap<Source, HashSet<PathBuf>> = HashMap::new();
        for (source, candidate) in &items {
            paths
                .entry(*source)
                .or_default()
                .insert(candidate.path.clone());
        }
        let count = items.len();
        let mut artifacts = Vec::new();
        let mut caches = Vec::new();
        let mut toolchains = Vec::new();
        let mut docker = Vec::new();
        let mut trash = Vec::new();
        let mut big = Vec::new();
        let mut system = Vec::new();
        for (source, candidate) in items {
            match source {
                Source::Artifact => artifacts.push(candidate.clone()),
                Source::Cache => caches.push(candidate.clone()),
                Source::Toolchain => toolchains.push(candidate.clone()),
                Source::Docker => docker.push(candidate.clone()),
                Source::Trash => trash.push(candidate.clone()),
                Source::Big => big.push(candidate.clone()),
                Source::System => system.push(candidate.clone()),
            }
        }
        let mut batches = Vec::new();
        if !artifacts.is_empty() {
            batches.push(Batch {
                source: Source::Artifact,
                roots: report.roots.clone(),
                candidates: artifacts,
            });
        }
        if !caches.is_empty() {
            batches.push(Batch {
                source: Source::Cache,
                roots: model::cache_roots(&caches),
                candidates: caches,
            });
        }
        if !toolchains.is_empty() {
            batches.push(Batch {
                source: Source::Toolchain,
                roots: kuizer::toolchains::roots(&toolchains),
                candidates: toolchains,
            });
        }
        if !docker.is_empty() {
            batches.push(Batch {
                source: Source::Docker,
                roots: Vec::new(),
                candidates: docker,
            });
        }
        if !trash.is_empty() {
            let mut roots: Vec<PathBuf> = report
                .trash
                .iter()
                .filter(|(_, listed)| trash.iter().any(|picked| picked.id == listed.id))
                .flat_map(|(folder, _)| kuizer::trashcan::roots(folder))
                .collect();
            roots.sort();
            roots.dedup();
            batches.push(Batch {
                source: Source::Trash,
                roots,
                candidates: trash,
            });
        }
        if !big.is_empty() {
            let mut roots = report.roots.clone();
            if self.config.big.downloads {
                roots.extend(kuizer::big::downloads_dir().filter(|dir| dir.is_dir()));
            }
            roots.sort();
            roots.dedup();
            batches.push(Batch {
                source: Source::Big,
                roots,
                candidates: big,
            });
        }
        if !system.is_empty() {
            batches.push(Batch {
                source: Source::System,
                roots: Vec::new(),
                candidates: system,
            });
        }
        self.run_clean(batches, paths, count, cx);
    }

    /// Hands the batches to a worker and shows their rows as leaving until it reports back.
    pub(super) fn run_clean(
        &mut self,
        batches: Vec<Batch>,
        paths: HashMap<Source, HashSet<PathBuf>>,
        count: usize,
        cx: &mut Context<Self>,
    ) {
        let Some(report) = self.report() else {
            return;
        };
        let history = report
            .history
            .as_ref()
            .ok()
            .map(|view| (view.history.clone(), view.trash.clone()));
        let delete_config = self.config.delete.clone();
        let engines = self.config.docker.engines.clone();
        let system_config = self.config.system.clone();
        let spawned = spawn_worker("kuizer-gui-clean", move || {
            let batches = batches.into_iter().map(model::refreshed).collect();
            model::clean(batches, &delete_config, &engines, &system_config, history)
        });
        let receiver = match spawned {
            Ok(receiver) => receiver,
            Err(error) => {
                self.overlays.dialog = Some(Dialog::Finished(Finished {
                    removed: 0,
                    removed_bytes: 0,
                    trashed: 0,
                    trashed_bytes: 0,
                    failures: vec![(String::new(), error)],
                    history_error: None,
                }));
                cx.notify();
                return;
            }
        };
        let task = cx.spawn(async move |this, cx| {
            let message = receiver.await.ok();
            let _ = this.update(cx, |app, cx| app.finish(message, cx));
        });
        self.session.cleaning = Some(Cleaning {
            paths,
            started: Instant::now(),
            _task: task,
        });
        self.show_toast(Notice::Deleting(count), cx);
    }

    /// Keeps deleted items out of the scan saved for the next launch: a running scan leaves
    /// them out when it saves, and the snapshot already on disk is rewritten without them.
    fn forget_in_snapshot(&self, removed: &HashMap<Source, HashSet<PathBuf>>) {
        let paths: HashSet<PathBuf> = removed.values().flatten().cloned().collect();
        if paths.is_empty() {
            return;
        }
        if self.session.cancel.is_some() {
            self.session.forgotten.add(paths.iter().cloned());
        }
        let (snapshots, roots) = (self.session.snapshots.clone(), self.session.roots.clone());
        let spawned = std::thread::Builder::new()
            .name("kuizer-gui-forget".to_owned())
            .spawn(move || snapshots.forget(&roots, &paths));
        if let Err(error) = spawned {
            eprintln!("kuizer-gui: cannot update the saved scan: {error}");
        }
    }

    pub(super) fn finish(
        &mut self,
        message: Option<(Outcome, Result<HistoryView, String>)>,
        cx: &mut Context<Self>,
    ) {
        let cleaning = self.session.cleaning.take();
        if matches!(
            self.overlays.toast,
            Some(Toast {
                notice: Notice::Deleting(_),
                ..
            })
        ) {
            self.overlays.toast = None;
        }
        let Some((outcome, history)) = message else {
            self.settle(cleaning, HashMap::new(), cx);
            self.overlays.dialog = Some(Dialog::Finished(Finished {
                removed: 0,
                removed_bytes: 0,
                trashed: 0,
                trashed_bytes: 0,
                failures: vec![(String::new(), "the cleanup stopped unexpectedly".to_owned())],
                history_error: None,
            }));
            cx.notify();
            return;
        };
        let mut removed: HashMap<Source, HashSet<PathBuf>> = HashMap::new();
        for (source, removal) in outcome.removed() {
            removed
                .entry(*source)
                .or_default()
                .insert(removal.candidate.path.clone());
        }
        let trashed = || {
            outcome
                .removed()
                .filter(|(source, _)| outcome.trashed(*source))
        };
        let finished = Finished {
            trashed: trashed().count(),
            trashed_bytes: trashed()
                .map(|(_, removal)| removal.candidate.usage.allocated)
                .sum(),
            removed: outcome.removed().count(),
            removed_bytes: outcome
                .removed()
                .map(|(_, removal)| removal.candidate.usage.allocated)
                .sum(),
            failures: outcome
                .failed()
                .map(|(_, removal)| {
                    (
                        display_path(&removal.candidate.path),
                        removal.error.clone().unwrap_or_default(),
                    )
                })
                .collect(),
            history_error: outcome.history_error.clone(),
        };
        let deselected: Vec<(Source, u64)> = self
            .selected()
            .into_iter()
            .filter(|(source, candidate)| {
                removed
                    .get(source)
                    .is_some_and(|paths| paths.contains(&candidate.path))
            })
            .map(|(source, candidate)| (source, candidate.id))
            .collect();
        for key in &deselected {
            self.list.selection.remove(key);
            self.session.flow.mark(*key);
        }
        if let Phase::Ready(report) = &mut self.session.phase {
            report.history = history;
        }
        self.forget_in_snapshot(&removed);
        if self.session.cancel.is_some() {
            self.session.history_fresh = true;
        }
        self.settle(cleaning, removed, cx);
        let clean = finished.failures.is_empty() && finished.history_error.is_none();
        if clean && finished.removed > 0 {
            self.show_toast(Notice::Info(finished.summary()), cx);
        }
        self.overlays.dialog = (!clean).then_some(Dialog::Finished(finished));
        cx.notify();
    }

    pub(super) fn render_toast(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
        let toast = self.overlays.toast.as_ref()?;
        let dismiss = || {
            self.button(
                "dismiss-toast",
                "Dismiss",
                ButtonKind::Ghost,
                true,
                cx,
                |app, _, cx| {
                    app.dismiss_toast(cx);
                },
            )
            .debug_selector(|| "dismiss-toast".to_owned())
            .h(unit(size::SEGMENT))
            .px(unit(space::M))
            .text_size(unit(font::SMALL))
            .tip(
                Tooltip::new("Hide this message")
                    .keys(&[&self.key_hint(Scope::GuiBack, Key::Back)])
                    .build(),
            )
        };
        let line = div()
            .flex()
            .items_center()
            .gap(unit(space::M))
            .min_h(unit(size::SEGMENT));
        let panel = floating(div().id("toast"))
            .debug_selector(|| "toast".to_owned())
            .flex()
            .flex_col()
            .gap(unit(space::S))
            .max_w(unit(size::PALETTE))
            .py(unit(space::S))
            .pl(unit(space::L))
            .pr(unit(space::S))
            .text_size(unit(font::SMALL));
        let panel = match &toast.notice {
            Notice::Deleting(count) => panel.child(
                line.child(
                    div()
                        .debug_selector(|| "toast-deleting".to_owned())
                        .text_color(theme::muted())
                        .child(format!("Deleting {}", plural(*count, "item"))),
                ),
            ),
            Notice::Restoring { session } => panel.child(
                line.child(
                    div()
                        .text_color(theme::muted())
                        .child(format!("Restoring cleanup s{session} from the trash")),
                ),
            ),
            Notice::Restored(restored) => {
                let failed = restored.problems.len();
                panel
                    .child(
                        line.child(div().flex_1().child(if restored.items > 0 {
                            format!(
                                "{}, {} restored",
                                plural(restored.items, "item"),
                                theme::bytes(restored.bytes)
                            )
                        } else {
                            "Nothing was restored".to_owned()
                        }))
                        .child(dismiss()),
                    )
                    .when(failed > 0, |this| {
                        this.child(
                            div()
                                .debug_selector(|| "toast-error".to_owned())
                                .text_color(theme::danger())
                                .child(format!("{} could not be restored", plural(failed, "item"))),
                        )
                        .children(
                            restored
                                .problems
                                .iter()
                                .take(TOAST_PROBLEMS)
                                .enumerate()
                                .map(|(index, (path, reason))| {
                                    div()
                                        .id(("toast-problem", index))
                                        .truncate()
                                        .text_size(unit(font::SMALL))
                                        .text_color(theme::faint())
                                        .tip(tooltip::path(path))
                                        .child(format!("{} {reason}", self.shown_path(path)))
                                }),
                        )
                        .when(failed > TOAST_PROBLEMS, |this| {
                            this.child(
                                div()
                                    .text_size(unit(font::SMALL))
                                    .text_color(theme::faint())
                                    .child(format!(
                                        "and {} more, kuizer history show lists them",
                                        failed - TOAST_PROBLEMS
                                    )),
                            )
                        })
                    })
                    .children(restored.history_error.as_ref().map(|error| {
                        div()
                            .text_color(theme::danger())
                            .child(format!("The history could not be saved: {error}"))
                    }))
            }
            Notice::Failed(error) => panel.child(
                line.child(
                    div()
                        .flex_1()
                        .debug_selector(|| "toast-error".to_owned())
                        .text_color(theme::danger())
                        .child(error.clone()),
                )
                .child(dismiss()),
            ),
            Notice::Info(text) => panel.child(
                line.child(icon::sized(Icon::Check, theme::ok(), size::CHECK))
                    .child(div().flex_1().child(text.clone()))
                    .child(dismiss()),
            ),
        };
        Some(panel.into_any_element())
    }

    pub(super) fn render_dialog(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
        let dialog = self.overlays.dialog.as_ref()?;
        let panel = div()
            .flex()
            .flex_col()
            .gap(unit(space::L))
            .w(unit(size::DIALOG))
            .p(unit(space::XL))
            .rounded(theme::radius_dialog())
            .bg(theme::elevated())
            .border_1()
            .border_color(theme::border_strong());
        let body = match dialog {
            Dialog::Branches { .. } | Dialog::Exclude { .. } | Dialog::Remove(_) => return None,
            Dialog::Finished(finished) => panel
                .child(
                    div()
                        .text_size(unit(font::TITLE))
                        .font_weight(FontWeight::SEMIBOLD)
                        .child(if finished.removed == 0 {
                            "Nothing was deleted".to_owned()
                        } else {
                            finished.summary()
                        }),
                )
                .when(!finished.failures.is_empty(), |this| {
                    this.child(
                        div()
                            .text_color(theme::danger())
                            .child(format!("{} could not be deleted", finished.failures.len())),
                    )
                    .children(
                        finished.failures.iter().take(LIST_LIMIT).enumerate().map(
                            |(index, (path, error))| {
                                div()
                                    .flex()
                                    .flex_col()
                                    .child(
                                        div()
                                            .id(("failure", index))
                                            .truncate()
                                            .tip(tooltip::plain(path.clone()))
                                            .child(path.clone()),
                                    )
                                    .child(
                                        div()
                                            .text_size(unit(font::SMALL))
                                            .text_color(theme::faint())
                                            .child(error.clone()),
                                    )
                            },
                        ),
                    )
                })
                .children(finished.history_error.as_ref().map(|error| {
                    div()
                        .text_color(theme::danger())
                        .child(format!("The history could not be saved: {error}"))
                }))
                .child(
                    div().flex().justify_end().child(
                        ui::button("done", "Done", ButtonKind::Primary, true)
                            .tip(
                                Tooltip::new("Close this summary")
                                    .keys(&[&self.key_hint(Scope::Dialog, Key::Confirm)])
                                    .build(),
                            )
                            .on_click(cx.listener(|app, _: &ClickEvent, _, cx| {
                                app.overlays.dialog = None;
                                cx.notify();
                            })),
                    ),
                ),
        };
        Some(
            div()
                .id("scrim")
                .absolute()
                .inset_0()
                .flex()
                .items_center()
                .justify_center()
                .bg(theme::scrim())
                .occlude()
                .child(body)
                .into_any_element(),
        )
    }

    /// The floating bar that sums up the selection and deletes it, over the bottom of the list.
    pub(super) fn render_summary(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
        let (stats, shown) = self.session.flow.bar()?;
        let total = stats.total();
        let count = total.all.count;
        let review = total.review.count;
        let mode = self.config.delete.mode;
        let lasting = lasting(&stats, mode);
        let trash = self.trashes(&stats);
        let note = match (trash, lasting) {
            (false, _) => "deleted for good".to_owned(),
            (true, 0) => "moved to the trash".to_owned(),
            (true, lasting) => format!(
                "{} to the trash, {} deleted for good",
                count - lasting,
                plural(
                    lasting,
                    if mode == DeleteMode::Trash {
                        "toolchain, Docker or trash item"
                    } else {
                        "item"
                    }
                )
            ),
        };
        let ready = self.report().is_some() && !self.busy();
        let lock = self.trash_lock();
        let bar = floating(div().id("summary-bar"))
            .debug_selector(|| "summary-bar".to_owned())
            .flex()
            .items_center()
            .gap(unit(space::L))
            .min_w(unit(size::SUMMARY))
            .max_w_full()
            .p(unit(space::S))
            .when(shown < 1.0, |this| {
                this.opacity(shown)
                    .relative()
                    .top(unit(space::M * (1.0 - shown)))
            })
            .child(
                theme::mono(ui::tabular(div()))
                    .flex()
                    .flex_none()
                    .items_center()
                    .justify_center()
                    .h(unit(size::TILE))
                    .min_w(unit(size::TILE))
                    .px(unit(space::M))
                    .rounded(theme::radius_control())
                    .bg(theme::tile_selected())
                    .font_weight(FontWeight::SEMIBOLD)
                    .child(count.to_string()),
            )
            .child(
                ui::tabular(div())
                    .id("summary-selection")
                    .flex()
                    .flex_none()
                    .items_center()
                    .gap(unit(space::XS))
                    .text_color(theme::muted())
                    .tip(selection_details(stats))
                    .child("selected ·")
                    .child(
                        div()
                            .text_color(theme::text())
                            .font_weight(FontWeight::SEMIBOLD)
                            .child(theme::bytes(total.all.bytes)),
                    ),
            )
            .when(review > 0, |this| {
                this.child(
                    ui::tag(
                        "summary-review",
                        format!("{review} review"),
                        ui::Tone::Review,
                    )
                    .tip(tooltip::term(Term::Review)),
                )
            })
            .child(div().flex_1())
            .child(
                div()
                    .debug_selector(move || {
                        if trash && lasting == 0 {
                            "trash-note".to_owned()
                        } else {
                            "permanent-warning".to_owned()
                        }
                    })
                    .min_w_0()
                    .truncate()
                    .text_size(unit(font::SMALL))
                    .text_color(theme::faint())
                    .child(note),
            )
            .child(
                self.button(
                    "clear",
                    "Clear",
                    ButtonKind::Ghost,
                    ready,
                    cx,
                    |app, _, cx| {
                        if !app.busy() {
                            app.list.selection.clear();
                            app.close_remove(cx);
                            cx.notify();
                        }
                    },
                )
                .flex_none()
                .pr(unit(space::S))
                .child(ui::kbd(self.key_hint(Scope::Dialog, Key::Back)))
                .tip(tooltip::plain("Clear the selection in every tab")),
            )
            .child(
                self.button(
                    "trash",
                    self.delete_label(&stats),
                    if trash {
                        ButtonKind::Primary
                    } else {
                        ButtonKind::Danger
                    },
                    ready && lock.is_none(),
                    cx,
                    |app, _, cx| app.delete(None, cx),
                )
                .flex_none()
                .h(unit(size::TILE))
                .pl(unit(space::M))
                .pr(unit(space::S))
                .gap(unit(space::S))
                .map(|this| {
                    let ink = if trash {
                        theme::on_primary()
                    } else {
                        theme::on_danger()
                    };
                    let fill = if trash {
                        theme::kbd()
                    } else {
                        theme::kbd_on_danger()
                    };
                    this.child(ui::kbd_on(
                        self.key_hint(Scope::Dialog, Key::Confirm),
                        fill,
                        ink,
                    ))
                })
                .map(|this| match lock {
                    Some(reason) => this.tip(tooltip::plain(reason)),
                    None => this.tip(tooltip::term(Term::Trash)),
                }),
            );
        Some(bar.into_any_element())
    }

    /// Whether removing these items moves any of them to the trash. An empty selection answers
    /// for the setting alone.
    pub(super) fn trashes(&self, stats: &SelectionStats) -> bool {
        let mode = self.config.delete.mode;
        match stats.total().all.count {
            0 => mode == DeleteMode::Trash,
            count => lasting(stats, mode) < count,
        }
    }

    pub(super) fn delete_label(&self, stats: &SelectionStats) -> &'static str {
        if self.trashes(stats) {
            "Move to trash"
        } else {
            "Delete"
        }
    }
}

fn lasting(stats: &SelectionStats, mode: DeleteMode) -> usize {
    Source::ALL
        .into_iter()
        .filter(|source| !source.trashed(mode))
        .map(|source| stats.source(source).all.count)
        .sum()
}

impl Finished {
    fn summary(&self) -> String {
        let deleted = self.removed - self.trashed;
        let freed = theme::bytes(self.removed_bytes - self.trashed_bytes);
        let trashed = format!(
            "{} moved to the trash, {}",
            plural(self.trashed, "item"),
            theme::bytes(self.trashed_bytes)
        );
        match (self.trashed, deleted) {
            (0, _) => format!("{} deleted, {freed} freed", plural(deleted, "item")),
            (_, 0) => trashed,
            _ => format!(
                "{trashed}. {} deleted, {freed} freed",
                plural(deleted, "item")
            ),
        }
    }
}

fn selection_details(
    stats: SelectionStats,
) -> impl Fn(&mut Window, &mut App) -> gpui::AnyView + use<> {
    move |window, cx| {
        let line = |tally: Tally| format!("{}, {}", tally.count, theme::bytes(tally.bytes));
        let total = stats.total();
        Tooltip::details("Selection")
            .row("safe", line(total.safe))
            .row("review", line(total.review))
            .row(
                "Project artifacts",
                line(stats.source(Source::Artifact).all),
            )
            .row("Caches", line(stats.source(Source::Cache).all))
            .row("Toolchains", line(stats.source(Source::Toolchain).all))
            .row("Docker", line(stats.source(Source::Docker).all))
            .row("Trash", line(stats.source(Source::Trash).all))
            .row("Large files", line(stats.source(Source::Big).all))
            .build()(window, cx)
    }
}

/// The look shared by the bars that float over the bottom of the list: the selection summary,
/// the toast and the branch confirmation.
pub(super) fn floating(bar: Stateful<Div>) -> Stateful<Div> {
    bar.rounded(theme::radius_dialog())
        .bg(theme::elevated())
        .border_1()
        .border_color(theme::border_strong())
        .shadow(vec![
            BoxShadow {
                color: theme::shadow(),
                offset: point(px(0.), px(space::M)),
                blur_radius: px(space::XXL),
                spread_radius: px(0.),
            },
            BoxShadow {
                color: theme::shadow_contact(),
                offset: point(px(0.), px(size::HAIR)),
                blur_radius: px(space::XXS),
                spread_radius: px(0.),
            },
        ])
        .occlude()
}