use super::*;
impl Kuizer {
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();
}
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();
}
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;
}
}
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()
}
}