use gpui::{Animation, AnimationExt, relative};
use kuizer::usage::{UsageNode, UsageTree};
use super::confirm::Explored;
use super::*;
use crate::squarify::{self, Rect};
const FALLBACK: (f32, f32) = (960., 240.);
const LABEL: (f32, f32) = (72., 36.);
const NAME: (f32, f32) = (40., 18.);
const PROTECTED: &str = "Protected: kuizer never removes a scanned folder, a mount point, the home folder or protected app data";
#[derive(Default)]
pub(super) struct Explorer {
pub folder: Option<PathBuf>,
pub bounds: Rc<Cell<Option<Bounds<Pixels>>>>,
pub epoch: usize,
}
pub(super) fn find<'a>(tree: &'a UsageTree, path: &Path) -> Option<&'a UsageNode> {
tree.roots.iter().find_map(|root| root.find(path))
}
pub(super) fn level<'a>(tree: &'a UsageTree, folder: Option<&Path>) -> Option<&'a UsageNode> {
match folder.and_then(|folder| find(tree, folder)) {
Some(node) => Some(node),
None if tree.roots.len() == 1 => tree.roots.first(),
None => None,
}
}
pub(super) fn children<'a>(tree: &'a UsageTree, folder: Option<&Path>) -> &'a [UsageNode] {
level(tree, folder).map_or(&tree.roots[..], |node| &node.children[..])
}
fn top(tree: &UsageTree) -> Option<&Path> {
(tree.roots.len() == 1).then(|| tree.roots[0].path.as_path())
}
impl Kuizer {
pub(super) fn explorer_active(&self) -> bool {
self.list.tab == Tab::DiskUsage && self.report().is_some_and(|r| r.usage.is_some())
}
fn usage(&self) -> Option<&UsageTree> {
self.report()?.usage.as_ref()
}
pub(super) fn explorer_folder(&self) -> Option<PathBuf> {
let tree = self.usage()?;
let folder = self.list.explorer.folder.as_deref()?;
folder
.ancestors()
.find(|path| find(tree, path).is_some_and(|node| node.is_dir))
.filter(|path| Some(*path) != top(tree))
.map(Path::to_path_buf)
}
fn explorer_level(&self) -> Option<&UsageNode> {
level(self.usage()?, self.explorer_folder().as_deref())
}
pub(super) fn explorer_children(&self) -> &[UsageNode] {
let Some(tree) = self.usage() else {
return &[];
};
children(tree, self.explorer_folder().as_deref())
}
fn explorer_node(&self, path: &Path) -> Option<&UsageNode> {
find(self.usage()?, path)
}
fn explorer_cursor(&self) -> Option<&UsageNode> {
match self.cursor_target()? {
Target::Row(Tab::DiskUsage, path) => self.explorer_node(&path),
_ => None,
}
}
pub(super) fn explorer_nested(&self) -> bool {
self.explorer_folder().is_some()
}
pub(super) fn explorer_open(&mut self, path: &Path) {
if !self.explorer_node(path).is_some_and(|node| node.is_dir) {
return;
}
self.list.explorer.folder = Some(path.to_path_buf());
self.list.cursors.remove(&Tab::DiskUsage);
self.list.explorer.epoch += 1;
}
pub(super) fn explorer_up(&mut self) {
let Some(folder) = self.explorer_folder() else {
return;
};
let parent = folder
.parent()
.filter(|parent| self.explorer_node(parent).is_some())
.map(Path::to_path_buf);
self.explorer_show(parent);
self.list
.cursors
.insert(Tab::DiskUsage, Target::Row(Tab::DiskUsage, folder));
}
pub(super) fn explorer_show(&mut self, folder: Option<PathBuf>) {
self.list.explorer.folder = folder;
self.list.cursors.remove(&Tab::DiskUsage);
self.list.explorer.epoch += 1;
}
pub(super) fn explorer_refusal(&self, path: &Path) -> Option<&'static str> {
let node = self.explorer_node(path)?;
if node.protected {
return Some(PROTECTED);
}
self.explorer_lock()
}
pub(super) fn explorer_lock(&self) -> Option<&'static str> {
if self.busy() {
return Some(keys::WAIT_FOR_SCAN);
}
if self.session.cleaning.is_some() {
return Some(keys::WAIT_FOR_CLEANUP);
}
if self.saving_protected_paths() {
return Some("Available once the protected paths are saved");
}
let outdated = self.session.stale.is_some()
|| (self.session.cancel.is_some() && self.session.pending.contains(&Part::Usage));
outdated.then_some(
"Available once the running scan measures these folders again, so every entry is current",
)
}
pub(super) fn explorer_delete_blocked(&self) -> Option<&'static str> {
match self.explorer_cursor() {
Some(node) => self.explorer_refusal(&node.path.clone()),
None => Some(keys::NO_ROWS),
}
}
pub(super) fn explorer_delete(&mut self, path: &Path, cx: &mut Context<Self>) {
if self.explorer_refusal(path).is_some() {
return;
}
let (Some(report), Some(node)) = (self.report(), self.explorer_node(path)) else {
return;
};
match model::explored(node, &report.roots, &self.config.delete.protected, 0) {
Some((candidate, root)) => self.ask_explored(Explored { candidate, root }, cx),
None => {
let shown = self.shown_path(path);
self.tell(
Notice::Failed(format!("{shown} is protected, kuizer leaves it alone")),
cx,
);
}
}
}
pub(super) fn clean_explored(&mut self, explored: Explored, cx: &mut Context<Self>) {
if self.explorer_refusal(&explored.candidate.path).is_some() {
return;
}
let path = explored.candidate.path.clone();
let paths = HashMap::from([(Source::Big, HashSet::from([path]))]);
let batches = vec![Batch {
source: Source::Big,
roots: vec![explored.root],
candidates: vec![explored.candidate],
}];
self.run_clean(batches, paths, 1, cx);
}
fn explorer_size(&self) -> (f32, f32) {
self.list
.explorer
.bounds
.get()
.map(|bounds| (f32::from(bounds.size.width), f32::from(bounds.size.height)))
.filter(|(width, height)| *width > 0. && *height > 0.)
.unwrap_or(FALLBACK)
}
pub(super) fn render_explorer(&self, cx: &mut Context<Self>) -> AnyElement {
let Some(report) = self.report() else {
return div().into_any_element();
};
let Some(tree) = &report.usage else {
let text = if report.options.usage {
"The disk explorer fills in once the scan has measured every folder"
} else {
"The disk explorer was skipped for this scan"
};
return centered(ui::empty(text).debug_selector(|| "explorer-empty".to_owned()));
};
let level = self.explorer_level();
let entries = self.explorer_children();
let (other_bytes, other_count) =
level.map_or((0, 0), |node| (node.other_bytes, node.other_count));
let header = table_header()
.child(div().w(unit(size::ICON)))
.child(column(col::XXL).child("NAME"))
.child(div().flex_1().child("SHARE"))
.child(head(col::M, "Size", Term::Size).text_right())
.child(column(col::M).text_right().child("FILES"))
.child(column(size::ACTIONS).text_right().child(""));
let listed = self.listed(Tab::DiskUsage);
let count = listed.slots.len();
let list = self
.table_list(
"explorer",
Tab::DiskUsage,
count,
|app, range, cx| app.explorer_rows(range, cx),
cx,
)
.debug_selector(|| "explorer-list".to_owned());
let body = if entries.is_empty() && other_bytes == 0 {
empty_list(
Tab::DiskUsage,
0,
"Nothing measured in this folder",
"No entries match this filter",
)
} else if count == 0 && other_bytes == 0 {
empty_list(Tab::DiskUsage, 1, "", "No entries match this filter")
} else {
div()
.flex()
.flex_col()
.flex_1()
.min_h_0()
.child(list)
.when(other_bytes > 0, |this| {
this.child(other_row(
other_bytes,
other_count,
level.map_or(0, |node| node.allocated),
))
})
.into_any_element()
};
div()
.flex()
.flex_col()
.size_full()
.child(self.explorer_bar(tree, level, cx))
.child(self.explorer_map(entries, other_bytes, cx))
.child(
self.list_toolbar(cx)
.child(div().flex_1())
.child(self.tally(Tab::DiskUsage, Some(listed.bytes))),
)
.child(table(header, body))
.child(
div()
.debug_selector(|| "explorer-footer".to_owned())
.flex_none()
.px(unit(space::GUTTER))
.py(unit(space::S))
.text_size(unit(font::SMALL))
.text_color(theme::muted())
.child(format!(
"{} opens a folder, {} goes up, {} reveals, {} copies the path, {} moves an entry that is not protected to the trash",
self.key_hint(Scope::Map, Key::MapIn),
self.key_hint(Scope::Map, Key::MapOut),
self.hint(&Command::Reveal),
self.hint(&Command::CopyPath),
self.key_hint(Scope::Gui, Key::Delete),
)),
)
.into_any_element()
}
fn explorer_bar(
&self,
tree: &UsageTree,
level: Option<&UsageNode>,
cx: &mut Context<Self>,
) -> Div {
let folder = self.explorer_folder();
let mut trail: Vec<(String, Option<PathBuf>)> = Vec::new();
match top(tree) {
Some(root) => trail.push((display_path(root), None)),
None => trail.push(("Scanned folders".to_owned(), None)),
}
if let Some(folder) = &folder {
let base = top(tree);
let mut steps: Vec<&Path> = folder
.ancestors()
.take_while(|path| Some(*path) != base && find(tree, path).is_some())
.collect();
steps.reverse();
for step in steps {
let name = step.file_name().map_or_else(
|| display_path(step),
|name| name.to_string_lossy().into_owned(),
);
let label = if base.is_none()
&& find(tree, step)
.is_some_and(|node| tree.roots.iter().any(|root| root.path == node.path))
{
display_path(step)
} else {
name
};
trail.push((label, Some(step.to_path_buf())));
}
}
let depth = trail.len() - 1;
let crumbs: Vec<AnyElement> = trail
.into_iter()
.enumerate()
.flat_map(|(index, (label, path))| {
let current = index == depth;
let separator = (index > 0).then(|| {
div()
.flex_none()
.text_color(theme::faint())
.child("/")
.into_any_element()
});
let crumb = div()
.id(("explorer-crumb", index))
.debug_selector(move || format!("explorer-crumb-{index}"))
.flex_none()
.max_w(unit(size::LABEL))
.truncate()
.px(unit(space::XS))
.rounded(theme::radius_control())
.text_color(if current {
theme::text()
} else {
theme::muted()
})
.when(!current, |this| {
this.cursor_pointer()
.hover(|style| style.bg(theme::hover()).text_color(theme::text()))
})
.child(label);
let crumb = if current {
crumb.into_any_element()
} else {
self.control(crumb, cx, move |app, _, cx| {
app.explorer_show(path.clone());
cx.notify();
})
.into_any_element()
};
separator.into_iter().chain([crumb])
})
.collect();
let (allocated, files, dirs) = level.map_or(
(tree.total_allocated, tree.total_files, tree.total_dirs),
|node| (node.allocated, node.files, node.dirs.saturating_sub(1)),
);
let up = self
.button(
"explorer-up",
"Up",
ButtonKind::Secondary,
self.explorer_nested(),
cx,
|app, _, cx| {
app.explorer_up();
cx.notify();
},
)
.debug_selector(|| "explorer-up".to_owned())
.tip(
Tooltip::new("Go up one folder")
.keys(&[&self.key_hint(Scope::Map, Key::MapOut)])
.build(),
);
div()
.flex()
.flex_none()
.items_center()
.gap(unit(space::L))
.px(unit(space::GUTTER))
.py(unit(space::S))
.child(up)
.child(
div()
.id("explorer-trail")
.debug_selector(|| "explorer-trail".to_owned())
.flex()
.flex_1()
.min_w_0()
.items_center()
.gap(unit(space::XXS))
.overflow_hidden()
.children(crumbs),
)
.child(
ui::tabular(div())
.debug_selector(|| "explorer-summary".to_owned())
.flex_none()
.text_size(unit(font::SMALL))
.text_color(theme::muted())
.child(format!(
"{}, {}, {}",
theme::bytes(allocated),
plural(usize::try_from(files).unwrap_or(usize::MAX), "file"),
plural(usize::try_from(dirs).unwrap_or(usize::MAX), "folder"),
)),
)
}
fn explorer_map(&self, entries: &[UsageNode], other: u64, cx: &mut Context<Self>) -> Div {
let (width, height) = self.explorer_size();
let mut sizes: Vec<u64> = entries.iter().map(|node| node.allocated).collect();
if other > 0 {
sizes.push(other);
}
let rects = squarify::squarify(&sizes, Rect::new(0., 0., width, height));
let focus = self.explorer_cursor().map(|node| node.path.clone());
let mut tiles: Vec<AnyElement> = entries
.iter()
.zip(&rects)
.enumerate()
.filter(|(_, (_, rect))| rect.area() > 0.)
.map(|(index, (node, rect))| {
let focused = focus.as_deref() == Some(node.path.as_path());
self.explorer_tile(index, node, *rect, (width, height), focused, cx)
})
.collect();
if let Some(rect) = rects.get(entries.len()).filter(|rect| rect.area() > 0.) {
tiles.push(rest_tile(*rect, (width, height), other));
}
let bounds = Rc::clone(&self.list.explorer.bounds);
let probe = canvas(
move |area, window, _| {
if bounds.get().map(|known| known.size) != Some(area.size) {
window.request_animation_frame();
}
bounds.set(Some(area));
},
|_, (), _, _| {},
)
.absolute()
.top_0()
.left_0()
.size_full();
let layer = div().absolute().inset_0().children(tiles);
let layer = if motion::reduced() {
layer.into_any_element()
} else {
layer
.with_animation(
("explorer-zoom", self.list.explorer.epoch),
Animation::new(motion::STEP).with_easing(motion::ease_out),
|layer, progress| layer.opacity(motion::fade_from(motion::ZOOM_FROM, progress)),
)
.into_any_element()
};
div()
.flex_none()
.px(unit(space::GUTTER))
.pb(unit(space::M))
.child(
div()
.id("explorer-map")
.debug_selector(|| "explorer-map".to_owned())
.relative()
.h(unit(size::MAP))
.w_full()
.overflow_hidden()
.rounded(theme::radius_panel())
.bg(theme::elevated())
.border_1()
.border_color(theme::border())
.child(probe)
.child(layer),
)
}
fn explorer_tile(
&self,
index: usize,
node: &UsageNode,
rect: Rect,
(width, height): (f32, f32),
focused: bool,
cx: &mut Context<Self>,
) -> AnyElement {
let labelled = rect.w >= LABEL.0 && rect.h >= LABEL.1;
let named = rect.w >= NAME.0 && rect.h >= NAME.1;
let (fill, edge) = if node.is_dir {
(theme::tile_folder(), None)
} else {
(
theme::tile(Category::Files),
Some(theme::tile_edge(Category::Files)),
)
};
let details = Tooltip::details(node.name.clone())
.row("Size", theme::bytes(node.allocated))
.row("Files", node.files.to_string())
.row("Protected", if node.protected { "Yes" } else { "No" })
.note(display_path(&node.path));
let inner = div()
.relative()
.size_full()
.overflow_hidden()
.flex()
.flex_col()
.gap(unit(size::HAIR))
.px(unit(space::S))
.py(unit(space::XS))
.bg(fill)
.when(node.is_dir, |this| {
this.border_1().border_color(theme::border_strong())
})
.when(focused, |this| this.border_2().border_color(theme::focus()))
.hover(|style| style.opacity(theme::DIM))
.when_some(edge, |this, edge| {
this.child(
div()
.absolute()
.top_0()
.left_0()
.right_0()
.h(unit(size::MARKER))
.bg(edge),
)
})
.when(named, |this| {
this.child(
div()
.truncate()
.text_size(unit(font::SMALL))
.text_color(theme::text())
.child(node.name.clone()),
)
})
.when(labelled, |this| {
this.child(
div()
.truncate()
.text_size(unit(font::CAPTION))
.text_color(theme::muted())
.child(theme::bytes(node.allocated)),
)
});
let path = node.path.clone();
let menu_path = node.path.clone();
let is_dir = node.is_dir;
div()
.id(("explorer-tile", index))
.debug_selector(move || format!("explorer-tile-{index}"))
.absolute()
.left(relative(rect.x / width))
.top(relative(rect.y / height))
.w(relative(rect.w / width))
.h(relative(rect.h / height))
.p(unit(size::HAIR))
.cursor_pointer()
.tip(details.build())
.on_click(cx.listener(move |app, _: &ClickEvent, _, cx| {
app.list.filtering = false;
if is_dir {
app.explorer_open(&path);
} else {
app.list
.cursors
.insert(Tab::DiskUsage, Target::Row(Tab::DiskUsage, path.clone()));
}
cx.notify();
}))
.on_mouse_down(
MouseButton::Right,
cx.listener(move |app, event: &MouseDownEvent, _, cx| {
cx.stop_propagation();
app.open_menu(
Target::Row(Tab::DiskUsage, menu_path.clone()),
event.position,
false,
cx,
);
}),
)
.child(inner)
.into_any_element()
}
fn explorer_rows(&self, range: Range<usize>, cx: &mut Context<Self>) -> Vec<Stateful<Div>> {
let entries = self.explorer_children();
let listed = self.listed(Tab::DiskUsage);
let cursor = self.cursor_target();
let largest = self.explorer_level().map_or_else(
|| entries.iter().map(|node| node.allocated).sum(),
|node| node.allocated,
);
range
.filter_map(|row| {
let node = entries.get(listed.slots.get(row)?.0)?;
Some(self.explorer_row(row, node, largest, cursor.as_ref(), cx))
})
.collect()
}
fn explorer_row(
&self,
index: usize,
node: &UsageNode,
whole: u64,
cursor: Option<&Target>,
cx: &mut Context<Self>,
) -> Stateful<Div> {
let key = index as u64;
let row = table_row(("explorer-row", key), false)
.debug_selector(move || format!("explorer-row-{index}"));
let target = Target::Row(Tab::DiskUsage, node.path.clone());
let refusal = self.explorer_refusal(&node.path);
let open_path = node.path.clone();
let reveal_path = node.path.clone();
let trash_path = node.path.clone();
let cursor_path = node.path.clone();
let is_dir = node.is_dir;
let action = |id: &'static str, label: &'static str| {
ui::segment((id, key), label, false).debug_selector(move || format!("{id}-{index}"))
};
self.menu_row(row, target, cursor, cx)
.child(icon::view(
if node.is_dir {
Icon::Folder
} else {
Icon::LargeFiles
},
theme::muted(),
))
.child(
column(col::XXL)
.id(("explorer-name", key))
.flex()
.items_center()
.gap(unit(space::S))
.overflow_hidden()
.tip(tooltip::path(&node.path))
.child(div().truncate().child(node.name.clone()))
.when(node.protected, |this| {
this.child(
ui::tag(("explorer-protected", key), "Protected", ui::Tone::Neutral)
.debug_selector(move || format!("explorer-protected-{index}")),
)
}),
)
.child(
div()
.flex_1()
.min_w_0()
.h(unit(size::TRACK))
.rounded(theme::radius_bar())
.bg(theme::track())
.when(node.allocated > 0, |this| {
this.child(
div()
.h_full()
.w(relative(theme::share(node.allocated, whole)))
.min_w(unit(size::SLIVER))
.rounded(theme::radius_bar())
.bg(theme::bar()),
)
}),
)
.child(
column(col::M)
.text_right()
.font_weight(FontWeight::MEDIUM)
.child(theme::bytes(node.allocated)),
)
.child(
column(col::M)
.text_right()
.text_color(theme::muted())
.child(grouped_files(node.files)),
)
.child(
column(size::ACTIONS)
.flex()
.justify_end()
.gap(unit(space::XXS))
.when(is_dir, |this| {
this.child(action("explorer-open", "Open").on_click(cx.listener(
move |app, _: &ClickEvent, _, cx| {
cx.stop_propagation();
app.explorer_open(&open_path);
cx.notify();
},
)))
})
.child(action("explorer-reveal", "Reveal").on_click(cx.listener(
move |app, _: &ClickEvent, _, cx| {
cx.stop_propagation();
app.reveal_path(reveal_path.clone(), cx);
},
)))
.child(match refusal {
Some(reason) => action("explorer-trash", "Trash")
.opacity(theme::DISABLED)
.tip(tooltip::plain(reason)),
None => action("explorer-trash", "Trash").on_click(cx.listener(
move |app, _: &ClickEvent, _, cx| {
cx.stop_propagation();
app.explorer_delete(&trash_path, cx);
},
)),
}),
)
.on_click(cx.listener(move |app, event: &ClickEvent, _, cx| {
app.list.filtering = false;
if is_dir && event.click_count() > 1 {
app.explorer_open(&cursor_path);
} else {
app.list.cursors.insert(
Tab::DiskUsage,
Target::Row(Tab::DiskUsage, cursor_path.clone()),
);
}
cx.notify();
}))
}
}
fn grouped_files(files: u64) -> String {
plural(usize::try_from(files).unwrap_or(usize::MAX), "file")
}
fn other_row(bytes: u64, count: u64, whole: u64) -> Div {
ui::tabular(div())
.debug_selector(|| "explorer-other".to_owned())
.flex()
.flex_none()
.items_center()
.gap(unit(space::M))
.h(unit(size::row()))
.px(unit(space::GUTTER))
.text_color(theme::faint())
.child(div().w(unit(size::ICON)))
.child(column(col::XXL).truncate().child("Other smaller items"))
.child(
div()
.flex_1()
.min_w_0()
.h(unit(size::TRACK))
.rounded(theme::radius_bar())
.bg(theme::track())
.child(
div()
.h_full()
.w(relative(theme::share(bytes, whole)))
.min_w(unit(size::SLIVER))
.rounded(theme::radius_bar())
.bg(theme::bar_rest()),
),
)
.child(column(col::M).text_right().child(theme::bytes(bytes)))
.child(
column(col::M)
.text_right()
.child(plural(usize::try_from(count).unwrap_or(usize::MAX), "item")),
)
.child(column(size::ACTIONS))
}
fn rest_tile(rect: Rect, (width, height): (f32, f32), bytes: u64) -> AnyElement {
div()
.id("explorer-rest")
.absolute()
.left(relative(rect.x / width))
.top(relative(rect.y / height))
.w(relative(rect.w / width))
.h(relative(rect.h / height))
.p(unit(size::HAIR))
.tip(
Tooltip::details("Other smaller items")
.row("Size", theme::bytes(bytes))
.note("Each of these is too small to keep on its own")
.build(),
)
.child(div().size_full().bg(theme::tile_rest()))
.into_any_element()
}