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
use gpui::{Animation, AnimationExt, Keystroke};

use super::*;

/// What the trash warning says, word for word.
pub(super) const TRASH_WARNING: &str = "Emptying the trash cannot be undone. Items kuizer moved there earlier can no longer be restored.";

/// What the confirmation says about cleaning system caches, word for word.
pub(super) const SYSTEM_NOTE: &str = "Each cache is cleaned by its package tool with the command below. A system dialog asks for your password when the tool needs administrator rights. Nothing goes to the trash.";

/// What the confirmation says about moving a disk explorer entry away, word for word.
pub(super) const EXPLORER_NOTE: &str =
    "It is moved to the trash, never deleted for good, so History can put it back.";

/// The longest count the confirmation takes, in digits.
const COUNT_DIGITS: usize = 7;

/// One disk explorer entry waiting to move to the trash, with the folder that holds it as the
/// guard root.
#[derive(Debug, Clone)]
pub(super) struct Explored {
    pub(super) candidate: Candidate,
    pub(super) root: PathBuf,
}

impl PartialEq for Explored {
    fn eq(&self, other: &Self) -> bool {
        self.candidate.path == other.candidate.path
            && self.candidate.identity == other.candidate.identity
            && self.root == other.root
    }
}

impl Eq for Explored {}

/// A removal waiting for its confirmation: the items, the exact commands system caches would
/// run, what has been typed so far and, when no count has to be typed, whether Cancel has the
/// keyboard.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(super) struct Ask {
    pub(super) keys: Vec<(Source, u64)>,
    pub(super) explored: Option<Explored>,
    pub(super) commands: Vec<String>,
    pub(super) bytes: u64,
    pub(super) generation: u64,
    pub(super) typed: String,
    pub(super) cancel: bool,
}

impl Ask {
    pub(super) fn has(&self, source: Source) -> bool {
        self.keys.iter().any(|(kind, _)| *kind == source)
    }

    fn count(&self) -> usize {
        self.keys.len() + usize::from(self.explored.is_some())
    }

    /// Whether the item count has to be typed before the removal can start.
    pub(super) fn counted(&self) -> bool {
        self.has(Source::Big) || self.explored.is_some()
    }

    /// Whether the confirmation would start the removal now.
    pub(super) fn ready(&self) -> bool {
        !self.counted() || self.typed == self.count().to_string()
    }
}

/// A removal confirmation that was just answered, sinking away over one motion step.
pub(super) struct Leaving {
    ask: Ask,
    at: Instant,
}

/// @name asks
/// @description Whether removing items of this source needs the inline confirmation: the trash
/// is emptied for good, large files are personal files and system caches run a package tool
/// that may ask for administrator rights.
///
/// @example
/// if keys.iter().any(|(source, _)| confirm::asks(*source)) { app.ask_remove(&keys, cx); }
pub(super) fn asks(source: Source) -> bool {
    matches!(source, Source::Trash | Source::Big | Source::System)
}

impl Kuizer {
    /// Opens the confirmation for these items in the footer, with the keyboard on Cancel or on
    /// the count field, so an Enter that follows at once removes nothing.
    pub(super) fn ask_remove(&mut self, keys: &[(Source, u64)], cx: &mut Context<Self>) {
        let mut seen = HashSet::new();
        let mut resolved = Vec::new();
        let mut bytes = 0u64;
        for &key in keys {
            if seen.insert(key)
                && let Some((_, candidate)) = self.item(key)
            {
                resolved.push(key);
                bytes += candidate.usage.allocated;
            }
        }
        if resolved.is_empty() {
            return;
        }
        let commands = self.system_commands(&resolved);
        self.open_ask(
            Ask {
                keys: resolved,
                explored: None,
                commands,
                bytes,
                generation: self.session.report_generation,
                typed: String::new(),
                cancel: true,
            },
            cx,
        );
    }

    /// Opens the confirmation that moves one disk explorer entry to the trash. The count has to
    /// be typed, as for large files.
    pub(super) fn ask_explored(&mut self, explored: Explored, cx: &mut Context<Self>) {
        let bytes = explored.candidate.usage.allocated;
        self.open_ask(
            Ask {
                keys: Vec::new(),
                explored: Some(explored),
                commands: Vec::new(),
                bytes,
                generation: self.session.report_generation,
                typed: String::new(),
                cancel: true,
            },
            cx,
        );
    }

    fn open_ask(&mut self, ask: Ask, cx: &mut Context<Self>) {
        self.overlays.menu = None;
        self.list.filtering = false;
        self.overlays.dialog = Some(Dialog::Remove(ask));
        cx.notify();
    }

    /// The exact command line each selected system cache runs from this window, which has no
    /// terminal and so asks for administrator rights through `pkexec` only.
    pub(super) fn system_commands(&self, keys: &[(Source, u64)]) -> Vec<String> {
        let Some(report) = self.report() else {
            return Vec::new();
        };
        let tools = kuizer::system::Tools::for_user();
        let session = kuizer::system::Session::graphical_only();
        keys.iter()
            .filter(|(source, _)| *source == Source::System)
            .filter_map(|&key| {
                let (position, _) = self.session.index.locate(report, key)?;
                let (item, _) = report.system.get(position)?;
                Some(
                    kuizer::system::preview_command(item, &self.config.system, &tools, &session)
                        .unwrap_or_else(|error| format!("{}: {error}", item.label)),
                )
            })
            .collect()
    }

    /// Drops any open removal confirmation without animating, used when the report or selection
    /// behind it changes.
    pub(super) fn drop_remove(&mut self) {
        if matches!(self.overlays.dialog, Some(Dialog::Remove(_))) {
            self.overlays.dialog = None;
        }
    }

    /// Closes the confirmation and removes nothing.
    pub(super) fn close_remove(&mut self, cx: &mut Context<Self>) {
        if !matches!(self.overlays.dialog, Some(Dialog::Remove(_))) {
            return;
        }
        if let Some(Dialog::Remove(ask)) = self.overlays.dialog.take() {
            self.leave_remove(ask, cx);
        }
        cx.notify();
    }

    /// Starts the removal when the confirmation is complete and still matches the current report.
    /// A count that does not match keeps the confirmation open.
    pub(super) fn accept_remove(&mut self, cx: &mut Context<Self>) {
        let Some(Dialog::Remove(ask)) = &self.overlays.dialog else {
            return;
        };
        if ask.generation != self.session.report_generation {
            self.close_remove(cx);
            return;
        }
        if !ask.ready() {
            return;
        }
        let Some(Dialog::Remove(ask)) = self.overlays.dialog.take() else {
            return;
        };
        let keys = ask.keys.clone();
        let explored = ask.explored.clone();
        self.leave_remove(ask, cx);
        match explored {
            Some(explored) => self.clean_explored(explored, cx),
            None => self.clean_keys(&keys, cx),
        }
        cx.notify();
    }

    fn leave_remove(&mut self, ask: Ask, cx: &mut Context<Self>) {
        if motion::reduced() {
            return;
        }
        let at = Instant::now();
        self.session.remove_leaving = Some(Leaving { ask, at });
        cx.spawn(async move |this, cx| {
            cx.background_executor().timer(motion::STEP).await;
            let _ = this.update(cx, |app, cx| {
                if app
                    .session
                    .remove_leaving
                    .as_ref()
                    .is_some_and(|leaving| leaving.at == at)
                {
                    app.session.remove_leaving = None;
                    cx.notify();
                }
            });
        })
        .detach();
    }

    /// Keys while the confirmation is open. With a count to type, digits and Backspace edit
    /// it and motions are off; otherwise the focus keys move between Cancel and the action.
    /// A held key never confirms.
    pub(super) fn remove_confirm_key(
        &mut self,
        keystroke: &Keystroke,
        repeat: bool,
        cx: &mut Context<Self>,
    ) {
        let action = self
            .keymap
            .lookup(Scope::Dialog, commands::stroke(keystroke));
        let Some(Dialog::Remove(ask)) = &mut self.overlays.dialog else {
            return;
        };
        match action {
            Some(Key::Back) => self.close_remove(cx),
            Some(Key::Confirm) if !ask.counted() && ask.cancel => self.close_remove(cx),
            Some(Key::Confirm) => {
                if !repeat {
                    self.accept_remove(cx);
                }
            }
            Some(Key::DialogToggle) if !ask.counted() => {
                ask.cancel = !ask.cancel;
                cx.notify();
            }
            _ if ask.counted() => {
                let mut typed = ask.typed.clone();
                if field::edit(&self.keymap, &mut typed, keystroke, field::WORDS, || None)
                    && typed.len() <= COUNT_DIGITS
                    && typed.chars().all(|ch| ch.is_ascii_digit())
                {
                    ask.typed = typed;
                    cx.notify();
                }
            }
            _ => {}
        }
    }

    /// The confirmation floating over the bottom of the list, right above the selection
    /// summary: it rises in when asked and sinks away once answered.
    pub(super) fn render_remove_confirm(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
        let (ask, open) = match (&self.overlays.dialog, &self.session.remove_leaving) {
            (Some(Dialog::Remove(ask)), _) => (ask, true),
            (_, Some(leaving)) => (&leaving.ask, false),
            _ => return None,
        };
        let bar = self.remove_bar(ask, open, cx);
        if motion::reduced() {
            return Some(bar.into_any_element());
        }
        Some(
            bar.with_animation(
                if open {
                    "remove-confirm-in"
                } else {
                    "remove-confirm-out"
                },
                Animation::new(motion::STEP).with_easing(motion::ease_out),
                move |bar, progress| {
                    let shown = if open { progress } else { 1.0 - progress };
                    bar.opacity(shown)
                        .relative()
                        .top(unit(space::M * (1.0 - shown)))
                },
            )
            .into_any_element(),
        )
    }

    fn remove_bar(&self, ask: &Ask, open: bool, cx: &mut Context<Self>) -> Stateful<Div> {
        let ring = || ring::outline(None, Rc::new(Cell::new(false)));
        let count = ask.count();
        let (trash, big) = (ask.has(Source::Trash), ask.has(Source::Big));
        let system = ask.has(Source::System);
        let only = ask.keys.iter().all(|(source, _)| *source == Source::Trash)
            || ask.keys.iter().all(|(source, _)| *source == Source::Big)
            || ask.keys.iter().all(|(source, _)| *source == Source::System);
        let size = theme::bytes(ask.bytes);
        let explored = ask.explored.as_ref().map(|explored| {
            explored.candidate.path.file_name().map_or_else(
                || display_path(&explored.candidate.path),
                |name| name.to_string_lossy().into_owned(),
            )
        });
        let title = match (&explored, trash, big, system) {
            (Some(name), ..) => format!("Move {name} to the trash, {size}?"),
            (None, true, false, false) if only => format!("Empty the trash, {size}?"),
            (None, false, true, false) if only => {
                format!("Move {} to the trash, {size}?", plural(count, "large file"))
            }
            (None, false, false, true) if only => {
                format!("Clean {}, {size}?", plural(count, "system cache"))
            }
            _ => format!("Remove {}, {size}?", plural(count, "item")),
        };
        let action = match (explored.is_some(), trash, big, system) {
            (true, ..) => "Move to trash",
            (false, true, false, false) if only => "Empty the trash",
            (false, false, true, false) if only => "Move to trash",
            (false, false, false, true) if only => "Clean",
            _ => "Remove",
        };
        let all_trashed = ask.explored.is_some()
            || ask
                .keys
                .iter()
                .all(|(source, _)| source.trashed(self.config.delete.mode));
        let counted = ask.counted();
        let ready = ask.ready();
        let focus_cancel = open && !counted && ask.cancel;
        let focus_action = open && !counted && !ask.cancel;
        clean::floating(div().id("remove-confirm"))
            .debug_selector(|| "remove-confirm".to_owned())
            .flex()
            .flex_col()
            .gap(unit(space::M))
            .w(unit(size::SUMMARY))
            .max_w_full()
            .p(unit(space::L))
            .child(div().font_weight(FontWeight::SEMIBOLD).child(title))
            .when(trash, |this| {
                this.child(
                    div()
                        .debug_selector(|| "trash-warning".to_owned())
                        .text_size(unit(font::SMALL))
                        .text_color(theme::danger())
                        .child(TRASH_WARNING),
                )
            })
            .when(system, |this| {
                this.child(
                    div()
                        .debug_selector(|| "system-note".to_owned())
                        .text_size(unit(font::SMALL))
                        .text_color(theme::muted())
                        .child(SYSTEM_NOTE),
                )
                .child(
                    theme::mono(div())
                        .debug_selector(|| "system-commands".to_owned())
                        .flex()
                        .flex_col()
                        .gap(unit(space::XXS))
                        .p(unit(space::S))
                        .rounded(theme::radius_control())
                        .bg(theme::panel())
                        .border_1()
                        .border_color(theme::border())
                        .text_size(unit(font::SMALL))
                        .children(
                            ask.commands
                                .iter()
                                .map(|command| div().truncate().child(command.clone())),
                        ),
                )
            })
            .when(ask.explored.is_some(), |this| {
                this.child(
                    div()
                        .debug_selector(|| "explorer-note".to_owned())
                        .text_size(unit(font::SMALL))
                        .text_color(theme::muted())
                        .child(EXPLORER_NOTE),
                )
            })
            .when(big, |this| {
                this.child(
                    div()
                        .debug_selector(|| "large-files-note".to_owned())
                        .text_size(unit(font::SMALL))
                        .text_color(theme::muted())
                        .child(
                            "Large files are personal files. They are moved to the trash, never deleted for good, so History can put them back.",
                        ),
                )
            })
            .when(counted, |this| {
                this.child(
                    div()
                        .flex()
                        .items_center()
                        .gap(unit(space::M))
                        .text_size(unit(font::SMALL))
                        .text_color(theme::muted())
                        .child(format!("Type {count} to confirm"))
                        .child(
                            field::view("remove-count", &ask.typed, count.to_string(), open)
                                .debug_selector(|| "remove-count".to_owned())
                                .w(unit(col::S))
                                .text_color(theme::text()),
                        )
                        .when(!ask.typed.is_empty() && !ready, |this| {
                            this.child(
                                div()
                                    .debug_selector(|| "remove-count-wrong".to_owned())
                                    .text_color(theme::danger())
                                    .child(format!("The count is {count}")),
                            )
                        }),
                )
            })
            .child(
                div()
                    .flex()
                    .justify_end()
                    .gap(unit(space::M))
                    .child(
                        ui::button("remove-cancel", "Cancel", ButtonKind::Secondary, open)
                            .debug_selector(|| "cancel-remove".to_owned())
                            .tip(
                                Tooltip::new("Keep everything")
                                    .keys(&[&self.key_hint(Scope::Dialog, Key::Back)])
                                    .build(),
                            )
                            .when(focus_cancel, |this| this.child(ring()))
                            .when(open, |this| {
                                this.on_click(cx.listener(|app, _: &ClickEvent, _, cx| {
                                    app.close_remove(cx);
                                }))
                            }),
                    )
                    .child(
                        ui::button(
                            "remove-accept",
                            action,
                            if all_trashed {
                                ButtonKind::Primary
                            } else {
                                ButtonKind::Danger
                            },
                            open && ready,
                        )
                        .debug_selector(|| "confirm-remove".to_owned())
                        .tip(
                            Tooltip::new(if counted && !ready {
                                "Type the item count first"
                            } else {
                                "Start the removal"
                            })
                            .keys(&[&self.key_hint(Scope::Dialog, Key::Confirm)])
                            .build(),
                        )
                        .when(focus_action, |this| this.child(ring()))
                        .when(open && ready, |this| {
                            this.on_click(cx.listener(|app, _: &ClickEvent, _, cx| {
                                app.accept_remove(cx);
                            }))
                        }),
                    ),
            )
    }
}