Files
disktree/crates/disktree-app/src/state.rs
T

6002 lines
208 KiB
Rust

//! Application state and every mutation the UI can perform.
//!
//! The screens in [`crate::views`] are pure functions of this state; all the
//! decisions — what is selected, what a mark means, what a key does, when to
//! re-scan — live here so they can be reasoned about in one place.
use std::cell::Cell;
use std::path::{Path, PathBuf};
use std::rc::Rc;
use std::sync::Arc;
use std::time::{Duration, Instant};
use disktree_core::access::file_table_readable;
use disktree_core::filter::{Keep, filter};
use disktree_core::insights::{Candidate, worth_a_look};
use disktree_core::path_style::PathStyle;
use disktree_core::removal::{
Plan, RemovalEvent, RemovalHandle, RemovalMode, Target, TrashBackend,
detect_trash_backend, plan,
};
use disktree_core::scan::{
Known, ScanHandle, ScanOptions, ScanSnapshot, ScanUpdate, arena_to_node,
node_to_arena,
};
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_filtered,
};
use disktree_scanner::{
CachePolicy, DEFAULT_CACHE_TTL, Freshness, Scanner, StorageMode,
SubtreeStatus, TreeArena,
};
use gpui_kit::base::input::{InputEvent, InputState};
use gpui_kit::{
AppContext as _, Context, Entity, FocusHandle, Focusable as _,
KeyDownEvent, MouseButton, MouseDownEvent, MouseMoveEvent,
NavigationDirection, Pixels, Point, Render, ScrollDelta, ScrollWheelEvent,
Size, Window, px, size,
};
use gpui_omarchy::Status;
use rustc_hash::{FxHashMap, FxHashSet};
use crate::git::GitState;
use crate::marks::{Marks, 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,
}
/// A trail crumb's sibling menu, open.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct CrumbMenu {
/// Crumbs of the directory whose children are listed.
pub parent: Vec<usize>,
/// The listed child the crumb stands for.
pub current: usize,
/// The row the arrow keys are on, as an index into [`Disktree::siblings`].
pub highlighted: usize,
}
/// One row of a sibling menu.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Sibling {
/// Index among the parent's children.
pub index: usize,
pub name: String,
pub value: u64,
pub category: disktree_core::classify::Category,
pub is_dir: bool,
}
/// Rows a sibling menu lists; the rest are counted.
pub const SIBLING_ROWS: usize = 24;
/// One step of the trail.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Crumb {
/// A directory above the scanned root: going there scans only what is
/// new at that level.
Above(PathBuf),
/// A directory in the tree, by crumbs from the scanned root.
Tree(Vec<usize>),
}
/// 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;
/// Duration of the tile freshness colour fade when a square becomes fresh.
const FRESHNESS_FADE_MS: f32 = 200.0;
/// Duration of smooth per-tile rectangle gliding when sizes update during a
/// live scan or background refresh.
const TILE_RECT_GLIDE_MS: f32 = 200.0;
/// Minimum interval between incremental subtree re-layouts during a background
/// scan so the treemap stays calm instead of thrashing on every checkpoint.
const LIVE_REPROJECT_BUFFER: Duration = Duration::from_millis(1200);
#[derive(Clone, Copy, Debug)]
struct TileRectAnim {
from: Rect,
target: Rect,
started: Instant,
}
impl TileRectAnim {
fn settled(rect: Rect, now: Instant) -> Self {
let elapsed = Duration::from_millis(250);
Self {
from: rect,
target: rect,
started: now.checked_sub(elapsed).unwrap_or(now),
}
}
fn rects_close(a: Rect, b: Rect) -> bool {
(a.x - b.x).abs() < 0.5
&& (a.y - b.y).abs() < 0.5
&& (a.w - b.w).abs() < 0.5
&& (a.h - b.h).abs() < 0.5
}
fn value(&self, now: Instant) -> Rect {
if Self::rects_close(self.from, self.target) {
return self.target;
}
let elapsed_ms =
now.saturating_duration_since(self.started).as_secs_f32() * 1000.0;
let t = (elapsed_ms / TILE_RECT_GLIDE_MS).clamp(0.0, 1.0);
let eased = 1.0 - (1.0 - t).powi(3);
Rect::new(
(self.target.x - self.from.x).mul_add(eased, self.from.x),
(self.target.y - self.from.y).mul_add(eased, self.from.y),
(self.target.w - self.from.w).mul_add(eased, self.from.w),
(self.target.h - self.from.h).mul_add(eased, self.from.h),
)
}
fn is_running(&self, now: Instant) -> bool {
!Self::rects_close(self.from, self.target)
&& now.saturating_duration_since(self.started).as_secs_f32()
* 1000.0
< TILE_RECT_GLIDE_MS
}
}
#[derive(Clone, Copy, Debug)]
struct TileFade {
from: f32,
target: f32,
started: Instant,
}
impl TileFade {
fn settled(value: f32, now: Instant) -> Self {
let elapsed = Duration::from_millis(250);
Self {
from: value,
target: value,
started: now.checked_sub(elapsed).unwrap_or(now),
}
}
fn value(&self, now: Instant) -> f32 {
if (self.from - self.target).abs() < f32::EPSILON {
return self.target;
}
let elapsed_ms =
now.saturating_duration_since(self.started).as_secs_f32() * 1000.0;
let t = (elapsed_ms / FRESHNESS_FADE_MS).clamp(0.0, 1.0);
let eased = 1.0 - (1.0 - t).powi(3);
(self.target - self.from).mul_add(eased, self.from)
}
fn is_running(&self, now: Instant) -> bool {
(self.from - self.target).abs() >= f32::EPSILON
&& now.saturating_duration_since(self.started).as_secs_f32()
* 1000.0
< FRESHNESS_FADE_MS
}
}
fn remote_cache_host(host: &str) -> disktree_scanner::HostKey {
disktree_scanner::HostKey::Remote(disktree_scanner::HostIdentity {
hostname: host.to_owned(),
machine_id: None,
})
}
/// Persistent list of successfully connected SSH hosts (MRU order, one host
/// per line in `$XDG_CONFIG_HOME/disktree/ssh-hosts`).
mod ssh_hosts {
use std::path::{Path, PathBuf};
const MAX_HOSTS: usize = 20;
pub fn default_path() -> Option<PathBuf> {
#[cfg(target_os = "macos")]
{
return std::env::home_dir().map(|home| {
home.join("Library/Application Support/disktree/ssh-hosts")
});
}
#[cfg(windows)]
{
return std::env::var_os("APPDATA")
.map(|dir| PathBuf::from(dir).join("disktree/ssh-hosts"));
}
#[cfg(not(any(target_os = "macos", windows)))]
{
if let Some(dir) =
std::env::var_os("XDG_CONFIG_HOME").filter(|s| !s.is_empty())
{
return Some(PathBuf::from(dir).join("disktree/ssh-hosts"));
}
std::env::home_dir()
.map(|home| home.join(".config/disktree/ssh-hosts"))
}
}
pub fn load_from(path: &Path) -> Vec<String> {
let Ok(content) = std::fs::read_to_string(path) else {
return Vec::new();
};
let mut hosts = Vec::new();
for line in content.lines() {
let host = line.trim();
if !host.is_empty()
&& disktree_core::remote::validate_host(host).is_ok()
&& !hosts.iter().any(|existing| existing == host)
{
hosts.push(host.to_owned());
if hosts.len() >= MAX_HOSTS {
break;
}
}
}
hosts
}
pub fn save_to(path: &Path, hosts: &[String]) {
if let Some(parent) = path.parent()
&& std::fs::create_dir_all(parent).is_err()
{
return;
}
let mut body = hosts.join("\n");
if !body.is_empty() {
body.push('\n');
}
let tmp = path.with_extension("tmp");
if std::fs::write(&tmp, body).is_ok() {
let _ = std::fs::rename(tmp, path);
}
}
pub fn record(hosts: &mut Vec<String>, host: &str) -> bool {
let host = host.trim();
if host.is_empty()
|| disktree_core::remote::validate_host(host).is_err()
{
return false;
}
if hosts.first().map(String::as_str) == Some(host) {
return false;
}
hosts.retain(|existing| existing != host);
hosts.insert(0, host.to_owned());
hosts.truncate(MAX_HOSTS);
true
}
pub fn remove(hosts: &mut Vec<String>, host: &str) -> bool {
let before = hosts.len();
hosts.retain(|existing| existing != host);
hosts.len() != before
}
}
/// Which screen the app is showing.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum Screen {
/// Walk the treemap and mark what should go.
#[default]
Explore,
/// Review every marked path and choose how to remove them.
Review,
/// A removal is running.
Running,
/// The removal finished; show what happened.
Done,
}
/// The treemap view transform: `screen = (base - origin) * scale`.
///
/// All viewport geometry stays in the base space of an unzoomed layout, so pan
/// and zoom never require a re-layout.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct View {
pub scale: f32,
pub origin_x: f32,
pub origin_y: f32,
}
impl Default for View {
fn default() -> Self {
Self::IDENTITY
}
}
impl View {
pub const IDENTITY: Self = Self {
scale: 1.0,
origin_x: 0.0,
origin_y: 0.0,
};
pub const MIN_SCALE: f32 = 1.0;
/// Past this, zooming again descends into whatever is under the cursor
/// instead of magnifying further: the continuous "keep zooming and you are
/// inside" gesture, with a breadcrumb to walk back out.
pub const MAX_SCALE: f32 = 5.0;
pub fn project(&self, rect: Rect) -> Rect {
Rect::new(
(rect.x - self.origin_x) * self.scale,
(rect.y - self.origin_y) * self.scale,
rect.w * self.scale,
rect.h * self.scale,
)
}
/// Viewport point to base-space point.
pub fn unproject(&self, x: f32, y: f32) -> (f32, f32) {
(
x / self.scale + self.origin_x,
y / self.scale + self.origin_y,
)
}
/// Zoom by `factor` toward `(x, y)` and no further than `ceiling`.
///
/// The base point under `(x, y)` stays put, which is what makes a wheel
/// zoom feel pointed at the tile rather than at the window.
pub fn zoomed_at(&self, x: f32, y: f32, factor: f32, ceiling: f32) -> Self {
let scale = (self.scale * factor).clamp(Self::MIN_SCALE, ceiling);
let (base_x, base_y) = self.unproject(x, y);
Self {
scale,
origin_x: base_x - x / scale,
origin_y: base_y - y / scale,
}
}
/// The scale at which `rect` exactly fits the viewport.
pub fn fit_scale(rect: Rect, area: Size<Pixels>) -> f32 {
let width = area.width.as_f32().max(1.0);
let height = area.height.as_f32().max(1.0);
if rect.w <= 0.0 || rect.h <= 0.0 {
return Self::MIN_SCALE;
}
(width / rect.w).min(height / rect.h)
}
/// The region of the base layout the viewport currently shows.
pub fn visible_base(&self, area: Size<Pixels>) -> Rect {
let width = area.width.as_f32().max(1.0);
let height = area.height.as_f32().max(1.0);
Rect::new(
self.origin_x,
self.origin_y,
width / self.scale,
height / self.scale,
)
}
/// Keep the viewport inside the layout: no empty margins, ever.
pub fn clamped(self, area: Size<Pixels>) -> Self {
let width = area.width.as_f32();
let height = area.height.as_f32();
let max_x = (width - width / self.scale).max(0.0);
let max_y = (height - height / self.scale).max(0.0);
Self {
scale: self.scale,
origin_x: self.origin_x.clamp(0.0, max_x),
origin_y: self.origin_y.clamp(0.0, max_y),
}
}
}
/// A layout transition: the region the user is looking at, and where that same
/// region lands in the layout being switched to.
///
/// Every descending or ascending move is one region of the tree changing
/// address. Rather than moving a camera, each tile is drawn from where that
/// region *was* to where it *is*, so the tiles inside the directory that is
/// being entered grow into place and the ones being left slide out. That is
/// what makes "zoom in and descend" read as one motion: the newly visible
/// level is always larger than it was a moment ago, never smaller.
#[derive(Clone, Copy, Debug)]
pub struct LayoutTransition {
/// The region in the old frame, in viewport coordinates.
src: Rect,
/// The same region in the new frame, in viewport coordinates.
dst: Rect,
started: Instant,
duration: Duration,
}
impl LayoutTransition {
fn new(src: Rect, dst: Rect) -> Self {
// Longer pulls take a little longer, but never enough to feel slow.
let ratio = if dst.w > 1.0 { src.w / dst.w } else { 1.0 };
let magnitude = ratio.abs().max(1.0).log2().clamp(0.0, 4.0);
Self {
src,
dst,
started: Instant::now(),
duration: Duration::from_millis(130 + (magnitude * 45.0) as u64),
}
}
/// Where a rectangle in the new layout was, before the switch.
fn origin_of(&self, rect: Rect) -> Rect {
let scale = if self.dst.w > 0.0 {
self.src.w / self.dst.w
} else {
1.0
};
Rect::new(
(rect.x - self.dst.x).mul_add(scale, self.src.x),
(rect.y - self.dst.y).mul_add(scale, self.src.y),
rect.w * scale,
rect.h * scale,
)
}
/// The rectangle to draw at this instant, and whether the transition is
/// still running.
fn sample(&self, rect: Rect) -> (Rect, bool) {
let elapsed =
self.started.elapsed().as_secs_f32() / self.duration.as_secs_f32();
if elapsed >= 1.0 {
return (rect, false);
}
let eased = 1.0 - (1.0 - elapsed).powi(3);
let from = self.origin_of(rect);
let lerp = |a: f32, b: f32| (b - a).mul_add(eased, a);
(
Rect::new(
lerp(from.x, rect.x),
lerp(from.y, rect.y),
lerp(from.w, rect.w),
lerp(from.h, rect.h),
),
true,
)
}
}
/// The marks as crumbs, for the tree and the marks they were resolved
/// against.
struct MarkedCrumbs {
/// [`Marks::generation`] when resolved.
generation: u64,
/// The tree then, by address and only ever compared. A tree re-ranked
/// in place keeps its address, and refreshes the marks, which moves
/// on `generation`.
tree: Option<*const Node>,
crumbs: Rc<FxHashSet<Vec<usize>>>,
}
/// Layout for one (crumbs, area, options) combination.
struct LayoutCache {
key: LayoutKey,
tiles: Vec<Tile>,
}
#[derive(Clone, PartialEq)]
struct LayoutKey {
crumbs: Vec<usize>,
width: f32,
height: f32,
options: LayoutOptions,
/// Bumped whenever the applied filter changes.
filter: u64,
}
/// Directories left behind and come back from, for `<` and `>`.
///
/// Kept as absolute paths, not crumbs: a re-scan or a widening renumbers the
/// tree, and crumbs would then silently point at other directories.
#[derive(Clone, Debug, Default)]
pub struct History {
pub back: Vec<PathBuf>,
pub forward: Vec<PathBuf>,
}
/// How many directories back is remembered. Far more than anyone clicks
/// through, and small enough that pruning after a scan costs nothing.
const HISTORY_DEPTH: usize = 100;
/// Result of the removal run, summarised for the final screen.
#[derive(Clone, Debug, Default)]
pub struct RunSummary {
pub total: usize,
pub removed: u64,
pub bytes: u64,
pub failed: usize,
}
/// Pure state machine for the Explore screen's find/filter bar.
///
/// Atomic transition: `step(state, event) -> (state, Vec<Effect>)`.
/// Emitted effects execute sequentially in the order returned; stale search
/// completions whose `epoch` does not match `state.epoch` are ignored.
pub mod find_machine {
use std::sync::Arc;
use disktree_core::filter::Matches;
#[derive(Clone, Debug, Default)]
pub struct State {
pub epoch: u64,
pub phase: Phase,
}
#[derive(Clone, Debug, Default)]
pub enum Phase {
#[default]
Closed,
Editing {
query: String,
matches: Option<Arc<Matches>>,
searching: bool,
},
/// Enter was pressed while a background search was still running.
Applying {
query: String,
matches: Option<Arc<Matches>>,
},
/// Filter is applied: only matching tiles are laid out.
Applied {
query: String,
matches: Arc<Matches>,
},
}
#[derive(Debug)]
pub enum Event {
Open,
PushText(String),
Backspace,
Submit,
SearchFinished {
epoch: u64,
found: Option<Arc<Matches>>,
},
Clear,
}
#[derive(Debug)]
pub enum Effect {
StartSearch { epoch: u64, query: String },
SelectBestMatch(Arc<Matches>),
WarnNoMatches(String),
ClearNotice,
InvalidateLayout,
}
impl State {
pub fn query(&self) -> &str {
match &self.phase {
Phase::Closed => "",
Phase::Editing { query, .. }
| Phase::Applying { query, .. }
| Phase::Applied { query, .. } => query,
}
}
pub const fn is_visible(&self) -> bool {
!matches!(self.phase, Phase::Closed)
}
pub const fn is_editing(&self) -> bool {
matches!(self.phase, Phase::Editing { .. })
}
pub const fn is_applied(&self) -> bool {
matches!(self.phase, Phase::Applied { .. })
}
pub const fn is_searching(&self) -> bool {
matches!(
self.phase,
Phase::Editing {
searching: true,
..
} | Phase::Applying { .. }
)
}
pub fn matches(&self) -> Option<&Matches> {
match &self.phase {
Phase::Closed => None,
Phase::Editing { matches, .. }
| Phase::Applying { matches, .. } => matches.as_deref(),
Phase::Applied { matches, .. } => Some(matches),
}
}
}
/// Pure transition: no background tasks, no GPUI context, no clocks.
pub fn step(state: State, event: Event) -> (State, Vec<Effect>) {
let State { epoch, phase } = state;
match (phase, event) {
// Clear is valid from every phase and invalidates any in-flight search.
(
Phase::Closed
| Phase::Editing { .. }
| Phase::Applying { .. }
| Phase::Applied { .. },
Event::Clear,
) => (
State {
epoch: epoch + 1,
phase: Phase::Closed,
},
vec![Effect::InvalidateLayout],
),
// Open enters Editing from Closed or Applied; already-open phases stay put.
(Phase::Closed, Event::Open) => (
State {
epoch,
phase: Phase::Editing {
query: String::new(),
matches: None,
searching: false,
},
},
vec![],
),
(Phase::Applied { query, matches }, Event::Open) => (
State {
epoch,
phase: Phase::Editing {
query,
matches: Some(matches),
searching: false,
},
},
vec![Effect::InvalidateLayout],
),
// Text edits only apply while Editing; ignored in other phases.
(
Phase::Editing {
mut query, matches, ..
},
Event::PushText(text),
) => {
query.push_str(&text);
begin_search(epoch, query, matches)
}
(
Phase::Editing {
mut query, matches, ..
},
Event::Backspace,
) => {
query.pop();
begin_search(epoch, query, matches)
}
// Submit commits ready matches, defers while searching, or closes empty.
(
Phase::Editing {
query,
matches,
searching: true,
},
Event::Submit,
) => (
State {
epoch,
phase: Phase::Applying { query, matches },
},
vec![],
),
(
Phase::Editing {
query,
matches: Some(matches),
searching: false,
},
Event::Submit,
) => finish_apply(epoch, query, matches),
(
Phase::Editing {
matches: None,
searching: false,
..
},
Event::Submit,
) => (
State {
epoch,
phase: Phase::Closed,
},
vec![],
),
// Async search results are accepted only for the current epoch.
(
Phase::Editing { query, .. },
Event::SearchFinished {
epoch: done_epoch,
found,
},
) if done_epoch == epoch => (
State {
epoch,
phase: Phase::Editing {
query,
matches: found,
searching: false,
},
},
vec![Effect::InvalidateLayout],
),
(
Phase::Applying { query, .. },
Event::SearchFinished {
epoch: done_epoch,
found: Some(matches),
},
) if done_epoch == epoch => finish_apply(epoch, query, matches),
(
Phase::Applying { .. },
Event::SearchFinished {
epoch: done_epoch,
found: None,
},
) if done_epoch == epoch => (
State {
epoch,
phase: Phase::Closed,
},
vec![Effect::InvalidateLayout],
),
// Explicitly ignored events: non-applicable inputs or stale epochs.
(
phase @ (Phase::Editing { .. } | Phase::Applying { .. }),
Event::Open,
)
| (
phase @ (Phase::Closed
| Phase::Applying { .. }
| Phase::Applied { .. }),
Event::PushText(_) | Event::Backspace | Event::Submit,
)
| (
phase @ (Phase::Closed
| Phase::Editing { .. }
| Phase::Applying { .. }
| Phase::Applied { .. }),
Event::SearchFinished { .. },
) => (State { epoch, phase }, vec![]),
}
}
fn begin_search(
epoch: u64,
query: String,
matches: Option<Arc<Matches>>,
) -> (State, Vec<Effect>) {
let next_epoch = epoch + 1;
if query.trim().is_empty() {
return (
State {
epoch: next_epoch,
phase: Phase::Editing {
query,
matches: None,
searching: false,
},
},
vec![Effect::InvalidateLayout],
);
}
let needle = query.clone();
(
State {
epoch: next_epoch,
phase: Phase::Editing {
query,
matches,
searching: true,
},
},
vec![Effect::StartSearch {
epoch: next_epoch,
query: needle,
}],
)
}
fn finish_apply(
epoch: u64,
query: String,
matches: Arc<Matches>,
) -> (State, Vec<Effect>) {
if matches.count == 0 {
let needle = matches.needle.clone();
return (
State {
epoch,
phase: Phase::Editing {
query,
matches: Some(matches),
searching: false,
},
},
vec![Effect::WarnNoMatches(needle), Effect::InvalidateLayout],
);
}
let selected_matches = Arc::clone(&matches);
(
State {
epoch,
phase: Phase::Applied { query, matches },
},
vec![
Effect::SelectBestMatch(selected_matches),
Effect::ClearNotice,
Effect::InvalidateLayout,
],
)
}
}
/// What an in-flight scan is doing to the current tree.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum ScanIntent {
/// First scan or new root: replaces the tree on completion.
Initial,
/// Widening to an ancestor while keeping the narrower tree on screen.
Widening { target: PathBuf },
/// Background refresh (`r`, Refresh button, or SWR revalidation): keeps
/// the current directory and selection by path when the new tree lands.
Refresh { metric: Metric, forced: bool },
}
/// Exclusive handle to at most one in-flight scan: local OR remote, never both.
#[derive(Debug)]
pub enum ActiveScan {
Local {
handle: ScanHandle,
intent: ScanIntent,
},
Remote {
handle: disktree_core::remote::RemoteScan,
intent: ScanIntent,
},
}
impl ActiveScan {
pub const fn intent(&self) -> &ScanIntent {
match self {
Self::Local { intent, .. } | Self::Remote { intent, .. } => intent,
}
}
pub fn widening_target(&self) -> Option<&Path> {
match self.intent() {
ScanIntent::Widening { target } => Some(target),
ScanIntent::Initial | ScanIntent::Refresh { .. } => None,
}
}
pub fn set_intent(&mut self, next: ScanIntent) {
match self {
Self::Local { intent, .. } | Self::Remote { intent, .. } => {
*intent = next;
}
}
}
}
/// Pure state machine for mount/volume discovery in the location picker.
///
/// Atomic transition: `step(state, event) -> (state, Vec<Effect>)`.
/// Each start or reset increments `epoch`; completions carrying an older epoch
/// are ignored so a slow local listing can never overwrite a newer remote error.
pub mod discovery_machine {
#[derive(Debug, Default)]
pub struct State {
pub epoch: u64,
pub phase: Phase,
}
#[derive(Debug, Default)]
pub enum Phase {
#[default]
Idle,
Loading {
job: Option<disktree_core::remote::RemoteRoots>,
},
Installing {
host: String,
},
Ready,
Failed(String),
}
#[derive(Debug)]
pub enum Event {
StartLocal,
StartRemote {
host: String,
},
StartInstall {
host: String,
command: String,
},
RemoteSpawned {
epoch: u64,
job: disktree_core::remote::RemoteRoots,
},
Completed {
epoch: u64,
outcome: Result<(), String>,
},
Reset,
}
#[derive(Debug, PartialEq, Eq)]
pub enum Effect {
SpawnLocalListing {
epoch: u64,
},
DiscoverRemote {
epoch: u64,
host: String,
},
InstallRemote {
epoch: u64,
host: String,
command: String,
},
PollRemote {
epoch: u64,
},
}
impl State {
pub const fn is_idle(&self) -> bool {
matches!(self.phase, Phase::Idle)
}
pub const fn is_loading(&self) -> bool {
matches!(
self.phase,
Phase::Loading { .. } | Phase::Installing { .. }
)
}
pub const fn is_ready(&self) -> bool {
matches!(self.phase, Phase::Ready)
}
pub fn error(&self) -> Option<&str> {
match &self.phase {
Phase::Failed(error) => Some(error),
Phase::Idle
| Phase::Loading { .. }
| Phase::Installing { .. }
| Phase::Ready => None,
}
}
}
/// Pure transition for mount discovery; every `(phase, event)` is handled
/// explicitly so no missing transition can hide behind a catch-all.
pub fn step(state: State, event: Event) -> (State, Vec<Effect>) {
let State { epoch, phase } = state;
match (phase, event) {
(
Phase::Idle
| Phase::Loading { .. }
| Phase::Installing { .. }
| Phase::Ready
| Phase::Failed(_),
Event::Reset,
) => (
State {
epoch: epoch + 1,
phase: Phase::Idle,
},
vec![],
),
(
Phase::Idle
| Phase::Loading { .. }
| Phase::Installing { .. }
| Phase::Ready
| Phase::Failed(_),
Event::StartLocal,
) => {
let next_epoch = epoch + 1;
(
State {
epoch: next_epoch,
phase: Phase::Loading { job: None },
},
vec![Effect::SpawnLocalListing { epoch: next_epoch }],
)
}
(
Phase::Idle
| Phase::Loading { .. }
| Phase::Installing { .. }
| Phase::Ready
| Phase::Failed(_),
Event::StartRemote { host },
) => {
let next_epoch = epoch + 1;
(
State {
epoch: next_epoch,
phase: Phase::Loading { job: None },
},
vec![Effect::DiscoverRemote {
epoch: next_epoch,
host,
}],
)
}
(
Phase::Idle
| Phase::Loading { .. }
| Phase::Installing { .. }
| Phase::Ready
| Phase::Failed(_),
Event::StartInstall { host, command },
) => {
let next_epoch = epoch + 1;
(
State {
epoch: next_epoch,
phase: Phase::Installing { host: host.clone() },
},
vec![Effect::InstallRemote {
epoch: next_epoch,
host,
command,
}],
)
}
(
Phase::Loading { .. },
Event::RemoteSpawned {
epoch: job_epoch,
job,
},
) if job_epoch == epoch => (
State {
epoch,
phase: Phase::Loading { job: Some(job) },
},
vec![Effect::PollRemote { epoch }],
),
(
Phase::Idle
| Phase::Loading { .. }
| Phase::Installing { .. }
| Phase::Ready
| Phase::Failed(_),
Event::Completed {
epoch: done_epoch,
outcome,
},
) if done_epoch == epoch => {
let next_phase = match outcome {
Ok(()) => Phase::Ready,
Err(message) => Phase::Failed(message),
};
(
State {
epoch,
phase: next_phase,
},
vec![],
)
}
// Stale spawns/completions from superseded epochs or non-loading
// phases are ignored explicitly.
(
phase @ (Phase::Idle
| Phase::Loading { .. }
| Phase::Installing { .. }
| Phase::Ready
| Phase::Failed(_)),
Event::RemoteSpawned { .. } | Event::Completed { .. },
) => (State { epoch, phase }, vec![]),
}
}
}
/// Everything the app knows and everything it can do.
pub struct Disktree {
/// The directory the tree was scanned from.
pub root_path: PathBuf,
pub remote: Option<String>,
remote_disk: bool,
pub remote_progress: disktree_core::remote_progress::Progress,
remote_stale_seq: u64,
/// Tailscale SSH check URL opened in the browser while waiting for approval.
pub auth_url: Option<String>,
pub scan_preview: Option<Arc<disktree_core::scan_preview::Preview>>,
preview_updated: Option<Instant>,
remote_platform: String,
pub remote_identity: Option<disktree_core::identity::HostIdentity>,
pub home: Option<PathBuf>,
pub options: ScanOptions,
scanner: Scanner,
pub arena: Option<Arc<TreeArena>>,
pub freshness: Option<Freshness>,
pub tree: Option<Arc<Node>>,
pub active_scan: Option<ActiveScan>,
pub updating_paths: FxHashSet<PathBuf>,
pub refreshed_paths: FxHashSet<PathBuf>,
pub active_scan_path: Option<PathBuf>,
pending_arena_flush: bool,
last_arena_flush: Option<Instant>,
pub scan_epoch: u64,
pub progress: ScanSnapshot,
pub scan_error: Option<String>,
pub screen: Screen,
/// Path from the scanned root to the directory currently drawn.
pub crumbs: Vec<usize>,
pub selected: Option<Vec<usize>>,
pub hovered: Option<Vec<usize>>,
pub history: History,
/// The history button under the pointer, `true` for `<`: its card is
/// drawn below it for as long as it is.
pub history_hover: Option<bool>,
/// The pointer moved more recently than the keyboard navigated. Then the
/// tile under the pointer is what Space, X and Enter act on; after an
/// arrow or Tab it is the keyboard selection again.
pub pointer_active: bool,
pub view: View,
/// The in-flight layout transition, if a level was just entered or left.
pub transition: Option<LayoutTransition>,
/// Per-tile smooth colour fade when freshness changes (200 ms ease-out).
tile_fades: FxHashMap<PathBuf, TileFade>,
/// Per-tile smooth rectangle glide when live updates shift sizes (200 ms).
tile_rects: FxHashMap<PathBuf, TileRectAnim>,
last_treemap_size: Size<Pixels>,
pub layout_options: LayoutOptions,
cache: Option<LayoutCache>,
marked: Option<MarkedCrumbs>,
/// Mouse position in treemap-local pixels, for hit-testing and the tooltip.
pub pointer: Option<Point<Pixels>>,
/// The treemap area in window space, recorded while painting.
pub treemap_origin: Rc<Cell<Point<Pixels>>>,
pub treemap_size: Rc<Cell<Size<Pixels>>>,
pub marks: Marks,
pub removal_mode: RemovalMode,
pub trash_backend: TrashBackend,
/// The permanent-deletion alert dialog is open. Trash needs no dialog: it
/// is reversible, so it commits directly.
pub confirm_open: bool,
/// Focus owner for the alert dialog while it is open.
pub confirm_focus: FocusHandle,
/// Focus to move on the next occasion a window is in hand. Key handling
/// has no window, and opening or closing the dialog must move focus.
pub focus_request: Option<FocusTarget>,
/// What the titlebar says, so it is only set when it changes.
window_title: String,
/// The window's `rem` in pixels, read each frame. The mosaic is laid out
/// in pixels, so its header band and label thresholds are scaled by this
/// to follow interface zoom like the rest of the interface.
pub rem: f32,
pub run: Option<RemovalHandle>,
pub run_epoch: u64,
pub run_summary: RunSummary,
pub run_log: Vec<(PathBuf, Result<(), String>)>,
pub space: Option<SpaceInfo>,
/// Free space before the removal, for the honest "what did it actually
/// free" number rather than the sum of what was marked.
pub space_baseline: Option<SpaceInfo>,
pub notice: Option<(String, Status)>,
pub find: find_machine::State,
filter_epoch: u64,
pub show_help: bool,
pub show_selection: bool,
pub focus: FocusHandle,
/// A trail crumb's sibling menu, when open.
pub crumb_menu: Option<CrumbMenu>,
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>,
/// Whether macOS lets this process read everything: asked once, since a
/// grant only takes effect after a relaunch. `None` off macOS.
pub full_disk_access: Option<bool>,
/// Whether disktree runs as an administrator, which lets a whole drive
/// be read from its file table instead of walked. `None` off Windows.
pub administrator: Option<bool>,
/// Whether the root is a whole NTFS drive, which an administrator reads
/// from its file table. Follows the root; `false` off Windows.
pub file_table: bool,
/// A restart as administrator was asked for and not yet declined, so a
/// second click does not raise a second prompt.
pub restarting: bool,
/// The top of the disk the scanned root lives on: what "Whole disk"
/// scans. Follows the root when a folder is opened.
pub disk_root: Option<PathBuf>,
/// The volume picker: open, what it listed, and which row the keys are
/// on. `None` when closed; empty when no volume besides the current one
/// could be read.
pub volumes_open: bool,
pub discovery: discovery_machine::State,
pub awaiting_root: bool,
pub picker_remote_tab: bool,
pub volumes_source: Option<String>,
/// Successfully connected SSH hosts (most recently used first).
pub saved_ssh_hosts: Vec<String>,
ssh_hosts_path: Option<PathBuf>,
pub picker_error: Option<String>,
pub picker_host: Option<Entity<InputState>>,
pub picker_path: Option<Entity<InputState>>,
pub volumes: Vec<disktree_core::space::Volume>,
pub volume_highlight: usize,
/// 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 {
#[cfg(test)]
pub fn new(
root_path: PathBuf,
options: ScanOptions,
depth: u32,
cx: &mut Context<'_, Self>,
) -> Self {
Self::open(root_path, options, depth, None, false, cx)
}
pub fn open(
root_path: PathBuf,
options: ScanOptions,
depth: u32,
remote: Option<String>,
remote_disk: bool,
cx: &mut Context<'_, Self>,
) -> Self {
Self::build(root_path, options, depth, remote, remote_disk, true, cx)
}
/// Startup without a scan: discovering roots is not consent to walk one.
pub fn choose(
options: ScanOptions,
depth: u32,
remote: Option<String>,
cx: &mut Context<'_, Self>,
) -> Self {
Self::build(PathBuf::new(), options, depth, remote, false, false, cx)
}
fn build(
root_path: PathBuf,
options: ScanOptions,
depth: u32,
remote: Option<String>,
remote_disk: bool,
start: bool,
cx: &mut Context<'_, Self>,
) -> Self {
let local = remote.is_none();
let home = if local { std::env::home_dir() } else { None };
let space = if local && start {
space_info(&root_path).ok()
} else {
None
};
let trash_backend = detect_trash_backend();
let scanner = if cfg!(test) {
Scanner::new(StorageMode::InMemory, CachePolicy::default())
.expect("in-memory scanner")
} else {
Scanner::open_default().unwrap_or_else(|_| {
Scanner::new(StorageMode::InMemory, CachePolicy::default())
.expect("in-memory fallback scanner")
})
};
let (ssh_hosts_path, saved_ssh_hosts) = if cfg!(test) {
(None, Vec::new())
} else {
let path = ssh_hosts::default_path();
let hosts = path
.as_deref()
.map(ssh_hosts::load_from)
.unwrap_or_default();
(path, hosts)
};
let mut tree = Self {
root_path,
remote,
remote_disk,
scan_preview: None,
preview_updated: None,
remote_progress: disktree_core::remote_progress::Progress::default(
),
remote_stale_seq: 0,
auth_url: None,
remote_platform: String::new(),
remote_identity: None,
home,
options,
scanner,
arena: None,
freshness: None,
tree: None,
active_scan: None,
updating_paths: FxHashSet::default(),
refreshed_paths: FxHashSet::default(),
active_scan_path: None,
pending_arena_flush: false,
last_arena_flush: None,
scan_epoch: 0,
progress: ScanSnapshot::default(),
scan_error: None,
screen: Screen::Explore,
crumbs: Vec::new(),
selected: None,
hovered: None,
history: History::default(),
history_hover: None,
pointer_active: false,
view: View::default(),
transition: None,
tile_fades: FxHashMap::default(),
tile_rects: FxHashMap::default(),
last_treemap_size: Size::default(),
layout_options: LayoutOptions {
max_depth: depth.clamp(1, 6),
..LayoutOptions::default()
},
cache: None,
marked: None,
pointer: None,
treemap_origin: Rc::new(Cell::new(Point::new(px(0.), px(0.)))),
treemap_size: Rc::new(Cell::new(size(px(0.), px(0.)))),
marks: Marks::default(),
// Reversible by default whenever this machine has a trash: the
// permanent path stays one choice away, behind a dialog.
removal_mode: if trash_backend.is_available() {
RemovalMode::Trash
} else {
RemovalMode::Permanent
},
trash_backend,
confirm_open: false,
confirm_focus: cx.focus_handle(),
focus_request: None,
window_title: String::new(),
rem: crate::ui::BASE_REM,
run: None,
run_epoch: 0,
run_summary: RunSummary::default(),
run_log: Vec::new(),
space,
space_baseline: None,
notice: None,
find: find_machine::State::default(),
filter_epoch: 0,
show_help: false,
show_selection: true,
focus: cx.focus_handle(),
crumb_menu: None,
color_mode: ColorMode::Kind,
insights: Vec::new(),
git: FxHashMap::default(),
git_pending: FxHashSet::default(),
device: None,
full_disk_access: None,
administrator: disktree_core::access::administrator(),
file_table: false,
restarting: false,
disk_root: None,
volumes_open: false,
discovery: discovery_machine::State::default(),
awaiting_root: !start,
picker_remote_tab: false,
volumes_source: None,
saved_ssh_hosts,
ssh_hosts_path,
picker_error: None,
picker_host: None,
picker_path: None,
volumes: Vec::new(),
volume_highlight: 0,
panel_rems: PANEL_REMS,
scan_started: None,
scan_elapsed: None,
scanned_at: now_seconds(),
};
if local && start {
tree.device = device_for(&tree.root_path);
tree.full_disk_access = tree
.home
.as_deref()
.and_then(disktree_core::access::full_disk_access);
// The disk of what is on screen, as `set_root` keeps it: `disktree
// /Volumes/Ext` then `g` measures that drive, like opening it with ⌘O.
tree.disk_root = volume_root_for(&tree.root_path);
tree.file_table = file_table_readable(&tree.root_path);
disktree_core::removal::prime_mount_points();
}
if start {
tree.start_scan(cx);
} else {
tree.open_volumes(cx);
}
Self::start_space_ticker(cx);
tree
}
/// Build a view over a tree that is already known.
///
/// Mirrors [`Self::new`] without starting a walk, so a test can hand the
/// screens a tree it already has instead of waiting on a real one. A
/// feature that opens an archived scan would use this too.
#[cfg(test)]
pub fn with_tree(
root_path: PathBuf,
tree: Node,
options: ScanOptions,
depth: u32,
cx: &mut Context<'_, Self>,
) -> Self {
let mut app = Self::new(root_path, options, depth, cx);
// `new` started a walk; this tree stands in for its result.
if let Some(ActiveScan::Local { handle, .. }) = app.active_scan.take() {
handle.cancel();
}
app.scan_epoch += 1;
app.marks.refresh(
&app.root_path,
&tree,
app.options.metric,
app.path_style(),
);
app.arena = Some(Arc::new(node_to_arena(app.root_path.clone(), &tree)));
app.tree = Some(Arc::new(tree));
app.cache = None;
app.refresh_insights();
app.select_largest(cx);
app
}
/// Scan a different root from scratch. 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 self.remote.is_some() {
self.root_path = root;
self.remote_disk = false;
self.start_scan(cx);
return;
}
self.space = space_info(&root).ok();
self.device = device_for(&root);
// "Whole disk" means the disk of what is on screen, which a new root
// can change: an external drive has its own.
self.disk_root =
volume_root_for(&root).or_else(|| self.disk_root.take());
self.file_table = file_table_readable(&root);
self.root_path = root;
self.screen = Screen::Explore;
self.start_scan(cx);
}
/// Go up to `above`, a directory containing the scanned root.
///
/// Memoized: the tree already measured is handed to the walk and reused
/// where it is reached, so only what is new at the wider level is read,
/// and the current view stays on screen until the wider tree lands.
pub fn widen_to(&mut self, above: PathBuf, cx: &mut Context<'_, Self>) {
if self.remote.is_some() {
self.set_root(above, cx);
return;
}
let Some(tree) = self.tree.clone() else {
self.set_root(above, cx);
return;
};
if !self.root_path.starts_with(&above) || self.root_path == above {
return;
}
if let Some(ActiveScan::Local { handle, .. }) = self.active_scan.take()
{
handle.cancel();
}
self.scan_epoch += 1;
let epoch = self.scan_epoch;
self.progress = ScanSnapshot::default();
self.scan_error = None;
self.scan_started = Some(Instant::now());
self.scan_elapsed = None;
self.remember();
let known_path = self
.root_path
.canonicalize()
.unwrap_or_else(|_| self.root_path.clone());
let arena = self.arena.clone().unwrap_or_else(|| {
Arc::new(node_to_arena(known_path.clone(), &tree))
});
let known = Known {
path: known_path,
arena,
};
let handle =
ScanHandle::spawn_with(above.clone(), self.options, Some(known));
self.active_scan = Some(ActiveScan::Local {
handle,
intent: ScanIntent::Widening { target: above },
});
Self::poll_scan(epoch, cx);
cx.notify();
}
/// `V`: list every volume and let the scan move to one. The in-flight walk
/// is left alone until a volume is picked; picking calls [`set_root`],
/// which cancels it.
pub fn open_volumes(&mut self, cx: &mut Context<'_, Self>) {
if self.run.is_some() || self.screen != Screen::Explore {
return;
}
self.volumes_open = true;
self.picker_remote_tab = self.remote.is_some();
self.picker_host = None;
self.picker_path = None;
self.focus_request = Some(FocusTarget::Dialog);
self.load_volume_source(self.remote.clone(), cx);
}
pub fn load_volume_source(
&mut self,
host: Option<String>,
cx: &mut Context<'_, Self>,
) {
if !self.volumes_open {
return;
}
self.picker_remote_tab = host.is_some();
self.volumes_source.clone_from(&host);
self.volumes.clear();
self.volume_highlight = 0;
self.picker_error = None;
self.auth_url = None;
let event = match host {
Some(host) => discovery_machine::Event::StartRemote { host },
None => discovery_machine::Event::StartLocal,
};
self.step_discovery(event, cx);
cx.notify();
}
fn step_discovery(
&mut self,
event: discovery_machine::Event,
cx: &mut Context<'_, Self>,
) {
let state = std::mem::take(&mut self.discovery);
let (next, effects) = discovery_machine::step(state, event);
self.discovery = next;
for effect in effects {
self.perform_discovery(effect, cx);
}
}
/// Install `disktree-cli` into `~/.local/bin/disktree-cli` on `host` over
/// SSH and automatically reconnect once installed.
pub fn install_remote_cli(
&mut self,
host: String,
command: String,
cx: &mut Context<'_, Self>,
) {
if !self.volumes_open {
return;
}
self.picker_error = None;
self.step_discovery(
discovery_machine::Event::StartInstall { host, command },
cx,
);
cx.notify();
}
fn perform_discovery(
&mut self,
effect: discovery_machine::Effect,
cx: &mut Context<'_, Self>,
) {
match effect {
discovery_machine::Effect::DiscoverRemote { epoch, host } => {
match disktree_core::remote::RemoteRoots::discover(&host) {
Ok(job) => self.step_discovery(
discovery_machine::Event::RemoteSpawned { epoch, job },
cx,
),
Err(error) => {
self.finish_volume_listing_for(epoch, Err(error), cx);
}
}
}
discovery_machine::Effect::InstallRemote {
epoch,
host,
command,
} => {
let target = host.clone();
let task = cx.background_executor().spawn(async move {
disktree_core::remote::install_remote_cli(&target, &command)
});
cx.spawn(async move |this, cx| {
let result = task.await;
let _ = this.update(cx, |this, cx| {
if !this.volumes_open || this.discovery.epoch != epoch {
return;
}
match result {
Ok(()) => {
this.load_volume_source(Some(host), cx);
}
Err(error) => {
this.step_discovery(
discovery_machine::Event::Completed {
epoch,
outcome: Err(error.to_string()),
},
cx,
);
cx.notify();
}
}
});
})
.detach();
}
discovery_machine::Effect::PollRemote { epoch } => {
cx.spawn(async move |this, cx| {
loop {
cx.background_executor()
.timer(Duration::from_millis(110))
.await;
let keep = this
.update(cx, |this, cx| {
this.poll_roots_once(epoch, cx)
})
.unwrap_or(false);
if !keep {
break;
}
}
})
.detach();
}
discovery_machine::Effect::SpawnLocalListing { epoch } => {
let task = cx.background_executor().spawn(async {
disktree_core::space::volume_roots()
.map(|volumes| (volumes, std::env::home_dir()))
});
cx.spawn(async move |this, cx| {
let result = task.await;
let _ = this.update(cx, |this, cx| {
if this.volumes_open {
this.finish_volume_listing_for(epoch, result, cx);
}
});
})
.detach();
}
}
}
pub(crate) fn poll_roots_once(
&mut self,
epoch: u64,
cx: &mut Context<'_, Self>,
) -> bool {
if !self.volumes_open || self.discovery.epoch != epoch {
return false;
}
let discovery_machine::Phase::Loading { job: Some(job) } =
&self.discovery.phase
else {
return false;
};
let auth_url = job.progress().auth_url;
let polled = job.poll();
self.handle_auth_url(auth_url, cx);
let Some(result) = polled else {
return true;
};
self.auth_url = None;
self.finish_volume_listing_for(
epoch,
result.map(|roots| (roots.volumes, roots.home)),
cx,
);
false
}
fn handle_auth_url(
&mut self,
url: Option<String>,
cx: &mut Context<'_, Self>,
) {
if let Some(url) = url {
if self.auth_url.as_deref() != Some(url.as_str()) {
self.auth_url = Some(url.clone());
cx.open_url(&url);
cx.notify();
}
} else if self.auth_url.take().is_some() {
cx.notify();
}
}
#[cfg(test)]
pub(crate) fn finish_volume_listing(
&mut self,
result: std::io::Result<(
Vec<disktree_core::space::Volume>,
Option<PathBuf>,
)>,
cx: &mut Context<'_, Self>,
) {
let epoch = self.discovery.epoch;
self.finish_volume_listing_for(epoch, result, cx);
}
fn finish_volume_listing_for(
&mut self,
epoch: u64,
result: std::io::Result<(
Vec<disktree_core::space::Volume>,
Option<PathBuf>,
)>,
cx: &mut Context<'_, Self>,
) {
if epoch != self.discovery.epoch {
return;
}
let outcome = match result {
Ok((mut volumes, home)) => {
if let Some(home) = home
&& !volumes.iter().any(|volume| volume.point == home)
{
volumes.insert(
0,
disktree_core::space::Volume {
point: home,
device: Some("Home directory".into()),
space: None,
},
);
}
self.volumes = volumes;
if let Some(host) = self.volumes_source.clone() {
self.record_saved_ssh_host(&host);
}
Ok(())
}
Err(error) => Err(error.to_string()),
};
self.step_discovery(
discovery_machine::Event::Completed { epoch, outcome },
cx,
);
cx.notify();
}
pub fn prepare_picker_inputs(
&mut self,
window: &mut Window,
cx: &mut Context<'_, Self>,
) {
if self.picker_host.is_none() {
let value = self.volumes_source.clone().unwrap_or_default();
let host = cx.new(|cx| {
InputState::new(window, cx)
.placeholder("SSH alias or user@host")
.default_value(value)
});
cx.subscribe(&host, |this, _, event, cx| {
if matches!(event, InputEvent::PressEnter { .. }) {
this.connect_picker(cx);
}
cx.notify();
})
.detach();
self.picker_host = Some(host);
}
if self.picker_path.is_none() {
let path = cx.new(|cx| {
InputState::new(window, cx).placeholder("/path/to/folder")
});
cx.subscribe(&path, |this, _, event, cx| {
if matches!(event, InputEvent::PressEnter { .. }) {
this.choose_picker_path(cx);
}
cx.notify();
})
.detach();
self.picker_path = Some(path);
}
}
pub fn picker_source_matches(&self, cx: &Context<'_, Self>) -> bool {
if self.picker_remote_tab && self.volumes_source.is_none() {
return false;
}
self.picker_host.as_ref().is_none_or(|input| {
input.read(cx).value().trim()
== self.volumes_source.as_deref().unwrap_or_default()
})
}
pub fn picker_path_value(&self, cx: &Context<'_, Self>) -> String {
self.picker_path
.as_ref()
.map(|input| input.read(cx).value().trim().to_owned())
.unwrap_or_default()
}
pub fn picker_has_path(&self, cx: &Context<'_, Self>) -> bool {
!self.picker_path_value(cx).is_empty()
}
pub fn set_picker_tab(
&mut self,
remote: bool,
window: &mut Window,
cx: &mut Context<'_, Self>,
) {
if self.picker_remote_tab == remote {
return;
}
if !remote {
self.choose_local_source(window, cx);
return;
}
self.picker_remote_tab = true;
self.picker_error = None;
if let Some(current_remote) = self.remote.clone() {
if let Some(host) = self.picker_host.clone() {
host.update(cx, |host, cx| {
host.set_value(current_remote.clone(), window, cx);
});
}
self.load_volume_source(Some(current_remote), cx);
} else {
self.step_discovery(discovery_machine::Event::Reset, cx);
self.volumes_source = None;
self.volumes.clear();
self.volume_highlight = 0;
if let Some(host) = self.picker_host.as_ref() {
let focus = host.read(cx).focus_handle(cx);
window.focus(&focus, cx);
}
cx.notify();
}
}
pub fn choose_local_source(
&mut self,
window: &mut Window,
cx: &mut Context<'_, Self>,
) {
if let Some(host) = self.picker_host.clone() {
host.update(cx, |host, cx| host.set_value("", window, cx));
}
self.load_volume_source(None, cx);
}
pub fn connect_picker(&mut self, cx: &mut Context<'_, Self>) {
self.picker_remote_tab = true;
let host = self
.picker_host
.as_ref()
.map(|input| input.read(cx).value().trim().to_owned())
.unwrap_or_default();
self.load_volume_source(Some(host), cx);
}
pub fn connect_saved_ssh_host(
&mut self,
host: &str,
window: &mut Window,
cx: &mut Context<'_, Self>,
) {
self.picker_remote_tab = true;
if let Some(input) = self.picker_host.clone() {
input.update(cx, |state, cx| {
state.set_value(host.to_owned(), window, cx);
});
}
self.load_volume_source(Some(host.to_owned()), cx);
}
pub fn remove_saved_ssh_host(
&mut self,
host: &str,
cx: &mut Context<'_, Self>,
) {
if ssh_hosts::remove(&mut self.saved_ssh_hosts, host) {
if let Some(path) = self.ssh_hosts_path.as_deref() {
ssh_hosts::save_to(path, &self.saved_ssh_hosts);
}
cx.notify();
}
}
fn record_saved_ssh_host(&mut self, host: &str) {
if ssh_hosts::record(&mut self.saved_ssh_hosts, host)
&& let Some(path) = self.ssh_hosts_path.as_deref()
{
ssh_hosts::save_to(path, &self.saved_ssh_hosts);
}
}
pub fn accept_picker(&mut self, cx: &mut Context<'_, Self>) {
if self.picker_has_path(cx) {
self.choose_picker_path(cx);
} else {
self.choose_volume(cx);
}
}
pub fn browse_local_folder(&mut self, cx: &mut Context<'_, Self>) {
self.close_volumes(cx);
self.open_folder(cx);
}
pub fn choose_picker_path(&mut self, cx: &mut Context<'_, Self>) {
let raw = self.picker_path_value(cx);
if raw.is_empty() {
self.choose_source_root(PathBuf::new(), cx);
return;
}
let path = if self.volumes_source.is_none() {
expand_tilde(&raw)
} else {
PathBuf::from(raw)
};
self.choose_source_root(path, cx);
}
fn clear_machine_state(&mut self, local: bool) {
// Absolute paths only identify marks within one machine.
self.marks.clear();
self.history = History::default();
self.remote_identity = None;
self.remote_platform.clear();
self.git.clear();
self.git_pending.clear();
self.space = None;
self.space_baseline = None;
self.disk_root = None;
self.device = None;
self.full_disk_access = None;
self.file_table = false;
self.home = if local { std::env::home_dir() } else { None };
}
pub fn choose_source_root(
&mut self,
mut path: PathBuf,
cx: &mut Context<'_, Self>,
) {
if !self.volumes_open
|| self.discovery.is_loading()
|| self.discovery.error().is_some()
{
return;
}
if !self.picker_source_matches(cx) {
self.picker_error =
Some("Connect to the SSH host before scanning.".into());
cx.notify();
return;
}
let absolute = if self.volumes_source.is_some() {
disktree_core::remote::is_remote_absolute(&path)
} else {
path.is_absolute()
};
if !absolute {
self.picker_error =
Some("Enter an absolute directory path.".into());
cx.notify();
return;
}
if self.volumes_source.is_none() {
match dunce::canonicalize(&path) {
Ok(root) if root.is_dir() => path = root,
_ => {
self.picker_error =
Some("Cannot open that local directory.".into());
cx.notify();
return;
}
}
}
self.picker_error = None;
if self.remote != self.volumes_source {
self.clear_machine_state(self.volumes_source.is_none());
}
self.remote.clone_from(&self.volumes_source);
if self.remote.is_some() {
self.options.follow_links = false;
self.options.one_filesystem = true;
}
self.awaiting_root = false;
self.close_volumes(cx);
self.set_root(path, cx);
}
/// Closing cancels discovery, not the scan already on screen.
pub fn close_volumes(&mut self, cx: &mut Context<'_, Self>) {
self.step_discovery(discovery_machine::Event::Reset, cx);
self.auth_url = None;
self.volumes_open = false;
self.focus_request = Some(FocusTarget::Root);
cx.notify();
}
pub fn choose_volume(&mut self, cx: &mut Context<'_, Self>) {
if let Some(point) = self
.volumes
.get(self.volume_highlight)
.map(|volume| volume.point.clone())
{
self.choose_source_root(point, cx);
}
}
/// Move the highlight in the open picker, wrapping at the ends.
pub fn move_volume_highlight(
&mut self,
step: i32,
cx: &mut Context<'_, Self>,
) {
if self.volumes.is_empty() {
return;
}
let len = self.volumes.len();
let at = self.volume_highlight;
// Picker steps are ±1, but wrap either way without casting the length
// down to a narrower type.
let next = match step.signum() {
1 => (at + 1) % len,
-1 => at.checked_sub(1).unwrap_or(len - 1),
_ => at,
};
self.volume_highlight = next;
cx.notify();
}
/// `g`: the whole disk. Widens when the disk is above the scanned root,
/// and goes to its top when it already is the root.
pub fn go_to_disk(&mut self, cx: &mut Context<'_, Self>) {
let Some(disk) = self.disk_root.clone() else {
return;
};
if disk == self.root_path {
self.go_to(Vec::new(), cx);
} else {
self.widen_to(disk, 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.remote.is_some()
|| self.git.contains_key(path)
|| self.git_pending.contains(path)
{
return;
}
let path = path.to_path_buf();
self.git_pending.insert(path.clone());
let epoch = self.scan_epoch;
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| {
if this.scan_epoch != epoch || this.remote.is_some() {
return;
}
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"
/// most of the time.
fn select_largest(&mut self, cx: &mut Context<'_, Self>) {
if self.selected.is_some() {
return;
}
if let Some(index) = self.current().and_then(Node::largest_child) {
self.selected = Some(vec![index]);
cx.notify();
}
}
// ── scanning ────────────────────────────────────────────────────────
/// Stop the walk in progress. A partial tree is never shown as if it
/// were the whole one: a first scan leaves the panel saying it stopped,
/// and a widening scan leaves the tree it started from on screen.
pub fn cancel_scan(&mut self, cx: &mut Context<'_, Self>) {
self.scan_preview = None;
self.auth_url = None;
self.updating_paths.clear();
self.refreshed_paths.clear();
self.active_scan_path = None;
let Some(active) = self.active_scan.take() else {
return;
};
self.scan_epoch += 1;
match active {
ActiveScan::Remote { .. } => {
self.progress.cancelled = true;
self.progress.finished = true;
}
ActiveScan::Local { handle, .. } => {
handle.cancel();
self.progress = handle.progress.snapshot();
}
}
self.scan_elapsed = self.scan_started.map(|started| started.elapsed());
cx.notify();
}
/// Refresh the whole scanned root in the background. Keeping its old tree
/// visible also preserves hardlink accounting across the current view and
/// the rest of the root; a subtree-only scan could charge a link twice.
pub fn refresh_scan(&mut self, cx: &mut Context<'_, Self>) {
if self.tree.is_none() {
self.start_scan_with_policy(
CachePolicy {
force_refresh: true,
..CachePolicy::default()
},
cx,
);
return;
}
if self.is_indexing() {
return;
}
self.scan_epoch += 1;
let epoch = self.scan_epoch;
let intent = ScanIntent::Refresh {
metric: self.options.metric,
forced: true,
};
self.updating_paths.clear();
self.refreshed_paths.clear();
self.active_scan_path = None;
self.progress = ScanSnapshot::default();
self.remote_progress =
disktree_core::remote_progress::Progress::default();
self.remote_stale_seq = 0;
self.scan_error = None;
self.scan_preview = None;
self.preview_updated = None;
self.scan_started = Some(Instant::now());
self.scan_elapsed = None;
if let Some(host) = &self.remote {
let request = disktree_core::remote::Request {
root: Some(self.root_path.clone()),
disk: self.remote_disk,
options: self.options,
};
match disktree_core::remote::RemoteScan::spawn_with_refresh(
host, &request, true,
) {
Ok(handle) => {
self.active_scan =
Some(ActiveScan::Remote { handle, intent });
}
Err(error) => {
self.scan_error = Some(error.to_string());
cx.notify();
return;
}
}
} else {
let policy = CachePolicy {
force_refresh: true,
..CachePolicy::default()
};
match ScanHandle::spawn_session(
&self.scanner,
self.root_path.clone(),
self.options,
policy,
) {
Ok(handle) => {
self.active_scan =
Some(ActiveScan::Local { handle, intent });
}
Err(error) => {
self.scan_error = Some(error.to_string());
cx.notify();
return;
}
}
}
Self::poll_scan(epoch, cx);
cx.notify();
}
/// Start a scan, serving fresh/stale cache immediately via SWR when
/// available and abandoning any walk still in progress.
pub fn start_scan(&mut self, cx: &mut Context<'_, Self>) {
self.start_scan_with_policy(CachePolicy::default(), cx);
}
fn start_scan_with_policy(
&mut self,
policy: CachePolicy,
cx: &mut Context<'_, Self>,
) {
if self.awaiting_root {
self.open_volumes(cx);
return;
}
if let Some(ActiveScan::Local { handle, .. }) = self.active_scan.take()
{
handle.cancel();
}
self.scan_epoch += 1;
let epoch = self.scan_epoch;
self.progress = ScanSnapshot::default();
self.scan_error = None;
self.remote_progress =
disktree_core::remote_progress::Progress::default();
self.remote_stale_seq = 0;
self.scan_preview = None;
self.preview_updated = None;
// A new scan starts at its root; where it was is one `<` away.
if !self.crumbs.is_empty() {
self.remember();
}
discard(self.tree.take());
self.arena = None;
self.freshness = None;
self.updating_paths.clear();
self.refreshed_paths.clear();
self.active_scan_path = None;
self.pending_arena_flush = false;
self.last_arena_flush = None;
self.tile_fades.clear();
self.tile_rects.clear();
self.crumbs.clear();
self.selected = None;
self.hovered = None;
self.view = View::default();
self.cache = None;
self.insights.clear();
self.git.clear();
self.git_pending.clear();
self.clear_filter();
self.scan_started = Some(Instant::now());
self.scan_elapsed = None;
if let Some(host) = self.remote.clone() {
let intent = if !self.root_path.as_os_str().is_empty()
&& let Some((arena, freshness)) = self.scanner.lookup_cached(
&remote_cache_host(&host),
&self.root_path,
&self.options.to_scanner(),
&policy,
)
&& !matches!(freshness, Freshness::Partial { .. })
{
let is_fresh = matches!(freshness, Freshness::Fresh { .. });
let node = disktree_core::scan::arena_to_node(
&arena,
self.options.apparent_size,
self.options.include_hidden,
self.options.dedup_hardlinks,
self.options.metric,
);
self.arena = Some(arena);
self.freshness = Some(freshness);
self.device = Some(format!("{host} · read-only · cached"));
self.install_tree(node, None, cx);
if is_fresh && !policy.force_refresh {
self.progress.finished = true;
self.scan_elapsed = self.scan_started.map(|t| t.elapsed());
cx.notify();
return;
}
ScanIntent::Refresh {
metric: self.options.metric,
forced: policy.force_refresh,
}
} else {
ScanIntent::Initial
};
let request = disktree_core::remote::Request {
root: (!self.root_path.as_os_str().is_empty())
.then(|| self.root_path.clone()),
disk: self.remote_disk,
options: self.options,
};
match disktree_core::remote::RemoteScan::spawn_with_refresh(
&host,
&request,
policy.force_refresh,
) {
Ok(handle) => {
self.active_scan =
Some(ActiveScan::Remote { handle, intent });
Self::poll_scan(epoch, cx);
}
Err(error) => {
if self.tree.is_some() {
self.notice = Some((
format!("Refresh failed: {error}"),
Status::Warning,
));
} else {
self.scan_error = Some(error.to_string());
}
}
}
cx.notify();
return;
}
match ScanHandle::spawn_session(
&self.scanner,
self.root_path.clone(),
self.options,
policy,
) {
Ok(handle) => {
self.active_scan = Some(ActiveScan::Local {
handle,
intent: ScanIntent::Initial,
});
// Drain any instant cache hit so warm launches paint on frame 1.
if self.poll_scan_once(epoch, cx) {
Self::poll_scan(epoch, cx);
}
}
Err(error) => {
self.scan_error = Some(error.to_string());
cx.notify();
}
}
}
fn poll_scan(epoch: u64, cx: &Context<'_, Self>) {
cx.spawn(async move |this, cx| {
loop {
cx.background_executor()
.timer(Duration::from_millis(110))
.await;
let keep_going = this
.update(cx, |this, cx| this.poll_scan_once(epoch, cx))
.unwrap_or(false);
if !keep_going {
break;
}
}
})
.detach();
}
pub(crate) fn update_remote_identity(
&mut self,
identity: Option<disktree_core::identity::HostIdentity>,
) {
// A stable SSH alias can be repointed to a different machine.
// Old marks must not acquire that machine's freshly captured guard.
if self.remote_identity != identity && !self.marks.is_empty() {
self.marks.clear();
self.notice = Some((
"Remote identity changed; previous marks were cleared.".into(),
Status::Warning,
));
}
self.remote_identity = identity;
}
/// Drain the scan channel once. Returns whether the poller should keep
/// ticking. Driven by the poll task above, and by the tests, which cannot
/// wait on the test clock while a real worker thread walks a directory.
pub(crate) fn poll_scan_once(
&mut self,
epoch: u64,
cx: &mut Context<'_, Self>,
) -> bool {
if epoch != self.scan_epoch {
return false;
}
let Some(active) = &self.active_scan else {
return false;
};
match active {
ActiveScan::Remote { handle, intent } => {
let outcome = handle.poll();
let refresh_metric = match intent {
ScanIntent::Refresh { metric, .. } => Some(*metric),
ScanIntent::Initial | ScanIntent::Widening { .. } => None,
};
self.remote_progress = handle.progress();
let auth_url = self.remote_progress.auth_url.clone();
self.handle_auth_url(auth_url, cx);
if self.remote_progress.stale_seq > self.remote_stale_seq
&& let Some(stale) =
self.remote_progress.stale_snapshot.clone()
{
self.remote_stale_seq = self.remote_progress.stale_seq;
let had_tree = self.tree.is_some();
let prev_dir = had_tree.then(|| self.current_path());
let prev_sel = had_tree.then(|| {
self.selected.as_deref().and_then(|c| self.path_at(c))
});
let stale_dirs = stale.tree.dirs;
self.root_path.clone_from(&stale.header.root);
self.home.clone_from(&stale.header.home);
self.disk_root.clone_from(&stale.header.disk_root);
self.space = stale.header.space;
self.remote_platform.clone_from(&stale.header.platform);
self.update_remote_identity(stale.header.identity.clone());
let ver = stale
.header
.helper_version
.as_deref()
.map_or_else(String::new, |v| format!(" · v{v}"));
self.device = self.remote.as_ref().map(|host| {
format!("{host}{ver} · read-only · live updating")
});
self.arena =
Some(Arc::new(disktree_core::scan::node_to_arena_at(
self.root_path.clone(),
&stale.tree,
1,
)));
self.freshness = Some(Freshness::Stale {
oldest_at: 1,
newest_at: 1,
stale_dirs,
});
if let Some(directory) = prev_dir {
self.install_refresh(
stale.tree.clone(),
self.options.metric,
&directory,
prev_sel.flatten(),
cx,
);
} else {
self.install_tree(stale.tree.clone(), None, cx);
}
}
if self.remote_progress.preview.is_some()
&& (self.scan_preview.is_none()
|| self
.preview_updated
.is_none_or(|at| at.elapsed().as_secs() >= 1))
{
self.scan_preview.clone_from(&self.remote_progress.preview);
self.preview_updated = Some(Instant::now());
}
self.progress.files = self.remote_progress.files;
self.progress.dirs = self.remote_progress.dirs;
self.progress.bytes = self.remote_progress.bytes;
self.progress.errors = self.remote_progress.errors;
let Some(outcome) = outcome else {
cx.notify();
return true;
};
match outcome {
Ok(snapshot) => {
let refresh_paths = refresh_metric.map(|metric| {
(
metric,
self.current_path(),
self.selected
.as_deref()
.and_then(|c| self.path_at(c)),
)
});
self.root_path = snapshot.header.root;
self.home = snapshot.header.home;
self.disk_root = snapshot.header.disk_root;
self.space = snapshot.header.space;
self.remote_platform = snapshot.header.platform;
self.update_remote_identity(snapshot.header.identity);
let ver = snapshot
.header
.helper_version
.as_deref()
.map_or_else(String::new, |v| format!(" · v{v}"));
self.device = self.remote.as_ref().map(|host| {
format!("{host}{ver} · read-only · space at scan")
});
let node = snapshot.tree;
let scanned_at = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map_or(0, |d| d.as_secs());
let arena =
Arc::new(disktree_core::scan::node_to_arena_at(
self.root_path.clone(),
&node,
scanned_at,
));
if let Some(host) = self.remote.clone() {
self.record_saved_ssh_host(&host);
self.scanner.store_snapshot(
&remote_cache_host(&host),
&arena,
&self.options.to_scanner(),
scanned_at,
);
}
self.arena = Some(arena);
self.freshness = Some(Freshness::Live { scanned_at });
if let Some((metric, directory, selected)) =
refresh_paths
{
self.install_refresh(
node, metric, &directory, selected, cx,
);
} else {
self.marks.refresh(
&self.root_path,
&node,
self.options.metric,
self.path_style(),
);
self.tree = Some(Arc::new(node));
self.refresh_insights();
self.select_largest(cx);
}
self.scan_elapsed =
self.scan_started.map(|t| t.elapsed());
}
Err(error) => {
if self.tree.is_some() {
self.notice = Some((
format!("Refresh failed: {error}"),
Status::Warning,
));
} else {
self.scan_error = Some(error.to_string());
}
}
}
self.active_scan = None;
self.auth_url = None;
self.scan_preview = None;
self.progress.finished = true;
cx.notify();
return false;
}
ActiveScan::Local { handle, intent } => {
let intent = intent.clone();
self.progress = handle.progress.snapshot();
self.active_scan_path = handle.active_path();
if self
.preview_updated
.is_none_or(|at| at.elapsed().as_secs() >= 1)
{
let preview = handle.progress.preview();
if !preview.entries.is_empty() {
self.scan_preview = Some(Arc::new(preview));
self.preview_updated = Some(Instant::now());
}
}
let mut drained = Vec::new();
while drained.len() < 64
&& let Some(update) = handle.poll_update()
{
let stop = matches!(
update,
ScanUpdate::Live { .. }
| ScanUpdate::Error(_)
| ScanUpdate::Finished
);
drained.push(update);
if stop {
break;
}
}
let mut keep_polling = true;
let mut spliced_arenas: Vec<(PathBuf, Arc<TreeArena>)> =
Vec::new();
for update in drained {
match update {
ScanUpdate::Cached {
arena,
node,
freshness,
} => {
let is_fresh =
matches!(freshness, Freshness::Fresh { .. });
self.arena = Some(arena);
self.freshness = Some(freshness);
self.install_tree(node, None, cx);
if is_fresh {
keep_polling = false;
break;
}
// Stale SWR hit: paint immediately and transition
// the active scan's intent to Refresh so the live
// landing preserves navigation by path.
if let Some(active) = &mut self.active_scan {
active.set_intent(ScanIntent::Refresh {
metric: self.options.metric,
forced: false,
});
}
}
ScanUpdate::SubtreeUpdating { path } => {
self.updating_paths.insert(path);
}
ScanUpdate::SubtreeRefreshed { path, arena: sub } => {
self.updating_paths.remove(&path);
self.refreshed_paths.insert(path.clone());
spliced_arenas.push((path, sub));
}
ScanUpdate::Live { arena, node } => {
spliced_arenas.clear();
self.pending_arena_flush = false;
self.arena = Some(arena);
self.freshness = Some(Freshness::Live {
scanned_at: disktree_scanner::unix_now(),
});
match &intent {
ScanIntent::Refresh { metric, .. } => {
let directory = self.current_path();
let selected = self
.selected
.as_deref()
.and_then(|c| self.path_at(c));
self.install_refresh(
node, *metric, &directory, selected, cx,
);
self.scan_elapsed = self
.scan_started
.map(|started| started.elapsed());
}
ScanIntent::Widening { target } => {
self.install_tree(
node,
Some(target.clone()),
cx,
);
}
ScanIntent::Initial => {
self.install_tree(node, None, cx);
}
}
keep_polling = false;
break;
}
ScanUpdate::Error(error) => {
self.scan_error = Some(error.to_string());
keep_polling = false;
break;
}
ScanUpdate::Finished => {
keep_polling = false;
break;
}
}
}
// Coalesce all SubtreeRefreshed checkpoints received on this
// tick into one arena splice, and buffer full tree re-layout to
// at most once per LIVE_REPROJECT_BUFFER so the treemap stays
// calm instead of jumping around on every folder.
if !spliced_arenas.is_empty()
&& let Some(current_arena) = self.arena.as_ref()
{
let root = current_arena.root_path().to_path_buf();
let mut next = (**current_arena).clone();
let mut changed = false;
for (path, sub) in spliced_arenas {
if path == root {
next = (*sub).clone();
changed = true;
} else if let Ok(rel) = path.strip_prefix(&root) {
let parts: Vec<String> = rel
.components()
.map(|c| {
c.as_os_str().to_string_lossy().into_owned()
})
.collect();
if let Some(target_id) = next
.find_relative(parts.iter().map(String::as_str))
{
next.replace_node_contents(target_id, &sub);
changed = true;
}
}
}
if changed {
next.aggregate(
self.options.dedup_hardlinks,
self.options.include_hidden,
);
self.arena = Some(Arc::new(next));
self.pending_arena_flush = true;
}
}
if self.pending_arena_flush
&& self
.last_arena_flush
.is_none_or(|t| t.elapsed() >= LIVE_REPROJECT_BUFFER)
&& let Some(arena) = self.arena.clone()
{
self.pending_arena_flush = false;
self.last_arena_flush = Some(Instant::now());
self.reproject_arena(&arena, cx);
}
if keep_polling {
cx.notify();
return true;
}
}
}
self.active_scan = None;
self.updating_paths.clear();
self.refreshed_paths.clear();
self.active_scan_path = None;
self.scan_preview = None;
self.progress.finished = true;
cx.notify();
false
}
fn install_tree(
&mut self,
node: Node,
widened_to: Option<PathBuf>,
cx: &mut Context<'_, Self>,
) {
let came_from = widened_to.as_ref().map(|_| self.root_path.clone());
if let Some(target) = widened_to {
self.clear_filter();
self.root_path = target;
self.space = space_info(&self.root_path).ok();
self.device = device_for(&self.root_path);
self.file_table = file_table_readable(&self.root_path);
}
let metric = self.options.metric;
self.marks
.refresh(&self.root_path, &node, metric, self.path_style());
discard(self.tree.replace(Arc::new(node)));
self.cache = None;
self.refresh_insights();
self.scan_elapsed = self.scan_started.map(|started| started.elapsed());
if let Some(from) = came_from {
let crumbs = self.crumbs_for_path(&from);
self.crumbs.clear();
self.view = View::default();
self.transition = None;
self.forget_hover();
self.selected =
crumbs.and_then(|crumbs| crumbs.first().map(|&top| vec![top]));
}
self.keep_selection_valid();
self.prune_history();
self.select_largest(cx);
}
/// Re-project the current `TreeArena` after toggling `apparent_size` or
/// `include_hidden` without rescanning disk.
pub fn toggle_hidden(&mut self, cx: &mut Context<'_, Self>) {
self.options.include_hidden = !self.options.include_hidden;
if self.remote.is_none()
&& let Some(arena) = self.arena.clone()
{
self.reproject_arena(&arena, cx);
} else {
self.start_scan(cx);
}
}
/// Toggle allocated vs apparent sizes with zero rescan when backed by a
/// local `TreeArena`.
pub fn toggle_apparent_size(&mut self, cx: &mut Context<'_, Self>) {
self.options.apparent_size = !self.options.apparent_size;
if self.remote.is_none()
&& let Some(arena) = self.arena.clone()
{
self.reproject_arena(&arena, cx);
} else {
self.start_scan(cx);
}
}
fn reproject_arena(
&mut self,
arena: &TreeArena,
cx: &mut Context<'_, Self>,
) {
let directory = self.current_path();
let selected = self.selected.as_deref().and_then(|c| self.path_at(c));
let node = arena_to_node(
arena,
self.options.apparent_size,
self.options.include_hidden,
self.options.dedup_hardlinks,
self.options.metric,
);
self.install_refresh(
node,
self.options.metric,
&directory,
selected,
cx,
);
self.select_largest(cx);
}
/// Reattach the view and selection by absolute path: sorting may have
/// changed every crumb while the old tree remained interactive.
fn install_refresh(
&mut self,
mut node: Node,
scanned_metric: Metric,
directory: &Path,
selected: Option<PathBuf>,
cx: &mut Context<'_, Self>,
) {
if scanned_metric != self.options.metric {
disktree_core::tree::aggregate(&mut node, self.options.metric);
}
self.marks.refresh(
&self.root_path,
&node,
self.options.metric,
self.path_style(),
);
discard(self.tree.replace(Arc::new(node)));
self.clear_filter();
self.cache = None;
self.transition = None;
self.forget_hover();
self.git.clear();
self.git_pending.clear();
self.refresh_insights();
let style = self.path_style();
self.crumbs = style
.ancestors(directory)
.find_map(|path| self.crumbs_for_path(path))
.unwrap_or_default();
self.selected = selected
.and_then(|path| self.crumbs_for_path(&path))
.filter(|crumbs| crumbs.starts_with(&self.crumbs));
self.prune_history();
cx.notify();
}
fn keep_selection_valid(&mut self) {
let Some(tree) = &self.tree else {
return;
};
if tree.resolve(&self.crumbs).is_none() {
self.crumbs.clear();
}
if let Some(selected) = self.selected.clone()
&& tree.resolve(&selected).is_none()
{
self.selected = None;
}
}
/// Space changes under us all the time; poll it so the meter is live
/// without repainting when nothing moved.
fn start_space_ticker(cx: &Context<'_, Self>) {
cx.spawn(async move |this, cx| {
loop {
let interval = this
.update(cx, |this, _| {
if this.screen == Screen::Running {
Duration::from_millis(150)
} else {
Duration::from_millis(1200)
}
})
.unwrap_or(Duration::from_millis(1200));
cx.background_executor().timer(interval).await;
let Ok(path) = this.update(cx, |this, _| {
if this.remote.is_some()
|| this.awaiting_root
|| this.tree.is_none()
{
None
} else {
Some(this.root_path.clone())
}
}) else {
break;
};
let Some(path) = path else {
continue;
};
// Asked off the UI thread: a network share or a drive
// spinning up can take seconds to answer, and the window,
// Escape included, must not wait with it.
let asked = path.clone();
let fresh = cx
.background_executor()
.spawn(async move { space_info(&asked).ok() })
.await;
let ok = this
.update(cx, |this, cx| {
if this.remote.is_some()
|| this.awaiting_root
|| this.tree.is_none()
{
return;
}
// A root chosen while the old one answered has
// been measured already; this is not its number.
if this.root_path == path && fresh != this.space {
this.space = fresh;
cx.notify();
}
})
.is_ok();
if !ok {
break;
}
}
})
.detach();
}
// ── navigation ──────────────────────────────────────────────────────
pub const fn is_indexing(&self) -> bool {
self.active_scan.is_some()
}
pub const fn is_refreshing(&self) -> bool {
matches!(
&self.active_scan,
Some(
ActiveScan::Local {
intent: ScanIntent::Refresh { .. },
..
} | ActiveScan::Remote {
intent: ScanIntent::Refresh { .. },
..
}
)
)
}
pub fn widening_target(&self) -> Option<&Path> {
self.active_scan
.as_ref()
.and_then(ActiveScan::widening_target)
}
pub fn tree(&self) -> Option<&Node> {
self.tree.as_deref()
}
/// The node the treemap is currently rooted at.
pub fn current(&self) -> Option<&Node> {
self.tree
.as_ref()
.and_then(|tree| tree.resolve(&self.crumbs))
}
pub fn node_at(&self, crumbs: &[usize]) -> Option<&Node> {
self.tree.as_ref().and_then(|tree| tree.resolve(crumbs))
}
pub fn path_at(&self, crumbs: &[usize]) -> Option<PathBuf> {
let tree = self.tree.as_ref()?;
Some(path_of(&self.root_path, tree, crumbs, self.path_style()))
}
/// The path rules of the machine on screen: an SSH host is Unix, so its
/// paths are POSIX on every client.
pub const fn path_style(&self) -> PathStyle {
PathStyle::of(self.remote.is_some())
}
/// `path` shortened under the scanned machine's home, in its separators.
pub fn display_path(&self, path: &Path) -> String {
crate::marks::display_path(
path,
self.home.as_deref(),
self.path_style(),
)
}
/// Path of the directory currently drawn.
pub fn current_path(&self) -> PathBuf {
self.path_at(&self.crumbs)
.unwrap_or_else(|| self.root_path.clone())
}
/// Breadcrumb labels from the scanned root to the current directory.
/// The trail, from `/`: the directories above the scanned root, which
/// widen the scan, then the root and the path into the tree.
pub fn breadcrumbs(&self) -> Vec<(String, Crumb)> {
let style = self.path_style();
let mut trail: Vec<(String, Crumb)> = style
.ancestors(&self.root_path)
.skip(1)
.collect::<Vec<_>>()
.into_iter()
.rev()
.map(|path| {
(crumb_label(path, style), Crumb::Above(path.to_path_buf()))
})
.collect();
trail.push((
crumb_label(&self.root_path, style),
Crumb::Tree(Vec::new()),
));
let Some(tree) = &self.tree else {
return trail;
};
let mut crumbs: Vec<usize> = Vec::new();
for &index in &self.crumbs {
let Some(node) =
tree.resolve(&crumbs).and_then(|node| node.child(index))
else {
break;
};
crumbs.push(index);
trail.push((node.name.to_string(), Crumb::Tree(crumbs.clone())));
}
trail
}
/// The children of `parent`, largest first, for a sibling menu, and how
/// many more there are beyond [`SIBLING_ROWS`].
pub fn siblings(&self, parent: &[usize]) -> (Vec<Sibling>, usize) {
let metric = self.options.metric;
let Some(node) = self.node_at(parent) else {
return (Vec::new(), 0);
};
// Ranked as plain numbers, with names copied only for the rows
// shown: a directory can hold a million entries, and the menu asks
// again on every key.
let mut ranked: Vec<(usize, u64)> = node
.children
.iter()
.enumerate()
.map(|(index, child)| (index, child.value(metric)))
.collect();
ranked.sort_by_key(|&(_, value)| std::cmp::Reverse(value));
let more = ranked.len().saturating_sub(SIBLING_ROWS);
ranked.truncate(SIBLING_ROWS);
let rows = ranked
.into_iter()
.map(|(index, value)| {
let child = &node.children[index];
Sibling {
index,
name: child.name.to_string(),
value,
category: child.category,
is_dir: child.is_dir(),
}
})
.collect();
(rows, more)
}
/// Open the sibling menu for the crumb at `crumbs` (not the root).
pub fn open_crumb_menu(
&mut self,
crumbs: &[usize],
cx: &mut Context<'_, Self>,
) {
let Some((&current, parent)) = crumbs.split_last() else {
return;
};
let (rows, _) = self.siblings(parent);
let highlighted = rows
.iter()
.position(|row| row.index == current)
.unwrap_or(0);
self.crumb_menu = Some(CrumbMenu {
parent: parent.to_vec(),
current,
highlighted,
});
cx.notify();
}
/// Go to a sibling: into it when it is a directory, beside it (selected)
/// when it is a file.
pub fn choose_sibling(
&mut self,
parent: &[usize],
index: usize,
cx: &mut Context<'_, Self>,
) {
self.crumb_menu = None;
let mut crumbs = parent.to_vec();
crumbs.push(index);
if self.node_at(&crumbs).is_some_and(Node::is_dir) {
self.go_to(crumbs, cx);
} else {
self.reveal(crumbs, cx);
}
}
/// Keys while a sibling menu is open: it owns the arrows, Enter and
/// Escape, and any other key closes it before acting.
fn on_menu_key(&mut self, key: &str, cx: &mut Context<'_, Self>) -> bool {
let Some(menu) = self.crumb_menu.clone() else {
return false;
};
let (rows, _) = self.siblings(&menu.parent);
let last = rows.len().saturating_sub(1);
match key {
"down" | "j" => {
self.set_highlight((menu.highlighted + 1).min(last));
}
"up" | "k" => {
self.set_highlight(menu.highlighted.saturating_sub(1));
}
"home" => self.set_highlight(0),
"end" => self.set_highlight(last),
"enter" | "space" | "right" | "l" => {
if let Some(row) = rows.get(menu.highlighted) {
self.choose_sibling(&menu.parent, row.index, cx);
}
}
"escape" | "left" | "h" => self.crumb_menu = None,
_ => {
self.crumb_menu = None;
cx.notify();
return false;
}
}
cx.notify();
true
}
const fn set_highlight(&mut self, row: usize) {
if let Some(menu) = &mut self.crumb_menu {
menu.highlighted = row;
}
}
/// Descend into the selected tile, or into the largest child of the
/// current root when nothing is selected.
pub fn descend(&mut self, cx: &mut Context<'_, Self>) {
let target = match self.selected.clone() {
// Enter what is selected, however deep: a directory opens itself,
// a file opens the directory holding it.
Some(selected) if selected.len() > self.crumbs.len() => {
if self.node_at(&selected).is_some_and(Node::is_dir) {
selected
} else {
selected[..selected.len() - 1].to_vec()
}
}
// Nothing below the root is selected: the largest entry.
_ => match self.current().and_then(Node::largest_child) {
Some(index) => {
let mut crumbs = self.crumbs.clone();
crumbs.push(index);
crumbs
}
None => return,
},
};
let from = self.tile_body(&target).map(|rect| self.view.project(rect));
self.enter(target, from, cx);
}
/// Go inside one child of the current root, so that it fills the viewport.
///
/// `from` is where the child was on screen, when the caller knows it.
/// Make `target` — any directory below the current root — the root.
///
/// `from` is where that directory's contents were on screen, so the
/// transition grows them from exactly there into the full viewport.
fn enter(
&mut self,
target: Vec<usize>,
from: Option<Rect>,
cx: &mut Context<'_, Self>,
) {
if target.len() <= self.crumbs.len()
|| !target.starts_with(&self.crumbs)
{
return;
}
let Some(node) = self.node_at(&target) else {
return;
};
if !node.is_dir() || node.children.is_empty() {
return;
}
self.remember();
self.selected = Some(target.clone());
self.crumbs = target;
self.forget_hover();
self.cache = None;
let area = self.treemap_size.get();
let src = from.unwrap_or_else(|| self.view.visible_base(area));
self.view = View::IDENTITY;
let dst = Rect::new(
0.0,
0.0,
area.width.as_f32().max(1.0),
area.height.as_f32().max(1.0),
);
self.transition = Some(LayoutTransition::new(src, dst));
cx.notify();
}
/// Where a drawn directory's contents sit: its tile below the name band.
/// This, not the whole tile, is the region its children occupy, so it is
/// what a transition into or out of it has to map.
pub fn tile_body(&mut self, crumbs: &[usize]) -> Option<Rect> {
let tile =
self.layout()?.iter().find(|tile| tile.crumbs() == crumbs)?;
Some(match tile.header {
Some(header) => Rect::new(
tile.rect.x,
header.bottom(),
tile.rect.w,
tile.rect.bottom() - header.bottom(),
),
None => tile.rect,
})
}
/// The deepest drawn directory under a viewport point that has contents
/// to show: what zooming at that point is zooming into.
fn zoom_target(&mut self, x: f32, y: f32) -> Option<Vec<usize>> {
let hovered = self.tile_at(x, y)?;
let root = self.crumbs.len();
(root + 1..=hovered.len())
.rev()
.map(|length| hovered[..length].to_vec())
.find(|crumbs| {
self.node_at(crumbs).is_some_and(|node| {
node.is_dir() && !node.children.is_empty()
}) && self.tile_body(crumbs).is_some()
})
}
/// Ascend to the parent directory, keeping the directory we came from in
/// view so the motion reads as zooming out.
pub fn ascend(&mut self, cx: &mut Context<'_, Self>) {
if let Some(parent_crumbs) = self.parent_crumbs() {
self.ascend_to(parent_crumbs, cx);
}
}
/// Make `ancestor`, a directory above the current root, the root.
///
/// The directory we leave shrinks back into its tile when that tile is
/// drawn at the new level; from further up it is too small to track, and
/// the new level simply lands.
fn ascend_to(&mut self, ancestor: Vec<usize>, cx: &mut Context<'_, Self>) {
self.remember();
// The region we are looking at now, and where it sits in the layout
// we are going back to.
let area = self.treemap_size.get();
let child_crumbs = self.crumbs.clone();
let src = self.view.visible_base(area);
self.crumbs.clone_from(&ancestor);
self.forget_hover();
self.cache = None;
self.selected = Some(ancestor);
self.view = View::IDENTITY;
self.transition = self
.tile_body(&child_crumbs)
.filter(|rect| rect.w > 1.0 && rect.h > 1.0)
.map(|dst| LayoutTransition::new(src, dst));
cx.notify();
}
/// The crumbs of the parent of the current root, if any.
pub fn parent_crumbs(&self) -> Option<Vec<usize>> {
if self.crumbs.is_empty() {
None
} else {
Some(self.crumbs[..self.crumbs.len() - 1].to_vec())
}
}
/// Jump straight to a crumb from the breadcrumb bar.
///
/// A jump can skip several levels, so there is no single region to move:
/// it lands immediately, the way selecting a folder does.
pub fn go_to(&mut self, crumbs: Vec<usize>, cx: &mut Context<'_, Self>) {
self.crumb_menu = None;
// A reveal in the directory on screen goes nowhere.
if crumbs != self.crumbs {
self.remember();
}
self.crumbs.clone_from(&crumbs);
self.selected = Some(crumbs);
self.forget_hover();
self.view = View::IDENTITY;
self.transition = None;
self.cache = None;
// Entering a directory while a background SWR refresh is running
// prioritizes that subtree first.
match &self.active_scan {
Some(ActiveScan::Local { handle, .. }) => {
let target = self.current_path();
handle.prioritize(&target);
}
Some(ActiveScan::Remote { handle, .. }) => {
let target = self.current_path();
handle.prioritize(&target);
}
None => {}
}
cx.notify();
}
/// Note the directory on screen as one to come back to, before leaving
/// it. A new departure ends whatever was ahead, as in a browser.
fn remember(&mut self) {
if self.tree.is_none() {
return;
}
let here = self.current_path();
if self.history.back.last() != Some(&here) {
self.history.back.push(here);
}
if self.history.back.len() > HISTORY_DEPTH {
self.history.back.remove(0);
}
self.history.forward.clear();
}
/// Drop what a new tree no longer holds: a removed directory, or one
/// outside a new root. What is left always resolves, so `<` and `>` are
/// enabled exactly when they would go somewhere.
fn prune_history(&mut self) {
let mut history = std::mem::take(&mut self.history);
history
.back
.retain(|path| self.crumbs_for_path(path).is_some());
history
.forward
.retain(|path| self.crumbs_for_path(path).is_some());
self.history = history;
}
/// Whether `<` would go anywhere: what drives its button's disabled state.
pub fn can_go_back(&self) -> bool {
self.history_target(true).is_some()
}
/// Whether `>` would go anywhere.
pub fn can_go_forward(&self) -> bool {
self.history_target(false).is_some()
}
/// `<`: the directory on screen before this one.
pub fn go_back(&mut self, cx: &mut Context<'_, Self>) {
self.step_history(true, cx);
}
/// `>`: undo a `<`.
pub fn go_forward(&mut self, cx: &mut Context<'_, Self>) {
self.step_history(false, cx);
}
/// Where `<` (or `>`) would go, and its place on that stack: the newest
/// entry that is somewhere else. An entry can be where we already are,
/// after a widening that was superseded; it is skipped rather than spend
/// a click on nothing. Every other entry resolves, being pruned whenever
/// a tree lands.
pub fn history_target(&self, back: bool) -> Option<(usize, Vec<usize>)> {
self.tree.as_ref()?;
let stack = if back {
&self.history.back
} else {
&self.history.forward
};
stack.iter().enumerate().rev().find_map(|(at, path)| {
self.crumbs_for_path(path)
.filter(|crumbs| *crumbs != self.crumbs)
.map(|crumbs| (at, crumbs))
})
}
fn step_history(&mut self, back: bool, cx: &mut Context<'_, Self>) {
let Some((at, target)) = self.history_target(back) else {
return;
};
let here = self.current_path();
let mut history = std::mem::take(&mut self.history);
let (from, to) = if back {
(&mut history.back, &mut history.forward)
} else {
(&mut history.forward, &mut history.back)
};
from.truncate(at);
to.push(here);
// The move is an ordinary one, animation and all; it records itself
// like any other, so the stacks are put back afterwards.
self.travel(target, cx);
self.history = history;
cx.notify();
}
/// Go to `target` with the motion that fits: grow into a directory
/// below, shrink back out to one above, or land on one beside.
fn travel(&mut self, target: Vec<usize>, cx: &mut Context<'_, Self>) {
let enterable = self
.node_at(&target)
.is_some_and(|node| node.is_dir() && !node.children.is_empty());
if target.len() > self.crumbs.len()
&& target.starts_with(&self.crumbs)
&& enterable
{
let from =
self.tile_body(&target).map(|rect| self.view.project(rect));
self.enter(target, from, cx);
} else if target.len() < self.crumbs.len()
&& self.crumbs.starts_with(&target)
{
self.ascend_to(target, cx);
} else {
self.go_to(target, cx);
}
}
/// 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,
crumbs: Option<Vec<usize>>,
cx: &mut Context<'_, Self>,
) {
self.selected = crumbs;
cx.notify();
}
/// Move the selection geometrically, falling back to the parent at an edge.
/// The tile a key acts on: under the pointer if the pointer moved last,
/// otherwise the keyboard selection.
pub fn action_target(&self) -> Option<Vec<usize>> {
if self.pointer_active {
self.hovered.clone().or_else(|| self.selected.clone())
} else {
self.selected.clone()
}
}
/// Make the pointed-at tile the selection before a key acts, so marking,
/// opening and arrow movement all start from what the user is looking at.
fn adopt_pointer_target(&mut self) {
if self.pointer_active
&& let Some(hovered) = self.hovered.clone()
{
self.selected = Some(hovered);
}
}
/// After the layout changes under a still pointer, its hover is stale
/// until the pointer moves again.
fn forget_hover(&mut self) {
self.hovered = None;
self.pointer_active = false;
}
pub fn move_selection(
&mut self,
direction: Direction,
cx: &mut Context<'_, Self>,
) {
self.pointer_active = false;
let area = self.treemap_size.get();
let _ = area;
let Some(tiles) = self.layout().map(<[Tile]>::to_vec) else {
return;
};
let Some(current) = self.selected.clone() else {
if let Some(first) = tiles.first() {
let crumbs = first.crumbs().to_vec();
self.select(Some(crumbs), cx);
}
return;
};
let Some(from) = tiles
.iter()
.find(|tile| tile.crumbs() == current.as_slice())
.map(|tile| self.view.project(tile.rect))
else {
return;
};
// Same-depth neighbours only: stepping into a child by arrow key would
// make the depth of the selection impossible to predict.
let depth = current.len();
let mut best: Option<(f32, Vec<usize>)> = None;
for tile in &tiles {
let crumbs = tile.crumbs();
if crumbs.len() != depth || crumbs == current.as_slice() {
continue;
}
let rect = self.view.project(tile.rect);
let Some(gap) = direction.gap(&from, &rect) else {
continue;
};
let offset = direction.offset(&from, &rect);
let score = offset.mul_add(2.5, gap);
if best.as_ref().is_none_or(|(existing, _)| score < *existing) {
best = Some((score, crumbs.to_vec()));
}
}
if let Some((_, crumbs)) = best {
self.select(Some(crumbs), cx);
} else if direction.is_backwards()
&& let Some(parent) = self.parent_crumbs()
{
self.select(Some(parent), cx);
}
}
/// Select the next sibling by rank, which is next-largest by the active
/// metric. Scanning a directory for space is exactly this walk.
pub fn cycle_sibling(&mut self, step: isize, cx: &mut Context<'_, Self>) {
self.pointer_active = false;
let siblings = self.ranked_siblings();
if siblings.is_empty() {
return;
}
let current = self.selected.as_ref().and_then(|selected| {
siblings
.iter()
.position(|crumbs| crumbs.as_slice() == selected.as_slice())
});
let next = match current {
Some(index) => {
let len = siblings.len().cast_signed();
(((index.cast_signed() + step) % len + len) % len) as usize
}
None if step >= 0 => 0,
None => siblings.len() - 1,
};
self.select(Some(siblings[next].clone()), cx);
}
fn ranked_siblings(&self) -> Vec<Vec<usize>> {
let parent = self.selected.as_ref().map_or_else(
|| self.crumbs.clone(),
|selected| {
if selected.len() <= self.crumbs.len() {
self.crumbs.clone()
} else {
selected[..selected.len() - 1].to_vec()
}
},
);
let Some(node) = self.node_at(&parent) else {
return Vec::new();
};
(0..node.children.len())
.map(|index| {
let mut crumbs = parent.clone();
crumbs.push(index);
crumbs
})
.collect()
}
/// Mark or unmark the current selection.
pub fn toggle_mark_selected(&mut self, cx: &mut Context<'_, Self>) {
let Some(crumbs) = self.selected.clone() else {
return;
};
if crumbs.is_empty() {
self.notice = Some((
"the scanned root cannot be removed; open a directory first"
.into(),
Status::Warning,
));
cx.notify();
return;
}
self.toggle_mark(&crumbs, cx);
}
/// Mark or unmark the node at `crumbs`.
///
/// A mark covers everything beneath it, since removing a directory takes
/// its contents with it: marking a directory absorbs the marks already
/// inside it, and a path inside a marked directory cannot be marked or
/// kept on its own — it says which mark it goes with instead.
pub fn toggle_mark(
&mut self,
crumbs: &[usize],
cx: &mut Context<'_, Self>,
) {
let Some(target) = self.target_at(crumbs) else {
return;
};
self.notice = None;
if !self.marks.contains(&target.path)
&& let Some(ancestor) = self.marked_ancestor(&target.path)
{
self.notice = Some((
format!(
"{} goes with the marked {}; unmark that to keep it",
self.display_path(&target.path),
self.display_path(&ancestor)
),
Status::Warning,
));
cx.notify();
return;
}
let path = target.path.clone();
let style = self.path_style();
if self.marks.toggle(target) {
self.space_baseline = self.space_baseline.or(self.space);
let inside: Vec<PathBuf> = self
.marks
.items()
.iter()
.filter(|item| style.is_below(&item.path, &path))
.map(|item| item.path.clone())
.collect();
for inner in &inside {
self.marks.remove(inner);
}
if !inside.is_empty() {
self.notice = Some((
format!(
"{} now covers {} mark{} inside it",
self.display_path(&path),
inside.len(),
if inside.len() == 1 { "" } else { "s" }
),
Status::Neutral,
));
}
}
cx.notify();
}
/// The marked directory `path` is inside, if any; never `path` itself.
pub fn marked_ancestor(&self, path: &Path) -> Option<PathBuf> {
self.marks
.items()
.iter()
.filter(|item| self.path_style().is_below(path, &item.path))
.map(|item| item.path.clone())
.min_by_key(|ancestor| ancestor.as_os_str().len())
}
pub fn target_at(&self, crumbs: &[usize]) -> Option<Target> {
let node = self.node_at(crumbs)?;
let path = self.path_at(crumbs)?;
Some(Target {
hidden: is_hidden(&path, self.path_style()),
path,
bytes: node.bytes,
is_dir: node.is_dir(),
})
}
pub fn unmark(&mut self, path: &Path, cx: &mut Context<'_, Self>) {
self.marks.remove(path);
cx.notify();
}
pub fn clear_marks(&mut self, cx: &mut Context<'_, Self>) {
self.marks.clear();
self.notice = None;
cx.notify();
}
/// The plan the review screen shows and the removal runs.
pub fn plan(&self) -> Plan {
if self.remote.is_some() {
// Never judge remote paths against this machine's filesystem.
// This is an export selection, not an executable removal plan.
let mut selection = Plan::default();
selection.targets = self
.marks
.items()
.iter()
.filter(|target| {
self.path_style().is_below(&target.path, &self.root_path)
})
.cloned()
.collect();
selection.root.clone_from(&self.root_path);
// Remote volume attribution is unknown; never infer it from
// this computer's mounts or project an unmeasured saving.
return selection;
}
plan(self.marks.items(), &self.root_path)
}
// ── layout and hit-testing ──────────────────────────────────────────
/// When a background refresh is running, returns `Some(forced)`:
/// `true` for an explicit `r` / Refresh button rescan, `false` for SWR.
pub const fn refresh_mode(&self) -> Option<bool> {
match &self.active_scan {
Some(
ActiveScan::Local {
intent: ScanIntent::Refresh { forced, .. },
..
}
| ActiveScan::Remote {
intent: ScanIntent::Refresh { forced, .. },
..
},
) => Some(*forced),
_ => None,
}
}
/// Freshness / refresh-queue state of the tile at `crumbs`.
pub fn tile_freshness(
&self,
crumbs: &[usize],
) -> crate::treemap_view::TileFreshness {
self.tile_freshness_at(
crumbs,
disktree_scanner::unix_now(),
self.refresh_mode(),
)
}
fn tile_freshness_at(
&self,
crumbs: &[usize],
now_unix: u64,
refresh_mode: Option<bool>,
) -> crate::treemap_view::TileFreshness {
use crate::treemap_view::TileFreshness;
let ttl = DEFAULT_CACHE_TTL.as_secs();
if let Some(forced) = refresh_mode {
let Some(path) = self.path_at(crumbs) else {
return TileFreshness::Fresh;
};
let is_updating = self
.updating_paths
.iter()
.any(|u| path.starts_with(u) || u.starts_with(&path))
|| self.active_scan_path.as_ref().is_some_and(|active| {
active.starts_with(&path) || path.starts_with(active)
});
if is_updating {
return TileFreshness::Updating;
}
if self.refreshed_paths.iter().any(|r| path.starts_with(r)) {
return TileFreshness::Fresh;
}
if forced || self.arena_path_is_stale(&path, now_unix, ttl) {
return TileFreshness::Scheduled;
}
return TileFreshness::Fresh;
}
// Fast path: a freshly completed live scan is within TTL everywhere.
if let Some(Freshness::Live { scanned_at }) = self.freshness
&& now_unix.saturating_sub(scanned_at) <= ttl
{
return TileFreshness::Fresh;
}
let Some(path) = self.path_at(crumbs) else {
return TileFreshness::Fresh;
};
if self.arena_path_is_stale(&path, now_unix, ttl) {
TileFreshness::Stale
} else {
TileFreshness::Fresh
}
}
/// Whether the directory at (or holding) `path` in `self.arena` is stale
/// relative to `now_unix` and `ttl`.
fn arena_path_is_stale(
&self,
path: &Path,
now_unix: u64,
ttl: u64,
) -> bool {
let Some(arena) = &self.arena else {
return false;
};
let root = arena.root_path();
let Ok(rel) = path.strip_prefix(root) else {
return false;
};
let parts: Vec<String> = rel
.components()
.map(|c| c.as_os_str().to_string_lossy().into_owned())
.collect();
let Some(mut id) =
arena.find_relative(parts.iter().map(String::as_str))
else {
return false;
};
// A leaf inherits its containing directory's freshness.
if !arena.node(id).is_dir()
&& let Some(parent) = arena.node(id).parent
{
id = parent;
}
let node = arena.node(id);
match node.status() {
SubtreeStatus::Stale { .. } | SubtreeStatus::Unscanned => true,
SubtreeStatus::Fresh { scanned_at } => {
scanned_at > 0 && now_unix.saturating_sub(scanned_at) > ttl
}
SubtreeStatus::Updating { .. } => false,
}
}
/// Resolve everything the mosaic needs for this frame.
///
/// Runs once per render, before the paint callbacks: painting then only has
/// to draw, and the marked/hidden/selected state of every tile is decided
/// here, where the tree and the marks are both at hand.
pub fn prepare(&mut self) -> Mosaic {
let metric = self.options.metric;
let view = self.view;
let hovered = self.hovered.clone();
let selected = self.selected.clone();
// Marks are paths; the mosaic thinks in crumbs.
let marked = self.marked_crumbs();
// Bring the cache up to date, then take it out for the pass and put
// it back after: the tiles are read beside the tree and the marks,
// and copying thousands of them, crumbs and all, ran on every
// pointer move.
let cache = if self.layout().is_some() {
self.cache.take()
} else {
None
};
let Some(cache) = cache else {
return Mosaic {
view,
..Mosaic::default()
};
};
let tiles = &cache.tiles;
// 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 now_unix = disktree_scanner::unix_now();
let refresh_mode = self.refresh_mode();
let mut decorations = Vec::with_capacity(tiles.len());
let mut slots: Vec<LabelSlot<'_>> = Vec::new();
let now_instant = Instant::now();
let current_area = self.treemap_size.get();
let viewport_resized = current_area != self.last_treemap_size;
self.last_treemap_size = current_area;
if viewport_resized || self.transition.is_some() {
self.tile_rects.clear();
}
let mut tile_fades = std::mem::take(&mut self.tile_fades);
let mut tile_rects = std::mem::take(&mut self.tile_rects);
let mut visible_fade_keys = FxHashSet::default();
for tile in tiles {
let crumbs = tile.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 filtered = match self.find.matches().map(|m| m.keep(crumbs)) {
None | Some(Some(Keep::Whole)) => Filtered::Shown,
Some(Some(Keep::Partial { .. })) => Filtered::Holds,
Some(None) => Filtered::Out,
};
let freshness =
self.tile_freshness_at(crumbs, now_unix, refresh_mode);
let target_fade = freshness.fade_amount();
let node_path = match &tile.kind {
TileKind::Node { crumbs } => self.path_at(crumbs),
TileKind::Others { .. } => None,
};
let freshness_fade = if let Some(path) = &node_path {
visible_fade_keys.insert(path.clone());
sample_tile_fade(
&mut tile_fades,
path.clone(),
target_fade,
now_instant,
)
} else {
target_fade
};
let is_marked = marked.contains(crumbs);
// Everything inside a marked directory goes with it, so it is
// drawn marked too.
let is_covered = !marked.is_empty()
&& (1..crumbs.len())
.any(|length| marked.contains(&crumbs[..length]));
let rect = if self.transition.is_some() {
self.animated_rect(tile.rect)
} else if let Some(path) = node_path {
sample_tile_rect(&mut tile_rects, path, tile.rect, now_instant)
} else {
tile.rect
};
decorations.push(TileDeco {
rect,
depth: tile.depth,
category,
age_bucket,
reclaimable: node.is_some_and(|n| n.reclaim.is_some()),
filtered,
freshness,
freshness_fade,
unreadable: node.is_some_and(|n| n.read_error),
marked: is_marked,
covered: is_covered,
hovered: hovered.as_deref() == Some(crumbs),
selected: selected.as_deref() == Some(crumbs),
});
// Labels are chosen in screen space: zooming in makes room for more
// of them, which is the point of zooming in.
let header = tile.header.map(|header| {
if self.transition.is_some() {
self.animated_rect(header)
} else {
Rect::new(
rect.x + (header.x - tile.rect.x),
rect.y + (header.y - tile.rect.y),
rect.w.min(header.w),
rect.h.min(header.h),
)
}
});
let screen = view.project(header.unwrap_or(rect));
if screen.w < LABEL_MIN_W_REMS * self.rem
|| screen.h < LABEL_MIN_H_REMS * self.rem
{
continue;
}
let (others, dim) = match &tile.kind {
TileKind::Node { .. } => {
if node.is_none() {
continue;
}
(0, filtered == Filtered::Out)
}
TileKind::Others { count, .. } => {
(*count, self.find.matches().is_some())
}
};
slots.push(LabelSlot {
node,
others,
rect,
header,
depth: tile.depth,
dim,
// The merged tail is never marked: its crumbs are its
// parent's, and a mark there is drawn on the parent.
marked: node.is_some() && (is_marked || is_covered),
});
}
tile_fades.retain(|path, fade| {
visible_fade_keys.contains(path) || fade.is_running(now_instant)
});
tile_rects.retain(|path, anim| {
visible_fade_keys.contains(path) || anim.is_running(now_instant)
});
drop(visible_fade_keys);
slots.sort_by(|left, right| {
let left_area = left.rect.w * left.rect.h;
let right_area = right.rect.w * right.rect.h;
right_area.total_cmp(&left_area)
});
slots.truncate(MAX_LABELS);
// Text only for the labels that will be shaped: a deep view has
// thousands of tiles big enough for one, and a name and a size
// formatted for each was thrown away for all but `MAX_LABELS`.
let labels = slots
.into_iter()
.map(|slot| Label {
text: slot.node.map_or_else(
|| format!("+{} more", slot.others),
|node| node.name.to_string(),
),
rect: slot.rect,
header: slot.header,
depth: slot.depth,
dim: slot.dim,
marked: slot.marked,
size_text: slot.node.map_or_else(String::new, |node| {
crate::widgets::short_value(node, metric)
}),
})
.collect();
self.cache = Some(cache);
self.tile_fades = tile_fades;
self.tile_rects = tile_rects;
Mosaic {
tiles: decorations,
labels,
view,
}
}
/// The marks as crumbs. Resolved when the marks or the tree change
/// rather than on every frame: each mark is a walk down the tree with
/// a search through a directory's entries at every level, and a frame
/// is drawn for every pointer move.
fn marked_crumbs(&mut self) -> Rc<FxHashSet<Vec<usize>>> {
let generation = self.marks.generation();
let tree = self.tree.as_ref().map(Arc::as_ptr);
if let Some(marked) = &self.marked
&& marked.generation == generation
&& marked.tree == tree
{
return Rc::clone(&marked.crumbs);
}
let crumbs: Rc<FxHashSet<Vec<usize>>> = Rc::new(
self.marks
.items()
.iter()
.filter_map(|item| self.crumbs_for_path(&item.path))
.collect(),
);
self.marked = Some(MarkedCrumbs {
generation,
tree,
crumbs: Rc::clone(&crumbs),
});
crumbs
}
/// Crumbs for an absolute path, if the tree still contains it.
#[allow(
clippy::unnecessary_wraps,
reason = "a marked path may have been removed from the tree already"
)]
pub fn crumbs_for_path(&self, path: &Path) -> Option<Vec<usize>> {
// The path is relative to the scanned root, so the walk starts there,
// not at the directory currently drawn.
// Names are split by the scanned machine's rules, so a Unix host's
// `a\b` stays one name on a Windows client.
let relative = self.path_style().relative(&self.root_path, path)?;
let tree = self.tree.clone()?;
let mut node: &Node = &tree;
let mut crumbs = Vec::new();
for name in relative {
let index = node
.children
.iter()
.position(|child| child.name.as_ref() == name)?;
crumbs.push(index);
node = node.child(index)?;
}
Some(crumbs)
}
/// 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;
// A filter is about the directory it was typed in: above it, it
// would hide everything beside that directory, so it lapses.
if self
.find
.matches()
.is_some_and(|matches| !self.crumbs.starts_with(&matches.base))
{
self.clear_filter();
}
let area = self.treemap_size.get();
let key = LayoutKey {
crumbs: self.crumbs.clone(),
width: area.width.as_f32().round(),
height: area.height.as_f32().round(),
options: self.layout_options.clone(),
filter: self.filter_epoch,
};
if key.width < 1.0 || key.height < 1.0 {
return None;
}
let stale = self.cache.as_ref().is_none_or(|cache| cache.key != key);
if stale {
let tree = self.tree.clone()?;
let node = tree.resolve(&self.crumbs)?;
let rect = Rect::new(0.0, 0.0, key.width, key.height);
let filter = self.find.matches().filter(|_| self.find.is_applied());
let tiles = layout_filtered(
node,
&key.crumbs,
rect,
self.options.metric,
&key.options,
filter,
);
self.cache = Some(LayoutCache { key, tiles });
}
self.cache.as_ref().map(|cache| cache.tiles.as_slice())
}
/// Base-space rect of the tile at `crumbs`, if it is currently drawn.
#[cfg(test)]
pub fn tile_rect(&mut self, crumbs: &[usize]) -> Option<Rect> {
self.layout()?
.iter()
.find(|tile| tile.crumbs() == crumbs)
.map(|tile| tile.rect)
}
/// The deepest tile under a viewport point.
pub fn tile_at(&mut self, x: f32, y: f32) -> Option<Vec<usize>> {
let (base_x, base_y) = self.view.unproject(x, y);
let tiles = self.layout()?;
hit(tiles, base_x, base_y).map(|tile| tile.crumbs().to_vec())
}
// ── view ────────────────────────────────────────────────────────────
/// Zoom toward a point.
///
/// When `descend` is set the wheel stops magnifying at the point where the
/// directory under the pointer exactly fits the viewport, and the next
/// notch goes inside it. That ceiling is what keeps the two gestures
/// continuous: at the moment the level changes, the tiles inside the
/// directory are already as large as they will be, so entering makes them
/// grow rather than shrink.
pub fn zoom_at(
&mut self,
x: f32,
y: f32,
factor: f32,
descend: bool,
cx: &mut Context<'_, Self>,
) {
let area = self.treemap_size.get();
// At the bottom of the zoom, zooming out goes up a level.
if factor < 1.0 && self.view.scale <= View::MIN_SCALE + f32::EPSILON {
if descend {
self.ascend(cx);
}
return;
}
// One directory decides both how far the wheel magnifies and where it
// then goes: the deepest one under the pointer. At the ceiling its
// contents fill the view, so going inside continues the same motion.
let target = if descend {
self.zoom_target(x, y)
} else {
None
};
let body = target.as_ref().and_then(|crumbs| self.tile_body(crumbs));
let ceiling = body
.map_or(View::MAX_SCALE, |rect| View::fit_scale(rect, area))
.clamp(View::MIN_SCALE, View::MAX_SCALE);
if factor > 1.0
&& self.view.scale >= ceiling - f32::EPSILON
&& let Some(target) = target
{
let from = body.map(|rect| self.view.project(rect));
self.enter(target, from, cx);
return;
}
self.view = self.view.zoomed_at(x, y, factor, ceiling).clamped(area);
cx.notify();
}
pub fn reset_view(&mut self, cx: &mut Context<'_, Self>) {
self.view = View::default();
cx.notify();
}
/// Change how many levels are drawn, which is the other meaning of zoom in
/// a treemap: seeing further in without changing what is on screen.
pub fn adjust_depth(&mut self, step: i32, cx: &mut Context<'_, Self>) {
let depth = (self.layout_options.max_depth.cast_signed() + step)
.clamp(1, 6) as u32;
self.layout_options.max_depth = depth;
self.cache = None;
cx.notify();
}
pub fn toggle_metric(&mut self, cx: &mut Context<'_, Self>) {
// Children are ordered by the metric, so every crumb moves. Keep the
// paths and find them again in the reordered tree.
let directory = self.current_path();
let selected = self.selected.as_deref().and_then(|c| self.path_at(c));
self.options.metric = self.options.metric.toggled();
let style = self.path_style();
if let Some(tree) = &mut self.tree {
// Re-ranked in place: copying a disk's millions of nodes took
// seconds and held two trees at once. Only a search or a
// widening scan still reading the tree makes this a copy, and
// then whichever of them finishes last frees the old one.
disktree_core::tree::aggregate(
Arc::make_mut(tree),
self.options.metric,
);
}
if let Some(tree) = &self.tree {
self.marks.refresh(
&self.root_path,
tree,
self.options.metric,
style,
);
}
self.crumbs = self.crumbs_for_path(&directory).unwrap_or_default();
self.selected = selected.and_then(|path| self.crumbs_for_path(&path));
self.forget_hover();
self.crumb_menu = None;
self.transition = None;
self.refresh_insights();
self.clear_filter();
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
/// a permanent deletion, which cannot be undone.
pub fn commit(&mut self, cx: &mut Context<'_, Self>) {
if self.remote.is_some() || self.plan().is_empty() {
return;
}
match self.removal_mode {
RemovalMode::Trash => self.begin_removal(cx),
RemovalMode::Permanent => {
self.confirm_open = true;
self.focus_request = Some(FocusTarget::Dialog);
cx.notify();
}
}
}
/// The alert dialog's `Delete`.
pub fn confirm_delete(&mut self, cx: &mut Context<'_, Self>) {
self.confirm_open = false;
self.focus_request = Some(FocusTarget::Root);
self.begin_removal(cx);
}
/// The alert dialog's `Cancel`, or Escape.
pub fn cancel_delete(&mut self, cx: &mut Context<'_, Self>) {
self.confirm_open = false;
self.focus_request = Some(FocusTarget::Root);
cx.notify();
}
/// Move focus if something asked for it. Called wherever a window is in
/// hand: the key listener and the click listeners.
pub fn apply_focus(
&mut self,
window: &mut Window,
cx: &mut Context<'_, Self>,
) {
match self.focus_request.take() {
Some(FocusTarget::Root) => window.focus(&self.focus, cx),
Some(FocusTarget::Dialog) => window.focus(&self.confirm_focus, cx),
None => {}
}
}
/// `ctrl =`, `ctrl -` and `ctrl 0`: interface zoom. Changes the window's
/// `rem`, which every size in this app is expressed in, so hierarchy and
/// spacing keep their proportions at every step.
pub fn zoom_interface(
&mut self,
event: &KeyDownEvent,
window: &mut Window,
) -> bool {
let keystroke = &event.keystroke;
if !(keystroke.modifiers.control || keystroke.modifiers.platform) {
return false;
}
let steps = crate::ui::ZOOM_STEPS;
let current = window.rem_size().as_f32() / crate::ui::BASE_REM;
let index = steps
.iter()
.position(|step| (step - current).abs() < 0.01)
.unwrap_or(2);
let next = match keystroke.key.as_str() {
"=" | "+" => (index + 1).min(steps.len() - 1),
"-" => index.saturating_sub(1),
"0" => 2,
_ => return false,
};
window.set_rem_size(px(crate::ui::BASE_REM * steps[next]));
self.cache = None;
true
}
pub fn begin_removal(&mut self, cx: &mut Context<'_, Self>) {
if self.remote.is_some() {
return;
}
let plan = self.plan();
if plan.is_empty() {
self.notice = Some(("nothing is marked".into(), Status::Warning));
cx.notify();
return;
}
// This window quits once the prompt is answered yes, and quitting
// would stop a permanent delete halfway.
if self.restarting {
self.notice = Some((
"not while restarting as administrator".into(),
Status::Warning,
));
cx.notify();
return;
}
self.space_baseline = self.space.or(self.space_baseline);
self.run_epoch += 1;
let epoch = self.run_epoch;
self.run_summary = RunSummary {
total: plan.targets.len(),
..RunSummary::default()
};
self.run_log.clear();
self.screen = Screen::Running;
self.run = Some(disktree_core::removal::spawn(plan, self.removal_mode));
Self::poll_removal(epoch, cx);
cx.notify();
}
fn poll_removal(epoch: u64, cx: &Context<'_, Self>) {
cx.spawn(async move |this, cx| {
loop {
cx.background_executor()
.timer(Duration::from_millis(60))
.await;
let keep_going = this
.update(cx, |this, cx| this.poll_removal_once(epoch, cx))
.unwrap_or(false);
if !keep_going {
break;
}
}
})
.detach();
}
/// Drain the removal channel once. Returns whether the run should keep
/// being polled. Driven by the poll task above, and by the tests, which
/// cannot wait on the test clock while a real worker thread runs.
pub(crate) fn poll_removal_once(
&mut self,
epoch: u64,
cx: &mut Context<'_, Self>,
) -> bool {
if epoch != self.run_epoch {
return false;
}
let Some(run) = &self.run else {
return false;
};
let mut finished = false;
while let Some(event) = run.poll() {
match event {
RemovalEvent::Start { total } => self.run_summary.total = total,
RemovalEvent::Item {
path,
bytes,
outcome,
} => {
if outcome.is_ok() {
self.run_summary.removed += 1;
self.run_summary.bytes =
self.run_summary.bytes.saturating_add(bytes);
} else {
self.run_summary.failed += 1;
}
self.run_log.push((path, outcome));
}
RemovalEvent::Done {
removed,
bytes,
failed,
} => {
self.run_summary.removed = removed;
self.run_summary.bytes = bytes;
self.run_summary.failed = failed;
finished = true;
}
}
}
if finished {
self.run = None;
self.marks.clear();
self.screen = Screen::Done;
// Invalidate every removed path in the cache DB so the follow-up
// scan refreshes them immediately while keeping untouched siblings
// fast.
let removed: Vec<PathBuf> = self
.run_log
.iter()
.filter(|(_, outcome)| outcome.is_ok())
.map(|(path, _)| path.clone())
.collect();
if !removed.is_empty() {
let _ = self
.scanner
.invalidate(&disktree_scanner::HostKey::Local, &removed);
}
// The tree on screen is now wrong; start over rather than leaving
// numbers that include what was just removed.
self.start_scan(cx);
}
cx.notify();
!finished
}
/// Drive the pure [`find_machine`] and execute any emitted effects.
fn step_find(
&mut self,
event: find_machine::Event,
cx: &mut Context<'_, Self>,
) {
let state = std::mem::take(&mut self.find);
let (next, effects) = find_machine::step(state, event);
self.find = next;
for effect in effects {
self.perform_find(effect, cx);
}
}
fn perform_find(
&mut self,
effect: find_machine::Effect,
cx: &mut Context<'_, Self>,
) {
match effect {
find_machine::Effect::StartSearch { epoch, query } => {
let Some(tree) = self.tree.clone() else {
self.step_find(
find_machine::Event::SearchFinished {
epoch,
found: None,
},
cx,
);
return;
};
let base = self.crumbs.clone();
let task = cx.background_executor().spawn(async move {
tree.resolve(&base)
.and_then(|node| filter(node, &base, &query))
});
cx.spawn(async move |this, cx| {
let found = task.await;
let _ = this.update(cx, |this, cx| {
this.step_find(
find_machine::Event::SearchFinished {
epoch,
found: found.map(Arc::new),
},
cx,
);
cx.notify();
});
})
.detach();
}
find_machine::Effect::SelectBestMatch(matches) => {
self.view = View::IDENTITY;
self.transition = None;
self.forget_hover();
self.pointer_active = false;
let tree = self.tree.clone();
self.selected = matches
.keep
.iter()
.filter(|(_, keep)| **keep == Keep::Whole)
.filter_map(|(crumbs, _)| {
let node = tree.as_deref()?.resolve(crumbs)?;
Some((node.bytes, crumbs))
})
.max_by_key(|(bytes, _)| *bytes)
.map(|(_, crumbs)| crumbs.clone());
}
find_machine::Effect::WarnNoMatches(needle) => {
self.notice = Some((
format!("nothing here matches {needle}"),
Status::Warning,
));
}
find_machine::Effect::ClearNotice => {
self.notice = None;
}
find_machine::Effect::InvalidateLayout => {
self.filter_epoch += 1;
}
}
}
/// Drop the find text and the filter with it.
pub fn clear_filter(&mut self) {
let state = std::mem::take(&mut self.find);
let (next, effects) =
find_machine::step(state, find_machine::Event::Clear);
self.find = next;
for effect in effects {
if matches!(effect, find_machine::Effect::InvalidateLayout) {
self.filter_epoch += 1;
}
}
}
// ── input ───────────────────────────────────────────────────────────
/// Handle a key press.
pub fn on_key_down(
&mut self,
event: &KeyDownEvent,
cx: &mut Context<'_, Self>,
) {
self.dispatch_key(event, cx);
}
/// Whether a menu command may replace the tree: where `r` would, not
/// behind the confirmation, and not under the review list or a removal
/// that is still running.
pub fn can_start_over(&self) -> bool {
self.screen == Screen::Explore
&& !self.confirm_open
&& !self.volumes_open
}
/// Ask for a local directory and scan it: an app opened from the launcher
/// or Dock has no command line to name one, and this also switches back
/// from an SSH session cleanly.
pub fn open_folder(&self, cx: &Context<'_, Self>) {
if !self.can_start_over() {
return;
}
let chosen = cx.prompt_for_paths(gpui_kit::PathPromptOptions {
files: false,
directories: true,
multiple: false,
prompt: Some("Scan".into()),
});
cx.spawn(async move |this, cx| {
let Ok(Ok(Some(paths))) = chosen.await else {
return;
};
let Some(path) = paths.into_iter().next() else {
return;
};
// Canonical, like a root from the command line, so a later
// widening recognises this tree in the wider walk.
let path = dunce::canonicalize(&path).unwrap_or(path);
// The panel does not block the window: the review list or a
// removal may have started while it was open.
let _ = this.update(cx, |this, cx| {
if this.can_start_over() {
if this.remote.is_some() {
this.clear_machine_state(true);
this.remote = None;
}
this.awaiting_root = false;
this.set_root(path, cx);
}
});
})
.detach();
}
/// Save what the plan would act on as a list of paths, one per line,
/// wherever the user chooses: for a script, or for later.
pub fn save_delete_list(&mut self, cx: &mut Context<'_, Self>) {
self.save_export(false, cx);
}
pub fn save_delete_script(&mut self, cx: &mut Context<'_, Self>) {
self.save_export(true, cx);
}
fn save_export(&mut self, script: bool, cx: &mut Context<'_, Self>) {
let plan = self.plan();
if plan.is_empty() {
self.notice = Some(("nothing to save".into(), Status::Warning));
cx.notify();
return;
}
let list = if script {
self.delete_script(&plan.targets)
} else {
disktree_core::export::delete_list(&plan.targets)
};
let count = plan.targets.len();
let directory =
std::env::home_dir().unwrap_or_else(|| PathBuf::from("."));
let filename = if script {
"disktree-delete.sh"
} else {
"disktree-delete-list.txt"
};
let chosen = cx.prompt_for_new_path(&directory, Some(filename));
cx.spawn(async move |this, cx| {
let Ok(Ok(Some(path))) = chosen.await else {
return;
};
let notice = match std::fs::write(&path, list) {
Ok(()) => (
format!(
"saved {count} {} to {}",
if count == 1 { "path" } else { "paths" },
path.display()
),
Status::Success,
),
Err(error) => (
format!("could not save {}: {error}", path.display()),
Status::Error,
),
};
let _ = this.update(cx, |this, cx| {
this.notice = Some(notice);
cx.notify();
});
})
.detach();
}
fn delete_script(&self, targets: &[Target]) -> String {
let identity = if self.remote.is_some() {
self.remote_identity.clone()
} else {
disktree_core::identity::HostIdentity::current()
};
disktree_core::export::delete_script_for(
targets,
&self.root_path,
self.remote.as_deref(),
identity.as_ref(),
)
}
pub fn copy_delete_script(&mut self, cx: &mut Context<'_, Self>) {
let plan = self.plan();
if plan.is_empty() {
self.notice = Some(("nothing to copy".into(), Status::Warning));
} else {
let script = self.delete_script(&plan.targets);
cx.write_to_clipboard(gpui_kit::ClipboardItem::new_string(script));
self.notice = Some((
"copied delete script; previews by default, checks host before deletion".into(),
Status::Success,
));
}
cx.notify();
}
/// Copy instructions for a coding agent to free the space by removing
/// what the plan would act on, after checking each path.
pub fn copy_agent_prompt(&mut self, cx: &mut Context<'_, Self>) {
let plan = self.plan();
if plan.is_empty() {
self.notice = Some(("nothing to copy".into(), Status::Warning));
cx.notify();
return;
}
let mut prompt = if self.remote.is_some() {
disktree_core::export::agent_prompt_for(
&plan.targets,
&self.root_path,
self.space,
&self.remote_platform,
self.remote_identity.as_ref(),
)
} else {
disktree_core::export::agent_prompt(
&plan.targets,
&self.root_path,
self.space,
)
};
if let Some(host) = &self.remote {
prompt = format!(
"The scan is from remote SSH host {host} ({}), NOT this \
computer. All paths below belong to that server. Connect \
via SSH; verify the host and paths before acting. \
Free space is a snapshot, not live.\n\n{prompt}",
self.remote_platform
);
}
cx.write_to_clipboard(gpui_kit::ClipboardItem::new_string(prompt));
let count = plan.targets.len();
self.notice = Some((
format!(
"copied a prompt for your agent: {count} {}, {}",
if count == 1 { "path" } else { "paths" },
disktree_core::size::human_bytes(plan.bytes())
),
Status::Success,
));
cx.notify();
}
/// Show the tile a key acts on in Finder (or the file manager), selected.
pub fn reveal_target(&mut self, cx: &mut Context<'_, Self>) {
if self.remote.is_some() {
return;
}
let crumbs =
self.action_target().unwrap_or_else(|| self.crumbs.clone());
let Some(path) = self.path_at(&crumbs) else {
return;
};
// GPUI's reveal cannot report failure, so check what it can't.
if std::fs::symlink_metadata(&path).is_err() {
self.notice = Some((
format!("{} is no longer on disk", self.display_path(&path)),
Status::Warning,
));
cx.notify();
return;
}
cx.reveal_path(&path);
}
/// Every binding, in reading order of the hint bar, so the keys and the
/// documented list cannot drift apart.
fn dispatch_key(
&mut self,
event: &KeyDownEvent,
cx: &mut Context<'_, Self>,
) {
let key = event.keystroke.key.as_str();
let control = event.keystroke.modifiers.control;
let shift = event.keystroke.modifiers.shift;
let alt = event.keystroke.modifiers.alt;
// The alert dialog owns Enter and Escape while it is open; a key that
// bubbles up to here must not also act on the screen behind it.
if self.confirm_open {
return;
}
// The volume picker owns its keys while open: arrows move, Enter
// picks, Escape closes, and nothing behind it acts.
if self.volumes_open {
match key {
"escape" => self.close_volumes(cx),
"enter" => self.choose_volume(cx),
"up" | "k" if !control => {
self.move_volume_highlight(-1, cx);
}
"down" | "j" if !control => {
self.move_volume_highlight(1, cx);
}
_ => {}
}
return;
}
// ⌘ chords belong to the menu bar (⌘Q, ⌘W, ⌘R) or to the system.
// Read as plain letters they would act twice or by surprise: ⌘D
// would re-scan with apparent sizes, ⌘H would hide *and* toggle.
// Zoom (⌘= ⌘- ⌘0) is handled before this, with a window in hand.
if event.keystroke.modifiers.platform {
return;
}
if self.crumb_menu.is_some() && self.on_menu_key(key, cx) {
return;
}
if self.show_help {
if matches!(key, "escape" | "?" | "/" | "q") {
self.show_help = false;
cx.notify();
}
return;
}
// The search field takes the keyboard while it is open. It is a field
// of three keys on purpose: no editor state to keep in sync with the
// tree, and Escape always means "give the keyboard back".
if self.screen == Screen::Explore && self.find.is_editing() {
match key {
"escape" => self.step_find(find_machine::Event::Clear, cx),
"enter" => self.step_find(find_machine::Event::Submit, cx),
"backspace" => {
self.step_find(find_machine::Event::Backspace, cx);
}
_ => {
// Some platforms report only `key` for a character and
// leave `key_char` empty; a one-character key is a
// character either way.
let typed = event
.keystroke
.key_char
.as_deref()
.unwrap_or(event.keystroke.key.as_str());
if !control && typed.chars().count() == 1 {
self.step_find(
find_machine::Event::PushText(typed.to_owned()),
cx,
);
}
}
}
cx.notify();
return;
}
match self.screen {
// Alt-arrows are history in every browser and file manager.
Screen::Explore if alt && key == "left" => self.go_back(cx),
Screen::Explore if alt && key == "right" => self.go_forward(cx),
Screen::Explore => self.on_explore_key(key, control, shift, cx),
Screen::Review => self.on_review_key(key, cx),
Screen::Running => {
if key == "escape"
&& let Some(run) = &self.run
{
run.cancel();
self.notice = Some((
"stopping after the current item".into(),
Status::Warning,
));
cx.notify();
}
}
Screen::Done => {
if matches!(key, "escape" | "enter") {
self.screen = Screen::Explore;
cx.notify();
}
}
}
}
fn on_explore_key(
&mut self,
key: &str,
control: bool,
shift: bool,
cx: &mut Context<'_, Self>,
) {
// Keys that act on "the current tile" start from the pointer when it
// moved last.
if matches!(
key,
"space"
| "x"
| "enter"
| "tab"
| "left"
| "right"
| "up"
| "down"
| "h"
| "j"
| "k"
| "l"
) {
self.adopt_pointer_target();
}
match key {
"/" | "s" if !control => {
self.step_find(find_machine::Event::Open, cx);
cx.notify();
}
"enter" => self.descend(cx),
"right" | "l" if !control => {
self.move_selection(Direction::Right, cx);
}
"left" | "h" if !control => {
self.move_selection(Direction::Left, cx);
}
"up" | "k" if !control => self.move_selection(Direction::Up, cx),
"down" | "j" if !control => {
self.move_selection(Direction::Down, cx);
}
"backspace" | "u" if !control => self.ascend(cx),
// A filter is the first thing Escape takes away.
"escape" if self.find.matches().is_some() => {
self.step_find(find_machine::Event::Clear, cx);
cx.notify();
}
"escape" if self.is_indexing() => {
self.cancel_scan(cx);
}
"escape" => {
if self.selected.is_some() {
self.selected = None;
} else {
self.ascend(cx);
}
cx.notify();
}
"space" => self.toggle_mark_selected(cx),
"x" if !control => self.toggle_mark_selected(cx),
"tab" => self.cycle_sibling(if shift { -1 } else { 1 }, cx),
"c" if !control => {
if self.marks.is_empty() {
self.notice = Some((
"mark something first: space marks the selected tile"
.into(),
Status::Warning,
));
} else {
self.screen = Screen::Review;
}
cx.notify();
}
"[" => self.adjust_depth(-1, cx),
"]" => self.adjust_depth(1, cx),
"-" => {
self.zoom_at(
self.half_width(),
self.half_height(),
1.0 / 1.25,
false,
cx,
);
}
"=" | "+" => {
self.zoom_at(
self.half_width(),
self.half_height(),
1.25,
false,
cx,
);
}
"0" => self.reset_view(cx),
"t" if !control => {
self.set_mode((self.mode_index() + 1) % 3, cx);
}
"r" if !control => self.refresh_scan(cx),
"g" if !control => self.go_to_disk(cx),
"v" if !control && !shift => self.open_volumes(cx),
"i" if !control => self.toggle_hidden(cx),
"d" if !control => self.toggle_apparent_size(cx),
"p" if !control => {
self.show_selection = !self.show_selection;
cx.notify();
}
"o" if !control => self.reveal_target(cx),
"?" => {
self.show_help = true;
cx.notify();
}
"q" if !control => cx.quit(),
_ => {}
}
}
fn on_review_key(&mut self, key: &str, cx: &mut Context<'_, Self>) {
if self.remote.is_some() && matches!(key, "m" | "p" | "enter") {
return;
}
if key == "e" {
self.save_delete_script(cx);
return;
}
match key {
"escape" => {
self.screen = Screen::Explore;
cx.notify();
}
"enter" => self.commit(cx),
"!" => self.clear_marks(cx),
"p" => {
self.removal_mode = RemovalMode::Permanent;
cx.notify();
}
"m" => {
self.removal_mode = RemovalMode::Trash;
cx.notify();
}
"s" => self.save_delete_list(cx),
"a" => self.copy_agent_prompt(cx),
"y" => self.copy_delete_script(cx),
"?" => {
self.show_help = true;
cx.notify();
}
_ => {}
}
}
fn half_width(&self) -> f32 {
self.treemap_size.get().width.as_f32() / 2.0
}
fn half_height(&self) -> f32 {
self.treemap_size.get().height.as_f32() / 2.0
}
/// Mouse moved over the treemap.
pub fn on_mouse_move(
&mut self,
event: &MouseMoveEvent,
cx: &mut Context<'_, Self>,
) {
let origin = self.treemap_origin.get();
let local = Point::new(
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();
self.hovered = self.tile_at(local.x.as_f32(), local.y.as_f32());
// The cursor tooltip is positioned from `pointer`, so a move *within*
// one tile still has to repaint — otherwise the tooltip sticks where
// the tile was first entered until the hover target changes.
if self.hovered != previous || self.hovered.is_some() {
cx.notify();
}
}
pub fn on_mouse_leave(&mut self, cx: &mut Context<'_, Self>) {
self.pointer = None;
self.pointer_active = false;
if self.hovered.take().is_some() {
cx.notify();
}
}
/// Click: select, then act on a repeat click, like a file manager.
pub fn on_mouse_down(
&mut self,
event: &MouseDownEvent,
cx: &mut Context<'_, Self>,
) {
let origin = self.treemap_origin.get();
let x = (event.position.x - origin.x).as_f32();
let y = (event.position.y - origin.y).as_f32();
let crumbs = self.tile_at(x, y);
match event.button {
MouseButton::Left if event.click_count >= 2 => {
if let Some(crumbs) = crumbs {
self.select(Some(crumbs), cx);
self.descend(cx);
}
}
MouseButton::Left
if event.modifiers.control || event.modifiers.platform =>
{
if let Some(crumbs) = crumbs {
self.toggle_mark(&crumbs, cx);
}
}
MouseButton::Left => {
let activate = crumbs.as_ref().is_some_and(|crumbs| {
self.selected.as_ref() == Some(crumbs)
&& self.node_at(crumbs).is_some_and(Node::is_dir)
});
if activate {
// A second click on the selection opens it, like a file
// manager, without needing a double click.
self.descend(cx);
return;
}
self.select(crumbs, cx);
}
MouseButton::Middle => {
if let Some(crumbs) = crumbs {
self.toggle_mark(&crumbs, cx);
}
}
// What `o` does, for the tile under the pointer: select it, then
// show it in Finder, File Explorer or the file manager.
MouseButton::Right => {
if let Some(crumbs) = crumbs {
self.select(Some(crumbs), cx);
self.reveal_target(cx);
}
}
// Buttons 8 and 9. gpui-pre maps them on X11, Wayland and
// Windows; a mouse with no side buttons never sends them, and
// then the header `<` / `>` and alt-arrows are the whole story.
MouseButton::Navigate(NavigationDirection::Back)
if self.screen == Screen::Explore =>
{
self.go_back(cx);
}
MouseButton::Navigate(NavigationDirection::Forward)
if self.screen == Screen::Explore =>
{
self.go_forward(cx);
}
// Side buttons off the explore screen.
MouseButton::Navigate(_) => {}
}
}
pub fn on_scroll_wheel(
&mut self,
event: &ScrollWheelEvent,
cx: &mut Context<'_, Self>,
) {
let origin = self.treemap_origin.get();
let x = (event.position.x - origin.x).as_f32();
let y = (event.position.y - origin.y).as_f32();
let lines = match event.delta {
ScrollDelta::Lines(delta) => delta.y,
ScrollDelta::Pixels(delta) => delta.y.as_f32() / 24.0,
};
if lines.abs() < f32::EPSILON {
return;
}
if event.modifiers.shift {
// Pan instead of zoom, for looking around a magnified view.
// Clamped at both ends, as zooming is: stopping only at the
// top let the mosaic be scrolled off the bottom of the view.
self.view.origin_y -= lines * 40.0 / self.view.scale;
self.view = self.view.clamped(self.treemap_size.get());
cx.notify();
return;
}
let factor = if lines > 0.0 { 1.15 } else { 1.0 / 1.15 };
self.zoom_at(x, y, factor, true, cx);
}
/// Advance the layout transition, if one is running.
pub fn tick_transition(&mut self, window: &Window) {
if let Some(transition) = self.transition {
let (_, running) = transition.sample(Rect::default());
if running {
window.request_animation_frame();
} else {
self.transition = None;
}
}
self.tick_freshness_fades(window);
}
/// Plain-language explanation of active scan work for the unified sidebar
/// status card (`(heading, why)`).
#[must_use]
pub fn scan_activity_summary(&self) -> Option<(String, String)> {
let active = self.active_scan.as_ref()?;
let has_tree = self.tree.is_some();
match active {
ActiveScan::Remote { intent, .. } => {
let host = self.remote.as_deref().unwrap_or("remote");
let stage = self.remote_progress.stage;
let (heading, why) = match intent {
ScanIntent::Refresh { forced: true, .. } => (
format!("Rescanning {host}"),
"Rescanning on request — keep browsing".into(),
),
ScanIntent::Refresh { forced: false, .. } => (
format!("Refreshing {host}"),
"Updating stale cache — keep browsing".into(),
),
ScanIntent::Widening { .. } => (
format!("Expanding {host}"),
"Reading parent folder — keep browsing".into(),
),
ScanIntent::Initial if has_tree => (
format!("Updating {host}"),
"Filling remaining folders — keep browsing".into(),
),
ScanIntent::Initial => (
format!("Scanning {host}"),
if stage
== disktree_core::remote_progress::Stage::Indexing
{
"Building initial index — preview is provisional"
.into()
} else {
stage.label().to_owned()
},
),
};
Some((heading, why))
}
ActiveScan::Local { intent, .. } => Some(match intent {
ScanIntent::Refresh { forced: true, .. } => (
"Rescanning".into(),
"Rescanning on request — keep browsing".into(),
),
ScanIntent::Refresh { forced: false, .. } => (
"Refreshing cache".into(),
"Updating folders >15m old — keep browsing".into(),
),
ScanIntent::Widening { .. } => (
"Expanding scan".into(),
"Reading parent folder — keep browsing".into(),
),
ScanIntent::Initial if has_tree => (
"Updating".into(),
"Filling remaining folders — keep browsing".into(),
),
ScanIntent::Initial => (
"Scanning".into(),
"Building initial index — preview is provisional".into(),
),
}),
}
}
/// Keep animation frames flowing while any tile is mid-fade or mid-glide
/// after a freshness/layout change (200 ms ease-out), then stop cleanly at
/// 0% idle CPU.
pub fn tick_freshness_fades(&self, window: &Window) {
let now = Instant::now();
if self.tile_fades.values().any(|fade| fade.is_running(now))
|| self.tile_rects.values().any(|anim| anim.is_running(now))
{
window.request_animation_frame();
}
}
}
fn sample_tile_rect(
tile_rects: &mut FxHashMap<PathBuf, TileRectAnim>,
path: PathBuf,
target: Rect,
now: Instant,
) -> Rect {
if let Some(anim) = tile_rects.get_mut(&path) {
if !TileRectAnim::rects_close(anim.target, target) {
let current = anim.value(now);
anim.from = current;
anim.target = target;
anim.started = now;
}
anim.value(now)
} else {
tile_rects.insert(path, TileRectAnim::settled(target, now));
target
}
}
fn sample_tile_fade(
tile_fades: &mut FxHashMap<PathBuf, TileFade>,
path: PathBuf,
target: f32,
now: Instant,
) -> f32 {
if let Some(fade) = tile_fades.get_mut(&path) {
if (fade.target - target).abs() >= f32::EPSILON {
let current = fade.value(now);
fade.from = current;
fade.target = target;
fade.started = now;
}
fade.value(now)
} else {
tile_fades.insert(path, TileFade::settled(target, now));
target
}
}
impl Disktree {
/// A tile's rectangle for this frame: mid-transition it is on its way from
/// where it was to where it is.
fn animated_rect(&self, rect: Rect) -> Rect {
match self.transition {
Some(transition) => transition.sample(rect).0,
None => rect,
}
}
}
/// A direction for geometric selection movement.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Direction {
Left,
Right,
Up,
Down,
}
impl Direction {
const fn is_backwards(self) -> bool {
matches!(self, Self::Left | Self::Up)
}
/// Distance from `from` to `rect` along the axis, if `rect` lies that way.
fn gap(self, from: &Rect, rect: &Rect) -> Option<f32> {
let epsilon = 0.5;
match self {
Self::Right => {
let gap = rect.x - from.right();
(gap >= -epsilon).then_some(gap.max(0.0))
}
Self::Left => {
let gap = from.x - rect.right();
(gap >= -epsilon).then_some(gap.max(0.0))
}
Self::Down => {
let gap = rect.y - from.bottom();
(gap >= -epsilon).then_some(gap.max(0.0))
}
Self::Up => {
let gap = from.y - rect.bottom();
(gap >= -epsilon).then_some(gap.max(0.0))
}
}
}
/// How far off the direction's axis `rect` sits, so the nearest tile in the
/// direction wins rather than any tile in that half-plane.
fn offset(self, from: &Rect, rect: &Rect) -> f32 {
let overlap =
|a_start: f32, a_end: f32, b_start: f32, b_end: f32| -> f32 {
(a_end.min(b_end) - a_start.max(b_start)).max(0.0)
};
match self {
Self::Left | Self::Right => {
let shared =
overlap(from.y, from.bottom(), rect.y, rect.bottom());
(from.h.min(rect.h) - shared).max(0.0)
}
Self::Up | Self::Down => {
let shared =
overlap(from.x, from.right(), rect.x, rect.right());
(from.w.min(rect.w) - shared).max(0.0)
}
}
}
}
/// A tile's label, resolved for painting.
#[derive(Clone, Debug)]
pub struct Label {
pub text: String,
/// Base-space rectangle; the view transform is applied while painting.
pub rect: Rect,
/// 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>,
/// Nesting depth in this view: the first level is set in bold.
pub depth: u32,
/// Filtered out while typing: drawn quietly.
pub dim: bool,
pub marked: bool,
pub size_text: String,
}
/// A label a tile has room for, before its text is made: only the
/// [`MAX_LABELS`] largest get any.
struct LabelSlot<'a> {
/// The tile's node; `None` for the merged tail.
node: Option<&'a Node>,
/// How many entries a merged tail stands for.
others: usize,
rect: Rect,
header: Option<Rect>,
depth: u32,
dim: bool,
marked: bool,
}
/// How many labels one frame will shape.
const MAX_LABELS: usize = 150;
/// 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;
/// A trail step's label: the directory's own name, or `/` for the root.
fn crumb_label(path: &Path, style: PathStyle) -> String {
style.file_name(path).map_or_else(
|| path.display().to_string(),
|name| name.to_string_lossy().into_owned(),
)
}
impl Disktree {
/// Start again as an administrator on the root this window is headed
/// for, with the same options, and close this window once the prompt is
/// accepted.
/// Declined, nothing changes. Not while a removal runs: quitting would
/// stop a permanent delete halfway.
pub fn restart_as_administrator(&mut self, cx: &mut Context<'_, Self>) {
if self.remote.is_some() || self.restarting || self.run.is_some() {
return;
}
self.restarting = true;
cx.notify();
// While a widening scan runs, the wider root is where this window
// ends up, and the drive the offer is about: reopening the folder
// still on screen would walk it again.
let root = self.widening_target().unwrap_or(&self.root_path);
let args =
restart_args(&self.options, self.layout_options.max_depth, root);
// Off the UI thread: the prompt runs its own message loop, which
// would re-enter this window while it is still being handled.
let restart = cx.background_executor().spawn(async move {
disktree_core::access::restart_as_administrator(&args)
});
cx.spawn(async move |this, cx| {
let outcome = restart.await;
let _ = this.update(cx, |this, cx| match outcome {
Ok(()) => cx.quit(),
Err(error) => {
this.restarting = false;
this.notice = Some((
format!("still not an administrator: {error}"),
Status::Warning,
));
cx.notify();
}
});
})
.detach();
}
}
/// The command line that reopens `root` with `options` and `depth`, in the
/// flags `parse_args` reads.
pub fn restart_args(
options: &ScanOptions,
depth: u32,
root: &Path,
) -> Vec<std::ffi::OsString> {
let mut args: Vec<std::ffi::OsString> = Vec::new();
for (on, flag) in [
(options.apparent_size, "--apparent-size"),
(options.follow_links, "--follow-links"),
(!options.include_hidden, "--no-hidden"),
(!options.one_filesystem, "--cross-filesystems"),
(options.metric == Metric::Files, "--metric"),
] {
if on {
args.push(flag.into());
}
}
if options.metric == Metric::Files {
args.push("files".into());
}
if let Some(threads) = options.threads {
args.push("--scan-threads".into());
args.push(threads.to_string().into());
}
args.push("--depth".into());
args.push(depth.to_string().into());
args.push(root.as_os_str().to_owned());
args
}
/// 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)
})
}
/// Expand a leading `~` or `~/` against the local home directory.
fn expand_tilde(raw: &str) -> PathBuf {
if raw == "~"
&& let Some(home) = std::env::home_dir()
{
return home;
}
if let Some(rest) =
raw.strip_prefix("~/").or_else(|| raw.strip_prefix("~\\"))
&& let Some(home) = std::env::home_dir()
{
return home.join(rest);
}
PathBuf::from(raw)
}
/// Let go of a tree off the UI thread: freeing a disk's millions of nodes
/// takes a good part of a second, and nothing waits on it.
fn discard(tree: Option<Arc<Node>>) {
if let Some(tree) = tree {
// When no thread can be made, the closure is dropped here instead,
// and the tree is freed in place rather than taking the window down.
let _ = std::thread::Builder::new().spawn(move || drop(tree));
}
}
/// Smallest tile, in rem, that gets a label: below this a name cannot be read.
const LABEL_MIN_W_REMS: f32 = 3.375;
const LABEL_MIN_H_REMS: f32 = 0.9375;
/// How a tile stands against the find text.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Filtered {
/// It matches, is inside a match, or nothing is being found.
Shown,
/// It holds matches: its fill steps back, its name stays readable.
Holds,
/// Nothing in it matches.
Out,
}
/// Where keyboard focus should go once a window is available.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum FocusTarget {
/// The treemap and screens, which own every key binding.
Root,
/// The permanent-deletion alert dialog.
Dialog,
}
impl Render for Disktree {
fn render(
&mut self,
window: &mut Window,
cx: &mut Context<'_, Self>,
) -> impl gpui_kit::IntoElement {
self.rem = window.rem_size().as_f32();
self.tick_transition(window);
// The titlebar names the directory on screen, however it got there:
// a key, a click, a rescan or a folder chosen from the menu.
let title = if self.awaiting_root {
"disktree · Choose a source".into()
} else {
format!(
"disktree{} · {}",
self.remote.as_ref().map_or_else(String::new, |host| {
format!(" · {host} · read-only")
}),
self.display_path(&self.current_path())
)
};
if title != self.window_title {
window.set_window_title(&title);
self.window_title = title;
}
crate::views::root(self, window, cx)
}
}
#[cfg(test)]
mod tests {
use super::*;
fn view() -> View {
View {
scale: 2.0,
origin_x: 100.0,
origin_y: 50.0,
}
}
#[test]
fn projecting_and_unprojecting_are_inverses() {
let view = view();
let (x, y) = view.unproject(400.0, 300.0);
let rect = Rect::new(x, y, 10.0, 10.0);
let screen = view.project(rect);
assert!((screen.x - 400.0).abs() < 0.001);
assert!((screen.y - 300.0).abs() < 0.001);
assert!((screen.w - 20.0).abs() < 0.001);
}
#[test]
fn zooming_keeps_the_point_under_the_cursor_still() {
let view = View::IDENTITY;
let (before_x, before_y) = view.unproject(300.0, 200.0);
let zoomed = view.zoomed_at(300.0, 200.0, 2.0, View::MAX_SCALE);
let rect = Rect::new(before_x, before_y, 1.0, 1.0);
let screen = zoomed.project(rect);
assert!((screen.x - 300.0).abs() < 0.01, "{screen:?}");
assert!((screen.y - 200.0).abs() < 0.01, "{screen:?}");
}
#[test]
fn clamping_never_leaves_a_margin() {
let area = size(px(800.), px(600.));
let clamped = View {
scale: 2.0,
origin_x: -500.0,
origin_y: 900.0,
}
.clamped(area);
assert!(clamped.origin_x.abs() < f32::EPSILON);
assert!((clamped.origin_y - 300.0).abs() < f32::EPSILON);
let identity = View {
scale: 1.0,
origin_x: 40.0,
origin_y: 40.0,
}
.clamped(area);
assert!(identity.origin_x.abs() < f32::EPSILON);
assert!(identity.origin_y.abs() < f32::EPSILON);
}
#[test]
fn a_transition_starts_where_the_region_was_and_ends_where_it_is() {
// A region that occupied the whole viewport, landing in the top-left
// quarter of the new layout: everything inside it must start twice as
// large and centred where it was.
let transition = LayoutTransition::new(
Rect::new(0.0, 0.0, 800.0, 600.0),
Rect::new(0.0, 0.0, 400.0, 300.0),
);
// A tile inside the destination, at the far corner.
let tile = Rect::new(200.0, 150.0, 200.0, 150.0);
let (_, running) = transition.sample(tile);
assert!(running, "the transition is in flight");
let origin = transition.origin_of(tile);
assert!((origin.x - 400.0).abs() < 0.001, "{origin:?}");
assert!((origin.y - 300.0).abs() < 0.001, "{origin:?}");
assert!((origin.w - 400.0).abs() < 0.001, "{origin:?}");
assert!((origin.h - 300.0).abs() < 0.001, "{origin:?}");
let finished = LayoutTransition {
started: Instant::now()
.checked_sub(Duration::from_millis(500))
.expect("a moment on a running machine"),
..transition
};
let (end, running) = finished.sample(tile);
assert!(!running);
assert_eq!(end, tile, "it ends exactly at the real layout");
}
#[test]
fn a_transition_grows_a_tile_that_is_being_entered() {
// Entering a child: the child's region becomes the viewport, so
// everything inside it gets bigger, never smaller.
let transition = LayoutTransition::new(
Rect::new(100.0, 100.0, 200.0, 200.0),
Rect::new(0.0, 0.0, 800.0, 600.0),
);
let tile = Rect::new(400.0, 300.0, 100.0, 100.0);
let origin = transition.origin_of(tile);
assert!(origin.w < tile.w, "it starts smaller: {origin:?}");
assert!(
origin.x > 100.0 && origin.x < 300.0,
"and where the child was: {origin:?}"
);
}
#[test]
fn directions_only_see_gaps_on_their_own_side() {
let from = Rect::new(100.0, 100.0, 50.0, 50.0);
let right = Rect::new(200.0, 100.0, 50.0, 50.0);
let left = Rect::new(0.0, 100.0, 50.0, 50.0);
assert!(Direction::Right.gap(&from, &right).is_some());
assert!(Direction::Right.gap(&from, &left).is_none());
assert!(Direction::Left.gap(&from, &left).is_some());
assert!(Direction::Down.gap(&from, &right).is_none());
assert_eq!(Direction::Right.gap(&from, &right), Some(50.0));
// Aligned neighbours have no perpendicular offset; stacked ones do.
assert!(Direction::Right.offset(&from, &right).abs() < f32::EPSILON);
assert!(
Direction::Right
.offset(&from, &Rect::new(200.0, 160.0, 20.0, 20.0))
> 0.0
);
}
#[test]
fn find_machine_ignores_stale_epochs_and_applies_pending_submit() {
use find_machine::{Effect, Event, Phase, State, step};
let sample_matches = |needle: &str, count: usize| {
Arc::new(disktree_core::filter::Matches {
needle: needle.to_owned(),
base: Vec::new(),
keep: FxHashMap::default(),
count,
bytes: count as u64 * 100,
files: count as u64,
})
};
let (state, effects) = step(State::default(), Event::Open);
assert!(state.is_editing());
assert!(effects.is_empty());
let (state, effects) = step(state, Event::PushText("b".into()));
let epoch_b = state.epoch;
assert!(matches!(
effects.as_slice(),
[Effect::StartSearch { epoch, query }] if *epoch == epoch_b && query == "b"
));
let (state, effects) = step(state, Event::PushText("lob".into()));
let epoch_blob = state.epoch;
assert!(epoch_blob > epoch_b);
assert!(matches!(
effects.as_slice(),
[Effect::StartSearch { epoch, query }] if *epoch == epoch_blob && query == "blob"
));
// Enter before the search lands enters Applying.
let (state, effects) = step(state, Event::Submit);
assert!(matches!(state.phase, Phase::Applying { .. }));
assert!(effects.is_empty());
// Stale completion for "b" is ignored.
let (state, effects) = step(
state,
Event::SearchFinished {
epoch: epoch_b,
found: Some(sample_matches("b", 9)),
},
);
assert!(matches!(state.phase, Phase::Applying { .. }));
assert!(effects.is_empty());
// Current completion for "blob" transitions straight to Applied.
let (state, effects) = step(
state,
Event::SearchFinished {
epoch: epoch_blob,
found: Some(sample_matches("blob", 2)),
},
);
assert!(state.is_applied());
assert_eq!(state.matches().map(|m| m.count), Some(2));
assert!(
effects
.iter()
.any(|e| matches!(e, Effect::SelectBestMatch(_)))
);
// Clear resets to Closed and invalidates the epoch.
let (state, effects) = step(state, Event::Clear);
assert!(matches!(state.phase, Phase::Closed));
assert!(state.epoch > epoch_blob);
assert!(
effects
.iter()
.any(|e| matches!(e, Effect::InvalidateLayout))
);
}
#[test]
fn discovery_machine_rejects_stale_local_completion_after_remote_error() {
use discovery_machine::{Effect, Event, Phase, State, step};
let (state, effects) = step(State::default(), Event::StartLocal);
let local_epoch = state.epoch;
assert!(state.is_loading());
assert_eq!(
effects,
vec![Effect::SpawnLocalListing { epoch: local_epoch }]
);
let (state, effects) = step(
state,
Event::StartRemote {
host: "-bad".into(),
},
);
let remote_epoch = state.epoch;
assert!(remote_epoch > local_epoch);
assert_eq!(
effects,
vec![Effect::DiscoverRemote {
epoch: remote_epoch,
host: "-bad".into(),
}]
);
let (state, effects) = step(
state,
Event::Completed {
epoch: remote_epoch,
outcome: Err("invalid SSH".into()),
},
);
assert_eq!(state.error(), Some("invalid SSH"));
assert!(effects.is_empty());
// Late local completion cannot overwrite the remote error.
let (state, effects) = step(
state,
Event::Completed {
epoch: local_epoch,
outcome: Ok(()),
},
);
assert_eq!(state.error(), Some("invalid SSH"));
assert!(effects.is_empty());
let (state, effects) = step(state, Event::Reset);
assert!(matches!(state.phase, Phase::Idle));
assert!(effects.is_empty());
}
#[test]
fn tile_fade_eases_smoothly_over_200ms() {
let start = Instant::now();
let fade = TileFade {
from: 0.28,
target: 0.0,
started: start,
};
assert!((fade.value(start) - 0.28).abs() < 1e-5);
assert!(fade.is_running(start));
let mid = fade.value(start + Duration::from_millis(100));
assert!(
mid > 0.0 && mid < 0.28,
"expected smooth mid fade, got {mid}"
);
let done = fade.value(start + Duration::from_millis(200));
assert!(done.abs() < 1e-5);
assert!(!fade.is_running(start + Duration::from_millis(200)));
}
#[test]
fn tile_rect_glides_smoothly_over_200ms() {
let start = Instant::now();
let anim = TileRectAnim {
from: Rect::new(0.0, 0.0, 100.0, 100.0),
target: Rect::new(50.0, 20.0, 200.0, 140.0),
started: start,
};
assert!(anim.is_running(start));
let mid = anim.value(start + Duration::from_millis(100));
assert!(mid.x > 0.0 && mid.x < 50.0);
assert!(mid.w > 100.0 && mid.w < 200.0);
let done = anim.value(start + Duration::from_millis(200));
assert!((done.x - 50.0).abs() < 1e-3);
assert!((done.w - 200.0).abs() < 1e-3);
assert!(!anim.is_running(start + Duration::from_millis(200)));
}
#[test]
fn ssh_hosts_record_deduplicates_mru_and_persists() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("disktree/ssh-hosts");
let mut hosts = Vec::new();
assert!(ssh_hosts::record(&mut hosts, "dev"));
assert!(ssh_hosts::record(&mut hosts, "user@prod"));
assert!(ssh_hosts::record(&mut hosts, "dev"));
assert!(!ssh_hosts::record(&mut hosts, "dev"));
assert!(!ssh_hosts::record(&mut hosts, "-oProxyCommand=bad"));
assert_eq!(hosts, vec!["dev", "user@prod"]);
ssh_hosts::save_to(&path, &hosts);
assert_eq!(ssh_hosts::load_from(&path), vec!["dev", "user@prod"]);
assert!(ssh_hosts::remove(&mut hosts, "user@prod"));
ssh_hosts::save_to(&path, &hosts);
assert_eq!(ssh_hosts::load_from(&path), vec!["dev"]);
}
}