mirror of
https://github.com/tobi/disktree.git
synced 2026-11-28 08:00:53 +00:00
disktree-app: a GPUI treemap explorer for Omarchy
Explore a scanned tree as a mosaic, mark what should go, review the list and remove it, with the volume's free space live on screen. - Keyboard and mouse throughout; keys act on the tile under the pointer when the pointer moved last. Cursor tooltip above the whole window. - The wheel magnifies toward a directory until it fills the view, then goes into it; tiles telescope from where they were to where they are. - Review screen with a segmented trash/permanent choice. The trash is the default when available; a permanent deletion asks in an alert dialog. - Layout follows the gpui-kit design guides: every size on one rem scale, ctrl =/-/0 interface zoom, and colours derived from the Omarchy theme. - Window-harness tests draw frames and press keys, end to end.
This commit is contained in:
@@ -0,0 +1,29 @@
|
||||
[package]
|
||||
name = "disktree-app"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
rust-version.workspace = true
|
||||
license.workspace = true
|
||||
description = "GPUI treemap explorer for disk usage, in Omarchy's visual language"
|
||||
|
||||
[[bin]]
|
||||
name = "disktree"
|
||||
path = "src/main.rs"
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
[dependencies]
|
||||
gpui-kit = { version = "=0.6.1", default-features = false, features = ["assets"] }
|
||||
gpui-omarchy = "0.1.2"
|
||||
disktree-core = { workspace = true }
|
||||
anyhow = { workspace = true }
|
||||
rustc-hash = { workspace = true }
|
||||
|
||||
[dev-dependencies]
|
||||
# The window harness: it lets the tests draw a real frame and press real keys.
|
||||
gpui-kit = { version = "=0.6.1", default-features = false, features = [
|
||||
"assets",
|
||||
"test-support",
|
||||
] }
|
||||
tempfile = "3"
|
||||
@@ -0,0 +1,180 @@
|
||||
//! `disktree`: find what is eating a volume, mark it, and remove it.
|
||||
//!
|
||||
//! The window opens on a treemap of the scanned root — the home directory
|
||||
//! unless another path is given — with a breadcrumb bar, a selection line, and a
|
||||
//! live free-space meter. Marking is non-destructive until the review screen
|
||||
//! is confirmed.
|
||||
|
||||
mod marks;
|
||||
mod palette;
|
||||
mod state;
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
mod treemap_view;
|
||||
mod ui;
|
||||
mod views;
|
||||
mod widgets;
|
||||
|
||||
use std::path::PathBuf;
|
||||
|
||||
use anyhow::{Context as _, Result};
|
||||
use disktree_core::scan::ScanOptions;
|
||||
use gpui_kit::{AppContext as _, WindowOptions, px, size};
|
||||
use state::Disktree;
|
||||
|
||||
/// What the command line asked for.
|
||||
#[derive(Debug)]
|
||||
struct Args {
|
||||
root: PathBuf,
|
||||
options: ScanOptions,
|
||||
depth: u32,
|
||||
}
|
||||
|
||||
const USAGE: &str = "\
|
||||
disktree — a treemap of what is using your disk
|
||||
|
||||
usage: disktree [OPTIONS] [PATH]
|
||||
|
||||
arguments:
|
||||
PATH directory to scan (default: the home directory)
|
||||
|
||||
The window opens on a treemap of the root, largest first. Space marks the
|
||||
selected tile, Enter opens it, c reviews the marked list, ? lists every key.
|
||||
|
||||
options:
|
||||
-a, --apparent-size measure apparent length instead of allocated blocks
|
||||
-l, --follow-links follow symlinks
|
||||
-H, --no-hidden skip dotfiles and dot-directories
|
||||
-x, --one-filesystem do not cross filesystem boundaries
|
||||
-d, --depth N how many levels to draw at once (1-6, default 3)
|
||||
--metric files rank by file count instead of bytes
|
||||
-h, --help show this help
|
||||
";
|
||||
|
||||
fn main() -> Result<()> {
|
||||
let args = parse_args()?;
|
||||
let root = args.root.clone();
|
||||
let depth = args.depth;
|
||||
let title_root = root.clone();
|
||||
|
||||
gpui_kit::application()
|
||||
.with_assets(gpui_kit::assets::Assets)
|
||||
.run(move |cx| {
|
||||
gpui_omarchy::init(cx);
|
||||
let options = args.options.clone();
|
||||
let root_for_app = root.clone();
|
||||
let window = cx
|
||||
.open_window(
|
||||
WindowOptions {
|
||||
window_bounds: Some(gpui_kit::WindowBounds::Windowed(
|
||||
gpui_kit::Bounds::new(
|
||||
gpui_kit::point(px(120.), px(90.)),
|
||||
size(px(1440.), px(900.)),
|
||||
),
|
||||
)),
|
||||
titlebar: Some(gpui_kit::TitlebarOptions {
|
||||
title: Some(
|
||||
format!(
|
||||
"disktree · {}",
|
||||
marks::display_path(
|
||||
&title_root,
|
||||
std::env::var_os("HOME")
|
||||
.map(PathBuf::from)
|
||||
.as_deref(),
|
||||
)
|
||||
)
|
||||
.into(),
|
||||
),
|
||||
..Default::default()
|
||||
}),
|
||||
// Below this the treemap stops being readable, so ask
|
||||
// the compositor not to go there.
|
||||
window_min_size: Some(size(px(900.), px(600.))),
|
||||
..Default::default()
|
||||
},
|
||||
move |_, cx| {
|
||||
cx.new(|cx| {
|
||||
Disktree::new(
|
||||
root_for_app.clone(),
|
||||
options.clone(),
|
||||
depth,
|
||||
cx,
|
||||
)
|
||||
})
|
||||
},
|
||||
)
|
||||
.expect("open the disktree window");
|
||||
|
||||
// The treemap owns the keyboard from the first frame; there is no
|
||||
// text field to focus first.
|
||||
let _ = window.update(cx, |this, window, cx| {
|
||||
let focus = this.focus.clone();
|
||||
window.focus(&focus, cx);
|
||||
});
|
||||
cx.activate(true);
|
||||
});
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn parse_args() -> Result<Args> {
|
||||
let mut root: Option<PathBuf> = None;
|
||||
let mut options = ScanOptions::default();
|
||||
let mut depth = 3_u32;
|
||||
let mut args = std::env::args().skip(1);
|
||||
|
||||
while let Some(arg) = args.next() {
|
||||
match arg.as_str() {
|
||||
"-h" | "--help" => {
|
||||
println!("{USAGE}");
|
||||
std::process::exit(0);
|
||||
}
|
||||
"-a" | "--apparent-size" => options.apparent_size = true,
|
||||
"-l" | "--follow-links" => options.follow_links = true,
|
||||
"-H" | "--no-hidden" => options.include_hidden = false,
|
||||
"-x" | "--one-filesystem" => options.one_filesystem = true,
|
||||
"-d" | "--depth" => {
|
||||
let value = args.next().context("--depth needs a number")?;
|
||||
depth = value.parse().context("--depth needs a number")?;
|
||||
anyhow::ensure!(
|
||||
(1..=6).contains(&depth),
|
||||
"--depth must be 1 to 6"
|
||||
);
|
||||
}
|
||||
"--metric" => {
|
||||
let value = args.next().context("--metric needs a value")?;
|
||||
options.metric = match value.as_str() {
|
||||
"files" => disktree_core::tree::Metric::Files,
|
||||
"bytes" | "size" => disktree_core::tree::Metric::Bytes,
|
||||
other => anyhow::bail!(
|
||||
"unknown metric {other}; try bytes or files"
|
||||
),
|
||||
};
|
||||
}
|
||||
other if other.starts_with('-') => {
|
||||
anyhow::bail!("unknown option {other}\n\n{USAGE}");
|
||||
}
|
||||
path => {
|
||||
anyhow::ensure!(root.is_none(), "only one path can be scanned");
|
||||
root = Some(PathBuf::from(path));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let root = match root {
|
||||
Some(root) => root,
|
||||
None => std::env::var_os("HOME")
|
||||
.map(PathBuf::from)
|
||||
.context("no path given and HOME is not set")?,
|
||||
};
|
||||
// Store the depth as the initial view setting rather than a scan option: it
|
||||
// is a display choice the run-time `[` and `]` keys also change.
|
||||
let metadata = std::fs::metadata(&root)
|
||||
.with_context(|| format!("cannot read {}", root.display()))?;
|
||||
anyhow::ensure!(metadata.is_dir(), "{} is not a directory", root.display());
|
||||
|
||||
Ok(Args {
|
||||
root,
|
||||
options,
|
||||
depth: depth.clamp(1, 6),
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,231 @@
|
||||
//! The set of paths marked for removal.
|
||||
//!
|
||||
//! Marks are keyed by absolute path, not by tree position: the tree is
|
||||
//! re-scanned after a removal, and a mark must survive that (or be reported as
|
||||
//! gone) rather than silently pointing at a different node.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use disktree_core::removal::Target;
|
||||
use disktree_core::tree::{Metric, Node};
|
||||
use rustc_hash::FxHashSet;
|
||||
|
||||
/// Marked paths, in the order they were marked.
|
||||
#[derive(Debug, Default)]
|
||||
pub struct Marks {
|
||||
items: Vec<Target>,
|
||||
index: FxHashSet<PathBuf>,
|
||||
}
|
||||
|
||||
impl Marks {
|
||||
pub fn contains(&self, path: &Path) -> bool {
|
||||
self.index.contains(path)
|
||||
}
|
||||
|
||||
pub fn items(&self) -> &[Target] {
|
||||
&self.items
|
||||
}
|
||||
|
||||
pub const fn len(&self) -> usize {
|
||||
self.items.len()
|
||||
}
|
||||
|
||||
pub const fn is_empty(&self) -> bool {
|
||||
self.items.is_empty()
|
||||
}
|
||||
|
||||
/// Mark `target`, or unmark it when it is already marked.
|
||||
///
|
||||
/// Returns `true` when the path ended up marked.
|
||||
pub fn toggle(&mut self, target: Target) -> bool {
|
||||
if self.index.remove(&target.path) {
|
||||
self.items.retain(|item| item.path != target.path);
|
||||
false
|
||||
} else {
|
||||
self.index.insert(target.path.clone());
|
||||
self.items.push(target);
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
pub fn remove(&mut self, path: &Path) {
|
||||
if self.index.remove(path) {
|
||||
self.items.retain(|item| item.path != path);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn clear(&mut self) {
|
||||
self.items.clear();
|
||||
self.index.clear();
|
||||
}
|
||||
|
||||
/// Re-read sizes from a freshly scanned tree and drop marks whose path no
|
||||
/// longer exists, so the tally never claims space that is already gone.
|
||||
pub fn refresh(&mut self, root_path: &Path, root: &Node, metric: Metric) {
|
||||
let mut resolved = Vec::with_capacity(self.items.len());
|
||||
for item in &self.items {
|
||||
match find(root_path, root, &item.path) {
|
||||
Some(node) => resolved.push(Target {
|
||||
bytes: node.value(metric),
|
||||
is_dir: node.is_dir(),
|
||||
hidden: is_hidden(&item.path),
|
||||
path: item.path.clone(),
|
||||
}),
|
||||
None => resolved.push(Target {
|
||||
bytes: 0,
|
||||
..item.clone()
|
||||
}),
|
||||
}
|
||||
}
|
||||
self.items = resolved;
|
||||
}
|
||||
}
|
||||
|
||||
/// Walk the tree to the node at an absolute path. Path components are compared
|
||||
/// one at a time, so a name containing a path separator cannot confuse it.
|
||||
pub fn find<'a>(
|
||||
root_path: &Path,
|
||||
root: &'a Node,
|
||||
path: &Path,
|
||||
) -> Option<&'a Node> {
|
||||
let relative = path.strip_prefix(root_path).ok()?;
|
||||
let mut node = root;
|
||||
for component in relative.components() {
|
||||
let name = component.as_os_str().to_string_lossy();
|
||||
node = node
|
||||
.children
|
||||
.iter()
|
||||
.find(|child| child.name.as_ref() == name)?;
|
||||
}
|
||||
Some(node)
|
||||
}
|
||||
|
||||
/// A dotfile or dot-directory by name.
|
||||
pub fn is_hidden(path: &Path) -> bool {
|
||||
path.file_name()
|
||||
.is_some_and(|name| name.to_string_lossy().starts_with('.'))
|
||||
}
|
||||
|
||||
/// Shorten a path for display: `~` for the home directory, and the path with
|
||||
/// the home prefix replaced when it is below it.
|
||||
pub fn display_path(path: &Path, home: Option<&Path>) -> String {
|
||||
match home
|
||||
.and_then(|home| path.strip_prefix(home).ok().map(|rest| (home, rest)))
|
||||
{
|
||||
Some((_, rest)) if rest.as_os_str().is_empty() => "~".to_string(),
|
||||
Some((_, rest)) => format!("~/{}", rest.display()),
|
||||
None => path.display().to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use disktree_core::tree::{NodeKind, aggregate};
|
||||
|
||||
fn file(name: &str, bytes: u64) -> Node {
|
||||
Node::entry(name, NodeKind::File, bytes)
|
||||
}
|
||||
|
||||
fn tree() -> Node {
|
||||
let mut root = Node::directory("home");
|
||||
let mut cache = Node::directory(".cache");
|
||||
cache.children.push(file("blob.bin", 900));
|
||||
root.children.push(cache);
|
||||
root.children.push(file("notes.bin", 100));
|
||||
aggregate(&mut root, Metric::Bytes);
|
||||
root
|
||||
}
|
||||
|
||||
fn target(path: &str, bytes: u64) -> Target {
|
||||
Target {
|
||||
path: PathBuf::from(path),
|
||||
bytes,
|
||||
is_dir: false,
|
||||
hidden: false,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn toggling_marks_and_unmarks() {
|
||||
let mut marks = Marks::default();
|
||||
assert!(marks.toggle(target("/home/tobi/a", 1)));
|
||||
assert!(marks.contains(Path::new("/home/tobi/a")));
|
||||
assert_eq!(marks.len(), 1);
|
||||
assert!(!marks.toggle(target("/home/tobi/a", 1)));
|
||||
assert!(marks.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn marking_the_same_path_twice_keeps_one_entry() {
|
||||
let mut marks = Marks::default();
|
||||
marks.toggle(target("/home/tobi/a", 1));
|
||||
marks.toggle(target("/home/tobi/a", 1));
|
||||
marks.toggle(target("/home/tobi/a", 1));
|
||||
assert_eq!(marks.len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn refresh_re_reads_sizes_from_a_new_tree() {
|
||||
let root_path = Path::new("/home/tobi");
|
||||
let root = tree();
|
||||
let mut marks = Marks::default();
|
||||
marks.toggle(target("/home/tobi/.cache", 0));
|
||||
marks.toggle(target("/home/tobi/gone", 500));
|
||||
|
||||
marks.refresh(root_path, &root, Metric::Bytes);
|
||||
assert_eq!(marks.items()[0].bytes, 900);
|
||||
assert!(marks.items()[0].is_dir);
|
||||
assert!(marks.items()[0].hidden, "the .cache mark is hidden");
|
||||
assert_eq!(marks.items()[1].bytes, 0, "a path that no longer exists");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn find_matches_whole_components_only() {
|
||||
let root = tree();
|
||||
assert!(
|
||||
find(
|
||||
Path::new("/home/tobi"),
|
||||
&root,
|
||||
Path::new("/home/tobi/.cache")
|
||||
)
|
||||
.is_some()
|
||||
);
|
||||
assert!(
|
||||
find(
|
||||
Path::new("/home/tobi"),
|
||||
&root,
|
||||
Path::new("/home/tobi/.cache/blob.bin")
|
||||
)
|
||||
.is_some()
|
||||
);
|
||||
assert!(
|
||||
find(
|
||||
Path::new("/home/tobi"),
|
||||
&root,
|
||||
Path::new("/home/tobi/cache")
|
||||
)
|
||||
.is_none()
|
||||
);
|
||||
assert!(
|
||||
find(
|
||||
Path::new("/elsewhere"),
|
||||
&root,
|
||||
Path::new("/home/tobi/notes.bin")
|
||||
)
|
||||
.is_none()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn display_path_shortens_the_home_prefix() {
|
||||
let home = Path::new("/home/tobi");
|
||||
assert_eq!(
|
||||
display_path(Path::new("/home/tobi/.cache/npm"), Some(home)),
|
||||
"~/.cache/npm"
|
||||
);
|
||||
assert_eq!(display_path(home, Some(home)), "~");
|
||||
assert_eq!(display_path(Path::new("/var/log"), Some(home)), "/var/log");
|
||||
assert_eq!(display_path(Path::new("/var/log"), None), "/var/log");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,135 @@
|
||||
//! Colours derived from the Omarchy theme.
|
||||
//!
|
||||
//! Nothing here invents a palette: every colour is the active theme's, shifted
|
||||
//! in hue, lightness or alpha. That keeps the app inside Omarchy's visual
|
||||
//! language across themes, and light and dark alike.
|
||||
|
||||
use gpui_kit::Hsla;
|
||||
use gpui_kit::base::ThemeAppearance;
|
||||
use gpui_omarchy::Theme;
|
||||
|
||||
/// Hue for a tile: nesting walks the wheel so levels are readable without
|
||||
/// borders, and hidden entries get a hue of their own instead of a shade.
|
||||
///
|
||||
/// Hidden directories under a home directory are usually the largest thing
|
||||
/// there — `~/.cache`, `~/.cargo`, `~/.local/share/Trash` — so they are marked
|
||||
/// by colour rather than hidden away.
|
||||
pub fn tile_hue(theme: &Theme, depth: u32, hidden: bool) -> f32 {
|
||||
let base = if hidden {
|
||||
theme.warning.h
|
||||
} else {
|
||||
theme.accent.h
|
||||
};
|
||||
wrap_hue((depth as f32).mul_add(0.075, base))
|
||||
}
|
||||
|
||||
fn wrap_hue(hue: f32) -> f32 {
|
||||
let hue = hue % 1.0;
|
||||
if hue < 0.0 { hue + 1.0 } else { hue }
|
||||
}
|
||||
|
||||
/// Fill for a tile at `depth`, as an opaque colour the mosaic can paint.
|
||||
pub fn tile_fill(
|
||||
theme: &Theme,
|
||||
depth: u32,
|
||||
hidden: bool,
|
||||
marked: bool,
|
||||
) -> Hsla {
|
||||
let dark = theme.appearance == ThemeAppearance::Dark;
|
||||
// Deeper levels lift slightly so nested tiles separate from their parent
|
||||
// without needing a border on every one of them.
|
||||
let lightness = if dark {
|
||||
(depth.min(4) as f32).mul_add(0.055, 0.20)
|
||||
} else {
|
||||
(depth.min(4) as f32).mul_add(-0.055, 0.86)
|
||||
};
|
||||
let saturation = if hidden { 0.55 } else { 0.42 };
|
||||
let fill = Hsla {
|
||||
h: tile_hue(theme, depth, hidden),
|
||||
s: saturation,
|
||||
l: lightness,
|
||||
a: 1.0,
|
||||
};
|
||||
// Keep the mosaic calm: pull it toward the theme background so the tile
|
||||
// colours read as tinted surfaces rather than a rainbow.
|
||||
let flattened = mix(fill, theme.background, 0.34);
|
||||
if marked {
|
||||
mix(flattened, theme.danger, 0.30)
|
||||
} else {
|
||||
flattened
|
||||
}
|
||||
}
|
||||
|
||||
/// Linear interpolation between two colours in HSLA.
|
||||
pub fn mix(from: Hsla, to: Hsla, t: f32) -> Hsla {
|
||||
let t = t.clamp(0.0, 1.0);
|
||||
let lerp = |a: f32, b: f32| (b - a).mul_add(t, a);
|
||||
Hsla {
|
||||
h: lerp(from.h, to.h),
|
||||
s: lerp(from.s, to.s),
|
||||
l: lerp(from.l, to.l),
|
||||
a: lerp(from.a, to.a),
|
||||
}
|
||||
}
|
||||
|
||||
/// The colour of a tile's label on top of its fill.
|
||||
pub fn label_color(theme: &Theme, depth: u32) -> Hsla {
|
||||
let dark = theme.appearance == ThemeAppearance::Dark;
|
||||
let base = if dark { theme.bright } else { theme.background };
|
||||
if depth == 0 { base } else { base.opacity(0.86) }
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn theme(appearance: ThemeAppearance) -> Theme {
|
||||
let mut theme = Theme::tokyo_night();
|
||||
theme.appearance = appearance;
|
||||
theme
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hidden_tiles_are_a_different_hue_from_visible_ones() {
|
||||
let theme = theme(ThemeAppearance::Dark);
|
||||
let visible = tile_fill(&theme, 0, false, false);
|
||||
let hidden = tile_fill(&theme, 0, true, false);
|
||||
assert!((visible.h - hidden.h).abs() > 0.02);
|
||||
assert!(visible.s > 0.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn marking_shifts_a_tile_toward_the_danger_colour() {
|
||||
let theme = theme(ThemeAppearance::Dark);
|
||||
let plain = tile_fill(&theme, 1, false, false);
|
||||
let marked = tile_fill(&theme, 1, false, true);
|
||||
let plain_distance = (plain.h - theme.danger.h).abs();
|
||||
let marked_distance = (marked.h - theme.danger.h).abs();
|
||||
assert!(marked_distance < plain_distance);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn light_and_dark_appearances_differ_in_lightness() {
|
||||
let dark = tile_fill(&theme(ThemeAppearance::Dark), 0, false, false);
|
||||
let light = tile_fill(&theme(ThemeAppearance::Light), 0, false, false);
|
||||
assert!(light.l > dark.l);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hue_stays_in_range_at_every_depth() {
|
||||
let theme = theme(ThemeAppearance::Dark);
|
||||
for depth in 0..12 {
|
||||
let hue = tile_hue(&theme, depth, false);
|
||||
assert!((0.0..1.0).contains(&hue), "depth {depth} gave {hue}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mix_clamps_its_parameter() {
|
||||
let theme = theme(ThemeAppearance::Dark);
|
||||
let clamped_low = mix(theme.background, theme.accent, -1.0).l;
|
||||
let clamped_high = mix(theme.background, theme.accent, 2.0).l;
|
||||
assert!((clamped_low - theme.background.l).abs() < f32::EPSILON);
|
||||
assert!((clamped_high - theme.accent.l).abs() < f32::EPSILON);
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,816 @@
|
||||
//! End-to-end tests through the real window harness.
|
||||
//!
|
||||
//! These drive the application the way a person does — draw a frame, press
|
||||
//! keys, type — so they catch what unit tests on the state cannot: a screen
|
||||
//! that panics while painting, a binding that never fires, a removal that
|
||||
//! reports success without removing anything.
|
||||
|
||||
use std::path::Path;
|
||||
|
||||
use disktree_core::removal::RemovalMode;
|
||||
use disktree_core::scan::{ScanOptions, scan};
|
||||
use disktree_core::treemap::Tile;
|
||||
use gpui_kit::{
|
||||
Bounds, Context, Entity, Pixels, Point, TestAppContext, VisualTestContext,
|
||||
px,
|
||||
};
|
||||
use gpui_omarchy::Theme;
|
||||
|
||||
use crate::state::{Disktree, Screen};
|
||||
|
||||
/// A small tree on disk: two directories, a nested file, and a hidden one.
|
||||
///
|
||||
/// The hidden directory holds the largest file, which is both the common case
|
||||
/// in a home directory and the one the ranking has to get right.
|
||||
fn fixture() -> tempfile::TempDir {
|
||||
let temp = tempfile::TempDir::new().expect("tempdir");
|
||||
let root = temp.path();
|
||||
for (path, bytes) in [
|
||||
("keep/notes.txt", 1_000_usize),
|
||||
("junk/blob.bin", 200_000),
|
||||
("junk/deeper/more.bin", 100_000),
|
||||
(".cache/blob.bin", 300_000),
|
||||
] {
|
||||
let file = root.join(path);
|
||||
std::fs::create_dir_all(file.parent().expect("parent")).expect("mkdir");
|
||||
std::fs::write(&file, vec![b'x'; bytes]).expect("write");
|
||||
}
|
||||
temp
|
||||
}
|
||||
|
||||
/// Apparent sizes, so the assertions are about the tree and not about how the
|
||||
/// filesystem rounds a small file up to a block.
|
||||
fn options() -> ScanOptions {
|
||||
ScanOptions {
|
||||
apparent_size: true,
|
||||
..ScanOptions::default()
|
||||
}
|
||||
}
|
||||
|
||||
type Window = VisualTestContext;
|
||||
|
||||
/// Open a window over a real scan of `root`, without the background walk.
|
||||
fn view_over<'a>(
|
||||
root: &Path,
|
||||
cx: &'a mut TestAppContext,
|
||||
) -> (Entity<Disktree>, &'a mut Window) {
|
||||
let tree = scan(root, options()).expect("scan the fixture");
|
||||
let root_path = root.to_path_buf();
|
||||
let (view, cx) = cx.add_window_view(move |_, cx| {
|
||||
Disktree::with_tree(root_path.clone(), tree, options(), 3, cx)
|
||||
});
|
||||
let focus = view.read_with(cx, |app, _| app.focus.clone());
|
||||
cx.update(|window, cx| window.focus(&focus, cx));
|
||||
(view, cx)
|
||||
}
|
||||
|
||||
fn draw(cx: &mut Window) {
|
||||
cx.update(|window, cx| {
|
||||
window.draw(cx).clear(cx);
|
||||
});
|
||||
}
|
||||
|
||||
fn press(cx: &mut Window, keys: &str) {
|
||||
cx.simulate_keystrokes(keys);
|
||||
draw(cx);
|
||||
}
|
||||
|
||||
fn update<R>(
|
||||
view: &Entity<Disktree>,
|
||||
cx: &mut Window,
|
||||
f: impl FnOnce(&mut Disktree, &mut Context<'_, Disktree>) -> R,
|
||||
) -> R {
|
||||
view.update(cx, f)
|
||||
}
|
||||
|
||||
fn read<R>(
|
||||
view: &Entity<Disktree>,
|
||||
cx: &Window,
|
||||
f: impl FnOnce(&Disktree) -> R,
|
||||
) -> R {
|
||||
view.read_with(cx, |app, _| f(app))
|
||||
}
|
||||
|
||||
#[gpui_kit::test]
|
||||
fn the_window_draws_a_treemap_with_tiles(cx: &mut TestAppContext) {
|
||||
cx.update(gpui_omarchy::init);
|
||||
let temp = fixture();
|
||||
let (view, cx) = view_over(temp.path(), cx);
|
||||
draw(cx);
|
||||
|
||||
let bounds: Bounds<Pixels> =
|
||||
cx.debug_bounds("disktree-root").expect("root element");
|
||||
assert!(bounds.size.width > px(0.) && bounds.size.height > px(0.));
|
||||
|
||||
let (size, tiles) = update(&view, cx, |app, _| {
|
||||
(
|
||||
app.treemap_size.get(),
|
||||
app.layout().map(<[Tile]>::len).unwrap_or_default(),
|
||||
)
|
||||
});
|
||||
assert!(size.width > px(0.), "treemap width {size:?}");
|
||||
assert!(size.height > px(0.), "treemap height {size:?}");
|
||||
assert!(tiles >= 3, "tiles laid out: {tiles}");
|
||||
}
|
||||
|
||||
#[gpui_kit::test]
|
||||
fn the_first_scan_shows_what_it_is_doing_then_the_treemap(
|
||||
cx: &mut TestAppContext,
|
||||
) {
|
||||
cx.update(gpui_omarchy::init);
|
||||
let temp = fixture();
|
||||
let root = temp.path().to_path_buf();
|
||||
// Through the real constructor, so this is the path every first run takes.
|
||||
let (view, cx) =
|
||||
cx.add_window_view(move |_, cx| Disktree::new(root, options(), 3, cx));
|
||||
draw(cx);
|
||||
|
||||
// Nothing is known yet, so the viewport counts the walk instead of showing
|
||||
// an empty mosaic.
|
||||
assert!(read(&view, cx, |app| app.tree().is_none()));
|
||||
assert!(cx.debug_bounds("disktree-root").is_some());
|
||||
|
||||
let epoch = read(&view, cx, |app| app.scan_epoch);
|
||||
let mut ready = false;
|
||||
for _ in 0..600 {
|
||||
std::thread::sleep(std::time::Duration::from_millis(5));
|
||||
ready = update(&view, cx, |app, cx| {
|
||||
app.poll_scan_once(epoch, cx);
|
||||
app.tree().is_some()
|
||||
});
|
||||
if ready {
|
||||
break;
|
||||
}
|
||||
}
|
||||
assert!(ready, "the scan landed");
|
||||
draw(cx);
|
||||
|
||||
let (tiles, selected, hidden_present) = update(&view, cx, |app, _| {
|
||||
(
|
||||
app.layout().map(<[Tile]>::len).unwrap_or_default(),
|
||||
app.selected.is_some(),
|
||||
app.tree().is_some_and(|tree| {
|
||||
tree.children.iter().any(|c| c.name.starts_with('.'))
|
||||
}),
|
||||
)
|
||||
});
|
||||
assert!(tiles >= 3, "tiles after the scan: {tiles}");
|
||||
assert!(
|
||||
selected,
|
||||
"the largest entry is selected for the selection line"
|
||||
);
|
||||
assert!(hidden_present, "hidden directories are part of the tree");
|
||||
}
|
||||
|
||||
#[gpui_kit::test]
|
||||
fn keys_walk_the_tree_and_mark_what_is_selected(cx: &mut TestAppContext) {
|
||||
cx.update(gpui_omarchy::init);
|
||||
let temp = fixture();
|
||||
let (view, cx) = view_over(temp.path(), cx);
|
||||
draw(cx);
|
||||
|
||||
// Largest first: .cache holds the biggest file.
|
||||
let (selected, name) = read(&view, cx, |app| {
|
||||
(
|
||||
app.selected.clone(),
|
||||
app.node_at(&[0]).map(|node| node.name.to_string()),
|
||||
)
|
||||
});
|
||||
assert_eq!(selected, Some(vec![0]));
|
||||
assert_eq!(name.as_deref(), Some(".cache"));
|
||||
|
||||
press(cx, "space");
|
||||
let (marks, bytes) =
|
||||
read(&view, cx, |app| (app.marks.len(), app.plan().bytes()));
|
||||
assert_eq!(marks, 1);
|
||||
assert_eq!(bytes, 300_000, "the whole hidden directory");
|
||||
|
||||
// Enter descends, Escape comes back out.
|
||||
press(cx, "enter");
|
||||
assert!(!read(&view, cx, |app| app.crumbs.is_empty()));
|
||||
press(cx, "escape");
|
||||
press(cx, "escape");
|
||||
assert!(read(&view, cx, |app| app.crumbs.is_empty()));
|
||||
|
||||
// Space twice more leaves the mark as it was.
|
||||
press(cx, "space");
|
||||
press(cx, "space");
|
||||
let marks = read(&view, cx, |app| app.marks.items().to_vec());
|
||||
assert_eq!(marks.len(), 1);
|
||||
assert_eq!(marks[0].bytes, 300_000);
|
||||
}
|
||||
|
||||
#[gpui_kit::test]
|
||||
fn a_permanent_deletion_asks_in_an_alert_dialog_then_removes(
|
||||
cx: &mut TestAppContext,
|
||||
) {
|
||||
cx.update(gpui_omarchy::init);
|
||||
let temp = fixture();
|
||||
let (view, cx) = view_over(temp.path(), cx);
|
||||
draw(cx);
|
||||
|
||||
// Mark "junk" directly, which is what clicking its tile would do, and
|
||||
// choose the permanent path: the trash path would reach the real trash.
|
||||
update(&view, cx, |app, cx| {
|
||||
app.removal_mode = RemovalMode::Permanent;
|
||||
let junk = app
|
||||
.tree()
|
||||
.and_then(|tree| {
|
||||
tree.children
|
||||
.iter()
|
||||
.position(|child| &*child.name == "junk")
|
||||
.map(|index| vec![index])
|
||||
})
|
||||
.expect("the junk directory");
|
||||
app.select(Some(junk.clone()), cx);
|
||||
app.toggle_mark(&junk, cx);
|
||||
assert_eq!(app.plan().bytes(), 300_000);
|
||||
});
|
||||
|
||||
press(cx, "c");
|
||||
assert_eq!(read(&view, cx, |app| app.screen), Screen::Review);
|
||||
|
||||
// Enter on the review screen opens the alert dialog; nothing is deleted.
|
||||
press(cx, "enter");
|
||||
assert!(read(&view, cx, |app| app.confirm_open));
|
||||
assert_eq!(read(&view, cx, |app| app.screen), Screen::Review);
|
||||
assert!(
|
||||
temp.path().join("junk").exists(),
|
||||
"nothing has happened yet"
|
||||
);
|
||||
|
||||
// Enter in the dialog is its confirm action.
|
||||
press(cx, "enter");
|
||||
assert!(!read(&view, cx, |app| app.confirm_open));
|
||||
assert_eq!(read(&view, cx, |app| app.screen), Screen::Running);
|
||||
|
||||
// The removal runs on a real worker thread, so the test drives the same
|
||||
// poll the UI's ticker drives rather than waiting on the test clock.
|
||||
let epoch = read(&view, cx, |app| app.run_epoch);
|
||||
let mut finished = false;
|
||||
for _ in 0..400 {
|
||||
std::thread::sleep(std::time::Duration::from_millis(5));
|
||||
finished = update(&view, cx, |app, cx| {
|
||||
app.poll_removal_once(epoch, cx);
|
||||
app.screen == Screen::Done
|
||||
});
|
||||
if finished {
|
||||
break;
|
||||
}
|
||||
}
|
||||
assert!(finished, "the removal finished");
|
||||
draw(cx);
|
||||
|
||||
let summary = read(&view, cx, |app| app.run_summary.clone());
|
||||
assert_eq!(summary.removed, 1, "{summary:?}");
|
||||
assert_eq!(summary.failed, 0, "{summary:?}");
|
||||
assert!(
|
||||
read(&view, cx, |app| app.marks.is_empty()),
|
||||
"the list clears after the run"
|
||||
);
|
||||
assert!(!temp.path().join("junk").exists(), "junk is gone");
|
||||
assert!(
|
||||
temp.path().join("keep/notes.txt").exists(),
|
||||
"an unmarked directory is untouched"
|
||||
);
|
||||
assert!(
|
||||
temp.path().join(".cache/blob.bin").exists(),
|
||||
"an unmarked hidden directory is untouched"
|
||||
);
|
||||
}
|
||||
|
||||
/// A subdivided directory keeps a band at the top for its own name, and its
|
||||
/// children start below it. That is what makes the inner tiles selectable: the
|
||||
/// parent's name never covers them.
|
||||
#[gpui_kit::test]
|
||||
fn a_parents_name_gets_its_own_band_above_its_children(
|
||||
cx: &mut TestAppContext,
|
||||
) {
|
||||
cx.update(gpui_omarchy::init);
|
||||
let temp = fixture();
|
||||
let (view, cx) = view_over(temp.path(), cx);
|
||||
draw(cx);
|
||||
|
||||
let (band, lowest_child_top, bands_in_mosaic) =
|
||||
update(&view, cx, |app, _| {
|
||||
let tiles = app.layout().map(<[Tile]>::to_vec).unwrap_or_default();
|
||||
let parent = tiles
|
||||
.iter()
|
||||
.find(|tile| tile.crumbs() == [1])
|
||||
.expect("the junk directory");
|
||||
let band = parent
|
||||
.header
|
||||
.expect("junk is subdivided, so it keeps a band");
|
||||
let children_top = tiles
|
||||
.iter()
|
||||
.filter(|tile| {
|
||||
tile.crumbs().starts_with(&[1]) && tile.crumbs().len() > 1
|
||||
})
|
||||
.map(|tile| tile.rect.y)
|
||||
.fold(f32::INFINITY, f32::min);
|
||||
let mosaic = app.prepare();
|
||||
let bands_in_mosaic = mosaic
|
||||
.labels
|
||||
.iter()
|
||||
.filter(|label| label.header.is_some())
|
||||
.count();
|
||||
(band, children_top, bands_in_mosaic)
|
||||
});
|
||||
|
||||
assert!(
|
||||
lowest_child_top >= band.bottom() - f32::EPSILON,
|
||||
"children start at {} but the band ends at {}",
|
||||
lowest_child_top,
|
||||
band.bottom()
|
||||
);
|
||||
assert!(
|
||||
band.h >= 8.0,
|
||||
"a band has to be tall enough to read: {}",
|
||||
band.h
|
||||
);
|
||||
assert!(
|
||||
bands_in_mosaic >= 1,
|
||||
"the parent's own label is placed in a band"
|
||||
);
|
||||
}
|
||||
|
||||
#[gpui_kit::test]
|
||||
fn hovering_reports_the_tile_under_the_pointer(cx: &mut TestAppContext) {
|
||||
cx.update(gpui_omarchy::init);
|
||||
let temp = fixture();
|
||||
let (view, cx) = view_over(temp.path(), cx);
|
||||
draw(cx);
|
||||
|
||||
let (origin, biggest, centre) = update(&view, cx, |app, _| {
|
||||
// A leaf tile, so "the deepest tile under the pointer" is unambiguous.
|
||||
let biggest = app
|
||||
.layout()
|
||||
.and_then(|tiles| {
|
||||
tiles
|
||||
.iter()
|
||||
.filter(|tile| {
|
||||
let crumbs = tile.crumbs();
|
||||
!tiles.iter().any(|other| {
|
||||
other.crumbs().len() > crumbs.len()
|
||||
&& other.crumbs().starts_with(crumbs)
|
||||
})
|
||||
})
|
||||
.max_by(|left, right| {
|
||||
left.rect.area().total_cmp(&right.rect.area())
|
||||
})
|
||||
.map(|tile| tile.crumbs().to_vec())
|
||||
})
|
||||
.expect("a tile to hover");
|
||||
let rect = app.tile_rect(&biggest).expect("a rectangle");
|
||||
let screen = app.view.project(rect);
|
||||
(
|
||||
app.treemap_origin.get(),
|
||||
biggest,
|
||||
(screen.x + screen.w / 2.0, screen.y + screen.h / 2.0),
|
||||
)
|
||||
});
|
||||
|
||||
let (x, y) = centre;
|
||||
cx.simulate_mouse_move(
|
||||
Point::new(origin.x + px(x), origin.y + px(y)),
|
||||
None,
|
||||
gpui_kit::Modifiers::default(),
|
||||
);
|
||||
draw(cx);
|
||||
|
||||
let hovered = read(&view, cx, |app| app.hovered.clone());
|
||||
assert_eq!(hovered.as_deref(), Some(biggest.as_slice()));
|
||||
}
|
||||
|
||||
#[gpui_kit::test]
|
||||
fn typing_in_the_find_field_jumps_to_a_match(cx: &mut TestAppContext) {
|
||||
cx.update(gpui_omarchy::init);
|
||||
let temp = fixture();
|
||||
let (view, cx) = view_over(temp.path(), cx);
|
||||
draw(cx);
|
||||
|
||||
press(cx, "/");
|
||||
assert!(read(&view, cx, |app| app.find_open));
|
||||
|
||||
cx.simulate_input("deeper");
|
||||
draw(cx);
|
||||
assert_eq!(read(&view, cx, |app| app.find.clone()), "deeper");
|
||||
|
||||
press(cx, "enter");
|
||||
let (open, crumbs, selected) = read(&view, cx, |app| {
|
||||
(app.find_open, app.crumbs.clone(), app.selected.clone())
|
||||
});
|
||||
assert!(!open);
|
||||
assert_eq!(crumbs, vec![1], "the matched entry's parent is drawn");
|
||||
// junk holds blob.bin (largest first) and then deeper, so the match sits at
|
||||
// the second index: the find jumps to the entry, not to its rank.
|
||||
assert_eq!(selected, Some(vec![1, 1]));
|
||||
}
|
||||
|
||||
#[gpui_kit::test]
|
||||
fn the_help_overlay_opens_and_closes(cx: &mut TestAppContext) {
|
||||
cx.update(gpui_omarchy::init);
|
||||
let temp = fixture();
|
||||
let (view, cx) = view_over(temp.path(), cx);
|
||||
draw(cx);
|
||||
|
||||
press(cx, "?");
|
||||
assert!(read(&view, cx, |app| app.show_help));
|
||||
press(cx, "escape");
|
||||
assert!(!read(&view, cx, |app| app.show_help));
|
||||
}
|
||||
|
||||
#[gpui_kit::test]
|
||||
fn the_treemap_zooms_with_the_wheel_and_resets(cx: &mut TestAppContext) {
|
||||
cx.update(gpui_omarchy::init);
|
||||
let temp = fixture();
|
||||
let (view, cx) = view_over(temp.path(), cx);
|
||||
draw(cx);
|
||||
|
||||
let middle = read(&view, cx, |app| {
|
||||
let size = app.treemap_size.get();
|
||||
Point::new(size.width / 2.0, size.height / 2.0)
|
||||
});
|
||||
update(&view, cx, |app, cx| {
|
||||
app.zoom_at(middle.x.as_f32(), middle.y.as_f32(), 1.5, false, cx);
|
||||
});
|
||||
let zoomed = read(&view, cx, |app| app.view.scale);
|
||||
assert!(zoomed > 1.0, "scale after zooming: {zoomed}");
|
||||
|
||||
press(cx, "0");
|
||||
assert!((read(&view, cx, |app| app.view.scale) - 1.0).abs() < f32::EPSILON);
|
||||
}
|
||||
|
||||
/// Both appearances Omarchy ships must draw: the palette is derived from the
|
||||
/// theme, so a light theme is a real second configuration.
|
||||
#[gpui_kit::test]
|
||||
fn both_appearances_draw(cx: &mut TestAppContext) {
|
||||
cx.update(gpui_omarchy::init);
|
||||
let temp = fixture();
|
||||
let (view, cx) = view_over(temp.path(), cx);
|
||||
for theme in [Theme::tokyo_night(), Theme::flexoki_light()] {
|
||||
view.update(cx, |_, cx| {
|
||||
theme.clone().apply(cx);
|
||||
cx.notify();
|
||||
});
|
||||
draw(cx);
|
||||
assert!(cx.debug_bounds("disktree-root").is_some());
|
||||
}
|
||||
}
|
||||
|
||||
/// A view built without a scan keeps working: the screens must not assume a
|
||||
/// walk is in flight.
|
||||
#[gpui_kit::test]
|
||||
fn a_view_without_flags_or_marks_still_draws(cx: &mut TestAppContext) {
|
||||
cx.update(gpui_omarchy::init);
|
||||
let temp = fixture();
|
||||
let (view, cx) = view_over(temp.path(), cx);
|
||||
update(&view, cx, |app, cx| {
|
||||
app.screen = Screen::Review;
|
||||
cx.notify();
|
||||
});
|
||||
draw(cx);
|
||||
assert!(cx.debug_bounds("disktree-root").is_some());
|
||||
|
||||
update(&view, cx, |app, cx| {
|
||||
app.screen = Screen::Running;
|
||||
cx.notify();
|
||||
});
|
||||
draw(cx);
|
||||
|
||||
update(&view, cx, |app, cx| {
|
||||
app.screen = Screen::Done;
|
||||
cx.notify();
|
||||
});
|
||||
draw(cx);
|
||||
assert!(cx.debug_bounds("disktree-root").is_some());
|
||||
}
|
||||
|
||||
/// The removal mode is a choice with two independent channels: the key and the
|
||||
/// button both have to reach the same state.
|
||||
#[gpui_kit::test]
|
||||
fn the_review_screen_switches_removal_mode(cx: &mut TestAppContext) {
|
||||
cx.update(gpui_omarchy::init);
|
||||
let temp = fixture();
|
||||
let (view, cx) = view_over(temp.path(), cx);
|
||||
update(&view, cx, |app, cx| {
|
||||
app.marks.toggle(disktree_core::removal::Target {
|
||||
path: temp.path().join("junk"),
|
||||
bytes: 300_000,
|
||||
is_dir: true,
|
||||
hidden: false,
|
||||
});
|
||||
app.screen = Screen::Review;
|
||||
cx.notify();
|
||||
});
|
||||
draw(cx);
|
||||
|
||||
press(cx, "m");
|
||||
assert_eq!(read(&view, cx, |app| app.removal_mode), RemovalMode::Trash);
|
||||
press(cx, "p");
|
||||
assert_eq!(
|
||||
read(&view, cx, |app| app.removal_mode),
|
||||
RemovalMode::Permanent
|
||||
);
|
||||
press(cx, "!");
|
||||
assert!(read(&view, cx, |app| app.marks.is_empty()));
|
||||
}
|
||||
|
||||
/// Escape in the alert dialog cancels: the dialog closes, the review screen
|
||||
/// stays, and nothing on disk changes.
|
||||
#[gpui_kit::test]
|
||||
fn escape_in_the_delete_dialog_cancels(cx: &mut TestAppContext) {
|
||||
cx.update(gpui_omarchy::init);
|
||||
let temp = fixture();
|
||||
let (view, cx) = view_over(temp.path(), cx);
|
||||
update(&view, cx, |app, cx| {
|
||||
app.removal_mode = RemovalMode::Permanent;
|
||||
app.marks.toggle(disktree_core::removal::Target {
|
||||
path: temp.path().join("junk"),
|
||||
bytes: 300_000,
|
||||
is_dir: true,
|
||||
hidden: false,
|
||||
});
|
||||
app.screen = Screen::Review;
|
||||
cx.notify();
|
||||
});
|
||||
draw(cx);
|
||||
|
||||
press(cx, "enter");
|
||||
assert!(read(&view, cx, |app| app.confirm_open));
|
||||
press(cx, "escape");
|
||||
assert!(!read(&view, cx, |app| app.confirm_open), "Escape cancels");
|
||||
assert_eq!(read(&view, cx, |app| app.screen), Screen::Review);
|
||||
assert!(temp.path().join("junk").exists());
|
||||
assert_eq!(
|
||||
read(&view, cx, |app| app.marks.len()),
|
||||
1,
|
||||
"the list is kept"
|
||||
);
|
||||
}
|
||||
|
||||
/// With a trash on the machine, the reversible path is the default and
|
||||
/// commits without a dialog; the permanent one is a deliberate choice.
|
||||
#[gpui_kit::test]
|
||||
fn the_trash_is_the_default_when_there_is_one(cx: &mut TestAppContext) {
|
||||
cx.update(gpui_omarchy::init);
|
||||
let temp = fixture();
|
||||
let (view, cx) = view_over(temp.path(), cx);
|
||||
let (mode, available) = read(&view, cx, |app| {
|
||||
(app.removal_mode, app.trash_backend.is_available())
|
||||
});
|
||||
if available {
|
||||
assert_eq!(mode, RemovalMode::Trash);
|
||||
} else {
|
||||
assert_eq!(mode, RemovalMode::Permanent);
|
||||
}
|
||||
}
|
||||
|
||||
/// `ctrl =` / `ctrl -` / `ctrl 0` change the window's rem, which every size
|
||||
/// in the app is expressed in, and the mosaic's header band follows it.
|
||||
#[gpui_kit::test]
|
||||
fn interface_zoom_scales_the_rem_and_the_header_band(cx: &mut TestAppContext) {
|
||||
cx.update(gpui_omarchy::init);
|
||||
let temp = fixture();
|
||||
let (view, cx) = view_over(temp.path(), cx);
|
||||
draw(cx);
|
||||
let rem =
|
||||
|cx: &mut Window| cx.update(|window, _| window.rem_size().as_f32());
|
||||
let base = rem(cx);
|
||||
let band = |view: &Entity<Disktree>, cx: &mut Window| {
|
||||
update(view, cx, |app, _| {
|
||||
app.layout();
|
||||
app.layout_options.header
|
||||
})
|
||||
};
|
||||
let base_band = band(&view, cx);
|
||||
|
||||
press(cx, "ctrl-=");
|
||||
let zoomed = rem(cx);
|
||||
assert!(zoomed > base, "{zoomed} after zooming in from {base}");
|
||||
let zoomed_band = band(&view, cx);
|
||||
assert!(
|
||||
(zoomed_band / base_band - zoomed / base).abs() < 0.01,
|
||||
"the band scales with the rem: {base_band} -> {zoomed_band}"
|
||||
);
|
||||
|
||||
press(cx, "ctrl--");
|
||||
press(cx, "ctrl--");
|
||||
assert!(rem(cx) < base, "zooming out goes below the default");
|
||||
press(cx, "ctrl-0");
|
||||
assert!((rem(cx) - base).abs() < 0.01, "ctrl 0 resets");
|
||||
}
|
||||
|
||||
/// The crumbs of the directory named `name` directly inside `parent`.
|
||||
fn child_crumbs(app: &Disktree, parent: &[usize], name: &str) -> Vec<usize> {
|
||||
let node = app.node_at(parent).expect("the parent");
|
||||
let index = node
|
||||
.children
|
||||
.iter()
|
||||
.position(|child| &*child.name == name)
|
||||
.unwrap_or_else(|| panic!("no {name}"));
|
||||
let mut crumbs = parent.to_vec();
|
||||
crumbs.push(index);
|
||||
crumbs
|
||||
}
|
||||
|
||||
/// Regression: the wheel magnified toward the deepest directory under the
|
||||
/// pointer, then went into the *top-level* one containing it, so the screen
|
||||
/// after the descent was never the area that was zoomed into.
|
||||
#[gpui_kit::test]
|
||||
fn the_wheel_goes_into_the_directory_it_zoomed_into(cx: &mut TestAppContext) {
|
||||
cx.update(gpui_omarchy::init);
|
||||
let temp = fixture();
|
||||
let (view, cx) = view_over(temp.path(), cx);
|
||||
draw(cx);
|
||||
|
||||
// Point at the middle of junk/deeper's contents: a directory one level
|
||||
// below a top-level one.
|
||||
let (deeper, point) = update(&view, cx, |app, _| {
|
||||
let junk = child_crumbs(app, &[], "junk");
|
||||
let deeper = child_crumbs(app, &junk, "deeper");
|
||||
let body = app.tile_body(&deeper).expect("deeper is drawn");
|
||||
(deeper, (body.x + body.w / 2.0, body.y + body.h / 2.0))
|
||||
});
|
||||
|
||||
let mut entered = None;
|
||||
for _ in 0..40 {
|
||||
let crumbs = update(&view, cx, |app, cx| {
|
||||
let (x, y) = app.view.unproject(point.0, point.1);
|
||||
let screen = app
|
||||
.view
|
||||
.project(disktree_core::treemap::Rect::new(x, y, 0.0, 0.0));
|
||||
app.zoom_at(screen.x, screen.y, 1.15, true, cx);
|
||||
app.crumbs.clone()
|
||||
});
|
||||
draw(cx);
|
||||
if !crumbs.is_empty() {
|
||||
entered = Some(crumbs);
|
||||
break;
|
||||
}
|
||||
}
|
||||
assert_eq!(
|
||||
entered.as_deref(),
|
||||
Some(deeper.as_slice()),
|
||||
"descended into the pointed-at directory, not its top-level ancestor"
|
||||
);
|
||||
}
|
||||
|
||||
/// Regression, keyboard side: Enter on a deep selection enters that
|
||||
/// directory, and on a file enters the directory holding it.
|
||||
#[gpui_kit::test]
|
||||
fn enter_opens_the_selected_directory_at_any_depth(cx: &mut TestAppContext) {
|
||||
cx.update(gpui_omarchy::init);
|
||||
let temp = fixture();
|
||||
let (view, cx) = view_over(temp.path(), cx);
|
||||
draw(cx);
|
||||
|
||||
let deeper = update(&view, cx, |app, cx| {
|
||||
let junk = child_crumbs(app, &[], "junk");
|
||||
let deeper = child_crumbs(app, &junk, "deeper");
|
||||
app.select(Some(deeper.clone()), cx);
|
||||
app.descend(cx);
|
||||
deeper
|
||||
});
|
||||
assert_eq!(read(&view, cx, |app| app.crumbs.clone()), deeper);
|
||||
|
||||
press(cx, "escape");
|
||||
press(cx, "escape");
|
||||
press(cx, "escape");
|
||||
let junk = update(&view, cx, |app, cx| {
|
||||
app.go_to(Vec::new(), cx);
|
||||
let junk = child_crumbs(app, &[], "junk");
|
||||
let blob = child_crumbs(app, &junk, "blob.bin");
|
||||
app.select(Some(blob), cx);
|
||||
app.descend(cx);
|
||||
junk
|
||||
});
|
||||
assert_eq!(
|
||||
read(&view, cx, |app| app.crumbs.clone()),
|
||||
junk,
|
||||
"a file opens its directory"
|
||||
);
|
||||
}
|
||||
|
||||
/// The mark key acts on what the pointer is over when the pointer moved
|
||||
/// last, and on the keyboard selection after an arrow.
|
||||
#[gpui_kit::test]
|
||||
fn the_mark_key_follows_the_pointer_until_the_keyboard_moves(
|
||||
cx: &mut TestAppContext,
|
||||
) {
|
||||
cx.update(gpui_omarchy::init);
|
||||
let temp = fixture();
|
||||
let (view, cx) = view_over(temp.path(), cx);
|
||||
draw(cx);
|
||||
|
||||
// Point at junk's name band, which belongs to junk itself (its body
|
||||
// belongs to its children). junk is not the default selection, .cache.
|
||||
let (keep, origin, centre) = update(&view, cx, |app, _| {
|
||||
let keep = child_crumbs(app, &[], "junk");
|
||||
let body = app
|
||||
.layout()
|
||||
.and_then(|tiles| {
|
||||
tiles.iter().find(|tile| tile.crumbs() == keep.as_slice())
|
||||
})
|
||||
.and_then(|tile| tile.header)
|
||||
.expect("junk is drawn with a band");
|
||||
(
|
||||
keep,
|
||||
app.treemap_origin.get(),
|
||||
(body.x + body.w / 2.0, body.y + body.h / 2.0),
|
||||
)
|
||||
});
|
||||
assert_ne!(
|
||||
read(&view, cx, |app| app.selected.clone()),
|
||||
Some(keep.clone())
|
||||
);
|
||||
cx.simulate_mouse_move(
|
||||
Point::new(origin.x + px(centre.0), origin.y + px(centre.1)),
|
||||
None,
|
||||
gpui_kit::Modifiers::default(),
|
||||
);
|
||||
draw(cx);
|
||||
|
||||
press(cx, "space");
|
||||
let marked = read(&view, cx, |app| app.marks.items().to_vec());
|
||||
assert_eq!(marked.len(), 1);
|
||||
assert!(
|
||||
marked[0].path.ends_with("junk"),
|
||||
"marked what the pointer is on: {:?}",
|
||||
marked[0].path
|
||||
);
|
||||
assert_eq!(read(&view, cx, |app| app.selected.clone()), Some(keep));
|
||||
|
||||
// An arrow hands control back to the keyboard selection.
|
||||
press(cx, "right");
|
||||
assert!(!read(&view, cx, |app| app.pointer_active));
|
||||
}
|
||||
|
||||
/// Regression: after descending, tiles resolved against the scanned root
|
||||
/// instead of the directory drawn, so labels, hover and marks named strangers.
|
||||
#[gpui_kit::test]
|
||||
fn after_descending_every_tile_is_inside_the_directory_drawn(
|
||||
cx: &mut TestAppContext,
|
||||
) {
|
||||
cx.update(gpui_omarchy::init);
|
||||
let temp = fixture();
|
||||
let (view, cx) = view_over(temp.path(), cx);
|
||||
draw(cx);
|
||||
|
||||
let junk = update(&view, cx, |app, cx| {
|
||||
let junk = child_crumbs(app, &[], "junk");
|
||||
app.select(Some(junk.clone()), cx);
|
||||
app.descend(cx);
|
||||
junk
|
||||
});
|
||||
assert_eq!(read(&view, cx, |app| app.crumbs.clone()), junk);
|
||||
draw(cx);
|
||||
|
||||
let (paths, labels) = update(&view, cx, |app, _| {
|
||||
let tiles = app.layout().map(<[Tile]>::to_vec).unwrap_or_default();
|
||||
let paths: Vec<_> = tiles
|
||||
.iter()
|
||||
.filter_map(|tile| app.path_at(tile.crumbs()))
|
||||
.collect();
|
||||
let labels: Vec<String> = app
|
||||
.prepare()
|
||||
.labels
|
||||
.into_iter()
|
||||
.map(|label| label.text)
|
||||
.collect();
|
||||
(paths, labels)
|
||||
});
|
||||
assert!(!paths.is_empty());
|
||||
let junk_path = temp.path().join("junk");
|
||||
for path in &paths {
|
||||
assert!(path.starts_with(&junk_path), "{path:?} is outside junk");
|
||||
}
|
||||
for label in &labels {
|
||||
assert!(
|
||||
["blob.bin", "deeper", "more.bin"].contains(&label.as_str())
|
||||
|| label.starts_with('+'),
|
||||
"label {label} does not belong to junk"
|
||||
);
|
||||
}
|
||||
|
||||
// Space on the selection marks something inside junk, never elsewhere.
|
||||
update(&view, cx, |app, cx| {
|
||||
let blob = child_crumbs(app, &junk, "blob.bin");
|
||||
app.select(Some(blob), cx);
|
||||
});
|
||||
press(cx, "space");
|
||||
let marked = read(&view, cx, |app| app.marks.items().to_vec());
|
||||
assert_eq!(marked.len(), 1);
|
||||
assert_eq!(marked[0].path, junk_path.join("blob.bin"));
|
||||
assert_eq!(marked[0].bytes, 200_000);
|
||||
|
||||
// And the mark is drawn on the right tile: its crumbs resolve here.
|
||||
let hatched = update(&view, cx, |app, _| {
|
||||
app.prepare()
|
||||
.tiles
|
||||
.iter()
|
||||
.filter(|tile| tile.marked)
|
||||
.count()
|
||||
});
|
||||
assert_eq!(hatched, 1, "exactly the marked tile is hatched");
|
||||
}
|
||||
@@ -0,0 +1,433 @@
|
||||
//! The mosaic: tiles painted on a canvas, labels shaped straight into it.
|
||||
//!
|
||||
//! Tiles are painted rather than composed from elements. A treemap can put
|
||||
//! thousands of rectangles on screen, and an element per rectangle would spend
|
||||
//! the frame in layout. Painting also means the marked hatch, the selection
|
||||
//! ring and the hover outline are drawn in one place, in one order.
|
||||
//!
|
||||
//! Text is shaped here too. GPUI caches shaped lines, so re-shaping the visible
|
||||
//! labels every frame costs a lookup, and it lets a label clip exactly to its
|
||||
//! own tile instead of bleeding into the neighbour.
|
||||
|
||||
use std::rc::Rc;
|
||||
|
||||
use disktree_core::treemap::Rect;
|
||||
use gpui_kit::{
|
||||
App, Bounds, ContentMask, Context, Corners, Edges, Font, Hsla,
|
||||
InteractiveElement as _, IntoElement, MouseButton, MouseDownEvent,
|
||||
MouseMoveEvent, ParentElement as _, Pixels, Point, ScrollWheelEvent,
|
||||
SharedString, Size, StatefulInteractiveElement as _, Styled, TextAlign,
|
||||
TextRun, Window, canvas, div, pattern_slash, px, quad,
|
||||
};
|
||||
use gpui_omarchy::{ActiveTheme, Theme};
|
||||
|
||||
use crate::palette;
|
||||
use crate::state::{Disktree, Label, View};
|
||||
|
||||
/// How one tile should be drawn, resolved before the paint callback runs so
|
||||
/// that painting never has to look anything up.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct TileDeco {
|
||||
/// Base-space rectangle: the view transform is applied while painting.
|
||||
pub rect: Rect,
|
||||
/// The band this directory reserved for its name, when it is subdivided.
|
||||
pub header: Option<Rect>,
|
||||
pub depth: u32,
|
||||
/// Depth from the scanned root, used for the fill so descending does not
|
||||
/// recolour the mosaic; `depth` stays view-relative for geometry.
|
||||
pub color_depth: u32,
|
||||
pub hidden: bool,
|
||||
pub marked: bool,
|
||||
/// Inside another marked directory, so it goes with its parent.
|
||||
pub covered: bool,
|
||||
pub hovered: bool,
|
||||
pub selected: bool,
|
||||
}
|
||||
|
||||
/// Everything the mosaic needs for one frame.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct Mosaic {
|
||||
pub tiles: Vec<TileDeco>,
|
||||
pub labels: Vec<Label>,
|
||||
pub view: View,
|
||||
}
|
||||
|
||||
/// Build the treemap viewport: canvas, input, and the cursor tooltip.
|
||||
pub fn mosaic(
|
||||
mosaic: Mosaic,
|
||||
app: &Disktree,
|
||||
window: &Window,
|
||||
cx: &Context<'_, Disktree>,
|
||||
) -> impl IntoElement {
|
||||
let theme = cx.omarchy().clone();
|
||||
let rem = window.rem_size();
|
||||
let origin = Rc::clone(&app.treemap_origin);
|
||||
let measured = Rc::clone(&app.treemap_size);
|
||||
|
||||
let colors = Colors::new(&theme);
|
||||
let font = theme.font.clone();
|
||||
let name_size = rem_px(0.75, rem);
|
||||
let size_size = rem_px(0.6875, rem);
|
||||
|
||||
let Mosaic {
|
||||
tiles,
|
||||
labels,
|
||||
view,
|
||||
} = mosaic;
|
||||
let canvas_origin = Rc::clone(&origin);
|
||||
let canvas_measured = Rc::clone(&measured);
|
||||
|
||||
div()
|
||||
.id("disktree-treemap")
|
||||
.relative()
|
||||
.flex_1()
|
||||
.min_h_0()
|
||||
.min_w_0()
|
||||
.overflow_hidden()
|
||||
.bg(theme.inset)
|
||||
.on_hover(cx.listener(|this, hovered: &bool, _, cx| {
|
||||
if !hovered {
|
||||
this.on_mouse_leave(cx);
|
||||
}
|
||||
}))
|
||||
.on_mouse_move(cx.listener(|this, event: &MouseMoveEvent, _, cx| {
|
||||
this.on_mouse_move(event, cx);
|
||||
}))
|
||||
.on_mouse_down(
|
||||
MouseButton::Left,
|
||||
cx.listener(|this, event: &MouseDownEvent, _, cx| {
|
||||
this.on_mouse_down(event, cx);
|
||||
}),
|
||||
)
|
||||
.on_mouse_down(
|
||||
MouseButton::Middle,
|
||||
cx.listener(|this, event: &MouseDownEvent, _, cx| {
|
||||
this.on_mouse_down(event, cx);
|
||||
}),
|
||||
)
|
||||
.on_scroll_wheel(cx.listener(
|
||||
|this, event: &ScrollWheelEvent, _, cx| {
|
||||
this.on_scroll_wheel(event, cx);
|
||||
},
|
||||
))
|
||||
.child(
|
||||
canvas(
|
||||
move |bounds, window, _| {
|
||||
canvas_origin.set(bounds.origin);
|
||||
// The layout was computed from the previous frame's size. Ask
|
||||
// for one more frame whenever the area is not what we assumed,
|
||||
// which is what makes the first paint and a resize settle.
|
||||
if canvas_measured.get() != bounds.size {
|
||||
canvas_measured.set(bounds.size);
|
||||
window.request_animation_frame();
|
||||
}
|
||||
bounds.size
|
||||
},
|
||||
move |bounds, _, window, cx| {
|
||||
paint_tiles(&tiles, bounds, view, &colors, window);
|
||||
paint_labels(
|
||||
&labels, bounds, view, &colors, &font, name_size,
|
||||
size_size, window, cx,
|
||||
);
|
||||
},
|
||||
)
|
||||
.absolute()
|
||||
.inset_0(),
|
||||
)
|
||||
}
|
||||
|
||||
/// Theme colours resolved once per frame.
|
||||
struct Colors {
|
||||
label: Vec<Hsla>,
|
||||
label_dim: Hsla,
|
||||
border: Hsla,
|
||||
hover_border: Hsla,
|
||||
selected_border: Hsla,
|
||||
marked_border: Hsla,
|
||||
marked_hatch: Hsla,
|
||||
marked_label: Hsla,
|
||||
covered_border: Hsla,
|
||||
header_tint: Hsla,
|
||||
header_rule: Hsla,
|
||||
fill: Vec<Hsla>,
|
||||
fill_hidden: Vec<Hsla>,
|
||||
fill_marked: Vec<Hsla>,
|
||||
}
|
||||
|
||||
impl Colors {
|
||||
fn new(theme: &Theme) -> Self {
|
||||
// Absolute depth runs past the visible nesting (each descent adds to
|
||||
// it), so the ladder is longer than `max_depth` and clamps at the end.
|
||||
let depth_range = 0..=12;
|
||||
Self {
|
||||
label: depth_range
|
||||
.clone()
|
||||
.map(|d| palette::label_color(theme, d))
|
||||
.collect(),
|
||||
label_dim: theme.bright.opacity(0.55),
|
||||
border: theme.background.opacity(0.55),
|
||||
hover_border: theme.bright.opacity(0.7),
|
||||
selected_border: theme.bright,
|
||||
marked_border: theme.danger,
|
||||
marked_hatch: theme.danger.opacity(0.4),
|
||||
marked_label: theme.bright,
|
||||
covered_border: theme.danger.opacity(0.45),
|
||||
// A band reads as a label strip because it is lifted a little and
|
||||
// closed with a rule, not because it is another colour.
|
||||
header_tint: theme.bright.opacity(0.09),
|
||||
header_rule: theme.background.opacity(0.75),
|
||||
fill: depth_range
|
||||
.clone()
|
||||
.map(|d| palette::tile_fill(theme, d, false, false))
|
||||
.collect(),
|
||||
fill_hidden: depth_range
|
||||
.clone()
|
||||
.map(|d| palette::tile_fill(theme, d, true, false))
|
||||
.collect(),
|
||||
fill_marked: depth_range
|
||||
.map(|d| palette::tile_fill(theme, d, false, true))
|
||||
.collect(),
|
||||
}
|
||||
}
|
||||
|
||||
fn fill(&self, tile: &TileDeco) -> Hsla {
|
||||
let index = (tile.color_depth as usize).min(self.fill.len() - 1);
|
||||
if tile.marked {
|
||||
self.fill_marked[index]
|
||||
} else if tile.hidden {
|
||||
self.fill_hidden[index]
|
||||
} else {
|
||||
self.fill[index]
|
||||
}
|
||||
}
|
||||
|
||||
fn label(&self, depth: u32) -> Hsla {
|
||||
self.label[(depth as usize).min(self.label.len() - 1)]
|
||||
}
|
||||
}
|
||||
|
||||
fn paint_tiles(
|
||||
tiles: &[TileDeco],
|
||||
bounds: Bounds<Pixels>,
|
||||
view: View,
|
||||
colors: &Colors,
|
||||
window: &mut Window,
|
||||
) {
|
||||
for tile in tiles {
|
||||
let rect = view.project(tile.rect);
|
||||
if rect.w <= 0.5 || rect.h <= 0.5 {
|
||||
continue;
|
||||
}
|
||||
let quad_bounds = to_window(&rect, bounds);
|
||||
|
||||
// Every tile gets a hairline of background rather than a bright border:
|
||||
// that is what separates nested levels without turning the mosaic into
|
||||
// a wireframe.
|
||||
let mut width = if tile.depth == 0 { 1.0 } else { 0.5 };
|
||||
let mut border = colors.border;
|
||||
if tile.marked {
|
||||
width = 2.0;
|
||||
border = colors.marked_border;
|
||||
} else if tile.covered {
|
||||
width = 1.0;
|
||||
border = colors.covered_border;
|
||||
}
|
||||
if tile.hovered {
|
||||
width = 2.0;
|
||||
border = colors.hover_border;
|
||||
}
|
||||
if tile.selected {
|
||||
width = 2.0;
|
||||
border = colors.selected_border;
|
||||
}
|
||||
|
||||
window.paint_quad(quad(
|
||||
quad_bounds,
|
||||
Corners::default(),
|
||||
colors.fill(tile),
|
||||
Edges::all(px(width)),
|
||||
border,
|
||||
gpui_kit::BorderStyle::Solid,
|
||||
));
|
||||
|
||||
// The band a subdivided directory keeps for its name: lifted, and
|
||||
// closed with a rule, so the group reads as a group and the space
|
||||
// inside it belongs to the children.
|
||||
if let Some(header) = tile.header {
|
||||
let header = view.project(header);
|
||||
if header.w > 1.0 && header.h > 1.0 {
|
||||
let band = to_window(&header, bounds);
|
||||
window.paint_quad(quad(
|
||||
band,
|
||||
Corners::default(),
|
||||
colors.header_tint,
|
||||
Edges::all(px(0.)),
|
||||
colors.header_rule,
|
||||
gpui_kit::BorderStyle::Solid,
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
// A hatched overlay is the conventional "this one is going away" mark,
|
||||
// and it survives on top of any tile colour the theme produces.
|
||||
if tile.marked {
|
||||
window.paint_quad(quad(
|
||||
inset(quad_bounds, px(2.)),
|
||||
Corners::default(),
|
||||
pattern_slash(colors.marked_hatch, 2.0, 9.0),
|
||||
Edges::all(px(0.)),
|
||||
colors.marked_border,
|
||||
gpui_kit::BorderStyle::Solid,
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[expect(
|
||||
clippy::too_many_arguments,
|
||||
reason = "the paint pass threads window state; a struct would only move
|
||||
these fields somewhere else"
|
||||
)]
|
||||
fn paint_labels(
|
||||
labels: &[Label],
|
||||
bounds: Bounds<Pixels>,
|
||||
view: View,
|
||||
colors: &Colors,
|
||||
font: &SharedString,
|
||||
name_size: Pixels,
|
||||
size_size: Pixels,
|
||||
window: &mut Window,
|
||||
cx: &mut App,
|
||||
) {
|
||||
let font = Font {
|
||||
family: font.clone(),
|
||||
..Font::default()
|
||||
};
|
||||
let name_line_height = name_size * 1.35;
|
||||
let text_system = window.text_system().clone();
|
||||
// Label geometry is proportioned to the label's own type size, which
|
||||
// already follows `rem`: padding, thresholds and gaps then keep their
|
||||
// relationship to the text at every interface zoom step.
|
||||
let text_padding = name_size * 0.42;
|
||||
let text_inset = name_size * 0.25;
|
||||
let min_width = name_size * 3.3;
|
||||
let size_gap = name_size * 0.67;
|
||||
|
||||
for label in labels {
|
||||
// A subdivided directory's name lives in the band it reserved; a leaf's
|
||||
// sits at the top of its own tile. Either way the mask is the region
|
||||
// the label owns, so no label can reach into another tile.
|
||||
let owned = label.header.unwrap_or(label.rect);
|
||||
let rect = view.project(owned);
|
||||
if px(rect.w) < min_width || px(rect.h) < name_size {
|
||||
continue;
|
||||
}
|
||||
let mask = to_window(&rect, bounds);
|
||||
let origin = Point::new(
|
||||
mask.origin.x + text_padding,
|
||||
mask.origin.y + text_inset,
|
||||
);
|
||||
let color = if label.marked {
|
||||
colors.marked_label
|
||||
} else {
|
||||
colors.label(label.color_depth)
|
||||
};
|
||||
|
||||
let run = TextRun {
|
||||
len: label.text.len(),
|
||||
font: font.clone(),
|
||||
color,
|
||||
..TextRun::default()
|
||||
};
|
||||
let line = text_system.shape_line(
|
||||
SharedString::from(label.text.clone()),
|
||||
name_size,
|
||||
&[run],
|
||||
None,
|
||||
);
|
||||
|
||||
window.with_content_mask(
|
||||
Some(ContentMask { bounds: mask }),
|
||||
|window| {
|
||||
let _ = line.paint(
|
||||
origin,
|
||||
name_line_height,
|
||||
TextAlign::Left,
|
||||
None,
|
||||
window,
|
||||
cx,
|
||||
);
|
||||
|
||||
if label.size_text.is_empty() {
|
||||
return;
|
||||
}
|
||||
let room = mask.size.width - (origin.x - mask.origin.x) * 2.;
|
||||
let size_run = TextRun {
|
||||
len: label.size_text.len(),
|
||||
font: font.clone(),
|
||||
color: colors.label_dim,
|
||||
..TextRun::default()
|
||||
};
|
||||
let size_line = text_system.shape_line(
|
||||
SharedString::from(label.size_text.clone()),
|
||||
size_size,
|
||||
&[size_run],
|
||||
None,
|
||||
);
|
||||
// Mixed sizes share the name's baseline, not its box. A line
|
||||
// paints centred in its line height, putting the baseline at
|
||||
// `height / 2 + (ascent - descent) / 2`; equate the two.
|
||||
let baseline = origin.y
|
||||
+ ((line.ascent - line.descent)
|
||||
- (size_line.ascent - size_line.descent))
|
||||
* 0.5;
|
||||
// In a band the size sits at the far end, where it reads as a
|
||||
// column; without one it follows the name when there is room.
|
||||
let size_origin = if label.header.is_some() {
|
||||
Point::new(
|
||||
mask.origin.x + mask.size.width
|
||||
- size_line.width()
|
||||
- text_padding,
|
||||
baseline,
|
||||
)
|
||||
} else {
|
||||
if room - line.width() < size_size * 3.0 {
|
||||
return;
|
||||
}
|
||||
Point::new(origin.x + line.width() + size_gap, baseline)
|
||||
};
|
||||
if size_origin.x > origin.x + line.width() + text_padding {
|
||||
let _ = size_line.paint(
|
||||
size_origin,
|
||||
name_line_height,
|
||||
TextAlign::Left,
|
||||
None,
|
||||
window,
|
||||
cx,
|
||||
);
|
||||
}
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
fn to_window(rect: &Rect, bounds: Bounds<Pixels>) -> Bounds<Pixels> {
|
||||
Bounds::new(
|
||||
Point::new(bounds.origin.x + px(rect.x), bounds.origin.y + px(rect.y)),
|
||||
Size::new(px(rect.w), px(rect.h)),
|
||||
)
|
||||
}
|
||||
|
||||
fn inset(bounds: Bounds<Pixels>, amount: Pixels) -> Bounds<Pixels> {
|
||||
Bounds::new(
|
||||
Point::new(bounds.origin.x + amount, bounds.origin.y + amount),
|
||||
Size::new(
|
||||
(bounds.size.width - amount * 2.).max(px(0.)),
|
||||
(bounds.size.height - amount * 2.).max(px(0.)),
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
fn rem_px(rems: f32, rem_size: Pixels) -> Pixels {
|
||||
px(rems * rem_size.as_f32())
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
//! The scale this app draws with: spacing, type, icons and region widths.
|
||||
//!
|
||||
//! Everything is in `rem`, following the gpui-kit design guide: type, spacing,
|
||||
//! controls and icons share one zoom axis, so interface zoom (`ctrl =`,
|
||||
//! `ctrl -`, `ctrl 0`) keeps every relationship intact instead of only
|
||||
//! enlarging text. Choose a step by what two things mean to each other, not by
|
||||
//! the pixels it happens to resolve to today.
|
||||
//!
|
||||
//! Radius has a single tier here: Omarchy's surfaces are square, so nothing in
|
||||
//! this app rounds a corner, and nested surfaces stay concentric by
|
||||
//! construction.
|
||||
//!
|
||||
//! Pixels remain only where a value is physical: hairline borders, the
|
||||
//! treemap's own geometry (laid out in viewport pixels, then scaled by the
|
||||
//! view), and positions that come from the pointer.
|
||||
|
||||
use gpui_kit::Rems;
|
||||
|
||||
/// The guide's semantic spacing scale: 2, 4, 8, 12, 16, 24 and 32 px at the
|
||||
/// default 16 px rem.
|
||||
pub mod space {
|
||||
use super::Rems;
|
||||
|
||||
/// Optical correction: an icon baseline, a compact separator.
|
||||
pub const XXS: Rems = Rems(0.125);
|
||||
/// Parts of one control: icon and label, title and its description.
|
||||
pub const XS: Rems = Rems(0.25);
|
||||
/// Closely related controls: a button group, dialog actions.
|
||||
pub const SM: Rems = Rems(0.5);
|
||||
/// One content group: columns of a row, compact form rows.
|
||||
pub const MD: Rems = Rems(0.75);
|
||||
/// Separate groups in one section, and region padding.
|
||||
pub const LG: Rems = Rems(1.0);
|
||||
/// Separate sections.
|
||||
pub const XL: Rems = Rems(1.5);
|
||||
/// A major region boundary: empty-state breathing room.
|
||||
pub const XXL: Rems = Rems(2.0);
|
||||
}
|
||||
|
||||
/// Type steps. Omarchy's own sizes, so the app reads like its components.
|
||||
pub mod text {
|
||||
use super::Rems;
|
||||
|
||||
/// Metadata, key caps and tooltips.
|
||||
pub const CAPTION: Rems = Rems(0.6875);
|
||||
/// Body text and control labels.
|
||||
pub const BODY: Rems = Rems(0.75);
|
||||
/// Window, section and dialog titles.
|
||||
pub const TITLE: Rems = Rems(0.875);
|
||||
}
|
||||
|
||||
/// Icon slots, sized with the text they sit beside.
|
||||
pub mod icon {
|
||||
use super::Rems;
|
||||
|
||||
pub const SM: Rems = Rems(0.75);
|
||||
pub const MD: Rems = Rems(0.875);
|
||||
pub const LG: Rems = Rems(1.375);
|
||||
}
|
||||
|
||||
/// Region and lane widths. Each is the comfortable default for its content at
|
||||
/// the default rem; they scale with zoom like everything else.
|
||||
pub mod size {
|
||||
use super::Rems;
|
||||
|
||||
/// The volume meter in the status bar.
|
||||
pub const SPACE_METER: Rems = Rems(20.0);
|
||||
/// The scan meter in the status bar.
|
||||
pub const SCAN_METER: Rems = Rems(15.0);
|
||||
/// The meter on the scanning panel.
|
||||
pub const SCANNING_METER: Rems = Rems(26.25);
|
||||
/// The Size | Files choice in the settings row.
|
||||
pub const RANKING_CHOICE: Rems = Rems(8.5);
|
||||
/// The review screen's summary column.
|
||||
pub const REVIEW_SUMMARY: Rems = Rems(22.5);
|
||||
/// The review list's share-bar lane.
|
||||
pub const SHARE_LANE: Rems = Rems(6.0);
|
||||
/// The review list's size lane: right-aligned, so sizes compare.
|
||||
pub const SIZE_LANE: Rems = Rems(5.0);
|
||||
/// The cursor tooltip.
|
||||
pub const TOOLTIP: Rems = Rems(16.75);
|
||||
/// The keyboard overlay.
|
||||
pub const HELP: Rems = Rems(32.5);
|
||||
/// The key column of the keyboard overlay.
|
||||
pub const KEY_LANE: Rems = Rems(7.0);
|
||||
}
|
||||
|
||||
/// Interface zoom steps, as a factor of the 16 px default rem.
|
||||
pub const ZOOM_STEPS: [f32; 7] = [0.75, 0.875, 1.0, 1.125, 1.25, 1.5, 1.75];
|
||||
|
||||
/// The default rem, in pixels.
|
||||
pub const BASE_REM: f32 = 16.0;
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,347 @@
|
||||
//! Small presentation pieces shared by the screens.
|
||||
//!
|
||||
//! Everything is built from the active Omarchy theme's tokens, and every piece
|
||||
//! is a plain function over borrowed data so the screens stay readable.
|
||||
|
||||
use disktree_core::size::{human_bytes, human_bytes_short, share, share_bar};
|
||||
use disktree_core::space::SpaceInfo;
|
||||
use disktree_core::tree::{Metric, Node};
|
||||
use gpui_kit::prelude::FluentBuilder as _;
|
||||
use gpui_kit::{
|
||||
App, Div, ElementId, FontWeight, Hsla, InteractiveElement as _,
|
||||
ParentElement, SharedString, Styled, div, relative,
|
||||
};
|
||||
use gpui_omarchy::{ActiveTheme, Status};
|
||||
|
||||
use crate::ui::{space, text};
|
||||
|
||||
use crate::state::Disktree;
|
||||
|
||||
/// The scanned root, shortened to `~` where it is the home directory.
|
||||
pub fn display_root(app: &Disktree) -> String {
|
||||
crate::marks::display_path(&app.root_path, app.home.as_deref())
|
||||
}
|
||||
|
||||
/// File counts, which is what a directory count is too.
|
||||
pub fn human_count(value: u64) -> String {
|
||||
disktree_core::size::human_count(value)
|
||||
}
|
||||
|
||||
/// The value to show for a node under the active metric.
|
||||
pub fn short_value(node: &Node, metric: Metric) -> String {
|
||||
match metric {
|
||||
Metric::Bytes => human_bytes_short(node.bytes),
|
||||
Metric::Files => human_count(node.files),
|
||||
}
|
||||
}
|
||||
|
||||
/// The value to show in tables and headers.
|
||||
pub fn value(node: &Node, metric: Metric) -> String {
|
||||
match metric {
|
||||
Metric::Bytes => human_bytes(node.bytes),
|
||||
Metric::Files => format!("{} files", human_count(node.files)),
|
||||
}
|
||||
}
|
||||
|
||||
/// A dim label above a number, for the header strip.
|
||||
pub fn stat(
|
||||
label: impl Into<SharedString>,
|
||||
value: impl Into<SharedString>,
|
||||
cx: &App,
|
||||
) -> Div {
|
||||
let theme = cx.omarchy();
|
||||
div()
|
||||
.flex()
|
||||
.flex_col()
|
||||
.gap(space::XXS)
|
||||
.child(
|
||||
div()
|
||||
.text_size(text::CAPTION)
|
||||
.text_color(theme.secondary.opacity(0.75))
|
||||
.child(label.into()),
|
||||
)
|
||||
.child(
|
||||
div()
|
||||
.text_size(text::TITLE)
|
||||
.font_weight(FontWeight::SEMIBOLD)
|
||||
.text_color(theme.bright)
|
||||
.child(value.into()),
|
||||
)
|
||||
}
|
||||
|
||||
/// A value with a status colour rather than the neutral one.
|
||||
pub fn stat_colored(
|
||||
label: impl Into<SharedString>,
|
||||
value: impl Into<SharedString>,
|
||||
color: Hsla,
|
||||
cx: &App,
|
||||
) -> Div {
|
||||
let theme = cx.omarchy();
|
||||
div()
|
||||
.flex()
|
||||
.flex_col()
|
||||
.gap(space::XXS)
|
||||
.child(
|
||||
div()
|
||||
.text_size(text::CAPTION)
|
||||
.text_color(theme.secondary.opacity(0.75))
|
||||
.child(label.into()),
|
||||
)
|
||||
.child(
|
||||
div()
|
||||
.text_size(text::TITLE)
|
||||
.font_weight(FontWeight::SEMIBOLD)
|
||||
.text_color(color)
|
||||
.child(value.into()),
|
||||
)
|
||||
}
|
||||
|
||||
/// A square chip, used for counts and states.
|
||||
pub fn chip(label: impl Into<SharedString>, color: Hsla, cx: &App) -> Div {
|
||||
let theme = cx.omarchy();
|
||||
div()
|
||||
.px(space::XS)
|
||||
.py(space::XXS)
|
||||
.border_1()
|
||||
.border_color(color.opacity(0.5))
|
||||
.bg(color.opacity(0.1))
|
||||
.text_color(color)
|
||||
.text_size(text::CAPTION)
|
||||
.font_family(theme.font.clone())
|
||||
.child(label.into())
|
||||
}
|
||||
|
||||
/// A labelled meter: `label · bar · value`.
|
||||
pub fn meter_row(
|
||||
label: impl Into<SharedString>,
|
||||
value: impl Into<SharedString>,
|
||||
fraction: f32,
|
||||
color: Hsla,
|
||||
cx: &App,
|
||||
) -> Div {
|
||||
let theme = cx.omarchy();
|
||||
div()
|
||||
.flex()
|
||||
.flex_col()
|
||||
.gap(space::XS)
|
||||
.child(
|
||||
div()
|
||||
.flex()
|
||||
.flex_row()
|
||||
.justify_between()
|
||||
.text_size(text::CAPTION)
|
||||
.text_color(theme.secondary)
|
||||
.child(div().child(label.into()))
|
||||
.child(
|
||||
div()
|
||||
.text_color(theme.bright)
|
||||
.font_weight(FontWeight::MEDIUM)
|
||||
.child(value.into()),
|
||||
),
|
||||
)
|
||||
.child(
|
||||
div()
|
||||
.w_full()
|
||||
.h(space::XS)
|
||||
.bg(theme.foreground.opacity(0.08))
|
||||
.child(
|
||||
div()
|
||||
.h_full()
|
||||
.w(relative(fraction.clamp(0.0, 1.0)))
|
||||
.bg(color),
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
/// The volume meter: what is used, what is free, and what the marks will free.
|
||||
///
|
||||
/// The projection is drawn as a separate segment so "this much comes back" is
|
||||
/// visible rather than only stated.
|
||||
pub fn space_meter(space: SpaceInfo, reclaiming: u64, cx: &App) -> Div {
|
||||
let theme = cx.omarchy();
|
||||
let total = space.total.max(1);
|
||||
let projected = space.after_removing(reclaiming);
|
||||
let used_now = space.used() as f32 / total as f32;
|
||||
let gained = (projected.used() as f32 / total as f32).max(0.0);
|
||||
let used_now = used_now.clamp(0.0, 1.0);
|
||||
let gained = gained.clamp(0.0, used_now);
|
||||
|
||||
let label = if reclaiming > 0 {
|
||||
format!(
|
||||
"{} free · {} after removing {}",
|
||||
human_bytes(space.available),
|
||||
human_bytes(projected.available),
|
||||
human_bytes(reclaiming)
|
||||
)
|
||||
} else {
|
||||
format!(
|
||||
"{} free of {}",
|
||||
human_bytes(space.available),
|
||||
human_bytes(space.total)
|
||||
)
|
||||
};
|
||||
|
||||
div()
|
||||
.flex()
|
||||
.flex_col()
|
||||
.gap(space::XS)
|
||||
.child(
|
||||
div()
|
||||
.flex()
|
||||
.flex_row()
|
||||
.justify_between()
|
||||
.text_size(text::CAPTION)
|
||||
.text_color(theme.secondary)
|
||||
.child(div().child(label)),
|
||||
)
|
||||
.child(
|
||||
div()
|
||||
.relative()
|
||||
.w_full()
|
||||
.h(space::XS)
|
||||
.bg(theme.foreground.opacity(0.08))
|
||||
.child(
|
||||
// Used space, as a bar from the left.
|
||||
div()
|
||||
.absolute()
|
||||
.left_0()
|
||||
.top_0()
|
||||
.h_full()
|
||||
.w(relative(used_now))
|
||||
.bg(theme.foreground.opacity(0.22)),
|
||||
)
|
||||
.child(
|
||||
// What stays used after the removals: the bar shrinks to
|
||||
// here, so the gap is exactly what comes back.
|
||||
div()
|
||||
.absolute()
|
||||
.left_0()
|
||||
.top_0()
|
||||
.h_full()
|
||||
.w(relative(gained))
|
||||
.bg(theme.danger.opacity(0.55)),
|
||||
)
|
||||
.child(
|
||||
// The reclaimed slice sits at the right edge of what is
|
||||
// currently used.
|
||||
div()
|
||||
.absolute()
|
||||
.left(relative(gained))
|
||||
.top_0()
|
||||
.h_full()
|
||||
.w(relative(used_now - gained))
|
||||
.bg(theme.success.opacity(0.65)),
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
/// A `key value` hint pair for the bottom bar.
|
||||
pub fn hint(
|
||||
keys: impl Into<SharedString>,
|
||||
label: impl Into<SharedString>,
|
||||
cx: &App,
|
||||
) -> Div {
|
||||
let theme = cx.omarchy();
|
||||
div()
|
||||
.flex()
|
||||
.flex_row()
|
||||
.items_center()
|
||||
.gap(space::XS)
|
||||
.child(gpui_omarchy::keycap(keys, cx))
|
||||
.child(
|
||||
div()
|
||||
.text_size(text::CAPTION)
|
||||
.text_color(theme.secondary)
|
||||
.child(label.into()),
|
||||
)
|
||||
}
|
||||
|
||||
/// A section heading inside a panel.
|
||||
pub fn section(label: impl Into<SharedString>, cx: &App) -> Div {
|
||||
let theme = cx.omarchy();
|
||||
div()
|
||||
.text_size(text::CAPTION)
|
||||
.font_weight(FontWeight::SEMIBOLD)
|
||||
.text_color(theme.secondary.opacity(0.85))
|
||||
.child(label.into())
|
||||
}
|
||||
|
||||
/// A definition row: label on the left, value on the right.
|
||||
pub fn row(
|
||||
label: impl Into<SharedString>,
|
||||
value: impl Into<SharedString>,
|
||||
cx: &App,
|
||||
) -> Div {
|
||||
let theme = cx.omarchy();
|
||||
div()
|
||||
.flex()
|
||||
.flex_row()
|
||||
.justify_between()
|
||||
.gap(space::SM)
|
||||
.text_size(text::CAPTION)
|
||||
.child(div().text_color(theme.secondary).child(label.into()))
|
||||
.child(div().min_w_0().text_color(theme.bright).child(value.into()))
|
||||
}
|
||||
|
||||
/// A block-glyph share bar, which reads as a bar at any font size.
|
||||
pub fn glyph_bar(
|
||||
part: u64,
|
||||
total: u64,
|
||||
width: usize,
|
||||
color: Hsla,
|
||||
cx: &App,
|
||||
) -> Div {
|
||||
let theme = cx.omarchy();
|
||||
div()
|
||||
.text_size(text::CAPTION)
|
||||
.font_family(theme.font.clone())
|
||||
.text_color(color)
|
||||
.child(SharedString::from(share_bar(part, total, width)))
|
||||
}
|
||||
|
||||
/// A percentage with one decimal below ten percent.
|
||||
pub fn percent(part: u64, total: u64) -> String {
|
||||
let value = share(part, total);
|
||||
if value < 9.95 {
|
||||
format!("{value:.1}%")
|
||||
} else {
|
||||
format!("{value:.0}%")
|
||||
}
|
||||
}
|
||||
|
||||
/// The status colour for an alert.
|
||||
pub fn alert_color(status: Status, cx: &App) -> Hsla {
|
||||
let theme = cx.omarchy();
|
||||
match status {
|
||||
Status::Neutral => theme.secondary,
|
||||
Status::Success => theme.success,
|
||||
Status::Warning => theme.warning,
|
||||
Status::Error => theme.danger,
|
||||
}
|
||||
}
|
||||
|
||||
/// A clickable breadcrumb segment.
|
||||
pub fn crumb(
|
||||
id: impl Into<ElementId>,
|
||||
label: impl Into<SharedString>,
|
||||
active: bool,
|
||||
cx: &App,
|
||||
) -> gpui_kit::Stateful<Div> {
|
||||
let theme = cx.omarchy();
|
||||
let color = if active {
|
||||
theme.bright
|
||||
} else {
|
||||
theme.secondary
|
||||
};
|
||||
div()
|
||||
.id(id)
|
||||
.px(space::XS)
|
||||
.py(space::XXS)
|
||||
.text_size(text::BODY)
|
||||
.text_color(color)
|
||||
.when(active, |this| this.font_weight(FontWeight::SEMIBOLD))
|
||||
.when(!active, |this| {
|
||||
this.hover(|style| style.bg(theme.hover_fill()))
|
||||
})
|
||||
.child(label.into())
|
||||
}
|
||||
Reference in New Issue
Block a user