mirror of
https://github.com/tobi/disktree.git
synced 2026-11-28 16:00:45 +00:00
app: colour that means something, a side panel, the whole disk
- Tiles are coloured by kind at one muted level, lighter with depth, and hatched where the space can be had back. Age mode colours by last write. Top-level directories carry a strip of their colour. - One highlight, the theme's amber: selection, the main action, what the marks free. Outlines paint after every fill and snap to device pixels. - A resizable side panel replaces the bottom bars: the selection with its size set large, share, files, last write and git state (changes, stashes, unpushed); worth a look; the marked list with a way off it; and the disk, free now and after, with the review button carrying the saving it would make. - Home or the whole disk, from the top bar or with g. - The mosaic stops hovering when the pointer leaves it, so its tooltip never covers the panel handle.
This commit is contained in:
@@ -0,0 +1,137 @@
|
||||
//! What git knows about a checkout, for the selection panel.
|
||||
//!
|
||||
//! Before deleting an agent worktree the question is "would anything be
|
||||
//! lost": uncommitted changes, stashes, commits nobody pushed. That is three
|
||||
//! cheap git calls, run off the UI thread when a checkout is selected and
|
||||
//! remembered per path.
|
||||
|
||||
use std::path::Path;
|
||||
use std::process::{Command, Stdio};
|
||||
|
||||
/// A checkout's state, as far as losing work is concerned.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
||||
pub struct GitState {
|
||||
/// Paths `git status --porcelain` lists: changed, staged or untracked.
|
||||
pub changed: usize,
|
||||
pub stashes: usize,
|
||||
/// Commits ahead of the upstream; `None` when there is no upstream.
|
||||
pub unpushed: Option<usize>,
|
||||
}
|
||||
|
||||
impl GitState {
|
||||
/// Nothing would be lost by deleting it.
|
||||
pub const fn is_clean(&self) -> bool {
|
||||
self.changed == 0
|
||||
&& self.stashes == 0
|
||||
&& matches!(self.unpushed, Some(0))
|
||||
}
|
||||
|
||||
/// One short line: `clean, no stash`, `3 changed, 1 stash, 2 unpushed`.
|
||||
pub fn summary(&self) -> String {
|
||||
let mut parts = Vec::new();
|
||||
parts.push(if self.changed == 0 {
|
||||
"clean".to_string()
|
||||
} else {
|
||||
format!("{} changed", self.changed)
|
||||
});
|
||||
parts.push(match self.stashes {
|
||||
0 => "no stash".to_string(),
|
||||
1 => "1 stash".to_string(),
|
||||
count => format!("{count} stashes"),
|
||||
});
|
||||
match self.unpushed {
|
||||
Some(0) => {}
|
||||
Some(count) => parts.push(format!("{count} unpushed")),
|
||||
None => parts.push("no upstream".to_string()),
|
||||
}
|
||||
parts.join(", ")
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `path` is the top of a checkout: it has a `.git` directory, or the
|
||||
/// `.git` file a worktree gets.
|
||||
pub fn is_checkout(path: &Path) -> bool {
|
||||
std::fs::symlink_metadata(path.join(".git")).is_ok()
|
||||
}
|
||||
|
||||
/// Ask git. `None` when `path` is not a checkout or git is not installed.
|
||||
pub fn state(path: &Path) -> Option<GitState> {
|
||||
if !is_checkout(path) {
|
||||
return None;
|
||||
}
|
||||
let status = run(path, &["status", "--porcelain=v1", "-z"])?;
|
||||
let changed = status.split('\0').filter(|line| !line.is_empty()).count();
|
||||
let stashes =
|
||||
run(path, &["stash", "list"]).map_or(0, |list| list.lines().count());
|
||||
let unpushed = run(path, &["rev-list", "--count", "@{upstream}..HEAD"])
|
||||
.and_then(|count| count.trim().parse().ok());
|
||||
Some(GitState {
|
||||
changed,
|
||||
stashes,
|
||||
unpushed,
|
||||
})
|
||||
}
|
||||
|
||||
fn run(path: &Path, args: &[&str]) -> Option<String> {
|
||||
let output = Command::new("git")
|
||||
.arg("-C")
|
||||
.arg(path)
|
||||
.args(args)
|
||||
// Never prompt, never page, never take a lock for the index refresh.
|
||||
.env("GIT_TERMINAL_PROMPT", "0")
|
||||
.env("GIT_OPTIONAL_LOCKS", "0")
|
||||
.stdin(Stdio::null())
|
||||
.stderr(Stdio::null())
|
||||
.output()
|
||||
.ok()?;
|
||||
output
|
||||
.status
|
||||
.success()
|
||||
.then(|| String::from_utf8_lossy(&output.stdout).into_owned())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn summaries_say_what_would_be_lost() {
|
||||
let clean = GitState {
|
||||
unpushed: Some(0),
|
||||
..GitState::default()
|
||||
};
|
||||
assert!(clean.is_clean());
|
||||
assert_eq!(clean.summary(), "clean, no stash");
|
||||
let busy = GitState {
|
||||
changed: 3,
|
||||
stashes: 1,
|
||||
unpushed: Some(2),
|
||||
};
|
||||
assert!(!busy.is_clean());
|
||||
assert_eq!(busy.summary(), "3 changed, 1 stash, 2 unpushed");
|
||||
let local = GitState::default();
|
||||
assert_eq!(local.summary(), "clean, no stash, no upstream");
|
||||
assert!(!local.is_clean(), "unpushed history could be lost");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reads_a_real_checkout() {
|
||||
let dir = tempfile::tempdir().expect("tempdir");
|
||||
assert_eq!(state(dir.path()), None, "not a checkout");
|
||||
let git = |args: &[&str]| {
|
||||
Command::new("git")
|
||||
.arg("-C")
|
||||
.arg(dir.path())
|
||||
.args(args)
|
||||
.output()
|
||||
.is_ok_and(|output| output.status.success())
|
||||
};
|
||||
if !git(&["init", "-q"]) {
|
||||
return; // no git on this machine
|
||||
}
|
||||
std::fs::write(dir.path().join("a.txt"), "hi").expect("write");
|
||||
let state = state(dir.path()).expect("a checkout");
|
||||
assert_eq!(state.changed, 1, "one untracked file");
|
||||
assert_eq!(state.stashes, 0);
|
||||
}
|
||||
}
|
||||
@@ -5,6 +5,7 @@
|
||||
//! live free-space meter. Marking is non-destructive until the review screen
|
||||
//! is confirmed.
|
||||
|
||||
mod git;
|
||||
mod marks;
|
||||
mod palette;
|
||||
mod state;
|
||||
@@ -45,7 +46,10 @@ 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, --disk scan the whole disk the home directory is on
|
||||
-X, --cross-filesystems
|
||||
also measure other disks, network shares and pseudo
|
||||
filesystems mounted below PATH (off by default)
|
||||
-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
|
||||
@@ -120,6 +124,7 @@ fn parse_args() -> Result<Args> {
|
||||
let mut root: Option<PathBuf> = None;
|
||||
let mut options = ScanOptions::default();
|
||||
let mut depth = 3_u32;
|
||||
let mut disk = false;
|
||||
let mut args = std::env::args().skip(1);
|
||||
|
||||
while let Some(arg) = args.next() {
|
||||
@@ -131,7 +136,11 @@ fn parse_args() -> Result<Args> {
|
||||
"-a" | "--apparent-size" => options.apparent_size = true,
|
||||
"-l" | "--follow-links" => options.follow_links = true,
|
||||
"-H" | "--no-hidden" => options.include_hidden = false,
|
||||
// Staying on one volume is the default; the flag is kept so
|
||||
// old invocations still work.
|
||||
"-x" | "--one-filesystem" => options.one_filesystem = true,
|
||||
"-X" | "--cross-filesystems" => options.one_filesystem = false,
|
||||
"-D" | "--disk" => disk = true,
|
||||
"-d" | "--depth" => {
|
||||
let value = args.next().context("--depth needs a number")?;
|
||||
depth = value.parse().context("--depth needs a number")?;
|
||||
@@ -160,7 +169,16 @@ fn parse_args() -> Result<Args> {
|
||||
}
|
||||
}
|
||||
|
||||
anyhow::ensure!(
|
||||
!(disk && root.is_some()),
|
||||
"--disk and a PATH cannot be combined"
|
||||
);
|
||||
let home = std::env::var_os("HOME").map(PathBuf::from);
|
||||
let root = match root {
|
||||
_ if disk => home
|
||||
.as_deref()
|
||||
.and_then(disktree_core::space::volume_root_for)
|
||||
.unwrap_or_else(|| PathBuf::from("/")),
|
||||
Some(root) => root,
|
||||
None => std::env::var_os("HOME")
|
||||
.map(PathBuf::from)
|
||||
|
||||
+230
-104
@@ -1,82 +1,176 @@
|
||||
//! Colours derived from the Omarchy theme.
|
||||
//! Colour that means something.
|
||||
//!
|
||||
//! 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.
|
||||
//! A tile's hue says what kind of data it is ([`Category`]); every hue sits
|
||||
//! at the same muted saturation and lightness, so no block stands out by
|
||||
//! accident, and deeper tiles lift slightly so nesting reads without borders.
|
||||
//! Reclaimable space is a hatch, not a colour, so "what is it" and "can it go"
|
||||
//! are read independently.
|
||||
//!
|
||||
//! One strong colour is kept apart: the highlight, the theme's warning amber.
|
||||
//! It marks the selection, the main action, reclaimable totals and the free
|
||||
//! space after a removal, and nothing else, so the eye goes straight to it.
|
||||
//!
|
||||
//! Lightness, saturation and the surface every fill is pulled toward come
|
||||
//! from the active Omarchy theme, so the mosaic sits inside it, light or dark.
|
||||
|
||||
use gpui_kit::Hsla;
|
||||
use disktree_core::classify::Category;
|
||||
use gpui_kit::base::ThemeAppearance;
|
||||
use gpui_kit::{Hsla, Rgba};
|
||||
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
|
||||
/// The hue a category is drawn in, and how much colour it carries. The
|
||||
/// neutral kinds (documents, unknown) carry almost none.
|
||||
const fn hue(category: Category) -> (f32, f32) {
|
||||
match category {
|
||||
Category::Code => (0.605, 1.0),
|
||||
Category::AgentScratch => (0.065, 1.0),
|
||||
Category::Toolchain => (0.415, 1.0),
|
||||
Category::Synced => (0.535, 1.0),
|
||||
Category::Git => (0.955, 1.0),
|
||||
Category::Media => (0.745, 1.0),
|
||||
Category::Cache => (0.125, 0.95),
|
||||
Category::Documents => (0.6, 0.18),
|
||||
Category::Other => (0.6, 0.08),
|
||||
}
|
||||
}
|
||||
|
||||
/// Linear interpolation between two colours in HSLA.
|
||||
const fn dark(theme: &Theme) -> bool {
|
||||
matches!(theme.appearance, ThemeAppearance::Dark)
|
||||
}
|
||||
|
||||
/// The fill for a tile of `category`, `depth` levels into the view.
|
||||
pub fn category_fill(theme: &Theme, category: Category, depth: u32) -> Hsla {
|
||||
let (h, chroma) = hue(category);
|
||||
let step = depth.min(4) as f32;
|
||||
let (s, l) = if dark(theme) {
|
||||
(0.26 * chroma, step.mul_add(0.028, 0.215))
|
||||
} else {
|
||||
(0.30 * chroma, step.mul_add(-0.03, 0.84))
|
||||
};
|
||||
// Pulled a little toward the theme surface, so each theme tints it.
|
||||
mix(Hsla { h, s, l, a: 1.0 }, theme.inset, 0.12)
|
||||
}
|
||||
|
||||
/// The saturated version of a category's hue: the strip over a top-level
|
||||
/// directory and the legend swatch.
|
||||
pub fn category_accent(theme: &Theme, category: Category) -> Hsla {
|
||||
let (h, chroma) = hue(category);
|
||||
let (s, l) = if dark(theme) {
|
||||
(0.42 * chroma, 0.52)
|
||||
} else {
|
||||
(0.45 * chroma, 0.46)
|
||||
};
|
||||
Hsla { h, s, l, a: 1.0 }
|
||||
}
|
||||
|
||||
/// The age ramp, newest first: this week, this month, this half-year, this
|
||||
/// year, older.
|
||||
pub const AGE_BUCKETS: [(i64, &str); 5] = [
|
||||
(7, "This week"),
|
||||
(30, "This month"),
|
||||
(182, "Six months"),
|
||||
(365, "This year"),
|
||||
(i64::MAX, "Older"),
|
||||
];
|
||||
|
||||
/// Which [`AGE_BUCKETS`] entry an age in days falls in.
|
||||
pub fn age_bucket(days: i64) -> usize {
|
||||
AGE_BUCKETS
|
||||
.iter()
|
||||
.position(|(limit, _)| days <= *limit)
|
||||
.unwrap_or(AGE_BUCKETS.len() - 1)
|
||||
}
|
||||
|
||||
/// The fill for age mode: recent writes carry the theme accent, and colour
|
||||
/// drains out of a tile as it goes untouched.
|
||||
pub fn age_fill(theme: &Theme, bucket: usize, depth: u32) -> Hsla {
|
||||
let fade = bucket.min(AGE_BUCKETS.len() - 1) as f32 / 4.0;
|
||||
let step = depth.min(4) as f32;
|
||||
let (s, l) = if dark(theme) {
|
||||
(
|
||||
(1.0 - fade).mul_add(0.34, 0.03),
|
||||
step.mul_add(0.028, 0.29 - fade * 0.09),
|
||||
)
|
||||
} else {
|
||||
(
|
||||
(1.0 - fade).mul_add(0.36, 0.04),
|
||||
step.mul_add(-0.03, 0.74 + fade * 0.1),
|
||||
)
|
||||
};
|
||||
mix(
|
||||
Hsla {
|
||||
h: theme.accent.h,
|
||||
s,
|
||||
l,
|
||||
a: 1.0,
|
||||
},
|
||||
theme.inset,
|
||||
0.1,
|
||||
)
|
||||
}
|
||||
|
||||
/// The age swatch for the legend.
|
||||
pub fn age_accent(theme: &Theme, bucket: usize) -> Hsla {
|
||||
let fade = bucket.min(AGE_BUCKETS.len() - 1) as f32 / 4.0;
|
||||
let l = if dark(theme) {
|
||||
0.55 - fade * 0.25
|
||||
} else {
|
||||
0.45 + fade * 0.25
|
||||
};
|
||||
Hsla {
|
||||
h: theme.accent.h,
|
||||
s: (1.0 - fade).mul_add(0.45, 0.04),
|
||||
l,
|
||||
a: 1.0,
|
||||
}
|
||||
}
|
||||
|
||||
/// The one strong colour: selection, the main action, what can be had back.
|
||||
pub const fn highlight(theme: &Theme) -> Hsla {
|
||||
theme.warning
|
||||
}
|
||||
|
||||
/// Text on a filled highlight.
|
||||
pub const fn on_highlight(theme: &Theme) -> Hsla {
|
||||
if dark(theme) {
|
||||
theme.background
|
||||
} else {
|
||||
theme.bright
|
||||
}
|
||||
}
|
||||
|
||||
/// The diagonal hatch over reclaimable space: quiet enough to leave the hue
|
||||
/// readable, visible on every fill.
|
||||
pub fn hatch(theme: &Theme) -> Hsla {
|
||||
if dark(theme) {
|
||||
theme.bright.opacity(0.16)
|
||||
} else {
|
||||
theme.foreground.opacity(0.18)
|
||||
}
|
||||
}
|
||||
|
||||
/// Linear interpolation between two colours, in RGB: interpolating hue
|
||||
/// would drag a colour around the wheel on its way to a grey.
|
||||
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),
|
||||
}
|
||||
let (a, b) = (from.to_rgb(), to.to_rgb());
|
||||
Hsla::from(Rgba {
|
||||
r: lerp(a.r, b.r),
|
||||
g: lerp(a.g, b.g),
|
||||
b: lerp(a.b, b.b),
|
||||
a: lerp(a.a, b.a),
|
||||
})
|
||||
}
|
||||
|
||||
/// The colour of a tile's label on top of its fill.
|
||||
/// A tile's name 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) }
|
||||
let base = if dark(theme) {
|
||||
theme.bright
|
||||
} else {
|
||||
theme.foreground
|
||||
};
|
||||
if depth == 0 { base } else { base.opacity(0.88) }
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -84,52 +178,84 @@ 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}");
|
||||
match appearance {
|
||||
ThemeAppearance::Dark => Theme::tokyo_night(),
|
||||
ThemeAppearance::Light => Theme::flexoki_light(),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_legend_category_has_its_own_hue() {
|
||||
let theme = theme(ThemeAppearance::Dark);
|
||||
let fills: Vec<Hsla> = Category::LEGEND
|
||||
.iter()
|
||||
.map(|&category| category_accent(&theme, category))
|
||||
.collect();
|
||||
for (index, left) in fills.iter().enumerate() {
|
||||
for right in &fills[index + 1..] {
|
||||
let apart = (left.h - right.h).abs() > 0.03
|
||||
|| (left.s - right.s).abs() > 0.1;
|
||||
assert!(apart, "{left:?} and {right:?} read as one colour");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn colourful_categories_share_one_level() {
|
||||
let theme = theme(ThemeAppearance::Dark);
|
||||
let code = category_fill(&theme, Category::Code, 0);
|
||||
let git = category_fill(&theme, Category::Git, 0);
|
||||
assert!((code.l - git.l).abs() < 0.02);
|
||||
assert!((code.s - git.s).abs() < 0.03);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn deeper_tiles_lift_away_from_the_background() {
|
||||
for appearance in [ThemeAppearance::Dark, ThemeAppearance::Light] {
|
||||
let theme = theme(appearance);
|
||||
let top = category_fill(&theme, Category::Code, 0);
|
||||
let deep = category_fill(&theme, Category::Code, 3);
|
||||
// Away from the background: lighter on dark, darker on light.
|
||||
let distance = |fill: Hsla| (fill.l - theme.background.l).abs();
|
||||
assert!(distance(deep) > distance(top) + 0.05, "{appearance:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_highlight_is_not_a_category_colour() {
|
||||
let theme = theme(ThemeAppearance::Dark);
|
||||
let highlight = highlight(&theme);
|
||||
for category in Category::LEGEND {
|
||||
let fill = category_fill(&theme, category, 0);
|
||||
assert!(highlight.s - fill.s > 0.2, "{category:?} competes");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn age_buckets_cover_every_age_in_order() {
|
||||
assert_eq!(age_bucket(0), 0);
|
||||
assert_eq!(age_bucket(8), 1);
|
||||
assert_eq!(age_bucket(100), 2);
|
||||
assert_eq!(age_bucket(300), 3);
|
||||
assert_eq!(age_bucket(5000), 4);
|
||||
let theme = theme(ThemeAppearance::Dark);
|
||||
assert!(age_fill(&theme, 0, 0).s > age_fill(&theme, 4, 0).s);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mixing_toward_a_grey_keeps_the_hue() {
|
||||
let theme = theme(ThemeAppearance::Dark);
|
||||
let orange = category_accent(&theme, Category::AgentScratch);
|
||||
let mixed = mix(orange, theme.inset, 0.3);
|
||||
assert!((mixed.h - orange.h).abs() < 0.02, "{mixed:?}");
|
||||
}
|
||||
|
||||
#[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);
|
||||
assert!((clamped_low - theme.background.l).abs() < 1e-3);
|
||||
assert!((clamped_high - theme.accent.l).abs() < 1e-3);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -9,13 +9,16 @@ use std::path::{Path, PathBuf};
|
||||
use std::rc::Rc;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use disktree_core::insights::{Candidate, worth_a_look};
|
||||
use disktree_core::removal::{
|
||||
Plan, RemovalEvent, RemovalHandle, RemovalMode, Target, TrashBackend,
|
||||
detect_trash_backend, plan,
|
||||
};
|
||||
use disktree_core::scan::{ScanHandle, ScanOptions, ScanSnapshot};
|
||||
use disktree_core::space::{SpaceInfo, space_info};
|
||||
use disktree_core::tree::{Node, path_of};
|
||||
use disktree_core::space::{
|
||||
SpaceInfo, device_for, space_info, volume_root_for,
|
||||
};
|
||||
use disktree_core::tree::{Metric, Node, path_of};
|
||||
use disktree_core::treemap::{
|
||||
LayoutOptions, Rect, Tile, TileKind, hit, layout,
|
||||
};
|
||||
@@ -25,11 +28,51 @@ use gpui_kit::{
|
||||
Window, px, size,
|
||||
};
|
||||
use gpui_omarchy::Status;
|
||||
use rustc_hash::FxHashSet;
|
||||
use rustc_hash::{FxHashMap, FxHashSet};
|
||||
|
||||
use crate::git::GitState;
|
||||
|
||||
use crate::marks::{Marks, display_path, is_hidden};
|
||||
use crate::treemap_view::{Mosaic, TileDeco};
|
||||
|
||||
/// What a tile's colour says.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
pub enum ColorMode {
|
||||
/// The kind of data it is.
|
||||
#[default]
|
||||
Kind,
|
||||
/// How long since anything in it was written.
|
||||
Age,
|
||||
}
|
||||
|
||||
/// What is scanned, as the trail's switch names it.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Scope {
|
||||
/// The home directory.
|
||||
Home,
|
||||
/// The whole disk the home directory lives on.
|
||||
Disk,
|
||||
}
|
||||
|
||||
/// The side panel's width in rem: default and limits. In rem, so interface
|
||||
/// zoom scales it with everything it holds.
|
||||
pub const PANEL_REMS: f32 = 23.0;
|
||||
pub const PANEL_MIN_REMS: f32 = 17.0;
|
||||
pub const PANEL_MAX_REMS: f32 = 44.0;
|
||||
|
||||
/// The panel width, in rem, for its left edge at `pointer_x` in a window
|
||||
/// `viewport` pixels wide: between its limits, and never so wide that the
|
||||
/// mosaic is squeezed below the panel's own minimum.
|
||||
pub fn panel_width(pointer_x: f32, viewport: f32, rem: f32) -> f32 {
|
||||
let width = (viewport - pointer_x) / rem;
|
||||
let max =
|
||||
(viewport / rem - PANEL_MIN_REMS).clamp(PANEL_MIN_REMS, PANEL_MAX_REMS);
|
||||
width.clamp(PANEL_MIN_REMS, max)
|
||||
}
|
||||
|
||||
/// How many "worth a look" findings the panel lists.
|
||||
const INSIGHT_LIMIT: usize = 6;
|
||||
|
||||
/// Which screen the app is showing.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
pub enum Screen {
|
||||
@@ -296,6 +339,25 @@ pub struct Disktree {
|
||||
pub show_help: bool,
|
||||
pub show_selection: bool,
|
||||
pub focus: FocusHandle,
|
||||
|
||||
pub color_mode: ColorMode,
|
||||
/// The largest things worth clearing, recomputed when a scan lands.
|
||||
pub insights: Vec<Candidate>,
|
||||
/// What git knows about each checkout that has been selected; `None`
|
||||
/// once asked and found not to be one.
|
||||
pub git: FxHashMap<PathBuf, Option<GitState>>,
|
||||
git_pending: FxHashSet<PathBuf>,
|
||||
/// The device the scanned volume is mounted from.
|
||||
pub device: Option<String>,
|
||||
/// The top of the disk the home directory lives on: what "Whole disk"
|
||||
/// scans.
|
||||
pub disk_root: Option<PathBuf>,
|
||||
/// The side panel's width, in rem; dragged from its left edge.
|
||||
pub panel_rems: f32,
|
||||
pub scan_started: Option<Instant>,
|
||||
pub scan_elapsed: Option<Duration>,
|
||||
/// Unix seconds when the tree landed: the "now" ages are measured from.
|
||||
pub scanned_at: i64,
|
||||
}
|
||||
|
||||
impl Disktree {
|
||||
@@ -357,7 +419,23 @@ impl Disktree {
|
||||
show_help: false,
|
||||
show_selection: true,
|
||||
focus: cx.focus_handle(),
|
||||
color_mode: ColorMode::Kind,
|
||||
insights: Vec::new(),
|
||||
git: FxHashMap::default(),
|
||||
git_pending: FxHashSet::default(),
|
||||
device: None,
|
||||
disk_root: None,
|
||||
panel_rems: PANEL_REMS,
|
||||
scan_started: None,
|
||||
scan_elapsed: None,
|
||||
scanned_at: now_seconds(),
|
||||
};
|
||||
tree.device = device_for(&tree.root_path);
|
||||
tree.disk_root = tree
|
||||
.home
|
||||
.as_deref()
|
||||
.or(Some(tree.root_path.as_path()))
|
||||
.and_then(volume_root_for);
|
||||
tree.start_scan(cx);
|
||||
Self::start_space_ticker(cx);
|
||||
tree
|
||||
@@ -380,10 +458,77 @@ impl Disktree {
|
||||
app.marks.refresh(&app.root_path, &tree, app.options.metric);
|
||||
app.tree = Some(Rc::new(tree));
|
||||
app.cache = None;
|
||||
app.refresh_insights();
|
||||
app.select_largest(cx);
|
||||
app
|
||||
}
|
||||
|
||||
/// Which scope the current root is, if it is one of the two.
|
||||
pub fn scope(&self) -> Option<Scope> {
|
||||
if self.home.as_deref() == Some(self.root_path.as_path()) {
|
||||
Some(Scope::Home)
|
||||
} else if self.disk_root.as_deref() == Some(self.root_path.as_path()) {
|
||||
Some(Scope::Disk)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
/// Scan a different root: the home directory, the whole disk, or any
|
||||
/// directory. Marks are kept; a mark outside the new root is shown as
|
||||
/// kept back, never removed.
|
||||
pub fn set_root(&mut self, root: PathBuf, cx: &mut Context<'_, Self>) {
|
||||
if root == self.root_path && self.tree.is_some() {
|
||||
return;
|
||||
}
|
||||
self.space = space_info(&root).ok();
|
||||
self.device = device_for(&root);
|
||||
self.root_path = root;
|
||||
self.screen = Screen::Explore;
|
||||
self.start_scan(cx);
|
||||
}
|
||||
|
||||
/// Switch to a scope.
|
||||
pub fn set_scope(&mut self, scope: Scope, cx: &mut Context<'_, Self>) {
|
||||
let root = match scope {
|
||||
Scope::Home => self.home.clone(),
|
||||
Scope::Disk => self.disk_root.clone(),
|
||||
};
|
||||
if let Some(root) = root {
|
||||
self.set_root(root, cx);
|
||||
}
|
||||
}
|
||||
|
||||
/// Recompute "worth a look" from the tree on screen.
|
||||
fn refresh_insights(&mut self) {
|
||||
self.scanned_at = now_seconds();
|
||||
self.insights = self.tree.as_deref().map_or_else(Vec::new, |tree| {
|
||||
worth_a_look(tree, self.scanned_at, INSIGHT_LIMIT)
|
||||
});
|
||||
}
|
||||
|
||||
/// Ask git about `path` once, off the UI thread, if it is a checkout.
|
||||
pub fn ensure_git(&mut self, path: &Path, cx: &Context<'_, Self>) {
|
||||
if self.git.contains_key(path) || self.git_pending.contains(path) {
|
||||
return;
|
||||
}
|
||||
let path = path.to_path_buf();
|
||||
self.git_pending.insert(path.clone());
|
||||
let task = cx.background_executor().spawn({
|
||||
let path = path.clone();
|
||||
async move { crate::git::state(&path) }
|
||||
});
|
||||
cx.spawn(async move |this, cx| {
|
||||
let state = task.await;
|
||||
let _ = this.update(cx, |this, cx| {
|
||||
this.git_pending.remove(&path);
|
||||
this.git.insert(path, state);
|
||||
cx.notify();
|
||||
});
|
||||
})
|
||||
.detach();
|
||||
}
|
||||
|
||||
/// Select the largest entry of the current root, so the selection line, the
|
||||
/// tooltip and the mark key all have something to act on from the first
|
||||
/// frame. The largest entry is also the answer to "what is eating my disk"
|
||||
@@ -415,6 +560,10 @@ impl Disktree {
|
||||
self.hovered = None;
|
||||
self.view = View::default();
|
||||
self.cache = None;
|
||||
self.insights.clear();
|
||||
self.git.clear();
|
||||
self.scan_started = Some(Instant::now());
|
||||
self.scan_elapsed = None;
|
||||
self.scan = Some(ScanHandle::spawn(
|
||||
self.root_path.clone(),
|
||||
self.options.clone(),
|
||||
@@ -465,6 +614,9 @@ impl Disktree {
|
||||
self.marks.refresh(&self.root_path, &node, metric);
|
||||
self.tree = Some(Rc::new(node));
|
||||
self.cache = None;
|
||||
self.refresh_insights();
|
||||
self.scan_elapsed =
|
||||
self.scan_started.map(|started| started.elapsed());
|
||||
self.keep_selection_valid();
|
||||
self.select_largest(cx);
|
||||
}
|
||||
@@ -719,6 +871,16 @@ impl Disktree {
|
||||
cx.notify();
|
||||
}
|
||||
|
||||
/// Show `crumbs` in its directory, selected: what a "worth a look" row
|
||||
/// or a found name does.
|
||||
pub fn reveal(&mut self, crumbs: Vec<usize>, cx: &mut Context<'_, Self>) {
|
||||
let parent = crumbs[..crumbs.len().saturating_sub(1)].to_vec();
|
||||
self.go_to(parent, cx);
|
||||
self.selected = Some(crumbs);
|
||||
self.pointer_active = false;
|
||||
cx.notify();
|
||||
}
|
||||
|
||||
/// Select the tile at `crumbs` without changing the root.
|
||||
pub fn select(
|
||||
&mut self,
|
||||
@@ -976,24 +1138,34 @@ impl Disktree {
|
||||
};
|
||||
};
|
||||
|
||||
// Colours are keyed to depth-from-the-scanned-root, not depth-from-this
|
||||
// view: the layout root is re-based every time the view descends, so a
|
||||
// view-relative key would recolour every tile as you walk in. The view
|
||||
// root's own absolute depth is the breadcrumb count.
|
||||
let base_depth = u32::try_from(self.crumbs.len()).unwrap_or(u32::MAX);
|
||||
// Hue comes from the node's kind; lightness from its depth in this
|
||||
// view, so the first level always reads as the first level.
|
||||
let age = self.color_mode == ColorMode::Age;
|
||||
let now = self.scanned_at;
|
||||
let mut decorations = Vec::with_capacity(tiles.len());
|
||||
let mut labels = Vec::new();
|
||||
for tile in &tiles {
|
||||
let crumbs = tile.crumbs();
|
||||
let hidden = self.crumbs_are_hidden(crumbs);
|
||||
let node = match &tile.kind {
|
||||
TileKind::Node { crumbs } => self.node_at(crumbs),
|
||||
TileKind::Others { .. } => None,
|
||||
};
|
||||
let category = node.map_or_else(Default::default, |n| n.category);
|
||||
let age_bucket = (age && node.is_some_and(|n| n.modified > 0))
|
||||
.then(|| {
|
||||
let days =
|
||||
(now - node.map_or(now, |n| n.modified)) / 86_400;
|
||||
crate::palette::age_bucket(days)
|
||||
});
|
||||
let is_marked = marked.contains(crumbs);
|
||||
let is_covered = covered.contains(crumbs);
|
||||
decorations.push(TileDeco {
|
||||
rect: self.animated_rect(tile.rect),
|
||||
header: tile.header.map(|header| self.animated_rect(header)),
|
||||
depth: tile.depth,
|
||||
color_depth: base_depth.saturating_add(tile.depth),
|
||||
hidden,
|
||||
category,
|
||||
age_bucket,
|
||||
reclaimable: node.is_some_and(|n| n.reclaim.is_some()),
|
||||
unreadable: node.is_some_and(|n| n.read_error),
|
||||
marked: is_marked,
|
||||
covered: is_covered,
|
||||
hovered: hovered.as_deref() == Some(crumbs),
|
||||
@@ -1023,7 +1195,7 @@ impl Disktree {
|
||||
header: tile
|
||||
.header
|
||||
.map(|header| self.animated_rect(header)),
|
||||
color_depth: base_depth.saturating_add(tile.depth),
|
||||
depth: tile.depth,
|
||||
marked: is_marked || is_covered,
|
||||
size_text: crate::widgets::short_value(node, metric),
|
||||
});
|
||||
@@ -1032,7 +1204,7 @@ impl Disktree {
|
||||
text: format!("+{count} more"),
|
||||
rect: self.animated_rect(tile.rect),
|
||||
header: None,
|
||||
color_depth: base_depth.saturating_add(tile.depth),
|
||||
depth: tile.depth,
|
||||
marked: false,
|
||||
size_text: String::new(),
|
||||
}),
|
||||
@@ -1077,21 +1249,12 @@ impl Disktree {
|
||||
Some(crumbs)
|
||||
}
|
||||
|
||||
/// Whether any component of the path to `crumbs` is a dotfile.
|
||||
fn crumbs_are_hidden(&self, crumbs: &[usize]) -> bool {
|
||||
let Some(tree) = &self.tree else {
|
||||
return false;
|
||||
};
|
||||
tree.resolve_chain(crumbs)
|
||||
.iter()
|
||||
.any(|node| node.name.starts_with('.'))
|
||||
}
|
||||
|
||||
/// Tiles for the current root and viewport size, computed once per change.
|
||||
pub fn layout(&mut self) -> Option<&[Tile]> {
|
||||
// A 17 px band at the default rem, scaled so zoom keeps the band's
|
||||
// relationship to the label inside it.
|
||||
self.layout_options.header = HEADER_REMS * self.rem;
|
||||
self.layout_options.header_inner = HEADER_INNER_REMS * self.rem;
|
||||
let area = self.treemap_size.get();
|
||||
let key = LayoutKey {
|
||||
crumbs: self.crumbs.clone(),
|
||||
@@ -1217,10 +1380,36 @@ impl Disktree {
|
||||
metric,
|
||||
);
|
||||
}
|
||||
// Children are ordered by the metric, so every crumb moved.
|
||||
self.refresh_insights();
|
||||
self.cache = None;
|
||||
cx.notify();
|
||||
}
|
||||
|
||||
/// The Size | Files | Age choice: what areas measure, and what colour
|
||||
/// says. Age keeps areas by size, since age has no area of its own.
|
||||
pub fn set_mode(&mut self, index: usize, cx: &mut Context<'_, Self>) {
|
||||
let (metric, color) = match index {
|
||||
1 => (Metric::Files, ColorMode::Kind),
|
||||
2 => (Metric::Bytes, ColorMode::Age),
|
||||
_ => (Metric::Bytes, ColorMode::Kind),
|
||||
};
|
||||
self.color_mode = color;
|
||||
if self.options.metric != metric {
|
||||
self.toggle_metric(cx);
|
||||
}
|
||||
cx.notify();
|
||||
}
|
||||
|
||||
/// The Size | Files | Age choice currently on.
|
||||
pub const fn mode_index(&self) -> usize {
|
||||
match (self.color_mode, self.options.metric) {
|
||||
(ColorMode::Age, _) => 2,
|
||||
(ColorMode::Kind, Metric::Files) => 1,
|
||||
(ColorMode::Kind, Metric::Bytes) => 0,
|
||||
}
|
||||
}
|
||||
|
||||
// ── removal ─────────────────────────────────────────────────────────
|
||||
|
||||
/// The review screen's commit: move to the trash at once, or ask first for
|
||||
@@ -1404,11 +1593,8 @@ impl Disktree {
|
||||
cx.notify();
|
||||
return;
|
||||
};
|
||||
let parent = crumbs[..crumbs.len().saturating_sub(1)].to_vec();
|
||||
self.go_to(parent, cx);
|
||||
self.selected = Some(crumbs);
|
||||
self.reveal(crumbs, cx);
|
||||
self.notice = None;
|
||||
cx.notify();
|
||||
}
|
||||
|
||||
// ── input ───────────────────────────────────────────────────────────
|
||||
@@ -1595,8 +1781,18 @@ impl Disktree {
|
||||
);
|
||||
}
|
||||
"0" => self.reset_view(cx),
|
||||
"t" if !control => self.toggle_metric(cx),
|
||||
"t" if !control => {
|
||||
self.set_mode((self.mode_index() + 1) % 3, cx);
|
||||
}
|
||||
"r" if !control => self.start_scan(cx),
|
||||
"g" if !control => {
|
||||
let next = if self.scope() == Some(Scope::Disk) {
|
||||
Scope::Home
|
||||
} else {
|
||||
Scope::Disk
|
||||
};
|
||||
self.set_scope(next, cx);
|
||||
}
|
||||
"i" if !control => {
|
||||
self.options.include_hidden = !self.options.include_hidden;
|
||||
self.start_scan(cx);
|
||||
@@ -1661,6 +1857,21 @@ impl Disktree {
|
||||
event.position.x - origin.x,
|
||||
event.position.y - origin.y,
|
||||
);
|
||||
// Moves are delivered here even when the pointer is elsewhere in the
|
||||
// window. Outside the mosaic there is nothing to hover, and a stale
|
||||
// tooltip would cover whatever the pointer went to — the panel's
|
||||
// resize handle, for one.
|
||||
let area = self.treemap_size.get();
|
||||
let inside = local.x >= px(0.)
|
||||
&& local.y >= px(0.)
|
||||
&& local.x < area.width
|
||||
&& local.y < area.height;
|
||||
if !inside {
|
||||
if self.pointer.is_some() || self.hovered.is_some() {
|
||||
self.on_mouse_leave(cx);
|
||||
}
|
||||
return;
|
||||
}
|
||||
self.pointer = Some(local);
|
||||
self.pointer_active = true;
|
||||
let previous = self.hovered.clone();
|
||||
@@ -1844,9 +2055,8 @@ pub struct Label {
|
||||
/// The band this label belongs in, when its tile reserved one. A parent's
|
||||
/// name goes in its own band, never over its children.
|
||||
pub header: Option<Rect>,
|
||||
/// Depth from the scanned root, used for the colour so it does not shift
|
||||
/// when the view descends.
|
||||
pub color_depth: u32,
|
||||
/// Nesting depth in this view: the first level is set in bold.
|
||||
pub depth: u32,
|
||||
pub marked: bool,
|
||||
pub size_text: String,
|
||||
}
|
||||
@@ -1854,8 +2064,20 @@ pub struct Label {
|
||||
/// How many labels one frame will shape.
|
||||
const MAX_LABELS: usize = 150;
|
||||
|
||||
/// Height of a directory's name band, in rem.
|
||||
const HEADER_REMS: f32 = 1.0625;
|
||||
/// Height of a top-level directory's name band, in rem.
|
||||
const HEADER_REMS: f32 = 1.375;
|
||||
|
||||
/// Height of the slim label row a deeper open directory keeps, in rem.
|
||||
const HEADER_INNER_REMS: f32 = 1.0;
|
||||
|
||||
/// Now, in Unix seconds.
|
||||
pub fn now_seconds() -> i64 {
|
||||
std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.map_or(0, |since| {
|
||||
i64::try_from(since.as_secs()).unwrap_or(i64::MAX)
|
||||
})
|
||||
}
|
||||
|
||||
/// Smallest tile, in rem, that gets a label: below this a name cannot be read.
|
||||
const LABEL_MIN_W_REMS: f32 = 3.375;
|
||||
|
||||
@@ -814,3 +814,100 @@ fn after_descending_every_tile_is_inside_the_directory_drawn(
|
||||
});
|
||||
assert_eq!(hatched, 1, "exactly the marked tile is hatched");
|
||||
}
|
||||
|
||||
/// Drive the scan the view started until its tree lands.
|
||||
fn finish_scan(view: &Entity<Disktree>, cx: &mut Window) {
|
||||
let epoch = read(view, cx, |app| app.scan_epoch);
|
||||
for _ in 0..600 {
|
||||
std::thread::sleep(std::time::Duration::from_millis(5));
|
||||
let ready = update(view, cx, |app, cx| {
|
||||
app.poll_scan_once(epoch, cx);
|
||||
app.tree().is_some()
|
||||
});
|
||||
if ready {
|
||||
return;
|
||||
}
|
||||
}
|
||||
panic!("the scan never landed");
|
||||
}
|
||||
|
||||
#[gpui_kit::test]
|
||||
fn dragging_the_panel_edge_resizes_it_within_its_limits(
|
||||
cx: &mut TestAppContext,
|
||||
) {
|
||||
use crate::state::{PANEL_MAX_REMS, PANEL_MIN_REMS, panel_width};
|
||||
use gpui_kit::{Modifiers, MouseButton};
|
||||
|
||||
cx.update(gpui_omarchy::init);
|
||||
let temp = fixture();
|
||||
let (view, cx) = view_over(temp.path(), cx);
|
||||
cx.simulate_resize(gpui_kit::size(px(1400.), px(900.)));
|
||||
draw(cx);
|
||||
let handle = cx.debug_bounds("panel-handle").expect("the panel is shown");
|
||||
let start = handle.center();
|
||||
let before = read(&view, cx, |app| app.panel_rems);
|
||||
|
||||
// A drag starts on the first move and reports moves after it, as a real
|
||||
// pointer does in many small steps.
|
||||
let drag = |cx: &mut Window, from: Point<Pixels>, to: Point<Pixels>| {
|
||||
cx.simulate_mouse_down(from, MouseButton::Left, Modifiers::none());
|
||||
for step in 1..=4 {
|
||||
let t = step as f32 / 4.0;
|
||||
let at = Point::new(from.x + (to.x - from.x) * t, to.y);
|
||||
cx.simulate_mouse_move(
|
||||
at,
|
||||
Some(MouseButton::Left),
|
||||
Modifiers::none(),
|
||||
);
|
||||
}
|
||||
cx.simulate_mouse_up(to, MouseButton::Left, Modifiers::none());
|
||||
draw(cx);
|
||||
};
|
||||
|
||||
// Wider: drag the edge 160 px to the left.
|
||||
let wider = Point::new(start.x - px(160.), start.y);
|
||||
drag(cx, start, wider);
|
||||
let after = read(&view, cx, |app| app.panel_rems);
|
||||
assert!(
|
||||
(after - before - 10.0).abs() < 0.5,
|
||||
"160 px is 10 rem: {before} -> {after}"
|
||||
);
|
||||
|
||||
// The limits, for any edge position: a minimum, a maximum, and never
|
||||
// so wide that the mosaic gets less room than the panel's own minimum.
|
||||
assert!((panel_width(1390., 1400., 16.) - PANEL_MIN_REMS).abs() < 1e-3);
|
||||
assert!((panel_width(0., 3000., 16.) - PANEL_MAX_REMS).abs() < 1e-3);
|
||||
let squeezed = panel_width(0., 800., 16.);
|
||||
assert!((squeezed - (800. / 16. - PANEL_MIN_REMS)).abs() < 1e-3);
|
||||
assert!((panel_width(0., 300., 16.) - PANEL_MIN_REMS).abs() < 1e-3);
|
||||
}
|
||||
|
||||
#[gpui_kit::test]
|
||||
fn g_switches_between_the_home_directory_and_the_whole_disk(
|
||||
cx: &mut TestAppContext,
|
||||
) {
|
||||
use crate::state::Scope;
|
||||
|
||||
cx.update(gpui_omarchy::init);
|
||||
let temp = fixture();
|
||||
let (view, cx) = view_over(temp.path(), cx);
|
||||
// Stand-ins: the fixture is "home", a directory in it is "the disk".
|
||||
let disk = temp.path().join("junk");
|
||||
update(&view, cx, |app, _| {
|
||||
app.home = Some(temp.path().to_path_buf());
|
||||
app.disk_root = Some(disk.clone());
|
||||
});
|
||||
assert_eq!(read(&view, cx, Disktree::scope), Some(Scope::Home));
|
||||
|
||||
press(cx, "g");
|
||||
assert_eq!(read(&view, cx, |app| app.root_path.clone()), disk);
|
||||
assert!(read(&view, cx, |app| app.scan.is_some()), "a new scan runs");
|
||||
finish_scan(&view, cx);
|
||||
assert_eq!(read(&view, cx, Disktree::scope), Some(Scope::Disk));
|
||||
let top = read(&view, cx, |app| app.tree().map(|tree| tree.bytes));
|
||||
assert!(top.is_some_and(|bytes| bytes > 0));
|
||||
|
||||
press(cx, "g");
|
||||
finish_scan(&view, cx);
|
||||
assert_eq!(read(&view, cx, Disktree::scope), Some(Scope::Home));
|
||||
}
|
||||
|
||||
@@ -13,7 +13,7 @@ use std::rc::Rc;
|
||||
|
||||
use disktree_core::treemap::Rect;
|
||||
use gpui_kit::{
|
||||
App, Bounds, ContentMask, Context, Corners, Edges, Font, Hsla,
|
||||
App, Bounds, ContentMask, Context, Corners, Edges, Font, FontWeight, Hsla,
|
||||
InteractiveElement as _, IntoElement, MouseButton, MouseDownEvent,
|
||||
MouseMoveEvent, ParentElement as _, Pixels, Point, ScrollWheelEvent,
|
||||
SharedString, Size, StatefulInteractiveElement as _, Styled, TextAlign,
|
||||
@@ -21,6 +21,8 @@ use gpui_kit::{
|
||||
};
|
||||
use gpui_omarchy::{ActiveTheme, Theme};
|
||||
|
||||
use disktree_core::classify::Category;
|
||||
|
||||
use crate::palette;
|
||||
use crate::state::{Disktree, Label, View};
|
||||
|
||||
@@ -30,13 +32,16 @@ use crate::state::{Disktree, Label, View};
|
||||
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>,
|
||||
/// Nesting depth in this view; `0` is the first level.
|
||||
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,
|
||||
/// What kind of data it is: the hue.
|
||||
pub category: Category,
|
||||
/// In age mode, which [`palette::AGE_BUCKETS`] entry it falls in.
|
||||
pub age_bucket: Option<usize>,
|
||||
/// Its space can be had back: hatched.
|
||||
pub reclaimable: bool,
|
||||
/// Part of it could not be read: flagged in its corner.
|
||||
pub unreadable: bool,
|
||||
pub marked: bool,
|
||||
/// Inside another marked directory, so it goes with its parent.
|
||||
pub covered: bool,
|
||||
@@ -138,71 +143,99 @@ pub fn mosaic(
|
||||
|
||||
/// Theme colours resolved once per frame.
|
||||
struct Colors {
|
||||
label: Vec<Hsla>,
|
||||
label: [Hsla; 2],
|
||||
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>,
|
||||
warning: Hsla,
|
||||
hatch: Hsla,
|
||||
/// Fills per category, then per depth.
|
||||
fill: Vec<[Hsla; DEPTHS]>,
|
||||
/// The strip over a top-level directory, per category.
|
||||
strip: Vec<Hsla>,
|
||||
/// Fills per age bucket, then per depth.
|
||||
age: Vec<[Hsla; DEPTHS]>,
|
||||
marked_fill: Hsla,
|
||||
}
|
||||
|
||||
/// Depth steps a fill distinguishes; deeper clamps.
|
||||
const DEPTHS: usize = 5;
|
||||
|
||||
/// Every category, in the order [`category_index`] numbers them.
|
||||
const CATEGORIES: [Category; 9] = [
|
||||
Category::Code,
|
||||
Category::AgentScratch,
|
||||
Category::Toolchain,
|
||||
Category::Synced,
|
||||
Category::Git,
|
||||
Category::Media,
|
||||
Category::Documents,
|
||||
Category::Cache,
|
||||
Category::Other,
|
||||
];
|
||||
|
||||
fn category_index(category: Category) -> usize {
|
||||
CATEGORIES
|
||||
.iter()
|
||||
.position(|&known| known == category)
|
||||
.unwrap_or(CATEGORIES.len() - 1)
|
||||
}
|
||||
|
||||
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;
|
||||
let ladder = |fill: &dyn Fn(u32) -> Hsla| {
|
||||
std::array::from_fn(|depth| fill(depth as u32))
|
||||
};
|
||||
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,
|
||||
label: [
|
||||
palette::label_color(theme, 0),
|
||||
palette::label_color(theme, 1),
|
||||
],
|
||||
label_dim: palette::label_color(theme, 1).opacity(0.5),
|
||||
hover_border: theme.bright.opacity(0.55),
|
||||
selected_border: palette::highlight(theme),
|
||||
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))
|
||||
marked_label: theme.danger,
|
||||
covered_border: theme.danger.opacity(0.4),
|
||||
warning: theme.warning,
|
||||
hatch: palette::hatch(theme),
|
||||
fill: CATEGORIES
|
||||
.iter()
|
||||
.map(|&category| {
|
||||
ladder(&|depth| {
|
||||
palette::category_fill(theme, category, depth)
|
||||
})
|
||||
})
|
||||
.collect(),
|
||||
fill_hidden: depth_range
|
||||
.clone()
|
||||
.map(|d| palette::tile_fill(theme, d, true, false))
|
||||
strip: CATEGORIES
|
||||
.iter()
|
||||
.map(|&category| palette::category_accent(theme, category))
|
||||
.collect(),
|
||||
fill_marked: depth_range
|
||||
.map(|d| palette::tile_fill(theme, d, false, true))
|
||||
age: (0..palette::AGE_BUCKETS.len())
|
||||
.map(|bucket| {
|
||||
ladder(&|depth| palette::age_fill(theme, bucket, depth))
|
||||
})
|
||||
.collect(),
|
||||
marked_fill: palette::mix(theme.inset, theme.danger, 0.16),
|
||||
}
|
||||
}
|
||||
|
||||
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]
|
||||
return self.marked_fill;
|
||||
}
|
||||
let depth = (tile.depth as usize).min(DEPTHS - 1);
|
||||
match tile.age_bucket {
|
||||
Some(bucket) => self.age[bucket.min(self.age.len() - 1)][depth],
|
||||
None => self.fill[category_index(tile.category)][depth],
|
||||
}
|
||||
}
|
||||
|
||||
fn label(&self, depth: u32) -> Hsla {
|
||||
self.label[(depth as usize).min(self.label.len() - 1)]
|
||||
const fn label(&self, depth: u32) -> Hsla {
|
||||
self.label[if depth == 0 { 0 } else { 1 }]
|
||||
}
|
||||
}
|
||||
|
||||
@@ -213,74 +246,127 @@ fn paint_tiles(
|
||||
colors: &Colors,
|
||||
window: &mut Window,
|
||||
) {
|
||||
let none = Edges::all(px(0.));
|
||||
let solid = gpui_kit::BorderStyle::Solid;
|
||||
let scale = window.scale_factor();
|
||||
// Outlines are drawn after every fill: a directory's children paint over
|
||||
// its body, and would otherwise cover its selection ring, leaving only
|
||||
// slivers of it showing in the gaps between them.
|
||||
let mut outlines: Vec<(u8, Bounds<Pixels>, f32, Hsla)> = Vec::new();
|
||||
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;
|
||||
}
|
||||
let quad_bounds = snap(to_window(&rect, bounds), scale);
|
||||
|
||||
// No border by default: the gaps between tiles, wider between the
|
||||
// top-level directories, are what separate them.
|
||||
window.paint_quad(quad(
|
||||
quad_bounds,
|
||||
Corners::default(),
|
||||
colors.fill(tile),
|
||||
Edges::all(px(width)),
|
||||
border,
|
||||
gpui_kit::BorderStyle::Solid,
|
||||
none,
|
||||
colors.hover_border,
|
||||
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 {
|
||||
// Reclaimable space is hatched, over any hue: the hatch answers
|
||||
// "can it go", the colour "what is it". Everything inside a
|
||||
// reclaimable directory is reclaimable too, so only the outermost
|
||||
// one needs painting; its children repaint their own fill and hatch.
|
||||
if tile.reclaimable && !tile.marked {
|
||||
window.paint_quad(quad(
|
||||
inset(quad_bounds, px(2.)),
|
||||
quad_bounds,
|
||||
Corners::default(),
|
||||
pattern_slash(colors.marked_hatch, 2.0, 9.0),
|
||||
Edges::all(px(0.)),
|
||||
colors.marked_border,
|
||||
gpui_kit::BorderStyle::Solid,
|
||||
pattern_slash(colors.hatch, 1.0, 6.0),
|
||||
none,
|
||||
colors.hatch,
|
||||
solid,
|
||||
));
|
||||
}
|
||||
|
||||
// A top-level directory carries a thin strip of its colour, so the
|
||||
// first level of structure reads before any detail.
|
||||
if tile.depth == 0 && tile.age_bucket.is_none() {
|
||||
let strip = Bounds::new(
|
||||
quad_bounds.origin,
|
||||
Size::new(
|
||||
quad_bounds.size.width,
|
||||
px(2.0_f32.min(quad_bounds.size.height.as_f32())),
|
||||
),
|
||||
);
|
||||
window.paint_quad(quad(
|
||||
strip,
|
||||
Corners::default(),
|
||||
colors.strip[category_index(tile.category)],
|
||||
none,
|
||||
colors.hover_border,
|
||||
solid,
|
||||
));
|
||||
}
|
||||
|
||||
if tile.unreadable && rect.w > 12.0 && rect.h > 12.0 {
|
||||
// A small warning corner: part of this was never measured.
|
||||
let mark = Bounds::new(
|
||||
Point::new(
|
||||
quad_bounds.origin.x + quad_bounds.size.width - px(6.),
|
||||
quad_bounds.origin.y + px(2.),
|
||||
),
|
||||
Size::new(px(4.), px(4.)),
|
||||
);
|
||||
window.paint_quad(quad(
|
||||
mark,
|
||||
Corners::default(),
|
||||
colors.warning,
|
||||
none,
|
||||
colors.warning,
|
||||
solid,
|
||||
));
|
||||
}
|
||||
|
||||
// Ranked so the most important ring is painted last, on top.
|
||||
let outline = if tile.selected {
|
||||
Some((3, 2.0, colors.selected_border))
|
||||
} else if tile.hovered {
|
||||
Some((2, 1.0, colors.hover_border))
|
||||
} else if tile.marked {
|
||||
Some((1, 2.0, colors.marked_border))
|
||||
} else if tile.covered {
|
||||
Some((0, 1.0, colors.covered_border))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
if let Some((rank, width, color)) = outline {
|
||||
outlines.push((rank, quad_bounds, width, color));
|
||||
}
|
||||
}
|
||||
outlines.sort_by_key(|(rank, ..)| *rank);
|
||||
for (_, ring, width, color) in outlines {
|
||||
window.paint_quad(quad(
|
||||
ring,
|
||||
Corners::default(),
|
||||
gpui_kit::transparent_black(),
|
||||
Edges::all(px(width)),
|
||||
color,
|
||||
solid,
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
/// Round a rectangle's edges to device pixels. Tiles land on fractional
|
||||
/// positions, and a 2 px strip or ring there smears across a pixel row and
|
||||
/// leaves a seam; rounding each edge, not the size, keeps neighbours flush.
|
||||
fn snap(bounds: Bounds<Pixels>, scale: f32) -> Bounds<Pixels> {
|
||||
let round = |value: Pixels| px((value.as_f32() * scale).round() / scale);
|
||||
let left = round(bounds.origin.x);
|
||||
let top = round(bounds.origin.y);
|
||||
let right = round(bounds.origin.x + bounds.size.width);
|
||||
let bottom = round(bounds.origin.y + bounds.size.height);
|
||||
Bounds::new(
|
||||
Point::new(left, top),
|
||||
Size::new((right - left).max(px(0.)), (bottom - top).max(px(0.))),
|
||||
)
|
||||
}
|
||||
|
||||
#[expect(
|
||||
@@ -330,12 +416,21 @@ fn paint_labels(
|
||||
let color = if label.marked {
|
||||
colors.marked_label
|
||||
} else {
|
||||
colors.label(label.color_depth)
|
||||
colors.label(label.depth)
|
||||
};
|
||||
// The first level is set in bold in its band: it names a region.
|
||||
let weight = if label.depth == 0 && label.header.is_some() {
|
||||
FontWeight::BOLD
|
||||
} else {
|
||||
FontWeight::NORMAL
|
||||
};
|
||||
|
||||
let run = TextRun {
|
||||
len: label.text.len(),
|
||||
font: font.clone(),
|
||||
font: Font {
|
||||
weight,
|
||||
..font.clone()
|
||||
},
|
||||
color,
|
||||
..TextRun::default()
|
||||
};
|
||||
@@ -381,9 +476,27 @@ fn paint_labels(
|
||||
+ ((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() {
|
||||
// A first-level band puts the size at the far end, where the
|
||||
// sizes read as a column; a deeper band follows the name. A
|
||||
// closed tile stacks it under the name when it is tall enough.
|
||||
let stacked = label.header.is_none()
|
||||
&& mask.size.height >= name_line_height * 2.0 + text_inset;
|
||||
if stacked {
|
||||
let _ = size_line.paint(
|
||||
Point::new(
|
||||
origin.x,
|
||||
origin.y + name_line_height * 0.92,
|
||||
),
|
||||
name_line_height,
|
||||
TextAlign::Left,
|
||||
None,
|
||||
window,
|
||||
cx,
|
||||
);
|
||||
return;
|
||||
}
|
||||
let size_origin = if label.header.is_some() && label.depth == 0
|
||||
{
|
||||
Point::new(
|
||||
mask.origin.x + mask.size.width
|
||||
- size_line.width()
|
||||
@@ -418,16 +531,6 @@ fn to_window(rect: &Rect, bounds: Bounds<Pixels>) -> Bounds<Pixels> {
|
||||
)
|
||||
}
|
||||
|
||||
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())
|
||||
}
|
||||
|
||||
@@ -47,6 +47,12 @@ pub mod text {
|
||||
pub const BODY: Rems = Rems(0.75);
|
||||
/// Window, section and dialog titles.
|
||||
pub const TITLE: Rems = Rems(0.875);
|
||||
/// The app name and the selection's name.
|
||||
pub const HEADING: Rems = Rems(1.125);
|
||||
/// A figure worth reading from across the room: the free space.
|
||||
pub const FIGURE: Rems = Rems(1.625);
|
||||
/// The selection's size: the one number the panel exists to show.
|
||||
pub const DISPLAY: Rems = Rems(2.5);
|
||||
}
|
||||
|
||||
/// Icon slots, sized with the text they sit beside.
|
||||
@@ -63,14 +69,16 @@ pub mod icon {
|
||||
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);
|
||||
/// A list row's share bar.
|
||||
pub const ROW_BAR: Rems = Rems(5.5);
|
||||
/// A legend or identity swatch.
|
||||
pub const SWATCH: Rems = Rems(0.625);
|
||||
/// A thin meter: share of the scan, the disk.
|
||||
pub const METER: Rems = Rems(0.3125);
|
||||
/// 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 Size | Files | Age choice in the settings row.
|
||||
pub const RANKING_CHOICE: Rems = Rems(11.0);
|
||||
/// The review screen's summary column.
|
||||
pub const REVIEW_SUMMARY: Rems = Rems(22.5);
|
||||
/// The review list's share-bar lane.
|
||||
|
||||
+1282
-604
File diff suppressed because it is too large
Load Diff
@@ -35,14 +35,6 @@ pub fn short_value(node: &Node, metric: Metric) -> String {
|
||||
}
|
||||
}
|
||||
|
||||
/// 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>,
|
||||
@@ -345,3 +337,174 @@ pub fn crumb(
|
||||
})
|
||||
.child(label.into())
|
||||
}
|
||||
|
||||
/// A small uppercase label over a region or a figure.
|
||||
pub fn eyebrow(label: impl Into<SharedString>, cx: &App) -> Div {
|
||||
let theme = cx.omarchy();
|
||||
let label: SharedString = label.into();
|
||||
div()
|
||||
.text_size(text::CAPTION)
|
||||
.text_color(theme.secondary.opacity(0.7))
|
||||
.whitespace_nowrap()
|
||||
.child(SharedString::from(label.to_uppercase()))
|
||||
}
|
||||
|
||||
/// An eyebrow over a value, for the top bar and the selection grid.
|
||||
pub fn figure(
|
||||
label: impl Into<SharedString>,
|
||||
value: impl Into<SharedString>,
|
||||
color: Hsla,
|
||||
cx: &App,
|
||||
) -> Div {
|
||||
div()
|
||||
.flex()
|
||||
.flex_col()
|
||||
.gap(space::XXS)
|
||||
.min_w_0()
|
||||
.child(eyebrow(label, cx))
|
||||
.child(
|
||||
div()
|
||||
.text_size(text::TITLE)
|
||||
.text_color(color)
|
||||
.whitespace_nowrap()
|
||||
.overflow_hidden()
|
||||
.child(value.into()),
|
||||
)
|
||||
}
|
||||
|
||||
/// A size split into number and unit, so the number can be set large:
|
||||
/// `90.1 GiB` is `("90.1", "GiB")`.
|
||||
pub fn split_size(text: &str) -> (String, String) {
|
||||
text.split_once(' ').map_or_else(
|
||||
|| (text.to_string(), String::new()),
|
||||
|(number, unit)| (number.to_string(), unit.to_string()),
|
||||
)
|
||||
}
|
||||
|
||||
/// How long ago a Unix time was, in the unit a person would use.
|
||||
pub fn ago(now: i64, then: i64) -> String {
|
||||
if then <= 0 {
|
||||
return "unknown".to_string();
|
||||
}
|
||||
let seconds = (now - then).max(0);
|
||||
let plural = |count: i64, unit: &str| {
|
||||
if count == 1 {
|
||||
format!("1 {unit} ago")
|
||||
} else {
|
||||
format!("{count} {unit}s ago")
|
||||
}
|
||||
};
|
||||
match seconds {
|
||||
0..60 => "just now".to_string(),
|
||||
60..3_600 => plural(seconds / 60, "minute"),
|
||||
3_600..86_400 => plural(seconds / 3_600, "hour"),
|
||||
86_400..5_184_000 => plural(seconds / 86_400, "day"),
|
||||
5_184_000..63_072_000 => plural(seconds / 2_592_000, "month"),
|
||||
_ => plural(seconds / 31_536_000, "year"),
|
||||
}
|
||||
}
|
||||
|
||||
/// A thin bar: `fraction` of a track, in `color`.
|
||||
pub fn bar(fraction: f32, color: Hsla, cx: &App) -> Div {
|
||||
let theme = cx.omarchy();
|
||||
div()
|
||||
.relative()
|
||||
.w_full()
|
||||
.h(crate::ui::size::METER)
|
||||
.bg(theme.foreground.opacity(0.08))
|
||||
.child(
|
||||
div()
|
||||
.absolute()
|
||||
.left_0()
|
||||
.top_0()
|
||||
.h_full()
|
||||
.w(relative(fraction.clamp(0.0, 1.0)))
|
||||
.bg(color),
|
||||
)
|
||||
}
|
||||
|
||||
/// A square of colour, for a legend or an identity.
|
||||
pub fn swatch(color: Hsla) -> Div {
|
||||
div()
|
||||
.flex_shrink_0()
|
||||
.size(crate::ui::size::SWATCH)
|
||||
.bg(color)
|
||||
}
|
||||
|
||||
/// The hatch swatch that stands for reclaimable space in the legend.
|
||||
pub fn hatch_swatch(color: Hsla, ground: Hsla) -> Div {
|
||||
div()
|
||||
.flex_shrink_0()
|
||||
.size(crate::ui::size::SWATCH)
|
||||
.bg(ground)
|
||||
.child(
|
||||
div()
|
||||
.size_full()
|
||||
.bg(gpui_kit::pattern_slash(color, 1.0, 3.0)),
|
||||
)
|
||||
}
|
||||
|
||||
/// A large number followed by its small unit, sharing one baseline.
|
||||
///
|
||||
/// Flex baseline alignment does not line up text of different sizes here,
|
||||
/// so both are set on bottom-aligned boxes exactly one line tall, and the
|
||||
/// unit is lifted by the difference in their descents: a font's descent is
|
||||
/// close to a fifth of its size.
|
||||
pub fn measure(
|
||||
number: impl Into<SharedString>,
|
||||
number_size: gpui_kit::Rems,
|
||||
unit: impl Into<SharedString>,
|
||||
unit_size: gpui_kit::Rems,
|
||||
cx: &App,
|
||||
) -> Div {
|
||||
let theme = cx.omarchy();
|
||||
let lift = gpui_kit::Rems((number_size.0 - unit_size.0) * DESCENT);
|
||||
div()
|
||||
.flex()
|
||||
.flex_row()
|
||||
.items_end()
|
||||
.gap(space::SM)
|
||||
.child(
|
||||
div()
|
||||
.text_size(number_size)
|
||||
.line_height(number_size)
|
||||
.font_weight(FontWeight::BOLD)
|
||||
.text_color(theme.bright)
|
||||
.child(number.into()),
|
||||
)
|
||||
.child(
|
||||
div()
|
||||
.text_size(unit_size)
|
||||
.line_height(unit_size)
|
||||
.pb(lift)
|
||||
.text_color(theme.secondary)
|
||||
.whitespace_nowrap()
|
||||
.child(unit.into()),
|
||||
)
|
||||
}
|
||||
|
||||
/// A font's descent as a share of its size, for lining up baselines.
|
||||
const DESCENT: f32 = 0.2;
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn ages_read_in_the_unit_a_person_would_use() {
|
||||
let now = 1_800_000_000;
|
||||
assert_eq!(ago(now, now - 5), "just now");
|
||||
assert_eq!(ago(now, now - 120), "2 minutes ago");
|
||||
assert_eq!(ago(now, now - 3_600), "1 hour ago");
|
||||
assert_eq!(ago(now, now - 19 * 86_400), "19 days ago");
|
||||
assert_eq!(ago(now, now - 90 * 86_400), "3 months ago");
|
||||
assert_eq!(ago(now, now - 800 * 86_400), "2 years ago");
|
||||
assert_eq!(ago(now, 0), "unknown");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sizes_split_into_number_and_unit() {
|
||||
assert_eq!(split_size("90.1 GiB"), ("90.1".into(), "GiB".into()));
|
||||
assert_eq!(split_size("0"), ("0".into(), String::new()));
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user