Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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` |
Expand Down
5 changes: 5 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
58 changes: 56 additions & 2 deletions crates/disktree-app/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ mod git;
mod marks;
mod palette;
mod power;
mod settings;
mod state;
#[cfg(test)]
mod tests;
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
})
},
Expand All @@ -209,17 +220,34 @@ fn parse_args(args: impl Iterator<Item = std::ffi::OsString>) -> Result<Args> {
parse_args_with_power(args, power::PowerEfficiency::default())
}

#[cfg(test)]
fn parse_args_with_power(
args: impl Iterator<Item = std::ffi::OsString>,
preset: power::PowerEfficiency,
) -> Result<Args> {
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<Item = std::ffi::OsString>,
preset: power::PowerEfficiency,
saved: &settings::Settings,
) -> Result<Args> {
let mut root: Option<PathBuf> = 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
Expand Down Expand Up @@ -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;
Expand Down
192 changes: 192 additions & 0 deletions crates/disktree-app/src/settings.rs
Original file line number Diff line number Diff line change
@@ -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::<u32>()
&& (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::<f32>()
&& (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<PathBuf> {
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<Settings> {
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);
}
}
Loading