From 5bdd76f98ade0a7b8ca9778619850e9f311a396c Mon Sep 17 00:00:00 2001 From: armada45-pixel Date: Tue, 13 Oct 2026 12:07:20 +0700 Subject: [PATCH] Remember the view choices between launches The depth, Size / Files / Age, hidden files, apparent size, and the side panel's width and whether it is shown were back at their defaults on every launch. They are now written to `disktree/settings`, beside the Power Efficiency preset, as each one changes; the panel's width, which moves continuously under a drag, is written on the way out. Reading is lenient, so an older and a newer build can share the file and a hand edit gone wrong costs one setting. The saved values are where the arguments start, so a flag on the command line still overrules them. Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 1 + README.md | 5 + crates/disktree-app/src/main.rs | 58 ++++++++- crates/disktree-app/src/settings.rs | 192 ++++++++++++++++++++++++++++ crates/disktree-app/src/state.rs | 78 +++++++++-- crates/disktree-app/src/tests.rs | 31 +++++ crates/disktree-app/src/views.rs | 10 +- 7 files changed, 357 insertions(+), 18 deletions(-) create mode 100644 crates/disktree-app/src/settings.rs diff --git a/AGENTS.md b/AGENTS.md index a567ce80..50bc6c4e 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -120,6 +120,7 @@ and `cargo build --release` directly; CI runs the gate on both systems. | what Windows lists, measures and compares differently | `crates/disktree-core/src/windows.rs` — `unsafe` for Win32 | | reading a whole NTFS drive from its file table | `crates/disktree-core/src/mft.rs` | | a key, a screen transition, a mark | `crates/disktree-app/src/state.rs` | +| a view choice kept between launches | `crates/disktree-app/src/settings.rs` | | spacing, type and size | `crates/disktree-app/src/ui.rs` — tokens only, no `px` in layout | | the mosaic's painting or labels | `crates/disktree-app/src/treemap_view.rs` | | layout of a screen | `crates/disktree-app/src/views.rs` | diff --git a/README.md b/README.md index 80442695..f98b9391 100644 --- a/README.md +++ b/README.md @@ -238,6 +238,11 @@ rescan, ⌘[ and ⌘] for back and forward, and ⌘Q, ⌘H and ⌘W (closing the window quits); other ⌘ chords are left to the system. On Linux and Windows the same work with ctrl, with F5 to rescan too. +The depth, Size / Files / Age, hidden files, apparent size, and the side +panel's width and whether it is shown are remembered between launches, in +`disktree/settings` beside the Power Efficiency preset; an option on the +command line still overrules what was saved. + On the review screen: `m` trash, `p` permanent, `!` unmark all, `enter` commits, `esc` goes back. Or hand the list on instead of acting on it: `s` saves it as a text file, one path per line, and `a` copies a prompt for a diff --git a/crates/disktree-app/src/main.rs b/crates/disktree-app/src/main.rs index 92fa2f76..79d459a5 100644 --- a/crates/disktree-app/src/main.rs +++ b/crates/disktree-app/src/main.rs @@ -17,6 +17,7 @@ mod git; mod marks; mod palette; mod power; +mod settings; mod state; #[cfg(test)] mod tests; @@ -100,7 +101,15 @@ fn run() -> Result<()> { eprintln!("Cannot load Power Efficiency: {error}; using Balanced"); power::PowerEfficiency::default() }); - let args = parse_args_with_power(std::env::args_os().skip(1), saved)?; + let settings_path = settings::path(); + let chosen = settings_path + .as_deref() + .map_or_else(|| Ok(settings::Settings::default()), settings::load) + .unwrap_or_else(|error| { + eprintln!("Cannot load settings: {error}; using the defaults"); + settings::Settings::default() + }); + let args = parse_args_with(std::env::args_os().skip(1), saved, &chosen)?; // When the app executable is reached through the command-line symlink, // cmux sends SIGTERM to its foreground process group as AppKit takes @@ -186,6 +195,8 @@ fn run() -> Result<()> { cx, ); app.power_choice = args.power; + app.settings_path.clone_from(&settings_path); + app.apply_settings(&chosen); app }) }, @@ -209,17 +220,34 @@ fn parse_args(args: impl Iterator) -> Result { parse_args_with_power(args, power::PowerEfficiency::default()) } +#[cfg(test)] fn parse_args_with_power( + args: impl Iterator, + preset: power::PowerEfficiency, +) -> Result { + parse_args_with(args, preset, &settings::Settings::default()) +} + +/// Saved choices are where the options start; a flag then overrules one. +fn parse_args_with( mut args: impl Iterator, preset: power::PowerEfficiency, + saved: &settings::Settings, ) -> Result { let mut root: Option = None; let mut options = ScanOptions { threads: preset.policy(power::cpu_threads()), + apparent_size: saved.apparent_size, + include_hidden: saved.include_hidden, + metric: if saved.mode == 1 { + disktree_core::tree::Metric::Files + } else { + disktree_core::tree::Metric::Bytes + }, ..ScanOptions::default() }; let mut power = Some(preset); - let mut depth = 3_u32; + let mut depth = saved.depth; let mut disk = false; // `std::env::args` panics on a name that is not Unicode, and a path is // any name: a restart as administrator hands the root back exactly as @@ -431,6 +459,32 @@ mod argument_tests { assert_eq!(args.options.threads.system_cpu_limit, None); } + #[test] + fn saved_view_choices_are_where_the_flags_start() { + let saved = settings::Settings { + depth: 5, + include_hidden: false, + apparent_size: true, + mode: 1, + ..settings::Settings::default() + }; + let preset = power::PowerEfficiency::default(); + let args = + parse_args_with(arguments(&[]), preset, &saved).expect("saved"); + assert_eq!(args.depth, 5); + assert!(!args.options.include_hidden); + assert!(args.options.apparent_size); + assert_eq!(args.options.metric, disktree_core::tree::Metric::Files); + let args = parse_args_with( + arguments(&["--depth", "2", "--metric", "bytes"]), + preset, + &saved, + ) + .expect("flags"); + assert_eq!(args.depth, 2); + assert_eq!(args.options.metric, disktree_core::tree::Metric::Bytes); + } + #[test] fn saved_power_is_loaded_before_cli_overrides() { use power::PowerEfficiency as Power; diff --git a/crates/disktree-app/src/settings.rs b/crates/disktree-app/src/settings.rs new file mode 100644 index 00000000..118d4fb0 --- /dev/null +++ b/crates/disktree-app/src/settings.rs @@ -0,0 +1,192 @@ +//! View choices kept between launches: what is measured, how deep it is +//! drawn, and the side panel. +//! +//! One `key=value` per line, beside the Power Efficiency preset. Reading is +//! lenient on purpose: a key this build does not know, or a value it cannot +//! use, is skipped and the rest still apply, so an older and a newer build +//! can share the file, and a hand edit gone wrong costs one setting instead +//! of all of them. The command line still wins over anything saved. + +use std::io::{self, Write as _}; +use std::path::{Path, PathBuf}; + +use crate::state::{PANEL_MAX_REMS, PANEL_MIN_REMS, PANEL_REMS}; + +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Settings { + /// Levels drawn at once: 1 to 6, as `--depth` takes them. + pub depth: u32, + pub include_hidden: bool, + pub apparent_size: bool, + /// The Size | Files | Age choice, as the control indexes it. + pub mode: usize, + /// The side panel's width, in rem. + pub panel_rems: f32, + /// Whether the side panel is shown at all. + pub show_selection: bool, +} + +impl Default for Settings { + fn default() -> Self { + Self { + depth: 3, + include_hidden: true, + apparent_size: false, + mode: 0, + panel_rems: PANEL_REMS, + show_selection: true, + } + } +} + +impl Settings { + /// Read `text`, keeping the default for anything missing or unusable. + pub fn parse(text: &str) -> Self { + let mut settings = Self::default(); + let flag = |value: &str| match value { + "true" => Some(true), + "false" => Some(false), + _ => None, + }; + for line in text.lines() { + let Some((key, value)) = line.split_once('=') else { + continue; + }; + let value = value.trim(); + match key.trim() { + "depth" => { + if let Ok(depth) = value.parse::() + && (1..=6).contains(&depth) + { + settings.depth = depth; + } + } + "hidden" => { + if let Some(on) = flag(value) { + settings.include_hidden = on; + } + } + "apparent-size" => { + if let Some(on) = flag(value) { + settings.apparent_size = on; + } + } + "mode" => { + if let Some(index) = + MODES.iter().position(|mode| *mode == value) + { + settings.mode = index; + } + } + "panel-width" => { + // A width outside the limits a drag keeps to would + // open a panel the handle could not have made. + if let Ok(rems) = value.parse::() + && (PANEL_MIN_REMS..=PANEL_MAX_REMS).contains(&rems) + { + settings.panel_rems = rems; + } + } + "panel" => { + if let Some(on) = flag(value) { + settings.show_selection = on; + } + } + _ => {} + } + } + settings + } + + fn text(&self) -> String { + format!( + "depth={}\nhidden={}\napparent-size={}\nmode={}\n\ + panel-width={:.2}\npanel={}\n", + self.depth, + self.include_hidden, + self.apparent_size, + MODES[self.mode.min(MODES.len() - 1)], + self.panel_rems, + self.show_selection, + ) + } +} + +/// The Size | Files | Age choice by name, in the control's order, so the +/// file still means the same if the control is ever reordered. +const MODES: [&str; 3] = ["size", "files", "age"]; + +/// Beside the Power Efficiency preset, in the same per-user directory. +pub fn path() -> Option { + crate::power::settings_path().map(|path| path.with_file_name("settings")) +} + +/// The saved settings, or the defaults when nothing was saved yet. +pub fn load(path: &Path) -> io::Result { + match std::fs::read_to_string(path) { + Ok(text) => Ok(Settings::parse(&text)), + Err(error) if error.kind() == io::ErrorKind::NotFound => { + Ok(Settings::default()) + } + Err(error) => Err(error), + } +} + +pub fn save(path: &Path, settings: &Settings) -> io::Result<()> { + let parent = path.parent().ok_or_else(|| { + io::Error::new(io::ErrorKind::InvalidInput, "no settings directory") + })?; + std::fs::create_dir_all(parent)?; + // Replaced whole, as the preset beside it is: a failed write leaves + // the previous choices, and a reader never sees half a file. + let mut file = tempfile::NamedTempFile::new_in(parent)?; + file.write_all(settings.text().as_bytes())?; + file.persist(path).map_err(|error| error.error)?; + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn saved_choices_come_back_as_they_were() { + let dir = tempfile::tempdir().expect("tempdir"); + let path = dir.path().join("config/settings"); + assert_eq!(load(&path).expect("missing"), Settings::default()); + let chosen = Settings { + depth: 5, + include_hidden: false, + apparent_size: true, + mode: 2, + panel_rems: 30.5, + show_selection: false, + }; + save(&path, &chosen).expect("save"); + assert_eq!(load(&path).expect("load"), chosen); + assert!(save(dir.path(), &chosen).is_err()); + } + + #[test] + fn one_bad_line_costs_one_setting() { + let settings = Settings::parse( + "depth=4\nfrom-a-newer-build=yes\nnot a setting\n\ + hidden=maybe\nmode=files\npanel-width=900\n", + ); + assert_eq!( + settings, + Settings { + depth: 4, + mode: 1, + ..Settings::default() + } + ); + } + + #[test] + fn a_depth_the_view_cannot_draw_is_not_taken() { + assert_eq!(Settings::parse("depth=0").depth, 3); + assert_eq!(Settings::parse("depth=6").depth, 6); + assert_eq!(Settings::parse("depth=7").depth, 3); + } +} diff --git a/crates/disktree-app/src/state.rs b/crates/disktree-app/src/state.rs index ee351f3a..648f011e 100644 --- a/crates/disktree-app/src/state.rs +++ b/crates/disktree-app/src/state.rs @@ -36,6 +36,7 @@ use rustc_hash::{FxHashMap, FxHashSet}; use crate::git::GitState; use crate::marks::{Marks, display_path, is_hidden}; +use crate::settings::Settings; use crate::treemap_view::{Mosaic, TileDeco}; /// What a tile's colour says. @@ -455,6 +456,9 @@ pub struct Disktree { pub scan_elapsed: Option, /// Unix seconds when the tree landed: the "now" ages are measured from. pub scanned_at: i64, + /// Where the view choices are saved. `None` keeps them for this run + /// only: no settings directory, or a test that must not write to one. + pub settings_path: Option, } impl Disktree { @@ -551,7 +555,15 @@ impl Disktree { scan_root: PathBuf::new(), scan_elapsed: None, scanned_at: now_seconds(), + settings_path: None, }; + // The panel's width changes continuously under a drag, so it is + // written down once, on the way out, with everything else. + cx.on_app_quit(|this, _| { + this.save_settings(); + std::future::ready(()) + }) + .detach(); tree.device = device_for(&tree.root_path); tree.full_disk_access = tree .home @@ -594,6 +606,59 @@ impl Disktree { app } + // ── saved choices ─────────────────────────────────────────────────── + + /// The view choices as they stand, for the settings file. + pub const fn settings(&self) -> Settings { + Settings { + depth: self.layout_options.max_depth, + include_hidden: self.options.include_hidden, + apparent_size: self.options.apparent_size, + mode: self.mode_index(), + panel_rems: self.panel_rems, + show_selection: self.show_selection, + } + } + + /// Take the saved choices the command line has no flag for. The depth + /// and the scan options arrive through the arguments instead, where a + /// flag can overrule them. + pub fn apply_settings(&mut self, saved: &Settings) { + // Age keeps areas by size, so it only holds while nothing, saved + // or flagged, asked for areas by files. + if saved.mode == 2 && self.options.metric == Metric::Bytes { + self.color_mode = ColorMode::Age; + } + self.panel_rems = saved.panel_rems; + self.show_selection = saved.show_selection; + } + + /// Write the view choices down. A failure goes to standard error and + /// no further: the choice still holds for this run, and a notice on + /// every click would be worse than the loss. + pub fn save_settings(&self) { + let Some(path) = self.settings_path.as_deref() else { + return; + }; + if let Err(error) = crate::settings::save(path, &self.settings()) { + eprintln!("Cannot save settings: {error}"); + } + } + + /// `i`: include or skip hidden entries, which changes what is measured. + pub fn toggle_hidden(&mut self, cx: &mut Context<'_, Self>) { + self.options.include_hidden = !self.options.include_hidden; + self.save_settings(); + self.start_scan(cx); + } + + /// `d`: disk usage or apparent size, which changes what is measured. + pub fn toggle_apparent_size(&mut self, cx: &mut Context<'_, Self>) { + self.options.apparent_size = !self.options.apparent_size; + self.save_settings(); + self.start_scan(cx); + } + /// 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>) { @@ -2051,6 +2116,7 @@ impl Disktree { .clamp(1, 6) as u32; self.layout_options.max_depth = depth; self.cache = None; + self.save_settings(); cx.notify(); } @@ -2094,6 +2160,7 @@ impl Disktree { if self.options.metric != metric { self.toggle_metric(cx); } + self.save_settings(); cx.notify(); } @@ -2730,16 +2797,11 @@ impl Disktree { "r" if !control => self.start_scan(cx), "g" if !control => self.go_to_disk(cx), "v" if !control && !shift => self.open_volumes(cx), - "i" if !control => { - self.options.include_hidden = !self.options.include_hidden; - self.start_scan(cx); - } - "d" if !control => { - self.options.apparent_size = !self.options.apparent_size; - self.start_scan(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; + self.save_settings(); cx.notify(); } "o" if !control => self.reveal_target(cx), diff --git a/crates/disktree-app/src/tests.rs b/crates/disktree-app/src/tests.rs index 3d7f151b..d033add8 100644 --- a/crates/disktree-app/src/tests.rs +++ b/crates/disktree-app/src/tests.rs @@ -1844,3 +1844,34 @@ fn the_power_menu_offers_only_what_the_cpus_can_tell_apart( draw(cx); assert!(read(&view, cx, |app| app.power_menu.is_none())); } + +#[gpui_kit::test] +fn view_choices_are_written_down_as_they_change(cx: &mut TestAppContext) { + cx.update(gpui_omarchy::init); + let temp = fixture(); + let config = tempfile::TempDir::new().expect("tempdir"); + let path = config.path().join("disktree").join("settings"); + let (view, cx) = view_over(temp.path(), cx); + update(&view, cx, |app, _| app.settings_path = Some(path.clone())); + draw(cx); + assert!(!path.exists(), "nothing changed yet"); + + press(cx, "]"); + press(cx, "t"); + press(cx, "p"); + let saved = crate::settings::load(&path).expect("saved"); + assert_eq!(saved.depth, 4); + assert_eq!(saved.mode, 1); + assert!(!saved.show_selection); + + // And a window opened with them starts as this one was left. + let again = update(&view, cx, |app, _| { + app.show_selection = true; + app.panel_rems = crate::state::PANEL_MIN_REMS; + app.apply_settings(&saved); + app.settings() + }); + assert!(!again.show_selection); + assert!((again.panel_rems - saved.panel_rems).abs() < f32::EPSILON); + assert_eq!(again.mode, 1); +} diff --git a/crates/disktree-app/src/views.rs b/crates/disktree-app/src/views.rs index c23e91b3..eac83def 100644 --- a/crates/disktree-app/src/views.rs +++ b/crates/disktree-app/src/views.rs @@ -834,10 +834,7 @@ fn view_settings( ) .tab_stop(false) .on_change(move |_, _, window, cx| { - let _ = entity.update(cx, |this, cx| { - this.options.include_hidden = !this.options.include_hidden; - this.start_scan(cx); - }); + let _ = entity.update(cx, Disktree::toggle_hidden); window.focus(&focus, cx); }) }; @@ -850,10 +847,7 @@ fn view_settings( ) .tab_stop(false) .on_change(move |_, _, window, cx| { - let _ = entity.update(cx, |this, cx| { - this.options.apparent_size = !this.options.apparent_size; - this.start_scan(cx); - }); + let _ = entity.update(cx, Disktree::toggle_apparent_size); window.focus(&focus, cx); }) };