kuizer-gui 0.3.0

Desktop app for kuizer, a keyboard-driven PC cleaner that also deeply cleans developer artifacts, caches, toolchains, Docker and duplicates, built on GPUI
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
use super::*;

impl Kuizer {
    /// @name Kuizer::find_duplicates
    /// @description Starts a duplicate search over the scanned folders beside the results on
    /// screen, and puts what it finds into the Duplicates section when it is done. Running it
    /// while a search is going stops that search instead.
    ///
    /// @example
    /// app.find_duplicates(cx);
    pub(super) fn find_duplicates(&mut self, cx: &mut Context<Self>) {
        if self.session.search.is_some() {
            self.stop_duplicates(cx);
            return;
        }
        if self.report().is_none() {
            return;
        }
        self.session.search_error = None;
        let (sender, mut receiver) = mpsc::unbounded();
        let config = self.config.clone();
        let roots = self.session.roots.clone();
        let options = self.session.options.clone();
        let snapshots = self.session.snapshots.clone();
        let excluded = self.session.excluded.clone();
        let cancel = Cancel::new();
        let worker_cancel = cancel.clone();
        let spawned = spawn_worker("kuizer-gui-duplicates", move || {
            let mut told: Option<Instant> = None;
            let mut found =
                model::find_duplicates(&config, &roots, &options, &worker_cancel, |stage| {
                    let quiet = matches!(stage, dupes::Stage::Walking { .. })
                        && told.is_some_and(|told| told.elapsed() < POLL);
                    if !quiet {
                        told = Some(Instant::now());
                        let _ = sender.unbounded_send(Searched::Stage(stage));
                    }
                });
            if worker_cancel.is_cancelled() {
                return;
            }
            let staged = found.as_ref().ok().map(|found| {
                let duplicate_options = dupes::Options::from_config(&options.apply(&config));
                snapshots.stage_duplicates(&roots, duplicate_options, found)
            });
            if let Ok(found) = &mut found {
                model::drop_duplicate_paths(found, &excluded);
            }
            let _ = sender.unbounded_send(Searched::Done(found));
            if let Some(staged) = staged {
                staged.save();
            }
        });
        let excluded_count = self.session.excluded.len();
        if let Err(error) = spawned {
            self.session.search_error = Some(error);
            cx.notify();
            return;
        }
        let task = cx.spawn(async move |this, cx| {
            while let Some(first) = receiver.next().await {
                let mut last = first;
                while let Ok(next) = receiver.try_recv() {
                    last = next;
                }
                let done = matches!(last, Searched::Done(_));
                let updated = this.update(cx, |app, cx| app.searched(last, cx));
                if done || updated.is_err() {
                    return;
                }
            }
            let _ = this.update(cx, |app, cx| {
                app.searched(
                    Searched::Done(Err("the duplicate search stopped unexpectedly".to_owned())),
                    cx,
                );
            });
        });
        self.session.search = Some(Search {
            roots: self.session.roots.clone(),
            excluded: excluded_count,
            stage: None,
            cancel,
            _task: task,
        });
        cx.notify();
    }

    /// @name Kuizer::stop_duplicates
    /// @description Cancels the running duplicate search. Its worker stops reading within one
    /// file or one MiB, saves nothing, and the Duplicates section goes back to offering a search.
    ///
    /// @example
    /// app.stop_duplicates(cx);
    pub(super) fn stop_duplicates(&mut self, cx: &mut Context<Self>) {
        if self.session.search.take().is_some() {
            cx.notify();
        }
    }

    pub(super) fn searched(&mut self, searched: Searched, cx: &mut Context<Self>) {
        let Some(search) = &mut self.session.search else {
            return;
        };
        match searched {
            Searched::Stage(stage) => search.stage = Some(stage),
            Searched::Done(found) => {
                let roots = std::mem::take(&mut search.roots);
                let excluded = search.excluded;
                self.session.search = None;
                match found {
                    Ok(found) => self.show_duplicates(&roots, found, excluded, cx),
                    Err(error) => self.session.search_error = Some(error),
                }
            }
        }
        cx.notify();
    }

    /// Puts a duplicate search result into the report on screen. The worker already left out
    /// the paths excluded before it started, the first `excluded` of them, so only paths
    /// excluded since are filtered here.
    pub(super) fn show_duplicates(
        &mut self,
        roots: &[PathBuf],
        mut found: Duplicates,
        excluded: usize,
        cx: &mut Context<Self>,
    ) {
        if let Phase::Ready(report) = &mut self.session.phase
            && report.roots == roots
        {
            model::drop_duplicate_paths(
                &mut found,
                self.session.excluded.get(excluded..).unwrap_or(&[]),
            );
            if let Some(old) = report.duplicates.replace(found) {
                cx.background_spawn(async move { drop(old) }).detach();
            }
            self.session.report_generation += 1;
        }
    }

    /// Reads the duplicates the last search under these folders found, off the UI thread, when
    /// the Duplicates section is opened and the report on screen has none yet.
    pub(super) fn load_duplicates(&mut self, cx: &mut Context<Self>) {
        let Some(report) = self.report() else {
            return;
        };
        if report.duplicates.is_some() || self.session.search.is_some() {
            return;
        }
        let roots = report.roots.clone();
        let snapshots = self.session.snapshots.clone();
        let options = dupes::Options::from_config(&self.session.options.apply(&self.config));
        let excluded = self.session.excluded.clone();
        let excluded_count = excluded.len();
        let spawned = spawn_worker("kuizer-gui-saved-duplicates", move || {
            let mut found = snapshots.load_duplicates(&roots, options);
            if let Some(found) = &mut found {
                model::drop_duplicate_paths(found, &excluded);
            }
            found
        });
        let receiver = match spawned {
            Ok(receiver) => receiver,
            Err(error) => {
                self.tell(
                    Notice::Failed(format!("Could not read the saved duplicates: {error}")),
                    cx,
                );
                return;
            }
        };
        let roots = self.session.roots.clone();
        cx.spawn(async move |this, cx| {
            if let Ok(Some(found)) = receiver.await {
                let _ = this.update(cx, |app, cx| {
                    if app.session.search.is_none()
                        && app
                            .report()
                            .is_some_and(|report| report.duplicates.is_none())
                    {
                        app.show_duplicates(&roots, found, excluded_count, cx);
                        cx.notify();
                    }
                });
            }
        })
        .detach();
    }

    pub(super) fn render_duplicate_search(&self, cx: &mut Context<Self>) -> AnyElement {
        let (text, label) = match (&self.session.search, &self.session.search_error) {
            (Some(search), _) => (
                match search.stage {
                    None => "Starting the duplicate search".to_owned(),
                    Some(dupes::Stage::Walking { files }) => {
                        format!("Collecting files, {} so far", activity::grouped(files))
                    }
                    Some(dupes::Stage::Hashing { files }) => {
                        format!(
                            "Hashing {} files of equal size",
                            activity::grouped(files as u64)
                        )
                    }
                    Some(dupes::Stage::Verifying { groups }) => format!(
                        "Comparing {} groups byte by byte",
                        activity::grouped(groups as u64)
                    ),
                },
                "Stop the search",
            ),
            (None, Some(error)) => (
                format!("The duplicate search failed: {error}"),
                "Find duplicates",
            ),
            (None, None) => (
                "Duplicate files are found on request. It reads every file, so it takes a while"
                    .to_owned(),
                "Find duplicates",
            ),
        };
        let tip = if self.session.search.is_some() {
            Tooltip::new("Stop the search. Nothing it found so far is kept")
                .keys(&[&self.hint(&Command::StopDuplicates)])
                .build()
        } else {
            Tooltip::new("Hash files under the scanned folders to find identical copies")
                .keys(&[&self.hint(&Command::FindDuplicates)])
                .build()
        };
        centered(
            div()
                .debug_selector(|| "duplicate-search".to_owned())
                .flex()
                .flex_col()
                .items_center()
                .gap(unit(space::L))
                .child(ui::empty(text))
                .child(
                    self.button(
                        "find-duplicates",
                        label,
                        ButtonKind::Secondary,
                        true,
                        cx,
                        |app, _, cx| {
                            app.find_duplicates(cx);
                        },
                    )
                    .tip(tip),
                ),
        )
    }

    pub(super) fn render_duplicates(&self, cx: &mut Context<Self>) -> AnyElement {
        let Some(report) = self.report() else {
            return div().into_any_element();
        };
        let Some(found) = &report.duplicates else {
            return self.render_duplicate_search(cx);
        };
        let wasted = found.reclaimable();
        let copies: usize = found.groups.iter().map(|group| group.members.len()).sum();
        let toolbar = self
            .list_toolbar(cx)
            .child(div().flex_1())
            .child(self.tally(Tab::Duplicates, None));
        let stats = div()
            .flex()
            .flex_wrap()
            .flex_none()
            .gap(unit(space::L))
            .p(unit(space::GUTTER))
            .child(
                ui::stat(
                    "Reclaimable",
                    theme::bytes(wasted),
                    "by keeping one copy of each",
                )
                .id("stat-reclaimable")
                .tip(tooltip::term(Term::Reclaimable)),
            )
            .child(
                ui::stat(
                    "Groups",
                    found.groups.len().to_string(),
                    format!("{copies} files in total"),
                )
                .id("stat-groups")
                .tip(tooltip::term(Term::Groups)),
            )
            .child(
                ui::stat(
                    "Files compared",
                    found.files.to_string(),
                    format!("in {:.1}s", found.duration.as_secs_f32()),
                )
                .id("stat-compared")
                .tip(tooltip::term(Term::FilesCompared)),
            );
        let header = table_header()
            .child(div().flex_1().child("FILE"))
            .child(head(col::L, "Changed", Term::Changed).text_right());
        let count = self.listed(Tab::Duplicates).lines.len();
        let list = self
            .table_list(
                "duplicates",
                Tab::Duplicates,
                count,
                |app, range, cx| app.duplicate_lines(range, cx),
                cx,
            )
            .debug_selector(|| "duplicate-list".to_owned());
        let body = div()
            .flex()
            .flex_col()
            .size_full()
            .child(stats)
            .child(table(
                header,
                if count == 0 {
                    empty_list(
                        Tab::Duplicates,
                        found.groups.len(),
                        "No duplicate files found",
                        "No duplicates match this filter",
                    )
                } else {
                    list.into_any_element()
                },
            ))
            .into_any_element();
        framed(toolbar, body)
    }

    fn duplicate_lines(&self, range: Range<usize>, cx: &mut Context<Self>) -> Vec<Stateful<Div>> {
        let Some(report) = self.report() else {
            return Vec::new();
        };
        let Some(found) = &report.duplicates else {
            return Vec::new();
        };
        let largest = found
            .groups
            .first()
            .map_or(0, kuizer::dupes::Group::reclaimable);
        let listed = self.listed(Tab::Duplicates);
        let cursor = self.cursor_target();
        let line = |id: (&'static str, usize)| {
            ui::tabular(div())
                .id(id)
                .flex()
                .items_center()
                .gap(unit(space::L))
                .w_full()
                .h(unit(size::row()))
                .px(unit(space::GUTTER))
        };
        range
            .filter_map(|at| match *listed.lines.get(at)? {
                Line::Group(index) => {
                    let group = found.groups.get(index)?;
                    let label = format!(
                        "{} copies of {}{}",
                        group.members.len(),
                        theme::bytes(group.size),
                        if group.verified {
                            ""
                        } else {
                            ", not byte-verified"
                        }
                    );
                    Some(
                        line(("duplicate-group", index))
                            .bg(theme::elevated())
                            .tip(group_details(group))
                            .child(
                                div()
                                    .flex_1()
                                    .min_w_0()
                                    .truncate()
                                    .font_weight(FontWeight::MEDIUM)
                                    .child(label),
                            )
                            .child(
                                div()
                                    .w(unit(col::L))
                                    .flex_none()
                                    .h(unit(size::TRACK))
                                    .rounded(theme::radius_bar())
                                    .bg(theme::track())
                                    .child(
                                        div()
                                            .h_full()
                                            .w(gpui::relative(theme::share(
                                                group.reclaimable(),
                                                largest,
                                            )))
                                            .min_w(unit(size::SLIVER))
                                            .rounded(theme::radius_bar())
                                            .bg(theme::bar()),
                                    ),
                            )
                            .child(
                                column(col::L)
                                    .text_right()
                                    .text_color(theme::muted())
                                    .child(format!(
                                        "{} reclaimable",
                                        theme::bytes(group.reclaimable())
                                    )),
                            ),
                    )
                }
                Line::Member(row) => {
                    let (index, position) = *listed.slots.get(row)?;
                    let member = found.groups.get(index)?.members.get(position)?;
                    let target = Target::Duplicate(member.path.clone());
                    let drawn = line(("duplicate", at))
                        .text_color(theme::muted())
                        .debug_selector(move || format!("duplicate-{index}-{position}"));
                    Some(
                        self.menu_row(drawn, target, cursor.as_ref(), cx)
                            .child(
                                div()
                                    .id(("duplicate-path", at))
                                    .flex_1()
                                    .min_w_0()
                                    .truncate()
                                    .pl(unit(space::L))
                                    .tip(tooltip::path(&member.path))
                                    .child(model::short_path(&member.path, &report.roots)),
                            )
                            .child(
                                column(col::L)
                                    .text_right()
                                    .text_color(theme::faint())
                                    .child(theme::age(member.modified)),
                            ),
                    )
                }
            })
            .collect()
    }
}

pub(super) fn group_details(
    group: &kuizer::dupes::Group,
) -> impl Fn(&mut Window, &mut App) -> gpui::AnyView + use<> {
    let details = Tooltip::details("Duplicate group")
        .row("Copies", group.members.len().to_string())
        .row("Size of each", theme::bytes(group.size))
        .row("Reclaimable", theme::bytes(group.reclaimable()));
    if group.verified {
        details.build()
    } else {
        details.note(Term::Unverified.text()).build()
    }
}