use std::cell::RefCell;
use gpui::UniformList;
use kuizer::big::FileKind;
use kuizer::caches::KnownCache;
use kuizer::catalog::Group;
use kuizer::docker;
use kuizer::system;
use kuizer::toolchains::Toolchain;
use crate::stats::developer;
use super::explorer;
use super::*;
pub(super) type Slot = (usize, usize);
struct SectionPage {
tab: Tab,
id: &'static str,
selector: &'static str,
total: usize,
banner: Option<String>,
footer: Option<String>,
empty: SharedString,
filtered: &'static str,
}
#[derive(Clone, Copy)]
pub(super) enum Line {
Group(usize),
Member(usize),
}
#[derive(Clone, Default)]
pub(super) struct Listed {
pub slots: Rc<[Slot]>,
pub targets: Rc<[Target]>,
pub bytes: u64,
pub lines: Rc<[Line]>,
pub line_of: Rc<[usize]>,
}
struct ListKey {
generation: u64,
len: usize,
text: String,
narrow: Narrow,
}
#[derive(Default)]
pub(super) struct Lists(RefCell<HashMap<Tab, (ListKey, Listed)>>);
pub(super) fn cache_matches(
needle: Option<&str>,
cache: &KnownCache,
candidate: &Candidate,
) -> bool {
found(
needle,
&[
candidate.path.to_string_lossy().as_ref(),
&cache.name,
&cache.tool,
group_label(cache.group),
],
)
}
fn group_label(group: Group) -> &'static str {
match group {
Group::Developer => "Developer",
Group::Apps => "Apps",
Group::Browsers => "Browsers",
Group::System => "System",
}
}
fn system_matches(needle: Option<&str>, item: &system::Item) -> bool {
found(
needle,
&[
item.manager.name(),
item.id.as_str(),
item.label.as_str(),
item.note.as_str(),
],
)
}
fn download(candidate: &Candidate) -> bool {
candidate.rule.name == "old-download"
}
fn large_folder(candidate: &Candidate) -> bool {
candidate.rule.name == kuizer::big::LARGE_FOLDER_RULE
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
pub(super) enum LargeFilter {
#[default]
All,
Folders,
Downloads,
Kind(FileKind),
}
impl LargeFilter {
pub(super) fn label(self) -> &'static str {
match self {
Self::All => "All",
Self::Folders => "Folders",
Self::Downloads => "Downloads",
Self::Kind(kind) => kind.label(),
}
}
pub(super) fn shows(self, candidate: &Candidate) -> bool {
match self {
Self::All => true,
Self::Folders => large_folder(candidate),
Self::Downloads => download(candidate),
Self::Kind(kind) => {
!large_folder(candidate) && FileKind::classify(&candidate.path) == kind
}
}
}
}
pub(super) fn large_filters(big: &[Candidate]) -> Vec<(LargeFilter, usize)> {
let mut chips = vec![(LargeFilter::All, big.len())];
let folders = big
.iter()
.filter(|candidate| large_folder(candidate))
.count();
if folders > 0 {
chips.push((LargeFilter::Folders, folders));
}
let downloads = big.iter().filter(|candidate| download(candidate)).count();
if downloads > 0 {
chips.push((LargeFilter::Downloads, downloads));
}
let mut kinds = [0usize; FileKind::ALL.len()];
for candidate in big {
if large_folder(candidate) {
continue;
}
let kind = FileKind::classify(&candidate.path);
if let Some(at) = FileKind::ALL.iter().position(|known| *known == kind) {
kinds[at] += 1;
}
}
chips.extend(
FileKind::ALL
.into_iter()
.zip(kinds)
.filter(|(_, count)| *count > 0)
.map(|(kind, count)| (LargeFilter::Kind(kind), count)),
);
chips
}
pub(super) fn issue_at(report: &Report, slot: Slot) -> Option<&scan::Issue> {
match slot.1 {
0 => report.issues.get(slot.0),
_ => report.trash_issues.get(slot.0),
}
}
pub(super) fn toolchain_matches(
needle: Option<&str>,
toolchain: &Toolchain,
candidate: &Candidate,
) -> bool {
found(
needle,
&[
candidate.path.to_string_lossy().as_ref(),
toolchain.tool.name(),
toolchain.runtime.as_str(),
toolchain.version.as_str(),
],
)
}
pub(super) fn docker_matches(
needle: Option<&str>,
item: &docker::Item,
candidate: &Candidate,
) -> bool {
found(
needle,
&[
candidate.path.to_string_lossy().as_ref(),
item.engine.as_str(),
item.object.name(),
item.label.as_str(),
item.note.as_str(),
],
)
}
pub(super) const SYSTEM_HINT: &str = "Selected caches are cleaned by their own package tool. A system dialog asks for your password when a tool needs administrator rights";
fn list_len(report: &Report, tab: Tab) -> usize {
match tab {
Tab::Overview | Tab::Artifacts | Tab::DiskUsage => 0,
Tab::Caches | Tab::AppCaches => report.caches.len(),
Tab::Toolchains => report.toolchains.len(),
Tab::Docker => report.docker.len(),
Tab::Repos => report.repos.len(),
Tab::Trash => report.trash.len(),
Tab::System => report.system.len(),
Tab::LargeFiles => report.big.len(),
Tab::Duplicates => report
.duplicates
.as_ref()
.map_or(0, |found| found.groups.len()),
Tab::Issues => report.issues.len() + report.trash_issues.len(),
Tab::History => report
.history
.as_ref()
.map_or(0, |view| view.history.runs.len()),
}
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub(super) struct Narrow {
pub(super) safety: Option<Safety>,
pub(super) large: LargeFilter,
pub(super) folder: Option<PathBuf>,
}
fn list_rows(report: &Report, tab: Tab, needle: Option<&str>, narrow: &Narrow) -> Listed {
let safety = narrow.safety;
let mut slots: Vec<Slot> = Vec::new();
let mut targets: Vec<Target> = Vec::new();
let mut bytes = 0;
let mut lines: Vec<Line> = Vec::new();
let mut line_of: Vec<usize> = Vec::new();
let graded =
|candidate: &Candidate| safety.is_none_or(|safety| candidate.rule.safety == safety);
match tab {
Tab::Overview | Tab::Artifacts => {}
Tab::DiskUsage => {
if let Some(tree) = &report.usage {
let children = explorer::children(tree, narrow.folder.as_deref());
for (at, node) in children.iter().enumerate() {
if found_path(needle, &node.path) {
slots.push((at, 0));
targets.push(Target::Row(Tab::DiskUsage, node.path.clone()));
bytes += node.allocated;
}
}
}
}
Tab::Caches => {
for (at, (cache, candidate)) in report.caches.iter().enumerate() {
if developer(cache) && graded(candidate) && cache_matches(needle, cache, candidate)
{
slots.push((at, 0));
targets.push(Target::Item(
Source::Cache,
candidate.id,
candidate.path.clone(),
));
bytes += candidate.usage.allocated;
}
}
}
Tab::AppCaches => {
for (at, (cache, candidate)) in report.caches.iter().enumerate() {
if !developer(cache) && graded(candidate) && cache_matches(needle, cache, candidate)
{
slots.push((at, 0));
targets.push(Target::Item(
Source::Cache,
candidate.id,
candidate.path.clone(),
));
bytes += candidate.usage.allocated;
}
}
}
Tab::Trash => {
for (at, (_, candidate)) in report.trash.iter().enumerate() {
if found_path(needle, &candidate.path) {
slots.push((at, 0));
targets.push(Target::Item(
Source::Trash,
candidate.id,
candidate.path.clone(),
));
bytes += candidate.usage.allocated;
}
}
}
Tab::System => {
for (at, (item, candidate)) in report.system.iter().enumerate() {
if graded(candidate) && system_matches(needle, item) {
slots.push((at, 0));
targets.push(Target::Item(
Source::System,
candidate.id,
candidate.path.clone(),
));
bytes += candidate.usage.allocated;
}
}
}
Tab::LargeFiles => {
for (at, candidate) in report.big.iter().enumerate() {
let path = candidate.path.to_string_lossy();
let kind = if large_folder(candidate) {
"Folder"
} else {
FileKind::classify(&candidate.path).label()
};
let origin = if download(candidate) { "Download" } else { "" };
if narrow.large.shows(candidate) && found(needle, &[path.as_ref(), kind, origin]) {
slots.push((at, 0));
targets.push(Target::Item(
Source::Big,
candidate.id,
candidate.path.clone(),
));
bytes += candidate.usage.allocated;
}
}
}
Tab::Toolchains => {
for (at, (toolchain, candidate)) in report.toolchains.iter().enumerate() {
if graded(candidate) && toolchain_matches(needle, toolchain, candidate) {
slots.push((at, 0));
targets.push(Target::Item(
Source::Toolchain,
candidate.id,
candidate.path.clone(),
));
bytes += candidate.usage.allocated;
}
}
}
Tab::Docker => {
for (at, (item, candidate)) in report.docker.iter().enumerate() {
if graded(candidate) && docker_matches(needle, item, candidate) {
slots.push((at, 0));
targets.push(Target::Item(
Source::Docker,
candidate.id,
candidate.path.clone(),
));
bytes += candidate.usage.allocated;
}
}
}
Tab::Duplicates => {
let groups = report.duplicates.iter().flat_map(|found| &found.groups);
for (group_at, group) in groups.enumerate() {
let mut heading = Some(group_at);
for (member_at, member) in group.members.iter().enumerate() {
if found_path(needle, &member.path) {
if let Some(group_at) = heading.take() {
lines.push(Line::Group(group_at));
}
line_of.push(lines.len());
lines.push(Line::Member(slots.len()));
slots.push((group_at, member_at));
targets.push(Target::Duplicate(member.path.clone()));
}
}
}
}
Tab::Issues => {
let scan = report
.issues
.iter()
.enumerate()
.map(|(at, issue)| ((at, 0), issue));
let trash =
(report.trash_issues.iter().enumerate()).map(|(at, issue)| ((at, 1), issue));
for (slot, issue) in scan.chain(trash) {
let path = issue.path.to_string_lossy();
if found(needle, &[path.as_ref(), issue.message.as_str()]) {
slots.push(slot);
targets.push(Target::Issue(issue.path.clone()));
}
}
}
Tab::Repos => {
for (at, repository) in report.repos.iter().enumerate() {
if repos::repo_matches(needle, repository) {
slots.push((at, 0));
targets.push(Target::Repo(repository.root.clone()));
}
}
}
Tab::History => {
if let Ok(view) = &report.history {
let runs = view.history.runs.iter().enumerate().rev();
for (at, run) in runs.filter(|(_, run)| run.action == Action::Delete) {
if shows_run(needle, run) {
slots.push((at, 0));
targets.push(Target::Run(run.id, run.command.clone()));
}
}
}
}
}
Listed {
slots: slots.into(),
targets: targets.into(),
bytes,
lines: lines.into(),
line_of: line_of.into(),
}
}
impl Kuizer {
pub(super) fn listed(&self, tab: Tab) -> Listed {
let Some(report) = self.report() else {
return Listed::default();
};
let text = self.list.filters.get(&tab).map_or("", |text| text.trim());
let narrow = Narrow {
safety: self.list.safety.filter(|_| tab.grades()),
large: if tab == Tab::LargeFiles {
self.list.large
} else {
LargeFilter::All
},
folder: (tab == Tab::DiskUsage)
.then(|| self.explorer_folder())
.flatten(),
};
let (generation, len) = (self.session.report_generation, list_len(report, tab));
if let Some((key, listed)) = self.list.lists.0.borrow().get(&tab)
&& key.generation == generation
&& key.len == len
&& key.text == text
&& key.narrow == narrow
{
return listed.clone();
}
let needle = self.needle(tab);
let listed = list_rows(report, tab, needle.as_deref(), &narrow);
let key = ListKey {
generation,
len,
text: text.to_owned(),
narrow,
};
self.list
.lists
.0
.borrow_mut()
.insert(tab, (key, listed.clone()));
listed
}
pub(super) fn targets(&self, tab: Tab) -> Rc<[Target]> {
let Some(report) = self.report() else {
return Rc::default();
};
if tab != Tab::Artifacts {
return self.listed(tab).targets;
}
self.list
.rows
.iter()
.map(|&index| {
let candidate = &report.candidates[index];
Target::Item(Source::Artifact, candidate.id, candidate.path.clone())
})
.collect()
}
pub(super) fn list_scroll(&self, tab: Tab) -> Option<&UniformListScrollHandle> {
match tab {
Tab::Artifacts => Some(&self.list.artifact_scroll),
_ => self.list.list_scrolls.get(&tab),
}
}
pub(super) fn table_list(
&self,
id: &'static str,
tab: Tab,
count: usize,
rows: impl Fn(&mut Self, Range<usize>, &mut Context<Self>) -> Vec<Stateful<Div>> + 'static,
cx: &mut Context<Self>,
) -> UniformList {
uniform_list(
id,
count,
cx.processor(move |app, range: Range<usize>, _window, cx| rows(app, range, cx)),
)
.track_scroll(self.list_scroll(tab).cloned().unwrap_or_default())
.flex_1()
.w_full()
.when(!self.list.selection.is_empty(), |this| {
this.pb(unit(size::SUMMARY_HEIGHT + space::L))
})
}
fn section_page(
&self,
page: SectionPage,
header: Div,
rows: impl Fn(&mut Self, Range<usize>, &mut Context<Self>) -> Vec<Stateful<Div>> + 'static,
cx: &mut Context<Self>,
) -> AnyElement {
let listed = self.listed(page.tab);
let count = listed.slots.len();
let selector = page.selector;
let list = self
.table_list(page.id, page.tab, count, rows, cx)
.debug_selector(move || selector.to_owned());
div()
.flex()
.flex_col()
.size_full()
.child(
self.list_toolbar(cx)
.child(div().flex_1())
.child(self.tally(page.tab, Some(listed.bytes))),
)
.when_some(page.banner, |this, text| {
this.child(
div()
.px(unit(space::GUTTER))
.py(unit(space::S))
.text_color(theme::faint())
.child(text),
)
})
.child(table(
header,
if count == 0 {
empty_list(page.tab, page.total, page.empty, page.filtered)
} else {
list.into_any_element()
},
))
.when_some(page.footer, |this, text| {
this.child(
div()
.debug_selector(move || format!("{selector}-footer"))
.flex_none()
.px(unit(space::GUTTER))
.py(unit(space::S))
.text_size(unit(font::SMALL))
.text_color(theme::muted())
.child(text),
)
})
.into_any_element()
}
pub(super) fn render_caches(&self, apps: bool, cx: &mut Context<Self>) -> AnyElement {
let Some(report) = self.report() else {
return div().into_any_element();
};
let tab = if apps { Tab::AppCaches } else { Tab::Caches };
let header = table_header()
.child(div().w(unit(size::CHECK)))
.child(head(col::M, "Size", Term::Size).text_right())
.child(head(col::S, "Safety", Term::Safety))
.child(head(col::M, "Tool", Term::Tool))
.when(apps, |this| this.child(column(col::S).child("GROUP")))
.child(column(col::XXL).child("CACHE"))
.child(head(col::XS, "Changed", Term::Changed).text_right())
.child(div().flex_1().child("PATH"));
let total = report
.caches
.iter()
.filter(|(cache, _)| developer(cache) != apps)
.count();
let empty = match (report.options.caches, apps) {
(false, _) => "Caches were skipped for this scan",
(true, false) => "No developer caches found",
(true, true) => "No app or browser caches found",
};
self.section_page(
SectionPage {
tab,
id: if apps { "app-caches" } else { "caches" },
selector: if apps { "app-cache-list" } else { "cache-list" },
total,
banner: None,
footer: None,
empty: empty.into(),
filtered: "No caches match these filters",
},
header,
move |app, range, cx| app.cache_rows(tab, range, cx),
cx,
)
}
fn cache_rows(
&self,
tab: Tab,
range: Range<usize>,
cx: &mut Context<Self>,
) -> Vec<Stateful<Div>> {
let Some(report) = self.report() else {
return Vec::new();
};
let listed = self.listed(tab);
let cursor = self.cursor_target();
range
.filter_map(|row| {
let (cache, candidate) = report.caches.get(listed.slots.get(row)?.0)?;
Some(match tab {
Tab::AppCaches => {
self.app_cache_row(row, cache, candidate, cursor.as_ref(), cx)
}
_ => self.cache_row(row, cache, candidate, cursor.as_ref(), cx),
})
})
.collect()
}
fn cache_row(
&self,
index: usize,
cache: &KnownCache,
candidate: &Candidate,
cursor: Option<&Target>,
cx: &mut Context<Self>,
) -> Stateful<Div> {
let id = candidate.id;
let checked = self.list.selection.contains(&(Source::Cache, id));
let row =
table_row(("cache", id), checked).debug_selector(move || format!("cache-row-{index}"));
let target = Target::Item(Source::Cache, id, candidate.path.clone());
let look = self.look(Source::Cache, id, &candidate.path);
let row = self
.menu_row(row, target, cursor, cx)
.child(ui::check_mark(look.checked));
let ids = ["cache-size", "cache-safety", "cache-path"];
cache_cells(row, ids, cache, candidate, None).on_click(cx.listener(
move |app, event: &ClickEvent, _, cx| {
app.click_row(Source::Cache, id, event, cx);
},
))
}
fn app_cache_row(
&self,
index: usize,
cache: &KnownCache,
candidate: &Candidate,
cursor: Option<&Target>,
cx: &mut Context<Self>,
) -> Stateful<Div> {
let id = candidate.id;
let checked = self.list.selection.contains(&(Source::Cache, id));
let row = table_row(("app-cache", id), checked)
.debug_selector(move || format!("app-cache-row-{index}"));
let target = Target::Item(Source::Cache, id, candidate.path.clone());
let look = self.look(Source::Cache, id, &candidate.path);
let row = self
.menu_row(row, target, cursor, cx)
.child(ui::check_mark(look.checked));
let ids = ["app-cache-size", "app-cache-safety", "app-cache-path"];
cache_cells(row, ids, cache, candidate, Some(cache.group)).on_click(cx.listener(
move |app, event: &ClickEvent, _, cx| {
app.click_row(Source::Cache, id, event, cx);
},
))
}
pub(super) fn render_trash(&self, cx: &mut Context<Self>) -> AnyElement {
let Some(report) = self.report() else {
return div().into_any_element();
};
let header = table_header()
.child(div().w(unit(size::CHECK)))
.child(head(col::M, "Size", Term::Size).text_right())
.child(column(col::M).text_right().child("ITEMS"))
.child(div().flex_1().child("PATH"));
let empty = if report.options.trash {
"The trash is empty"
} else {
"The trash was skipped for this scan"
};
self.section_page(
SectionPage {
tab: Tab::Trash,
id: "trash",
selector: "trash-list",
total: report.trash.len(),
banner: None,
footer: None,
empty: empty.into(),
filtered: "No trash folders match this filter",
},
header,
|app, range, cx| app.trash_rows(range, cx),
cx,
)
}
fn trash_rows(&self, range: Range<usize>, cx: &mut Context<Self>) -> Vec<Stateful<Div>> {
let Some(report) = self.report() else {
return Vec::new();
};
let listed = self.listed(Tab::Trash);
let cursor = self.cursor_target();
range
.filter_map(|row| {
let (folder, candidate) = report.trash.get(listed.slots.get(row)?.0)?;
let id = candidate.id;
let checked = self.list.selection.contains(&(Source::Trash, id));
let line = table_row(("trash", id), checked)
.debug_selector(move || format!("trash-row-{row}"));
let target = Target::Item(Source::Trash, id, candidate.path.clone());
let look = self.look(Source::Trash, id, &candidate.path);
Some(
self.menu_row(line, target, cursor.as_ref(), cx)
.child(ui::check_mark(look.checked))
.child(size_cell(("trash-size", id), candidate))
.child(
column(col::M)
.text_right()
.text_color(theme::muted())
.child(plural(folder.items, "item")),
)
.child(path_cell(("trash-path", id), &candidate.path))
.on_click(cx.listener(move |app, event: &ClickEvent, _, cx| {
app.click_row(Source::Trash, id, event, cx);
})),
)
})
.collect()
}
pub(super) fn render_system(&self, cx: &mut Context<Self>) -> AnyElement {
let Some(report) = self.report() else {
return div().into_any_element();
};
let header = table_header()
.child(div().w(unit(size::CHECK)))
.child(head(col::M, "Size", Term::Size).text_right())
.child(head(col::S, "Safety", Term::Safety))
.child(column(col::M).child("PASSWORD"))
.child(column(col::XXL).child("NAME"))
.child(div().flex_1().child("NOTE"));
let empty = if !report.options.system {
"System caches were skipped for this scan".to_owned()
} else if report.system_issues.is_empty() {
"No system package caches found".to_owned()
} else {
report.system_issues.join(". ")
};
let banner = (!report.system.is_empty() && !report.system_issues.is_empty())
.then(|| report.system_issues.join(". "));
self.section_page(
SectionPage {
tab: Tab::System,
id: "system",
selector: "system-list",
total: report.system.len(),
banner,
footer: Some(SYSTEM_HINT.to_owned()),
empty: empty.into(),
filtered: "No system caches match this filter",
},
header,
|app, range, cx| app.system_rows(range, cx),
cx,
)
}
fn system_rows(&self, range: Range<usize>, cx: &mut Context<Self>) -> Vec<Stateful<Div>> {
let Some(report) = self.report() else {
return Vec::new();
};
let listed = self.listed(Tab::System);
let cursor = self.cursor_target();
range
.filter_map(|row| {
let (item, candidate) = report.system.get(listed.slots.get(row)?.0)?;
Some(self.system_row(row, item, candidate, cursor.as_ref(), cx))
})
.collect()
}
fn system_row(
&self,
index: usize,
item: &system::Item,
candidate: &Candidate,
cursor: Option<&Target>,
cx: &mut Context<Self>,
) -> Stateful<Div> {
let id = candidate.id;
let checked = self.list.selection.contains(&(Source::System, id));
let row = table_row(("system", id), checked)
.debug_selector(move || format!("system-row-{index}"));
let target = Target::Item(Source::System, id, candidate.path.clone());
let look = self.look(Source::System, id, &candidate.path);
let size = if item.size_known {
theme::bytes(item.bytes)
} else {
"Unknown".to_owned()
};
self.menu_row(row, target, cursor, cx)
.child(ui::check_mark(look.checked))
.child(
column(col::M)
.text_right()
.font_weight(FontWeight::MEDIUM)
.when(!item.size_known, |this| this.text_color(theme::faint()))
.child(size),
)
.child(column(col::S).flex().child(ui::safety_label(
("system-safety", id),
item.safety == Safety::Review,
)))
.child(
column(col::M)
.text_color(theme::muted())
.child(if item.needs_root { "Yes" } else { "No" }),
)
.child(
column(col::XXL)
.id(("system-name", id))
.truncate()
.tip(tooltip::plain(format!(
"{} {}",
item.manager.name(),
item.id
)))
.child(item.label.clone()),
)
.child(
div()
.flex_1()
.min_w_0()
.truncate()
.text_color(theme::muted())
.child(item.note.clone()),
)
.on_click(cx.listener(move |app, event: &ClickEvent, _, cx| {
app.click_row(Source::System, id, event, cx);
}))
}
pub(super) fn render_large_files(&self, cx: &mut Context<Self>) -> AnyElement {
let Some(report) = self.report() else {
return div().into_any_element();
};
let header = table_header()
.child(div().w(unit(size::CHECK)))
.child(head(col::M, "Size", Term::Size).text_right())
.child(column(col::XS).text_right().child("MODIFIED"))
.child(column(col::XL).child("KIND"))
.child(div().flex_1().child("PATH"));
let empty = if report.options.big {
"No large files or old downloads found. The window looks in the scanned folders and Downloads; kuizer big searches the whole home folder"
} else {
"Large files were skipped for this scan"
};
self.section_page(
SectionPage {
tab: Tab::LargeFiles,
id: "large-files",
selector: "large-list",
total: report.big.len(),
banner: None,
footer: None,
empty: empty.into(),
filtered: "No large files match this filter",
},
header,
|app, range, cx| app.large_rows(range, cx),
cx,
)
}
fn large_rows(&self, range: Range<usize>, cx: &mut Context<Self>) -> Vec<Stateful<Div>> {
let Some(report) = self.report() else {
return Vec::new();
};
let listed = self.listed(Tab::LargeFiles);
let cursor = self.cursor_target();
range
.filter_map(|row| {
let candidate = report.big.get(listed.slots.get(row)?.0)?;
let id = candidate.id;
let checked = self.list.selection.contains(&(Source::Big, id));
let line = table_row(("large", id), checked)
.debug_selector(move || format!("large-row-{row}"));
let target = Target::Item(Source::Big, id, candidate.path.clone());
let look = self.look(Source::Big, id, &candidate.path);
Some(
self.menu_row(line, target, cursor.as_ref(), cx)
.child(ui::check_mark(look.checked))
.child(size_cell(("large-size", id), candidate))
.child(
column(col::XS)
.text_right()
.text_color(theme::muted())
.child(theme::age(candidate.newest)),
)
.child(large_badges(id, candidate))
.child(path_cell(("large-path", id), &candidate.path))
.on_click(cx.listener(move |app, event: &ClickEvent, _, cx| {
app.click_row(Source::Big, id, event, cx);
})),
)
})
.collect()
}
pub(super) fn render_toolchains(&self, cx: &mut Context<Self>) -> AnyElement {
let Some(report) = self.report() else {
return div().into_any_element();
};
let header = table_header()
.child(div().w(unit(size::CHECK)))
.child(head(col::M, "Size", Term::Size).text_right())
.child(head(col::S, "Safety", Term::Safety))
.child(head(col::S, "Tool", Term::Tool))
.child(column(col::WIDE).child("VERSION"))
.child(div().flex_1().child("PATH"));
let empty = if report.options.toolchains {
"No installed toolchain versions found"
} else {
"Toolchains were skipped for this scan"
};
self.section_page(
SectionPage {
tab: Tab::Toolchains,
id: "toolchains",
selector: "toolchain-list",
total: report.toolchains.len(),
banner: None,
footer: None,
empty: empty.into(),
filtered: "No toolchain versions match these filters",
},
header,
|app, range, cx| app.toolchain_rows(range, cx),
cx,
)
}
fn toolchain_rows(&self, range: Range<usize>, cx: &mut Context<Self>) -> Vec<Stateful<Div>> {
let Some(report) = self.report() else {
return Vec::new();
};
let listed = self.listed(Tab::Toolchains);
let cursor = self.cursor_target();
range
.filter_map(|row| {
let (toolchain, candidate) = report.toolchains.get(listed.slots.get(row)?.0)?;
Some(self.toolchain_row(row, toolchain, candidate, cursor.as_ref(), cx))
})
.collect()
}
fn toolchain_row(
&self,
index: usize,
toolchain: &Toolchain,
candidate: &Candidate,
cursor: Option<&Target>,
cx: &mut Context<Self>,
) -> Stateful<Div> {
let id = candidate.id;
let checked = self.list.selection.contains(&(Source::Toolchain, id));
let review = candidate.rule.safety == Safety::Review;
let note = toolchain.note();
let row = table_row(("toolchain", id), checked)
.debug_selector(move || format!("toolchain-row-{index}"));
let target = Target::Item(Source::Toolchain, id, candidate.path.clone());
let look = self.look(Source::Toolchain, id, &candidate.path);
self.menu_row(row, target, cursor, cx)
.child(ui::check_mark(look.checked))
.child(
column(col::M)
.id(("toolchain-size", id))
.text_right()
.tip(size_details(candidate, &[]))
.font_weight(FontWeight::MEDIUM)
.child(theme::bytes(candidate.usage.allocated)),
)
.child(
column(col::S)
.flex()
.child(ui::safety_label(("toolchain-safety", id), review)),
)
.child(
column(col::S)
.text_color(theme::muted())
.child(toolchain.tool.name()),
)
.child(
column(col::WIDE)
.id(("toolchain-version", id))
.truncate()
.tip(tooltip::plain(toolchain.version.clone()))
.child(toolchain_label(toolchain)),
)
.child(
div()
.flex()
.flex_col()
.justify_center()
.flex_1()
.min_w_0()
.child(
div()
.id(("toolchain-path", id))
.truncate()
.text_color(theme::muted())
.tip(tooltip::path(&candidate.path))
.child(display_path(&candidate.path)),
)
.when(!note.is_empty(), |this| {
this.child(
div()
.truncate()
.text_size(unit(font::SMALL))
.text_color(theme::faint())
.child(note),
)
}),
)
.h(unit(size::row_tall()))
.on_click(cx.listener(move |app, event: &ClickEvent, _, cx| {
app.click_row(Source::Toolchain, id, event, cx);
}))
}
pub(super) fn render_docker(&self, cx: &mut Context<Self>) -> AnyElement {
let Some(report) = self.report() else {
return div().into_any_element();
};
let header = table_header()
.child(div().w(unit(size::CHECK)))
.child(head(col::M, "Size", Term::Size).text_right())
.child(head(col::S, "Safety", Term::Safety))
.child(head(col::S, "Engine", Term::Engine))
.child(column(col::L).child("OBJECT"))
.child(div().flex_1().child("NAME"));
let empty = if !report.options.docker {
"Docker and Podman were skipped for this scan".to_owned()
} else if report.docker_issues.is_empty() {
"Nothing to free in Docker or Podman".to_owned()
} else {
report.docker_issues.join(". ")
};
let banner = (!report.docker.is_empty() && !report.docker_issues.is_empty())
.then(|| report.docker_issues.join(". "));
self.section_page(
SectionPage {
tab: Tab::Docker,
id: "docker",
selector: "docker-list",
total: report.docker.len(),
banner,
footer: None,
empty: empty.into(),
filtered: "No Docker or Podman objects match these filters",
},
header,
|app, range, cx| app.docker_rows(range, cx),
cx,
)
}
fn docker_rows(&self, range: Range<usize>, cx: &mut Context<Self>) -> Vec<Stateful<Div>> {
let Some(report) = self.report() else {
return Vec::new();
};
let listed = self.listed(Tab::Docker);
let cursor = self.cursor_target();
range
.filter_map(|row| {
let (item, candidate) = report.docker.get(listed.slots.get(row)?.0)?;
Some(self.docker_row(row, item, candidate, cursor.as_ref(), cx))
})
.collect()
}
fn docker_row(
&self,
index: usize,
item: &docker::Item,
candidate: &Candidate,
cursor: Option<&Target>,
cx: &mut Context<Self>,
) -> Stateful<Div> {
let id = candidate.id;
let checked = self.list.selection.contains(&(Source::Docker, id));
let review = candidate.rule.safety == Safety::Review;
let row = table_row(("docker", id), checked)
.debug_selector(move || format!("docker-row-{index}"));
let target = Target::Item(Source::Docker, id, candidate.path.clone());
let look = self.look(Source::Docker, id, &candidate.path);
self.menu_row(row, target, cursor, cx)
.child(ui::check_mark(look.checked))
.child(
column(col::M)
.text_right()
.font_weight(FontWeight::MEDIUM)
.child(theme::bytes(candidate.usage.allocated)),
)
.child(
column(col::S)
.flex()
.child(ui::safety_label(("docker-safety", id), review)),
)
.child(
column(col::S)
.text_color(theme::muted())
.child(item.engine.clone()),
)
.child(
column(col::L)
.text_color(theme::muted())
.child(item.object.name()),
)
.child(
div()
.flex()
.flex_col()
.justify_center()
.flex_1()
.min_w_0()
.child(
div()
.id(("docker-name", id))
.truncate()
.tip(tooltip::plain(format!("{} {}", item.label, item.id)))
.child(item.label.clone()),
)
.when(!item.note.is_empty(), |this| {
this.child(
div()
.truncate()
.text_size(unit(font::SMALL))
.text_color(theme::faint())
.child(item.note.clone()),
)
}),
)
.h(unit(size::row_tall()))
.on_click(cx.listener(move |app, event: &ClickEvent, _, cx| {
app.click_row(Source::Docker, id, event, cx);
}))
}
}
fn large_badges(id: u64, candidate: &Candidate) -> Div {
let kind_label = if large_folder(candidate) {
"Folder"
} else {
FileKind::classify(&candidate.path).label()
};
column(col::XL)
.flex()
.items_center()
.gap(unit(space::S))
.overflow_hidden()
.child(ui::tag(("large-kind", id), kind_label, ui::Tone::Neutral))
.when(download(candidate), |this| {
this.child(ui::tag(
("large-download", id),
"Download",
ui::Tone::Review,
))
})
}
fn size_cell(id: (&'static str, u64), candidate: &Candidate) -> Stateful<Div> {
column(col::M)
.id(id)
.text_right()
.tip(size_details(candidate, &[]))
.font_weight(FontWeight::MEDIUM)
.child(theme::bytes(candidate.usage.allocated))
}
fn path_cell(id: (&'static str, u64), path: &Path) -> Stateful<Div> {
div()
.id(id)
.flex_1()
.min_w_0()
.truncate()
.text_color(theme::muted())
.tip(tooltip::path(path))
.child(display_path(path))
}
fn cache_cells(
row: Stateful<Div>,
ids: [&'static str; 3],
cache: &KnownCache,
candidate: &Candidate,
group: Option<Group>,
) -> Stateful<Div> {
let id = candidate.id;
let review = candidate.rule.safety == Safety::Review;
let [size_id, safety_id, path_id] = ids;
row.child(
column(col::M)
.id((size_id, id))
.text_right()
.tip(size_details(candidate, &[]))
.font_weight(FontWeight::MEDIUM)
.child(theme::bytes(candidate.usage.allocated)),
)
.child(
column(col::S)
.flex()
.child(ui::safety_label((safety_id, id), review)),
)
.child(
column(col::M)
.text_color(theme::muted())
.child(cache.tool.clone()),
)
.when_some(group, |this, group| {
this.child(
column(col::S)
.text_color(theme::muted())
.child(group_label(group)),
)
})
.child(column(col::XXL).truncate().child(cache.name.clone()))
.child(
column(col::XS)
.text_right()
.text_color(theme::muted())
.child(theme::age(candidate.newest)),
)
.child(
div()
.flex()
.flex_col()
.justify_center()
.flex_1()
.min_w_0()
.child(
div()
.id((path_id, id))
.truncate()
.text_color(theme::muted())
.tip(tooltip::path(&candidate.path))
.child(display_path(&candidate.path)),
)
.when(!cache.note.is_empty(), |this| {
this.child(
div()
.truncate()
.text_size(unit(font::SMALL))
.text_color(theme::faint())
.child(cache.note.clone()),
)
}),
)
.h(unit(size::row_tall()))
}
#[cfg(test)]
mod tests {
use gpui::{Entity, Modifiers, TestAppContext, VisualTestContext};
use super::*;
use crate::app::tests::{artifact, open, project, wait_for_refresh};
fn draw(cx: &mut VisualTestContext) {
cx.update(|window, cx| window.draw(cx).clear());
}
#[gpui::test]
fn an_empty_list_says_whether_the_scan_or_the_filter_emptied_it(cx: &mut TestAppContext) {
let dir = tempfile::tempdir().unwrap();
let (view, cx) = open(cx, dir.path().join("recent"));
view.update(cx, |app, cx| {
app.session.roots = vec![PathBuf::from("/p")];
let mut report = Report::empty(&app.session.roots, &app.session.options);
let cache = KnownCache {
name: "npm".to_owned(),
tool: "npm".to_owned(),
group: kuizer::catalog::Group::Developer,
category: kuizer::detect::Category::Cache,
kind: kuizer::detect::Kind::Dir,
path: PathBuf::from("/c/npm"),
safety: Safety::Safe,
note: String::new(),
processes: Vec::new(),
};
report.caches = vec![(cache, artifact(1, Path::new("/c/npm")))];
app.session.phase = Phase::Ready(Box::new(report));
app.refresh_stats();
app.list.tab = Tab::Caches;
cx.notify();
});
draw(cx);
assert!(cx.debug_bounds("cache-row-0").is_some());
view.update(cx, |app, cx| {
app.list
.filters
.insert(Tab::Caches, "nothing-like-this".to_owned());
cx.notify();
});
draw(cx);
assert!(
cx.debug_bounds("empty-Caches-filtered").is_some(),
"a filter that hides every cache says so instead of a blank table"
);
view.update(cx, |app, cx| {
app.list.tab = Tab::Toolchains;
cx.notify();
});
draw(cx);
assert!(cx.debug_bounds("empty-Toolchains-none").is_some());
assert!(
cx.debug_bounds("empty-Toolchains-filtered").is_none(),
"a list the scan left empty does not blame the filter"
);
}
#[gpui::test]
fn a_failed_scan_offers_rescan_and_new_scan(cx: &mut TestAppContext) {
let dir = tempfile::tempdir().unwrap();
let root = project(dir.path());
let (view, cx) = open(cx, dir.path().join("recent"));
let fail = |view: &Entity<Kuizer>, cx: &mut VisualTestContext| {
view.update(cx, |app, cx| {
app.session.roots = vec![root.clone()];
app.set_phase(Phase::Failed("Permission denied".to_owned()), cx);
cx.notify();
});
draw(cx);
};
fail(&view, cx);
assert!(cx.debug_bounds("scan-failed").is_some());
assert!(cx.debug_bounds("failed-rescan").is_some());
cx.simulate_keystrokes("ctrl-r");
view.read_with(cx, |app, _| {
assert!(
!matches!(app.session.phase, Phase::Failed(_)),
"the Rescan key scans again"
);
});
wait_for_refresh(&view, cx);
view.read_with(cx, |app, _| {
assert!(matches!(app.session.phase, Phase::Ready(_)))
});
fail(&view, cx);
let new_scan = cx
.debug_bounds("failed-new-scan")
.expect("a New scan button");
cx.simulate_click(new_scan.center(), Modifiers::default());
view.read_with(cx, |app, _| {
assert!(matches!(app.session.phase, Phase::Start))
});
fail(&view, cx);
cx.simulate_keystrokes("escape");
view.read_with(cx, |app, _| {
assert!(
matches!(app.session.phase, Phase::Start),
"Esc backs out of a failed scan to the start screen"
);
});
}
fn cache(name: &str, group: Group) -> KnownCache {
KnownCache {
name: name.to_owned(),
tool: name.to_owned(),
group,
category: kuizer::detect::Category::Cache,
kind: kuizer::detect::Kind::Dir,
path: PathBuf::from(format!("/c/{name}")),
safety: Safety::Safe,
note: String::new(),
processes: Vec::new(),
}
}
fn empty_report(view: &Entity<Kuizer>, cx: &mut VisualTestContext) -> Report {
view.read_with(cx, |app, _| {
Report::empty(&[PathBuf::from("/p")], &app.session.options)
})
}
fn show(view: &Entity<Kuizer>, cx: &mut VisualTestContext, report: Report, tab: Tab) {
view.update(cx, |app, cx| {
app.session.roots = report.roots.clone();
app.session.phase = Phase::Ready(Box::new(report));
app.refresh_stats();
app.list.tab = tab;
cx.notify();
});
draw(cx);
}
#[gpui::test]
fn app_caches_and_developer_caches_split_by_group(cx: &mut TestAppContext) {
let dir = tempfile::tempdir().unwrap();
let (view, cx) = open(cx, dir.path().join("recent"));
let mut report = empty_report(&view, cx);
report.caches = vec![
(
cache("npm", Group::Developer),
artifact(1, Path::new("/c/npm")),
),
(
cache("thumbnails", Group::Apps),
artifact(2, Path::new("/c/thumbnails")),
),
];
show(&view, cx, report, Tab::Caches);
assert!(cx.debug_bounds("cache-row-0").is_some());
view.update(cx, |app, cx| {
assert_eq!(app.counts(Tab::Caches), (1, 1));
assert_eq!(app.counts(Tab::AppCaches), (1, 1));
assert_eq!(
&*app.targets(Tab::AppCaches),
[Target::Item(
Source::Cache,
2,
PathBuf::from("/c/thumbnails")
)]
);
app.list.filters.insert(Tab::AppCaches, "apps".to_owned());
assert_eq!(app.counts(Tab::AppCaches), (1, 1), "the group is matched");
app.list.filters.clear();
app.list.tab = Tab::AppCaches;
cx.notify();
});
draw(cx);
assert!(cx.debug_bounds("app-cache-row-0").is_some());
}
#[gpui::test]
fn new_sections_list_their_rows(cx: &mut TestAppContext) {
let dir = tempfile::tempdir().unwrap();
let (view, cx) = open(cx, dir.path().join("recent"));
let mut report = empty_report(&view, cx);
let folder = kuizer::trashcan::Folder {
path: PathBuf::from("/t/Trash"),
items: 3,
layout: kuizer::trashcan::Layout::Freedesktop,
};
report.trash = vec![(folder, artifact(1, Path::new("/t/Trash")))];
let item = system::Item {
manager: system::Manager::Pacman,
id: "pkg".to_owned(),
label: "Package cache".to_owned(),
bytes: 0,
size_known: false,
safety: Safety::Review,
needs_root: true,
note: String::new(),
};
let candidate = item.candidate(1);
report.system = vec![(item, candidate)];
report.big = vec![
artifact(1, Path::new("/p/disk.iso")),
artifact(2, Path::new("/p/video.mkv")),
];
show(&view, cx, report, Tab::Trash);
for (tab, row) in [
(Tab::Trash, "trash-row-0"),
(Tab::System, "system-row-0"),
(Tab::LargeFiles, "large-row-0"),
] {
view.update(cx, |app, cx| {
app.list.tab = tab;
cx.notify();
});
draw(cx);
assert!(cx.debug_bounds(row).is_some(), "{row} is not shown");
assert!(tab.selects(), "{tab:?}");
}
cx.simulate_keystrokes("j");
view.read_with(cx, |app, _| {
assert_eq!(
app.cursor_target(),
Some(Target::Item(Source::Big, 2, PathBuf::from("/p/video.mkv"))),
"the list motions move through the new lists"
);
});
}
#[gpui::test]
fn system_caches_are_selected_and_confirmed_with_their_command(cx: &mut TestAppContext) {
let dir = tempfile::tempdir().unwrap();
let (view, cx) = open(cx, dir.path().join("recent"));
let mut report = empty_report(&view, cx);
let item = system::Item {
manager: system::Manager::Journal,
id: "journal".to_owned(),
label: "System journal".to_owned(),
bytes: 4096,
size_known: true,
safety: Safety::Safe,
needs_root: true,
note: String::new(),
};
let candidate = item.candidate(1);
report.system = vec![(item, candidate)];
show(&view, cx, report, Tab::System);
assert!(cx.debug_bounds("system-list-footer").is_some());
cx.simulate_keystrokes("space");
view.read_with(cx, |app, _| {
assert!(app.list.selection.contains(&(Source::System, 1)));
assert_eq!(
app.cursor_target()
.and_then(|target| target.path().map(Path::to_path_buf)),
None
);
});
cx.simulate_keystrokes("enter");
draw(cx);
view.read_with(cx, |app, _| {
let Some(Dialog::Remove(ask)) = &app.overlays.dialog else {
panic!("cleaning a system cache asks first");
};
assert!(ask.cancel, "Cancel has the keyboard");
assert!(!ask.counted(), "no count to type for system caches alone");
assert_eq!(ask.commands.len(), 1);
assert!(
ask.commands
.iter()
.all(|command| !command.contains("sudo --")),
"the window never runs sudo: {:?}",
ask.commands
);
});
assert!(cx.debug_bounds("system-commands").is_some());
cx.simulate_keystrokes("enter");
view.read_with(cx, |app, _| {
assert!(app.overlays.dialog.is_none(), "Enter on Cancel closes it");
assert!(app.session.cleaning.is_none(), "and cleans nothing");
});
}
#[gpui::test]
fn large_files_filter_by_kind_and_show_it(cx: &mut TestAppContext) {
let dir = tempfile::tempdir().unwrap();
let (view, cx) = open(cx, dir.path().join("recent"));
let mut report = empty_report(&view, cx);
report.big = vec![
artifact(1, Path::new("/p/disk.iso")),
artifact(2, Path::new("/p/talk.MKV")),
artifact(3, Path::new("/p/notes.bin")),
];
let chips: Vec<(LargeFilter, usize)> = large_filters(&report.big);
assert_eq!(
chips,
[
(LargeFilter::All, 3),
(LargeFilter::Kind(FileKind::Video), 1),
(LargeFilter::Kind(FileKind::DiskImage), 1),
(LargeFilter::Kind(FileKind::Other), 1),
]
);
show(&view, cx, report, Tab::LargeFiles);
assert!(cx.debug_bounds("large-filters").is_some());
view.update(cx, |app, _| {
app.list.large = LargeFilter::Kind(FileKind::Video);
assert_eq!(
&*app.targets(Tab::LargeFiles),
[Target::Item(Source::Big, 2, PathBuf::from("/p/talk.MKV"))]
);
app.list.large = LargeFilter::All;
app.list
.filters
.insert(Tab::LargeFiles, "disk image".to_owned());
assert_eq!(
&*app.targets(Tab::LargeFiles),
[Target::Item(Source::Big, 1, PathBuf::from("/p/disk.iso"))],
"the text filter matches the kind label"
);
});
}
#[gpui::test]
fn app_caches_selection_stays_on_app_caches_tab(cx: &mut TestAppContext) {
let dir = tempfile::tempdir().unwrap();
let (view, cx) = open(cx, dir.path().join("recent"));
let mut report = empty_report(&view, cx);
report.caches = vec![
(
cache("npm", Group::Developer),
artifact(1, Path::new("/c/npm")),
),
(
cache("thumbnails", Group::Apps),
artifact(2, Path::new("/c/thumbnails")),
),
(
cache("firefox", Group::Browsers),
artifact(3, Path::new("/c/firefox")),
),
];
show(&view, cx, report, Tab::AppCaches);
cx.simulate_keystrokes("space");
view.read_with(cx, |app, _| {
assert_eq!(app.list.tab, Tab::AppCaches);
assert!(app.list.selection.contains(&(Source::Cache, 2)));
assert!(
!app.list.cursors.contains_key(&Tab::Caches),
"the cursor never lands in Developer caches"
);
assert!(matches!(
app.list.cursors.get(&Tab::AppCaches),
Some(Target::Item(Source::Cache, 3, _))
));
assert_eq!(
app.target_tab(&Target::Item(Source::Cache, 3, PathBuf::from("/c/firefox"))),
Tab::AppCaches
);
});
draw(cx);
assert!(cx.debug_bounds("summary-bar").is_some());
cx.simulate_keystrokes("ctrl-a");
view.read_with(cx, |app, _| {
assert_eq!(
app.list.selection,
HashSet::from([(Source::Cache, 2), (Source::Cache, 3)]),
"Select all on App caches leaves developer caches alone"
);
});
view.update(cx, |app, cx| {
app.toggle(Source::Cache, 1, cx);
app.list.tab = Tab::Caches;
cx.notify();
});
cx.simulate_keystrokes("ctrl-shift-a");
view.read_with(cx, |app, _| {
assert_eq!(
app.list.selection,
HashSet::from([(Source::Cache, 2), (Source::Cache, 3)]),
"Select none on Developer caches keeps the app caches"
);
});
}
}