diff --git a/Cargo.lock b/Cargo.lock index afbab0d..2d9aee6 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -112,6 +112,15 @@ version = "2.13.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" +[[package]] +name = "block-buffer" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71" +dependencies = [ + "generic-array", +] + [[package]] name = "bstr" version = "1.13.1" @@ -237,6 +246,15 @@ version = "0.8.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" +[[package]] +name = "cpufeatures" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280" +dependencies = [ + "libc", +] + [[package]] name = "crc32fast" version = "1.5.4" @@ -305,6 +323,16 @@ dependencies = [ "winapi", ] +[[package]] +name = "crypto-common" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a" +dependencies = [ + "generic-array", + "typenum", +] + [[package]] name = "darling" version = "0.24.1" @@ -345,6 +373,16 @@ version = "0.5.8" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7cd812cc2bc1d69d4764bd80df88b4317eaef9e773c75226407d9bc0876b211c" +[[package]] +name = "digest" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" +dependencies = [ + "block-buffer", + "crypto-common", +] + [[package]] name = "dirs" version = "6.0.0" @@ -397,6 +435,16 @@ dependencies = [ "simd-adler32", ] +[[package]] +name = "filetime" +version = "0.2.30" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e1255e7a9f1902190d4c10a75f2f7f495d3d3ce13e9ba26e6c48683a0f4dbed7" +dependencies = [ + "cfg-if", + "libc", +] + [[package]] name = "find-msvc-tools" version = "0.1.14" @@ -444,6 +492,16 @@ dependencies = [ "slab", ] +[[package]] +name = "generic-array" +version = "0.14.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" +dependencies = [ + "typenum", + "version_check", +] + [[package]] name = "globset" version = "0.4.20" @@ -990,6 +1048,17 @@ dependencies = [ "serde", ] +[[package]] +name = "sha2" +version = "0.10.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283" +dependencies = [ + "cfg-if", + "cpufeatures", + "digest", +] + [[package]] name = "shlex" version = "2.0.1" @@ -1091,11 +1160,13 @@ dependencies = [ "chrono", "crossbeam-channel", "dirs", + "filetime", "globset", "libc", "rayon", "serde", "serde_json", + "sha2", "squid-core", "squid-platform", "squid-rules", @@ -1335,6 +1406,12 @@ version = "0.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5d99f8c9a7727884afe522e9bd5edbfc91a3312b36a77b5fb8926e4c31a41801" +[[package]] +name = "typenum" +version = "1.20.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" + [[package]] name = "unicode-ident" version = "1.0.27" @@ -1376,6 +1453,12 @@ version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" +[[package]] +name = "version_check" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" + [[package]] name = "walkdir" version = "2.5.0" diff --git a/Cargo.toml b/Cargo.toml index a7bd2a4..decb316 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -33,6 +33,8 @@ dirs = "6" libc = "0.2" plist = "1" chrono = { version = "0.4", default-features = false, features = ["clock", "std"] } +sha2 = "0.10" +filetime = "0.2" sysinfo = { version = "0.34", default-features = false, features = ["system", "network", "disk"] } crossterm = "0.28" ratatui = "0.29" diff --git a/crates/squid-cli/src/main.rs b/crates/squid-cli/src/main.rs index c2c59ec..1c2f125 100644 --- a/crates/squid-cli/src/main.rs +++ b/crates/squid-cli/src/main.rs @@ -64,6 +64,8 @@ enum Command { Uninstall(UninstallArgs), /// Deep clean: node_modules, build folders, disk images, stale archives Purge(PurgeArgs), + /// Find byte-identical duplicate files (three-stage hash funnel) + Dupes(DupesArgs), /// Open the interface: disk map, system meters, cleanup, history State, /// One-shot system snapshot (scripts, dotfiles, cron) @@ -141,6 +143,18 @@ struct PurgeArgs { min_age: Option, } +#[derive(Args, Debug)] +struct DupesArgs { + /// Where to look; defaults to your user folders on every drive + paths: Vec, + /// Size floor in bytes (default 1 MiB) + #[arg(long)] + min_size: Option, + /// How many groups to print + #[arg(long, default_value_t = 20)] + top: usize, +} + #[derive(Args, Debug)] struct StatusArgs { /// How many processes to list @@ -374,6 +388,7 @@ fn run() -> Result { Some(Command::Clean(args)) => cmd_clean(args, cli.json), Some(Command::Uninstall(args)) => cmd_uninstall(args, cli.json), Some(Command::Purge(args)) => cmd_purge(args, cli.json), + Some(Command::Dupes(args)) => cmd_dupes(args, cli.json), Some(Command::Status(args)) => cmd_status(args, cli.json), Some(Command::Analyze(args)) => cmd_analyze(args, cli.json), Some(Command::History(args)) => cmd_history(args, cli.json), @@ -594,7 +609,10 @@ fn with_progress( ), ); } - Event::Bucket { .. } | Event::Metered { .. } | Event::Done(_) => {} + Event::Bucket { .. } + | Event::Metered { .. } + | Event::Group { .. } + | Event::Done(_) => {} } } if stop_now { @@ -1142,6 +1160,75 @@ fn cmd_purge(args: PurgeArgs, json: bool) -> Result { // ---------------------------------------------------------------------- status +fn cmd_dupes(args: DupesArgs, json: bool) -> Result { + use squid_engine::duplicates; + let roots: Vec = if args.paths.is_empty() { + duplicates::default_roots() + } else { + args.paths.iter().map(|path| paths::expand(path)).collect() + }; + heading("Duplicate files"); + let report = with_progress("dupes", move |_engine, progress, cancel| { + duplicates::scan( + &roots, + args.min_size.unwrap_or(duplicates::DEFAULT_MIN_SIZE), + progress, + cancel, + ) + })?; + if json { + println!("{}", serde_json::to_string_pretty(&report)?); + return Ok(0); + } + shout( + "90", + &format!( + " funnel: {} walked → {} same-size → {} confirmed files in {} groups", + squid_core::bytes::format_thousands(report.walked), + squid_core::bytes::format_thousands(report.same_size), + squid_core::bytes::format_thousands(report.confirmed_files), + squid_core::bytes::format_thousands(report.confirmed_groups), + ), + ); + for group in report.groups.iter().take(args.top) { + let waste = group.size * (group.copies.len() as u64 - 1); + shout( + "36", + &format!( + " {} {} copies · {} each (wastes {})", + bullet(), + group.copies[0] + .path + .rsplit(['\\', '/']) + .next() + .unwrap_or("?"), + squid_core::Bytes(group.size).human(), + squid_core::Bytes(waste).human(), + ), + ); + for copy in &group.copies { + shout("90", &format!(" · {}", copy.path)); + } + } + if report.groups.len() > args.top { + shout( + "90", + &format!( + " … {} more groups (--top N to see them)", + report.groups.len() - args.top + ), + ); + } + shout( + "90", + &format!( + " total waste {}\n nothing deleted — the app offers these with recycle-bin undo", + squid_core::Bytes(report.wasted).human_long(), + ), + ); + Ok(0) +} + fn cmd_status(args: StatusArgs, json: bool) -> Result { let mut sampler = squid_stats::Sampler::new(); let _ = sampler.prime(); diff --git a/crates/squid-core/src/model.rs b/crates/squid-core/src/model.rs index 5c163cd..1089374 100644 --- a/crates/squid-core/src/model.rs +++ b/crates/squid-core/src/model.rs @@ -20,10 +20,16 @@ pub enum Category { LanguagePacks, Leftovers, UpdateInstallers, + /// Duplicate-file scan results (its own page, streamed group by group). + Duplicates, + /// AI tool caches and local model files (Ollama, HuggingFace, …). + AiTools, + /// Privacy traces: browser history, recent items, clipboard, activity. + Privacy, } impl Category { - pub const ALL: [Category; 10] = [ + pub const ALL: [Category; 13] = [ Category::SystemJunk, Category::AppCaches, Category::BrowserCaches, @@ -34,6 +40,9 @@ impl Category { Category::LanguagePacks, Category::Leftovers, Category::UpdateInstallers, + Category::Duplicates, + Category::AiTools, + Category::Privacy, ]; pub fn id(self) -> &'static str { @@ -48,6 +57,9 @@ impl Category { Category::LanguagePacks => "languages", Category::Leftovers => "leftovers", Category::UpdateInstallers => "update-installers", + Category::Duplicates => "duplicates", + Category::AiTools => "ai", + Category::Privacy => "privacy", } } @@ -63,6 +75,9 @@ impl Category { Category::LanguagePacks => "Unneeded Languages", Category::Leftovers => "Uninstaller Leftovers", Category::UpdateInstallers => "Update Installers", + Category::Duplicates => "Duplicate Files", + Category::AiTools => "AI Tools & Models", + Category::Privacy => "Privacy Traces", } } @@ -81,6 +96,9 @@ impl Category { Category::LanguagePacks => "Speech and localization data for languages you do not use", Category::Leftovers => "Data belonging to apps that are no longer installed", Category::UpdateInstallers => "Installer packages apps keep after a successful update", + Category::Duplicates => "Byte-identical files confirmed by a three-stage hash funnel", + Category::AiTools => "Local model weights and caches that re-download when needed", + Category::Privacy => "History and traces that disappear without a recycle bin", } } @@ -109,6 +127,9 @@ impl Category { "update-installer" | "update-installers" | "upgrades" | "upgrade-packages" => { Category::UpdateInstallers } + "duplicate" | "duplicates" | "duplicate-files" => Category::Duplicates, + "ai" | "ai-tools" | "ai-models" | "models" => Category::AiTools, + "privacy" | "privacy-traces" | "private" => Category::Privacy, _ => return None, }; Some(alias) diff --git a/crates/squid-core/src/progress.rs b/crates/squid-core/src/progress.rs index f6ac574..433f8ac 100644 --- a/crates/squid-core/src/progress.rs +++ b/crates/squid-core/src/progress.rs @@ -36,6 +36,13 @@ pub enum Event { files: u64, bytes: Bytes, }, + /// A finished work unit streamed as soon as it is confirmed, shaped by + /// the producing engine (duplicate groups land while the scan still + /// runs — MangoDisk's lesson that results beat progress bars). + Group { + kind: &'static str, + payload: serde_json::Value, + }, Deleted { path: PathBuf, freed: Bytes, diff --git a/crates/squid-core/src/safety.rs b/crates/squid-core/src/safety.rs index 769d28a..cac5229 100644 --- a/crates/squid-core/src/safety.rs +++ b/crates/squid-core/src/safety.rs @@ -186,6 +186,13 @@ pub struct SafetyPolicy { /// Roots whose contents a non-admin run may still reach — on Unix /// `/Applications`, on Windows `%ProgramData%` and `%PUBLIC%`. pub outside_home_ok: Vec, + /// Accept *any* existing volume as an allowed anchor, not just system + /// paths. The duplicate-file scan runs over whole drives by design — the + /// files are the user's own, they were confirmed byte-identical, and + /// deletion still goes through the recycle bin + undo path. Everything + /// else about the policy (hard-deny roots, protected folders, symlink + /// refusal) keeps its full teeth. + pub all_volumes_ok: bool, } impl Default for SafetyPolicy { @@ -208,6 +215,7 @@ impl Default for SafetyPolicy { allow_system_paths: true, follow_symlinks: false, outside_home_ok: outside_home_ok(), + all_volumes_ok: false, } } } @@ -234,6 +242,33 @@ impl SafetyPolicy { self } + /// Let an unprivileged run reach files on any existing volume (the + /// duplicate-file scan); see [`SafetyPolicy::all_volumes_ok`]. + pub fn with_all_volumes(mut self) -> Self { + self.all_volumes_ok = true; + self + } + + /// True when `norm` sits on a drive/volume that exists right now. The + /// scan-anchors-are-volumes rule keeps its teeth in the other checks: + /// hard-deny roots, deny-exact folders and reserved names all run first. + fn on_existing_volume(&self, norm: &Path) -> bool { + #[cfg(windows)] + { + match norm.components().next() { + Some(std::path::Component::Prefix(prefix)) => { + PathBuf::from(prefix.as_os_str()).exists() + } + _ => false, + } + } + #[cfg(not(windows))] + { + let _ = norm; + true + } + } + fn is_exact_denied(&self, path: &Path) -> bool { self.deny_exact.iter().any(|deny| { // Trailing glob star entries deny the directory itself only. @@ -304,6 +339,7 @@ impl SafetyPolicy { } if !self.allow_system_paths + && !(self.all_volumes_ok && self.on_existing_volume(&norm)) && !paths::is_within(&paths::home_dir(), &norm) && !self .outside_home_ok diff --git a/crates/squid-engine/Cargo.toml b/crates/squid-engine/Cargo.toml index d551d18..a1cbed9 100644 --- a/crates/squid-engine/Cargo.toml +++ b/crates/squid-engine/Cargo.toml @@ -19,5 +19,7 @@ walkdir.workspace = true globset.workspace = true crossbeam-channel.workspace = true chrono.workspace = true +sha2.workspace = true +filetime.workspace = true dirs.workspace = true libc.workspace = true diff --git a/crates/squid-engine/src/analyze.rs b/crates/squid-engine/src/analyze.rs index 32a401f..9447bc9 100644 --- a/crates/squid-engine/src/analyze.rs +++ b/crates/squid-engine/src/analyze.rs @@ -8,7 +8,7 @@ use serde::{Deserialize, Serialize}; use squid_core::fs; -use squid_core::progress::{CancelToken, Progress}; +use squid_core::progress::{CancelToken, Event, Progress}; use squid_core::Bytes; use std::path::{Path, PathBuf}; @@ -308,6 +308,117 @@ pub fn largest_files( Ok(found) } +/// Type buckets the large-file page filters on (extension → class). +/// Anything not listed lands in the catch-all "other". +pub fn file_class(path: &Path) -> &'static str { + let ext = path + .extension() + .and_then(|e| e.to_str()) + .unwrap_or("") + .to_ascii_lowercase(); + match ext.as_str() { + "mp4" | "mkv" | "avi" | "mov" | "wmv" | "flv" | "webm" | "ts" | "m2ts" => "video", + "zip" | "rar" | "7z" | "tar" | "gz" | "bz2" | "xz" | "zst" => "archive", + "exe" | "msi" | "msp" | "appx" | "msix" | "dmg" | "pkg" | "deb" | "rpm" | "appimage" => { + "installer" + } + "iso" | "img" | "vhd" | "vhdx" | "vmdk" | "qcow2" | "wim" | "esd" => "image", + _ => "other", + } +} + +/// Large files across several roots with a byte threshold and optional +/// type-class filter. Streams `Metered` (folders walked / bytes found); +/// returns every hit at or above `min_bytes` — the UI counts them all, +/// "共 214 个" honesty beats a capped top-list. +pub fn large_files( + roots: &[PathBuf], + min_bytes: u64, + class: Option<&str>, + cancel: &CancelToken, + progress: &Progress, +) -> squid_core::Result> { + let mut found: Vec = Vec::new(); + let mut stack: Vec<(PathBuf, usize)> = roots + .iter() + .filter(|root| root.is_dir()) + .map(|root| (root.clone(), 0usize)) + .collect(); + let mut visited = 0usize; + let mut emitted = 0u64; + progress.phase("bigfiles", "scanning for large files"); + while let Some((dir, depth)) = stack.pop() { + cancel.check()?; + visited += 1; + if visited % 256 == 0 { + progress.publish(Event::Metered { + files: visited as u64, + bytes: Bytes(emitted), + }); + } + if depth > 24 { + continue; + } + let Ok(entries) = std::fs::read_dir(&dir) else { + continue; + }; + for entry in entries.flatten() { + let path = entry.path(); + let Ok(meta) = entry.metadata() else { + continue; + }; + if meta.is_dir() { + if !is_mountpoint(&path) && !skip_infra(&entry.file_name().to_string_lossy()) { + stack.push((path, depth + 1)); + } + continue; + } + if !meta.is_file() || meta.len() < min_bytes { + continue; + } + if let Some(wanted) = class { + if file_class(&path) != wanted { + continue; + } + } + emitted += meta.len(); + let modified_ms = meta + .modified() + .or_else(|_| meta.created()) + .ok() + .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok()) + .map(|d| d.as_millis() as u64); + found.push(FileEntry { + path, + logical: Bytes(meta.len()), + allocated: Bytes(allocated_of(&meta)), + modified_ms, + }); + } + } + found.sort_by_key(|entry| std::cmp::Reverse(entry.size())); + progress.publish(Event::Metered { + files: visited as u64, + bytes: Bytes(emitted), + }); + Ok(found) +} + +/// System churn a large-file sweep should not crawl through. +fn skip_infra(name: &str) -> bool { + const SKIP: &[&str] = &[ + "$recycle.bin", + "system volume information", + "windows", + "program files", + "program files (x86)", + "node_modules", + ".git", + ]; + let lower = name.to_lowercase(); + SKIP.iter().any(|wanted| lower == *wanted) +} + #[cfg(unix)] fn allocated_of(meta: &std::fs::Metadata) -> u64 { use std::os::unix::fs::MetadataExt; diff --git a/crates/squid-engine/src/duplicates.rs b/crates/squid-engine/src/duplicates.rs new file mode 100644 index 0000000..c526f91 --- /dev/null +++ b/crates/squid-engine/src/duplicates.rs @@ -0,0 +1,641 @@ +//! Duplicate-file finder — the MangoDisk lesson, with our safety net. +//! +//! Finding byte-identical files cheaply is a **three-stage funnel**: +//! +//! 1. walk everything, bucket by exact size — a file with a unique size can +//! not have a duplicate, so terabytes drop out for the price of one `stat`; +//! 2. hash a 16 KiB sample from head, middle and tail of every same-size +//! candidate — different files diverge in those windows almost always, so +//! this kills the remaining false candidates with ~48 KiB of I/O each; +//! 3. full-stream SHA-256 only for what survived the sample — the expensive +//! stage runs on a small, pre-filtered set. +//! +//! Results land **group by group while the scan still runs** (a confirmed +//! group is pushed the moment its last file hashes), and every hash is +//! cached on disk keyed by *path + size + mtime*, so re-running the scan on +//! an unchanged disk costs the walk alone. +//! +//! Deletion is deliberately *not* this module's job: confirmed groups are +//! turned into ordinary [`CleanupItem`]s (one per copy, File kind) so the +//! engine's single delete path — safety re-validation, Recycle Bin, undo +//! ledger — guards duplicates exactly like every other byte squid touches. +//! MangoDisk deletes permanently; we do not. + +use crate::assets; +use serde::Serialize; +use sha2::{Digest, Sha256}; +use squid_core::progress::{CancelToken, Event, Progress}; +use squid_core::{Bytes, Category, CleanupItem, ItemKind}; +use std::collections::HashMap; +use std::fs::File; +use std::io::Read; +use std::path::PathBuf; +use std::sync::atomic::{AtomicU64, Ordering}; + +/// Files below this size are never offered: deduplicating a 4 KiB config is +/// noise, and the 1 MiB floor keeps the funnel's first stage cheap. +pub const DEFAULT_MIN_SIZE: u64 = 1024 * 1024; +/// Sample window at each of head / middle / tail. +const SAMPLE: usize = 16 * 1024; + +/// One file that survived the walk and is waiting for its hashes. +#[derive(Clone, Debug)] +struct Candidate { + path: PathBuf, + size: u64, + mtime_ms: u64, +} + +/// A confirmed group of byte-identical files. +#[derive(Clone, Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct DupGroup { + pub size: u64, + /// One entry per copy: (pretty path, mtime ms). + pub copies: Vec, + /// Index of the copy the UI should mark 「保留」 by default (shortest + /// path — the "original" almost always lives at the tidier address). + pub keep: usize, + /// True when at least one copy sits in a protected user-asset folder + /// (WeChat FileStorage …): the group is flagged, never auto-selected. + pub personal: bool, +} + +#[derive(Clone, Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct DupCopy { + /// Display spelling (home folded to `~`) for the row. + pub path: String, + pub mtime_ms: u64, + /// Why this copy may not be deleted (asset lock), when it may not. + pub locked: Option, + /// Exact path for the delete layer — serialised only for the app-side + /// cache, never rendered. + #[serde(skip)] + pub raw: PathBuf, +} + +/// Funnel counters streamed as `Metered`-style notes plus the final report. +#[derive(Clone, Debug, Default, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct DupStats { + pub walked: u64, + pub same_size: u64, + pub sample_hits: u64, + pub confirmed: u64, + pub wasted: u64, +} + +/// Persisted hash cache: path → (size, mtime, sample hash, full hash). +/// A stale entry (size or mtime moved) is re-measured, so correctness never +/// depends on the cache — only speed does. +mod cache { + use serde::{Deserialize, Serialize}; + use std::collections::HashMap; + use std::path::{Path, PathBuf}; + + #[derive(Default, Serialize, Deserialize)] + pub struct HashCache { + /// key: normalised path (lower-case on Windows) + /// value: (size, mtime_ms, sample_hash_hex, full_hash_hex) + pub entries: HashMap, + } + + impl HashCache { + pub fn path() -> PathBuf { + squid_core::Settings::config_dir().join("hash-cache.json") + } + + pub fn load() -> HashCache { + std::fs::read_to_string(Self::path()) + .ok() + .and_then(|text| serde_json::from_str(&text).ok()) + .unwrap_or_default() + } + + pub fn save(&self) { + if let Ok(text) = serde_json::to_string(&self) { + let path = Self::path(); + if let Some(parent) = path.parent() { + let _ = std::fs::create_dir_all(parent); + } + let _ = std::fs::write(path, text); + } + } + + pub fn lookup(&self, key: &Path, size: u64, mtime_ms: u64) -> Option<(&str, &str)> { + let (s, m, sample, full) = self.entries.get(key)?; + (*s == size && *m == mtime_ms).then_some((sample.as_str(), full.as_str())) + } + + pub fn put(&mut self, key: PathBuf, size: u64, mtime_ms: u64, sample: &str, full: &str) { + self.entries + .insert(key, (size, mtime_ms, sample.to_string(), full.to_string())); + } + } + + pub fn key_for(path: &Path) -> PathBuf { + let text = path.to_string_lossy().to_lowercase(); + PathBuf::from(text.replace('/', "\\")) + } +} + +fn mtime_ms(meta: &std::fs::Metadata) -> u64 { + meta.modified() + .or_else(|_| meta.created()) + .ok() + .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok()) + .map(|d| d.as_millis() as u64) + .unwrap_or(0) +} + +/// Read SAMPLE bytes at each of three offsets and hash the concatenation. +/// Tiny files (size < 3·SAMPLE) simply overlap — same answer, still cheap. +fn sample_digest(file: &mut File, size: u64) -> std::io::Result { + let mut hasher = Sha256::new(); + let window = SAMPLE.min(size as usize); + let third = ((size as i64) - window as i64).max(0) / 2; + for offset in [0i64, third, ((size as i64) - window as i64).max(0)] { + use std::io::Seek; + file.seek(std::io::SeekFrom::Start(offset as u64))?; + let mut buf = vec![0u8; window]; + file.read_exact(&mut buf)?; + hasher.update(&buf); + } + Ok(hex(&hasher.finalize())) +} + +fn full_digest(file: &mut File) -> std::io::Result { + let mut hasher = Sha256::new(); + let mut buf = vec![0u8; 256 * 1024]; + loop { + let read = file.read(&mut buf)?; + if read == 0 { + break; + } + hasher.update(&buf[..read]); + } + Ok(hex(&hasher.finalize())) +} + +fn hex(bytes: &[u8]) -> String { + bytes.iter().map(|b| format!("{b:02x}")).collect() +} + +/// Default scan scope: the user's own file areas — home folder (Documents, +/// Desktop, Downloads, Pictures, …) without descending into AppData churn, +/// plus every other fixed drive's user-shaped folders when present. +pub fn default_roots() -> Vec { + let home = squid_core::paths::home_dir(); + let mut roots = vec![home.clone()]; + // Other drives: add their root-level Users / Documents-style containers. + let platform = squid_platform::current(); + if let Ok(volumes) = platform.volumes() { + for volume in volumes { + if volume.is_removable || volume.is_root { + continue; + } + let users = volume.mount_point.join("Users"); + if users.is_dir() { + roots.push(users); + } else if volume.mount_point.is_dir() { + roots.push(volume.mount_point); + } + } + } + roots +} + +/// Skip infrastructure we have no business hashing: OS plumbing, recycle +/// bins, app data internals, and any VCS/package store folder by name. +fn skip_dir(name: &str) -> bool { + const SKIP: &[&str] = &[ + "$recycle.bin", + "system volume information", + "windows", + "program files", + "program files (x86)", + "programdata", + "appdata", + "node_modules", + ".git", + ".hg", + ".svn", + "target", + "__pycache__", + ".venv", + "venv", + ".terraform", + ".gradle", + ".m2", + ".cargo", + "vendor", + ]; + let lower = name.to_lowercase(); + SKIP.iter().any(|wanted| lower == *wanted) +} + +/// Run the funnel. Groups stream out as `Event::Group { kind: "dup", … }`; +/// the return value is the same data collected, with per-copy locks +/// resolved, so the command layer can hand the frontend a finished list too. +pub fn scan( + roots: &[PathBuf], + min_size: u64, + progress: &Progress, + cancel: &CancelToken, +) -> squid_core::Result { + let min_size = min_size.max(4096); + let mut hash_cache = cache::HashCache::load(); + let walked = AtomicU64::new(0); + + // ── Stage 1: walk, bucket by exact size ────────────────────────────── + progress.phase("duplicates", "第一级 · 按大小分组"); + let mut by_size: HashMap> = HashMap::new(); + { + let mut stack: Vec<(PathBuf, usize)> = roots + .iter() + .filter(|root| root.is_dir()) + .map(|root| (root.clone(), 0usize)) + .collect(); + while let Some((dir, depth)) = stack.pop() { + cancel.check()?; + if depth > 24 { + continue; + } + let Ok(entries) = std::fs::read_dir(&dir) else { + continue; + }; + for entry in entries.flatten() { + let path = entry.path(); + let Ok(file_type) = entry.file_type() else { + continue; + }; + if file_type.is_dir() { + if skip_dir(&entry.file_name().to_string_lossy()) { + continue; + } + stack.push((path, depth + 1)); + continue; + } + if !file_type.is_file() { + continue; + } + let count = walked.fetch_add(1, Ordering::Relaxed) + 1; + if count % 512 == 0 { + progress.publish(Event::Metered { + files: count, + bytes: Bytes(0), + }); + } + let Ok(meta) = entry.metadata() else { + continue; + }; + let size = meta.len(); + if size < min_size { + continue; + } + by_size.entry(size).or_default().push(Candidate { + path, + size, + mtime_ms: mtime_ms(&meta), + }); + } + } + } + let same_size: usize = by_size + .iter() + .filter(|(_, group)| group.len() > 1) + .map(|(_, group)| group.len()) + .sum(); + // Funnel counters ride structured notes the UI parses by prefix: + // `funnel::::`. + progress.publish(Event::Note(format!( + "funnel:{}:{same_size}:0:0", + walked.load(Ordering::Relaxed) + ))); + + // ── Stage 2: head/middle/tail sample hash ──────────────────────────── + progress.phase("duplicates", "第二级 · 头中尾采样哈希"); + let mut by_sample: HashMap<(u64, String), Vec> = HashMap::new(); + let mut sample_seen = 0u64; + for (_, group) in by_size.drain() { + if group.len() < 2 { + continue; + } + for candidate in group { + cancel.check()?; + sample_seen += 1; + progress.publish(Event::Tick { + done: sample_seen, + total: Some(same_size as u64), + subject: Some(candidate.path.clone()), + }); + let key = cache::key_for(&candidate.path); + let mut file = match File::open(&candidate.path) { + Ok(file) => file, + Err(_) => continue, + }; + let digest = match hash_cache.lookup(&key, candidate.size, candidate.mtime_ms) { + Some((sample, _full)) => sample.to_string(), + None => match sample_digest(&mut file, candidate.size) { + Ok(digest) => digest, + Err(_) => continue, + }, + }; + by_sample + .entry((candidate.size, digest)) + .or_default() + .push(candidate); + } + } + let sample_hits: usize = by_sample + .iter() + .filter(|(_, group)| group.len() > 1) + .map(|(_, group)| group.len()) + .sum(); + progress.publish(Event::Note(format!( + "funnel:{}:{same_size}:{sample_hits}:0", + walked.load(Ordering::Relaxed) + ))); + + // ── Stage 3: full hash on the survivors ────────────────────────────── + progress.phase("duplicates", "第三级 · 全量校验确认"); + let mut report = DupReport::default(); + let mut confirmed_seen = 0u64; + let groups: Vec<((u64, String), Vec)> = by_sample + .drain() + .filter(|(_, group)| group.len() > 1) + .collect(); + let total_full: u64 = groups.iter().map(|(_, group)| group.len() as u64).sum(); + for ((size, sample), group) in groups { + let mut by_full: HashMap> = HashMap::new(); + for candidate in group { + cancel.check()?; + confirmed_seen += 1; + progress.publish(Event::Tick { + done: confirmed_seen, + total: Some(total_full), + subject: Some(candidate.path.clone()), + }); + let key = cache::key_for(&candidate.path); + let digest = match hash_cache.lookup(&key, size, candidate.mtime_ms) { + Some((_sample, full)) => full.to_string(), + None => { + let Ok(mut file) = File::open(&candidate.path) else { + continue; + }; + // The sample matched; if the cache was cold this file was + // just read for the sample, so re-opening it is the price + // of a stateless cache layout. + match full_digest(&mut file) { + Ok(digest) => { + hash_cache.put(key.clone(), size, candidate.mtime_ms, &sample, &digest); + digest + } + Err(_) => continue, + } + } + }; + by_full.entry(digest).or_default().push(candidate); + } + for (_, copies) in by_full { + if copies.len() < 2 { + continue; + } + let group = build_group(size, &copies); + report.wasted += (copies.len() as u64 - 1) * size; + report.confirmed_groups += 1; + report.confirmed_files += copies.len() as u64; + progress.publish(Event::Group { + kind: "dup", + payload: serde_json::to_value(&group).unwrap_or_default(), + }); + report.groups.push(group); + } + } + // Persist the cold-half of the work so the next scan is a walk only. + // Keep the file bounded: half of it is dropped when it outgrows 600k + // entries (a few tens of MB of JSON is already generous). + if hash_cache.entries.len() > 600_000 { + let keep = hash_cache.entries.len() / 2; + let keys: Vec = hash_cache.entries.keys().skip(keep).cloned().collect(); + for key in keys { + hash_cache.entries.remove(&key); + } + } + hash_cache.save(); + report.walked = walked.load(Ordering::Relaxed); + report.same_size = same_size as u64; + report.sample_hits = sample_hits as u64; + report + .groups + .sort_by_key(|group| std::cmp::Reverse(group.size * (group.copies.len() as u64 - 1))); + progress.publish(Event::Note(format!( + "funnel:{}:{same_size}:{sample_hits}:{}", + report.walked, report.confirmed_files + ))); + Ok(report) +} + +/// Shape one confirmed group for the UI: keep-shortest-path, asset locks. +fn build_group(size: u64, copies: &[Candidate]) -> DupGroup { + let mut ordered: Vec<&Candidate> = copies.iter().collect(); + // Shortest path wins the 「保留」 chip; ties fall back to oldest mtime + // (the copy that has been there longest is the least likely accident). + ordered.sort_by(|a, b| { + a.path + .components() + .count() + .cmp(&b.path.components().count()) + .then(a.mtime_ms.cmp(&b.mtime_ms)) + .then(a.path.cmp(&b.path)) + }); + let mut personal = false; + let copies = ordered + .iter() + .map(|candidate| { + let locked = assets::asset_reason(&candidate.path).map(str::to_string); + if locked.is_some() { + personal = true; + } + DupCopy { + path: squid_core::paths::pretty(&candidate.path), + mtime_ms: candidate.mtime_ms, + locked, + raw: candidate.path.clone(), + } + }) + .collect(); + DupGroup { + size, + copies, + keep: 0, + personal, + } +} + +impl DupReport { + /// Flatten the user's deletion picks into engine items: one File item per + /// chosen copy. `selections` is (group index, copy indexes to delete) — + /// the keep decision belongs to the UI, this layer only executes what was + /// confirmed identical and explicitly picked. + pub fn items_for(&self, selections: &[(usize, Vec)]) -> Vec { + let now_ms = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map(|d| d.as_millis() as u64) + .unwrap_or(0); + let mut items = Vec::new(); + for (group_index, copies) in selections { + let Some(group) = self.groups.get(*group_index) else { + continue; + }; + for copy_index in copies { + let Some(copy) = group.copies.get(*copy_index) else { + continue; + }; + if group.copies.len() <= 1 || copy.locked.is_some() { + continue; + } + let path = copy.raw.clone(); + // Anchor two levels up: the safety policy demands the target + // sit *strictly below* an anchor (depth ≥ 1), and the file's + // own parent would place it at depth 0. + let anchor = path + .ancestors() + .nth(2) + .map(|dir| dir.to_path_buf()) + .unwrap_or_else(|| PathBuf::from("/")); + let mut item = CleanupItem::new( + path.clone(), + ItemKind::File, + Category::Duplicates, + path.file_name() + .map(|n| n.to_string_lossy().into_owned()) + .unwrap_or_default(), + ) + .with_rule("duplicates") + .with_anchors(std::iter::once(anchor)) + .with_note(format!("{} 份相同 · 已全量校验一致", group.copies.len())); + item.size = Bytes(group.size); + item.allocated = Bytes(group.size); + item.file_count = 1; + item.last_write_secs = Some(now_ms.saturating_sub(copy.mtime_ms) / 1000); + item.evidence = vec![format!("record:sha256:{}", group.size)]; + items.push(item); + } + } + items + } +} + +/// Everything a finished scan says: the groups plus the funnel counters the +/// UI prints under its title. +#[derive(Clone, Debug, Default, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct DupReport { + pub groups: Vec, + pub walked: u64, + pub same_size: u64, + pub sample_hits: u64, + pub confirmed_groups: u64, + pub confirmed_files: u64, + pub wasted: u64, +} + +#[cfg(test)] +mod tests { + use super::*; + use squid_core::progress::Progress; + + fn scratch(tag: &str) -> Option { + // Keep test hashes out of the real config-dir cache file. + static STATE: std::sync::Once = std::sync::Once::new(); + STATE.call_once(|| { + let dir = std::env::temp_dir().join(format!("squid-dups-state-{}", std::process::id())); + if std::fs::create_dir_all(&dir).is_ok() { + std::env::set_var("SQUID_STATE_DIR", &dir); + } + }); + let dir = std::env::temp_dir().join(format!( + "squid-dups-{}-{tag}-{}", + std::process::id(), + squid_core::ledger::new_session_id() + )); + match std::fs::create_dir_all(&dir) { + Ok(()) => Some(dir), + Err(error) => { + eprintln!("skipping: scratch denied ({error})"); + None + } + } + } + + #[test] + fn identical_files_land_in_one_group_with_the_neat_copy_kept() { + let Some(root) = scratch("same") else { return }; + let payload = vec![7u8; 2 * 1024 * 1024]; + let deep = root.join("a").join("b").join("c"); + std::fs::create_dir_all(&deep).unwrap(); + std::fs::write(root.join("copy.bin"), &payload).unwrap(); + std::fs::write(deep.join("copy.bin"), &payload).unwrap(); + std::fs::write(root.join("other.bin"), vec![9u8; payload.len()]).unwrap(); + + let progress = Progress::new(); + let report = scan( + std::slice::from_ref(&root), + 1024 * 1024, + &progress, + &CancelToken::new(), + ) + .expect("scan"); + assert_eq!(report.groups.len(), 1, "{:?}", report.groups); + let group = &report.groups[0]; + assert_eq!(group.copies.len(), 2); + // keep = shortest path: the root-level copy wins the chip. + assert!(!group.copies[group.keep].path.contains("b\\c")); + assert_eq!(report.confirmed_files, 2); + let _ = std::fs::remove_dir_all(&root); + } + + #[test] + fn same_size_different_bytes_never_matches() { + // The whole point of stage 2/3: two same-size files differing only in + // the middle byte past the head sample window. + let Some(root) = scratch("diff") else { return }; + let a = vec![3u8; 200_000]; + let mut b = vec![3u8; 200_000]; + b[100_001] = 4; + std::fs::write(root.join("a.bin"), &a).unwrap(); + std::fs::write(root.join("b.bin"), &b).unwrap(); + drop(a); + drop(b); + let progress = Progress::new(); + let report = scan( + std::slice::from_ref(&root), + 1024, + &progress, + &CancelToken::new(), + ) + .expect("scan"); + assert!(report.groups.is_empty(), "{:?}", report.groups); + let _ = std::fs::remove_dir_all(&root); + } + + #[test] + fn tiny_files_are_not_offered_at_all() { + let Some(root) = scratch("tiny") else { return }; + std::fs::write(root.join("one.txt"), b"same").unwrap(); + std::fs::write(root.join("two.txt"), b"same").unwrap(); + let progress = Progress::new(); + let report = scan( + std::slice::from_ref(&root), + DEFAULT_MIN_SIZE, + &progress, + &CancelToken::new(), + ) + .expect("scan"); + assert_eq!(report.walked, 2); + assert_eq!(report.same_size, 0); + let _ = std::fs::remove_dir_all(&root); + } +} diff --git a/crates/squid-engine/src/lib.rs b/crates/squid-engine/src/lib.rs index 704693a..5722792 100644 --- a/crates/squid-engine/src/lib.rs +++ b/crates/squid-engine/src/lib.rs @@ -15,6 +15,7 @@ pub mod analyze; pub mod assets; pub mod clean; pub mod delete; +pub mod duplicates; pub mod insights; pub mod purge; pub mod uninstall; @@ -82,6 +83,15 @@ impl Engine { self.platform.as_ref() } + /// An engine whose safety policy lets an unprivileged run reach files + /// on any existing volume. Built for the duplicate-file delete path: + /// byte-confirmed copies of the user's own files, deleted to the + /// recycle bin, everywhere the scan looked. All other guardrails stay. + pub fn with_volume_wide_safety(mut self) -> Engine { + self.safety = self.safety.clone().with_all_volumes(); + self + } + pub fn settings(&self) -> &Settings { &self.settings } diff --git a/crates/squid-tui/src/app.rs b/crates/squid-tui/src/app.rs index 0cd2b6c..c4a3d72 100644 --- a/crates/squid-tui/src/app.rs +++ b/crates/squid-tui/src/app.rs @@ -890,6 +890,7 @@ impl App { panel.buckets.insert(category, (total, count)); } Event::Metered { .. } => {} + Event::Group { .. } => {} Event::Deleted { path, freed } => { self.push_log(format!( "removed {} ({})", diff --git a/crates/squid-tui/src/theme.rs b/crates/squid-tui/src/theme.rs index cceeedc..bb8935b 100644 --- a/crates/squid-tui/src/theme.rs +++ b/crates/squid-tui/src/theme.rs @@ -135,6 +135,9 @@ impl Strings { C::LanguagePacks => "多余语言包", C::Leftovers => "卸载残留", C::UpdateInstallers => "升级安装包", + C::Duplicates => "重复文件", + C::AiTools => "AI 工具与模型", + C::Privacy => "隐私痕迹", C::Trash => self.bin(), }, }) diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock index f21054a..c7cf648 100644 --- a/src-tauri/Cargo.lock +++ b/src-tauri/Cargo.lock @@ -1135,6 +1135,16 @@ dependencies = [ "rustc_version", ] +[[package]] +name = "filetime" +version = "0.2.30" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e1255e7a9f1902190d4c10a75f2f7f495d3d3ce13e9ba26e6c48683a0f4dbed7" +dependencies = [ + "cfg-if", + "libc", +] + [[package]] name = "find-msvc-tools" version = "0.1.15" @@ -3551,11 +3561,13 @@ dependencies = [ "chrono", "crossbeam-channel", "dirs 6.0.0", + "filetime", "globset", "libc", "rayon", "serde", "serde_json", + "sha2 0.10.9", "squid-core", "squid-platform", "squid-rules", diff --git a/src/App.tsx b/src/App.tsx index 47b9842..5c3d2fa 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -3,7 +3,9 @@ import { Boxes, ChevronDown, CircleGauge, + CopyX, Eraser, + FileArchive, History, LayoutDashboard, MonitorSmartphone, @@ -32,7 +34,9 @@ import { useToast } from "./components/ui"; import { SetupPanel } from "./components/SetupPanel"; import appIconUrl from "../src-tauri/icons/128x128.png"; import { ApplicationsPage } from "./pages/ApplicationsPage"; +import { DuplicateFilesPage } from "./pages/DuplicateFilesPage"; import { HistoryPage } from "./pages/HistoryPage"; +import { LargeFilesPage } from "./pages/LargeFilesPage"; import { OverviewPage } from "./pages/OverviewPage"; import { PermissionsPage } from "./pages/PermissionsPage"; import { SettingsPage } from "./pages/SettingsPage"; @@ -91,6 +95,18 @@ const NAV_GROUPS: { labelZh: "存储空间", icon: Boxes, }, + { + id: "duplicates", + labelEn: "Duplicate files", + labelZh: "重复文件", + icon: CopyX, + }, + { + id: "large-files", + labelEn: "Large files", + labelZh: "大文件", + icon: FileArchive, + }, { id: "system", labelEn: "Real-time monitor", @@ -120,6 +136,11 @@ const PAGE_TITLES: Record = { permissions: ["Permissions", "权限管理"], widget: ["Desktop widget", "桌面小工具"], storage: ["Storage", "存储空间"], + duplicates: ["Duplicate files", "重复文件"], + "large-files": ["Large files", "大文件"], + maintenance: ["System maintenance", "系统维护"], + privacy: ["Privacy cleaning", "隐私清理"], + optimization: ["System optimisation", "系统优化"], system: ["Real-time monitor", "实时监控"], history: ["History", "历史记录"], settings: ["Settings", "设置"], @@ -357,6 +378,8 @@ export default function App() { {page === "permissions" ? : null} {page === "widget" ? : null} {page === "storage" ? : null} + {page === "duplicates" ? : null} + {page === "large-files" ? : null} {page === "system" ? ( max) max = a; + if (a < min) min = a; + } + const s2 = sum * sum; + const l2 = length * length; + return Math.max((l2 * max) / s2, s2 / (l2 * min)); +} + +function squarify( + items: TreemapItem[], + rect: { x: number; y: number; w: number; h: number }, + total: number, + out: TreemapRect[], +) { + const area = rect.w * rect.h; + if (items.length === 0 || area <= 0 || total <= 0) return; + if (items.length === 1) { + out.push({ ...rect, item: items[0] }); + return; + } + // Greedy squarify: extend a row along the shorter side while the worst + // aspect ratio improves; lay the row down and recurse the remainder. + const shorter = Math.min(rect.w, rect.h); + let row: TreemapItem[] = []; + let rest = items; + for (let i = 0; i < items.length; i += 1) { + const candidate = [...row, items[i]]; + if (row.length === 0 || worst(candidate, shorter, total, area) <= worst(row, shorter, total, area)) { + row = candidate; + rest = items.slice(i + 1); + } else { + break; + } + } + const rowValue = row.reduce((sum, item) => sum + item.value, 0); + if (rowValue <= 0) { + row.forEach((item) => out.push({ ...rect, item })); + return; + } + const thickness = (rowValue / total) * area / shorter; + let offset = 0; + for (const item of row) { + const span = ((item.value / total) * area) / Math.max(thickness, 1e-9); + if (rect.w >= rect.h) { + out.push({ x: rect.x, y: rect.y + offset, w: thickness, h: span, item }); + } else { + out.push({ x: rect.x + offset, y: rect.y, w: span, h: thickness, item }); + } + offset += span; + } + const consumed = (rowValue / total) * area / shorter; + const remainder = + rect.w >= rect.h + ? { x: rect.x + consumed, y: rect.y, w: rect.w - consumed, h: rect.h } + : { x: rect.x, y: rect.y + consumed, w: rect.w, h: rect.h - consumed }; + const restTotal = total - rowValue; + squarify(rest, remainder, restTotal, out); +} + +export function Treemap({ + items, + width, + height, + onSelect, +}: { + items: TreemapItem[]; + width: number; + height: number; + onSelect: (id: string) => void; +}) { + const rects = useMemo(() => { + const sorted = [...items].filter((item) => item.value > 0).sort((a, b) => b.value - a.value); + const total = sorted.reduce((sum, item) => sum + item.value, 0); + const out: TreemapRect[] = []; + squarify(sorted, { x: 0, y: 0, w: width, h: height }, total, out); + return out; + }, [items, width, height]); + + return ( +
+ {rects.map((rect) => { + const roomy = rect.w > 84 && rect.h > 42; + const midSized = rect.w > 46 && rect.h > 20; + return ( + + ); + })} +
+ ); +} diff --git a/src/components/ui.tsx b/src/components/ui.tsx index 67e41ff..a2e77ef 100644 --- a/src/components/ui.tsx +++ b/src/components/ui.tsx @@ -2,10 +2,13 @@ import { AlertTriangle, AppWindow, Boxes, + Bot, Check, ChevronDown, Code2, + CopyX, DownloadCloud, + EyeOff, FileWarning, Globe2, Languages, @@ -120,6 +123,30 @@ export const CATEGORY_META: Record = { icon: DownloadCloud, tone: "green", }, + duplicates: { + en: "Duplicate files", + zh: "重复文件", + blurbEn: "Byte-identical copies confirmed by full hashing", + blurbZh: "全量哈希确认的完全相同文件", + icon: CopyX, + tone: "orange", + }, + "ai-tools": { + en: "AI tools & models", + zh: "AI 工具与模型", + blurbEn: "Local models and caches that re-download on demand", + blurbZh: "本地模型与缓存;模型删除后需重新下载", + icon: Bot, + tone: "violet", + }, + privacy: { + en: "Privacy traces", + zh: "隐私痕迹", + blurbEn: "History and traces removed without a recycle bin", + blurbZh: "历史与痕迹;删除不进回收站", + icon: EyeOff, + tone: "slate", + }, }; export const CATEGORY_ORDER = Object.keys(CATEGORY_META) as Category[]; @@ -300,6 +327,8 @@ export function ProgressCard({ plan: ["Finding application leftovers", "正在查找应用残留"], storage: ["Measuring folders", "正在测量文件夹"], files: ["Finding the largest files", "正在查找大文件"], + bigfiles: ["Scanning every drive for large files", "正在遍历所有磁盘查找大文件"], + duplicates: ["Hashing duplicates (3-stage funnel)", "正在哈希校验重复文件(三级漏斗)"], orphans: ["Finding unused leftovers", "正在查找孤立残留"], }; const pair = labels[progress.phase]; diff --git a/src/hooks/useDuplicatesWorkspace.ts b/src/hooks/useDuplicatesWorkspace.ts new file mode 100644 index 0000000..34c39bf --- /dev/null +++ b/src/hooks/useDuplicatesWorkspace.ts @@ -0,0 +1,339 @@ +import { useCallback, useRef, useState } from "react"; +import { api, subscribeJobProgress } from "../lib/api"; +import { messageFrom } from "../lib/format"; +import type { DeleteResult, DupsResult, DupGroup, JobProgress } from "../types"; + +function jobId(): string { + return crypto.randomUUID?.() ?? `${Date.now()}-${Math.random().toString(36).slice(2)}`; +} + +/** Funnel counters streamed as `funnel::::` + * notes — the scan tells the UI how much each stage eliminated, live. */ +export interface Funnel { + walked: number; + sameSize: number; + sampleHits: number; + confirmed: number; +} + +export type KeepStrategy = "shortest" | "oldest"; + +/** Which copy of a group survives under a strategy. Locked (personal) + * copies are preferred keeps — a WeChat FileStorage copy should never be + * the one an automatic rule picks for deletion. */ +export function keepIndexOf(group: DupGroup, strategy: KeepStrategy): number { + let best = 0; + for (let i = 1; i < group.copies.length; i += 1) { + const candidate = group.copies[i]; + const current = group.copies[best]; + if (candidate.locked && !current.locked) { + best = i; + continue; + } + if (!candidate.locked && current.locked) continue; + if (strategy === "oldest") { + if (candidate.mtimeMs < current.mtimeMs) best = i; + } else if ( + candidate.path.length < current.path.length || + (candidate.path.length === current.path.length && candidate.mtimeMs < current.mtimeMs) + ) { + best = i; + } + } + return best; +} + +/** Deletion picks per group: group index → copy indexes marked for removal. */ +export type Picks = Map>; + +export function smartPicks(groups: DupGroup[], strategy: KeepStrategy): Picks { + const picks: Picks = new Map(); + groups.forEach((group, groupIndex) => { + const keep = keepIndexOf(group, strategy); + const copies = new Set(); + group.copies.forEach((copy, copyIndex) => { + if (copyIndex !== keep && !copy.locked) copies.add(copyIndex); + }); + if (copies.size > 0) picks.set(groupIndex, copies); + }); + return picks; +} + +/** Stable signature for a group: ignore decisions survive the final report + * re-sorting the confirmation-order stream. */ +export function groupKey(group: DupGroup): string { + return `${group.size}|${group.copies[0]?.path ?? ""}`; +} + +export interface DuplicatesWorkspace { + result: DupsResult | null; + /** Visible groups with their backend scan indices (picks/ignore keep both + * layers addressed by the same stable index). */ + visible: { group: DupGroup; index: number }[]; + funnel: Funnel; + progress: JobProgress | null; + scanning: boolean; + deleting: boolean; + error: string | null; + summary: DeleteResult | null; + picks: Picks; + keepStrategy: KeepStrategy; + /** Group signatures the user dismissed with 「忽略本组」 — filtered from + * the visible list, sums adjust live, backend indices stay stable. */ + ignored: Set; + selectedCount: number; + selectedBytes: number; + runScan: (roots: string[], minSize: number | null) => Promise; + cancel: () => Promise; + smartSelect: (strategy?: KeepStrategy) => void; + invertSelection: () => void; + clearPicks: () => void; + toggleCopy: (groupIndex: number, copyIndex: number) => void; + setKeepStrategy: (strategy: KeepStrategy) => void; + removeGroup: (groupIndex: number) => void; + clean: (mode: "trash" | "permanent") => Promise; + clearError: () => void; +} + +export function useDuplicatesWorkspace(): DuplicatesWorkspace { + const [result, setResult] = useState(null); + const [liveGroups, setLiveGroups] = useState([]); + const [funnel, setFunnel] = useState({ + walked: 0, + sameSize: 0, + sampleHits: 0, + confirmed: 0, + }); + const [progress, setProgress] = useState(null); + const [scanning, setScanning] = useState(false); + const [deleting, setDeleting] = useState(false); + const [error, setError] = useState(null); + const [summary, setSummary] = useState(null); + const [picks, setPicks] = useState(new Map()); + const [ignored, setIgnored] = useState>(new Set()); + const [keepStrategy, setStrategy] = useState("shortest"); + const currentJob = useRef(null); + const strategyRef = useRef(keepStrategy); + strategyRef.current = keepStrategy; + + const runScan = useCallback( + async (roots: string[], minSize: number | null) => { + if (scanning || deleting) return; + const id = jobId(); + currentJob.current = id; + setScanning(true); + setError(null); + setSummary(null); + setResult(null); + setProgress(null); + setLiveGroups([]); + setIgnored(new Set()); + setFunnel({ walked: 0, sameSize: 0, sampleHits: 0, confirmed: 0 }); + setPicks(new Map()); + const stop = await subscribeJobProgress(id, (event) => { + if (event.event === "note" && event.detail?.startsWith("funnel:")) { + const [, walked, same, hits, confirmed] = event.detail.split(":"); + setFunnel({ + walked: Number(walked) || 0, + sameSize: Number(same) || 0, + sampleHits: Number(hits) || 0, + confirmed: Number(confirmed) || 0, + }); + return; + } + if (event.event === "group" && event.detail?.startsWith("dup:")) { + try { + const group = JSON.parse(event.detail.slice(4)) as DupGroup; + setLiveGroups((current) => + [...current, group].sort( + (a, b) => b.size * (b.copies.length - 1) - a.size * (a.copies.length - 1), + ), + ); + } catch { + /* malformed frame: the final report replaces the stream anyway */ + } + return; + } + if (event.event === "metered" && event.done !== null) { + // Stage-1 walk: files streamed; stage-2/3 ticks drive `progress`. + setFunnel((current) => ({ ...current, walked: event.done as number })); + return; + } + setProgress(event); + }); + try { + const view = await api.duplicatesScan(id, roots, minSize); + setResult(view); + setLiveGroups(view.report.groups); + setFunnel((current) => ({ + walked: view.report.walked || current.walked, + sameSize: view.report.sameSize || current.sameSize, + sampleHits: view.report.sampleHits || current.sampleHits, + confirmed: view.report.confirmedFiles || current.confirmed, + })); + setPicks(smartPicks(view.report.groups, strategyRef.current)); + } catch (reason) { + if (!messageFrom(reason).includes("cancel")) setError(messageFrom(reason)); + } finally { + stop(); + setScanning(false); + currentJob.current = null; + } + }, + [deleting, scanning], + ); + + const cancel = useCallback(async () => { + if (currentJob.current) { + await api.cancelJob(currentJob.current).catch(() => undefined); + } + }, []); + + const groups = result?.report.groups ?? liveGroups; + const ignoredRef = useRef(ignored); + ignoredRef.current = ignored; + + const smartSelect = useCallback( + (strategy?: KeepStrategy) => { + const fresh = smartPicks(groups, strategy ?? strategyRef.current); + // An ignored group stays ignored: no picks come back for it. + fresh.forEach((_copies, index) => { + const group = groups[index]; + if (group && ignoredRef.current.has(groupKey(group))) fresh.delete(index); + }); + setPicks(fresh); + }, + [groups], + ); + + const invertSelection = useCallback(() => { + setPicks((current) => { + const next: Picks = new Map(); + groups.forEach((group, groupIndex) => { + if (ignoredRef.current.has(groupKey(group))) return; + const keep = keepIndexOf(group, strategyRef.current); + const chosen = current.get(groupIndex) ?? new Set(); + const copies = new Set(); + group.copies.forEach((copy, copyIndex) => { + if (copyIndex === keep || copy.locked) return; + if (!chosen.has(copyIndex)) copies.add(copyIndex); + }); + if (copies.size > 0) next.set(groupIndex, copies); + }); + return next; + }); + }, [groups]); + + const clearPicks = useCallback(() => setPicks(new Map()), []); + + const toggleCopy = useCallback((groupIndex: number, copyIndex: number) => { + setPicks((current) => { + const next = new Map(current); + const chosen = new Set(next.get(groupIndex) ?? []); + if (chosen.has(copyIndex)) chosen.delete(copyIndex); + else chosen.add(copyIndex); + if (chosen.size > 0) next.set(groupIndex, chosen); + else next.delete(groupIndex); + return next; + }); + }, []); + + const setKeepStrategy = useCallback( + (strategy: KeepStrategy) => { + setStrategy(strategy); + smartSelect(strategy); + }, + [smartSelect], + ); + + /** Ignore keeps the group out of the list and out of every sum, but the + * backend scan indices stay untouched — deletion talks in those. */ + const removeGroup = useCallback((groupIndex: number) => { + const group = groups[groupIndex]; + if (!group) return; + const key = groupKey(group); + setIgnored((current) => new Set(current).add(key)); + setPicks((current) => { + const next = new Map(current); + next.delete(groupIndex); + return next; + }); + }, [groups]); + + /** Visible groups paired with their *backend scan index* so picks and + * deletes never drift after a group is ignored. */ + const entries = groups + .map((group, index) => ({ group, index })) + .filter(({ group }) => !ignored.has(groupKey(group))); + + const clean = useCallback( + async (mode: "trash" | "permanent") => { + if (!result || deleting) return null; + const selections: [number, number[]][] = []; + picks.forEach((copies, groupIndex) => { + if (groupIndex < result.report.groups.length && copies.size > 0) { + selections.push([groupIndex, [...copies]]); + } + }); + if (selections.length === 0) return null; + const id = jobId(); + currentJob.current = id; + setDeleting(true); + setError(null); + try { + const outcome = await api.duplicatesDelete(id, result.scanId, selections, mode); + setSummary(outcome); + setResult(null); + setLiveGroups([]); + setPicks(new Map()); + setIgnored(new Set()); + setFunnel({ walked: 0, sameSize: 0, sampleHits: 0, confirmed: 0 }); + return outcome; + } catch (reason) { + setError(messageFrom(reason)); + return null; + } finally { + setDeleting(false); + currentJob.current = null; + } + }, + [deleting, picks, result], + ); + + const clearError = useCallback(() => setError(null), []); + + let count = 0; + let bytes = 0; + picks.forEach((copies, groupIndex) => { + const group = groups[groupIndex]; + if (!group) return; + count += copies.size; + bytes += copies.size * group.size; + }); + + return { + result, + visible: entries, + funnel, + progress, + scanning, + deleting, + error, + summary, + picks, + keepStrategy, + ignored, + selectedCount: count, + selectedBytes: bytes, + runScan, + cancel, + smartSelect, + invertSelection, + clearPicks, + toggleCopy, + setKeepStrategy, + removeGroup, + clean, + clearError, + }; +} diff --git a/src/lib/api.ts b/src/lib/api.ts index 7df003d..44f841d 100644 --- a/src/lib/api.ts +++ b/src/lib/api.ts @@ -5,9 +5,11 @@ import type { Bootstrap, DeleteMode, DeleteResult, + DupsResult, ExploreResult, HistorySession, JobProgress, + LargeFile, LargestFile, ManageView, PageId, @@ -61,6 +63,23 @@ export const api = { invoke("purge_scan", { jobId, roots, minAgeDays, force }), purgeDelete: (jobId: string, scanId: string, selected: number[], mode: DeleteMode) => invoke("purge_delete", { jobId, scanId, selected, mode }), + duplicatesScan: (jobId: string, roots: string[] = [], minSize: number | null = null) => + invoke("duplicates_scan", { jobId, roots, minSize }), + duplicatesDelete: ( + jobId: string, + scanId: string, + // (group index, copy indexes to delete) — the keep decision is the UI's. + selections: [number, number[]][], + mode: DeleteMode, + ) => invoke("duplicates_delete", { jobId, scanId, selections, mode }), + largeFilesScan: ( + jobId: string, + roots: string[] = [], + minBytes: number | null = null, + fileClass: string | null = null, + ) => invoke("large_files_scan", { jobId, roots, minBytes, class: fileClass }), + largeFilesDelete: (jobId: string, paths: string[], mode: DeleteMode) => + invoke("large_files_delete", { jobId, paths, mode }), appsScan: (jobId: string) => invoke("apps_scan", { jobId }), appPlan: (jobId: string, appKey: string) => invoke("app_plan", { jobId, appKey }), appUninstall: (jobId: string, planId: string, selected: number[], mode: DeleteMode) => diff --git a/src/pages/DuplicateFilesPage.tsx b/src/pages/DuplicateFilesPage.tsx new file mode 100644 index 0000000..1fdfa1b --- /dev/null +++ b/src/pages/DuplicateFilesPage.tsx @@ -0,0 +1,393 @@ +import { + CopyX, + FileQuestion, + FolderPlus, + Lock, + MapPin, + ShieldAlert, + Sparkles, + Trash2, + X, +} from "lucide-react"; +import { useState } from "react"; +import { open } from "@tauri-apps/plugin-dialog"; +import * as apiClient from "../lib/api"; +import { useI18n } from "../i18n"; +import { agoLabel, formatBytes, formatCount } from "../lib/format"; +import { keepIndexOf, useDuplicatesWorkspace } from "../hooks/useDuplicatesWorkspace"; +import { + Button, + Checkbox, + EmptyState, + InlineError, + PageHeader, + ProgressCard, + useToast, +} from "../components/ui"; +import type { DupGroup } from "../types"; + +const MIN_SIZE_OPTIONS = [ + { value: 1024 * 1024, label: "≥1MB" }, + { value: 10 * 1024 * 1024, label: "≥10MB" }, + { value: 100 * 1024 * 1024, label: "≥100MB" }, +]; + +function FunnelStage({ + value, + label, + hot, +}: { + value: number; + label: string; + hot?: boolean; +}) { + return ( +
+ {formatCount(value)} + {label} +
+ ); +} + +function DupGroupCard({ + group, + index, + keep, + picked, + lang, + onToggle, + onDismiss, +}: { + group: DupGroup; + index: number; + keep: number; + picked: Set | undefined; + lang: "zh" | "en"; + onToggle: (groupIndex: number, copyIndex: number) => void; + onDismiss: (groupIndex: number) => void; +}) { + const { t } = useI18n(); + const wasted = group.size * (group.copies.length - 1); + return ( +
+
+
+ + {group.copies.length} {t("copies", "份相同")} + + {group.copies[keep]?.path.split(/[\\/]/).pop()} + + {t("wastes", "重复浪费")} {formatBytes(wasted)} + + {group.personal ? ( + + + {t("personal files", "个人文件")} + + ) : null} +
+
+ {formatBytes(group.size)} {t("each", "/ 份")} +
+ +
+
    + {group.copies.map((copy, copyIndex) => { + const isKeep = copyIndex === keep; + const checked = picked?.has(copyIndex) ?? false; + return ( +
  • + onToggle(index, copyIndex)} + label={copy.path} + /> + {isKeep ? {t("keep", "保留")} : null} + {copy.locked ? ( + + + + ) : null} + + {copy.path} + + + {copy.mtimeMs ? agoLabel(copy.mtimeMs, lang) : ""} + + +
  • + ); + })} +
+
+ ); +} + +export function DuplicateFilesPage() { + const { t, lang } = useI18n(); + const { push } = useToast(); + const workspace = useDuplicatesWorkspace(); + const [minSize, setMinSize] = useState(1024 * 1024); + const [extraRoots, setExtraRoots] = useState([]); + const [confirming, setConfirming] = useState(false); + + const entries = workspace.visible; + const groups = entries.map((entry) => entry.group); + const report = workspace.result?.report; + + const addRoot = async () => { + const chosen = await open({ + directory: true, + multiple: true, + title: t("Add folders to the duplicate scan", "选择要一起扫描的文件夹"), + }); + if (Array.isArray(chosen)) setExtraRoots((current) => [...current, ...chosen]); + else if (typeof chosen === "string") setExtraRoots((current) => [...current, chosen]); + }; + + const start = () => { + setConfirming(false); + void workspace.runScan(extraRoots, minSize); + }; + + const confirmClean = async () => { + const outcome = await workspace.clean("trash"); + setConfirming(false); + if (outcome) { + push( + lang === "zh" + ? `已将 ${outcome.removed} 个副本移入回收站(${formatBytes(outcome.freed)}),可在「历史记录」撤销` + : `Moved ${outcome.removed} copies to the Recycle Bin (${formatBytes(outcome.freed)}) — undo from History`, + "success", + ); + } + }; + + // Totals next to the toolbar follow the *visible* groups: an ignored group + // stops counting toward what the page offers to reclaim. + const visibleWasted = groups.reduce((sum, g) => sum + g.size * (g.copies.length - 1), 0); + + return ( +
+ + {workspace.error ? : null} + +
+ {t("Scan scope", "扫描范围")} + + {t( + "Home folders + all drives (system folders skipped)", + "用户目录 + 各磁盘(自动跳过系统与软件数据目录)", + )} + + {extraRoots.map((root) => ( + + {root} + + + ))} + + + {t("Min size", "最小体积")} +
+ {MIN_SIZE_OPTIONS.map((option) => ( + + ))} +
+ +
+ + {workspace.scanning || (workspace.funnel.walked > 0 && groups.length > 0) ? ( +
+
+ + → + + → + + → + +
+ {t("duplicates found", "已发现重复")}{" "} + {formatCount(groups.length)} {t("groups", "组")} ·{" "} + {t("recoverable", "可回收")} {formatBytes(visibleWasted)} +
+
+ {workspace.progress?.subject ? ( +
+ {t("Checking", "正在校验")} {workspace.progress.subject} +
+ ) : null} +
+ ) : null} + + {workspace.scanning ? ( + void workspace.cancel()} + capAt99 + /> + ) : null} + + {!workspace.scanning && groups.length === 0 && !workspace.result && !workspace.error ? ( + } + title={t("No duplicate scan yet", "还没有扫描过重复文件")} + description={t( + "The first scan walks your files once; later scans reuse the hash cache and only re-check what changed.", + "首次扫描遍历一遍文件;之后的扫描复用哈希缓存,只重算发生变化的文件。", + )} + /> + ) : null} + + {!workspace.scanning && groups.length === 0 && workspace.result ? ( + } + title={t("No duplicate files found", "没有发现重复文件")} + description={ + lang === "zh" + ? `已检查 ${formatCount(workspace.result.report.walked)} 个达到体积门槛的文件,无重复。` + : `${formatCount(workspace.result.report.walked)} files checked above the size floor.` + } + /> + ) : null} + + {!workspace.scanning && groups.length > 0 ? ( + <> +
+ + + + + {formatCount(groups.length)} {t("groups · duplicate copies", "组 · 重复副本")}{" "} + {formatCount(groups.reduce((sum, g) => sum + g.copies.length - 1, 0))} ·{" "} + {formatBytes(visibleWasted)} + + +
+ {confirming ? ( +
+ +
+ + {lang === "zh" + ? `将 ${workspace.selectedCount} 个副本(${formatBytes(workspace.selectedBytes)})移入回收站?` + : `Move ${workspace.selectedCount} copies (${formatBytes(workspace.selectedBytes)}) to the Recycle Bin?`} + + + {t( + "Every group keeps at least one copy; a mis-click is one Undo away from History.", + "每组至少保留一份;误删可从「历史记录 → 撤销」找回。", + )} + +
+ + +
+ ) : null} +
+ {entries.map(({ group, index }) => ( + + ))} +
+ + ) : null} +
+ ); +} diff --git a/src/pages/LargeFilesPage.tsx b/src/pages/LargeFilesPage.tsx new file mode 100644 index 0000000..15609bb --- /dev/null +++ b/src/pages/LargeFilesPage.tsx @@ -0,0 +1,347 @@ +import { + Archive, + Disc3, + Cloud, + FileVideo, + HardDrive, + Lock, + MapPin, + Package, + ShieldAlert, + Trash2, +} from "lucide-react"; +import { useCallback, useMemo, useRef, useState } from "react"; +import * as apiClient from "../lib/api"; +import { subscribeJobProgress } from "../lib/api"; +import { useI18n } from "../i18n"; +import { agoLabel, formatBytes, formatCount, messageFrom } from "../lib/format"; +import { + Button, + Checkbox, + EmptyState, + InlineError, + PageHeader, + ProgressCard, + useToast, +} from "../components/ui"; +import type { JobProgress, LargeFile } from "../types"; + +const THRESHOLDS = [ + { value: 100 * 1024 * 1024, label: "≥100MB" }, + { value: 500 * 1024 * 1024, label: "≥500MB" }, + { value: 1024 * 1024 * 1024, label: "≥1GB" }, +]; + +const CLASSES = [ + { id: "all", en: "All", zh: "全部", icon: HardDrive }, + { id: "video", en: "Video", zh: "视频", icon: FileVideo }, + { id: "archive", en: "Archives", zh: "归档", icon: Archive }, + { id: "installer", en: "Installers", zh: "安装包", icon: Package }, + { id: "image", en: "Disk images", zh: "镜像/VHD", icon: Disc3 }, +]; + +const CLASS_ICON: Record = { + video: FileVideo, + archive: Archive, + installer: Package, + image: Disc3, + other: HardDrive, +}; + +/** 休眠判定沿用清理页口径:180 天无修改即值得标记。 */ +const DORMANT_SECS = 180 * 86_400; + +export function LargeFilesPage() { + const { t, lang } = useI18n(); + const { push } = useToast(); + const [files, setFiles] = useState(null); + const [scope, setScope] = useState([]); + const [threshold, setThreshold] = useState(500 * 1024 * 1024); + const [klass, setKlass] = useState("all"); + const [hideCritical, setHideCritical] = useState(true); + const [scanning, setScanning] = useState(false); + const [deleting, setDeleting] = useState(false); + const [error, setError] = useState(null); + const [progress, setProgress] = useState(null); + const [picked, setPicked] = useState>(new Set()); + const [confirming, setConfirming] = useState(false); + const job = useRef(null); + + const run = useCallback(async () => { + if (scanning) return; + const id = crypto.randomUUID?.() ?? String(Date.now()); + job.current = id; + setScanning(true); + setError(null); + setFiles(null); + setPicked(new Set()); + setProgress(null); + const stop = await subscribeJobProgress(id, (event) => { + if (event.event === "metered") { + setProgress(event); + } else if (event.event === "tick" || event.event === "phase") { + setProgress(event); + } + }); + try { + const found = await apiClient.api.largeFilesScan( + id, + scope, + threshold, + klass === "all" ? null : klass, + ); + setFiles(found); + } catch (reason) { + if (!messageFrom(reason).toLowerCase().includes("cancel")) { + setError(messageFrom(reason)); + } + } finally { + stop(); + setScanning(false); + job.current = null; + } + }, [klass, scanning, scope, threshold]); + + const visible = useMemo(() => { + if (!files) return null; + return files.filter((file) => !hideCritical || !file.maybeMounted); + }, [files, hideCritical]); + + const totalBytes = visible?.reduce((sum, file) => sum + file.size, 0) ?? 0; + const pickedBytes = visible + ?.filter((file) => picked.has(file.path)) + .reduce((sum, file) => sum + file.size, 0) ?? 0; + const pickedCount = picked.size; + + const toggle = (path: string) => { + setPicked((current) => { + const next = new Set(current); + if (next.has(path)) next.delete(path); + else next.add(path); + return next; + }); + }; + + const confirmDelete = async () => { + const id = crypto.randomUUID?.() ?? String(Date.now()); + setDeleting(true); + try { + const outcome = await apiClient.api.largeFilesDelete(id, [...picked], "trash"); + setFiles((current) => current?.filter((f) => !picked.has(f.path)) ?? null); + setPicked(new Set()); + setConfirming(false); + push( + lang === "zh" + ? `已将 ${outcome.removed} 个大文件移入回收站(${formatBytes(outcome.freed)}),可在「历史记录」撤销` + : `Moved ${outcome.removed} files to the Recycle Bin (${formatBytes(outcome.freed)})`, + "success", + ); + } catch (reason) { + setError(messageFrom(reason)); + } finally { + setDeleting(false); + } + }; + + const now = Date.now(); + + return ( +
+ + {error ? setError(null)} /> : null} + +
+ {t("Scope", "范围")} +
+ + {["C:", "D:", "E:"].map((drive) => ( + + ))} +
+ {t("At least", "阈值")} +
+ {THRESHOLDS.map((option) => ( + + ))} +
+ {t("Type", "类型")} +
+ {CLASSES.map((option) => { + const Icon = option.icon; + return ( + + ); + })} +
+ +
+ + {scanning ? ( + { + if (job.current) void apiClient.api.cancelJob(job.current); + }} + /> + ) : null} + + {visible && visible.length === 0 && !scanning ? ( + } + title={t("No files above the threshold", "没有超过阈值的大文件")} + description={t( + "Try a lower size floor or another scope.", + "可以调低体积门槛或更换扫描范围再试。", + )} + /> + ) : null} + + {visible && visible.length > 0 ? ( + <> +
+
+ + {formatCount(visible.length)} {t("large files", "个大文件")} ·{" "} + {formatBytes(totalBytes)} + + + {pickedCount > 0 + ? t( + `${pickedCount} selected · ${formatBytes(pickedBytes)} → Recycle Bin`, + `已选 ${pickedCount} 项 · ${formatBytes(pickedBytes)} → 移入回收站`, + ) + : t( + "Dormant files (180 days untouched) are tagged; disk images held by Hyper-V/WSL stay locked.", + "长期未修改(180 天+)的文件会带休眠标记;被 Hyper-V/WSL 使用的镜像会锁定。", + )} + +
+ + +
+ {confirming ? ( +
+ +
+ + {lang === "zh" + ? `将 ${pickedCount} 个大文件(${formatBytes(pickedBytes)})移入回收站?` + : `Move ${pickedCount} files (${formatBytes(pickedBytes)}) to the Recycle Bin?`} + + + {t( + "Undo from History while the Recycle Bin holds them.", + "回收站清空前,可随时在「历史记录」撤销。", + )} + +
+ + +
+ ) : null} +
    + {visible.map((file, index) => { + const Icon = CLASS_ICON[file.class] ?? HardDrive; + const dormant = + file.modifiedMs > 0 && (now - file.modifiedMs) / 1000 > DORMANT_SECS; + return ( +
  • + toggle(file.path)} + label={file.displayPath} + /> + {String(index + 1).padStart(2, "0")} + + + +
    + {file.path.split(/[\\/]/).pop()} + {file.displayPath} +
    + {dormant ? ( + + {agoLabel(file.modifiedMs, lang)} {t("untouched", "未修改")} + + ) : null} + {file.cloudHint ? ( + + {t("cloud copy?", "网盘可能有副本?")} + + ) : null} + {file.maybeMounted ? ( + + {t("check in use", "占用检查")} + + ) : null} + {formatBytes(file.size)} + +
  • + ); + })} +
+ + ) : null} +
+ ); +} diff --git a/src/pages/StoragePage.tsx b/src/pages/StoragePage.tsx index 179861c..83a4560 100644 --- a/src/pages/StoragePage.tsx +++ b/src/pages/StoragePage.tsx @@ -13,7 +13,7 @@ import { ScanSearch, TimerReset, } from "lucide-react"; -import { useEffect, useMemo, useState } from "react"; +import { useEffect, useMemo, useRef, useState } from "react"; import { open } from "@tauri-apps/plugin-dialog"; import * as apiClient from "../lib/api"; import { useI18n } from "../i18n"; @@ -27,6 +27,7 @@ import { } from "../lib/format"; import type { Bootstrap, SpaceInsight, StorageNode } from "../types"; import { useStorageWorkspace } from "../hooks/useStorageWorkspace"; +import { Treemap, type TreemapItem } from "../components/Treemap"; import { Button, InlineError, @@ -59,6 +60,19 @@ export function StoragePage({ bootstrap }: { bootstrap: Bootstrap }) { const [pathInput, setPathInput] = useState(""); const [manualPath, setManualPath] = useState(false); const [insights, setInsights] = useState(null); + // D4: list ⇄ squarified treemap over the same measured tree (no re-scan). + const [view, setView] = useState<"list" | "map">("list"); + const [mapWidth, setMapWidth] = useState(860); + const mapRef = useRef(null); + useEffect(() => { + if (view !== "map" || !mapRef.current) return; + const node = mapRef.current; + const measure = () => setMapWidth(Math.max(node.clientWidth, 320)); + measure(); + const observer = new ResizeObserver(measure); + observer.observe(node); + return () => observer.disconnect(); + }, [view]); // A⑤: hidden space hogs measured quietly once per page visit. useEffect(() => { @@ -93,6 +107,27 @@ export function StoragePage({ bootstrap }: { bootstrap: Bootstrap }) { const visibleShare = children.reduce((sum, child) => sum + nodeSize(child), 0); const rest = percent(visibleShare, nodeTotal); + // Treemap wants flat weighted cells, biggest-tone-darkest. + const treemapItems: TreemapItem[] = useMemo(() => { + if (!workspace.node || children.length === 0) return []; + const biggest = Math.max(nodeSize(children[0]), 1); + const cells: TreemapItem[] = children.map((child, index) => ({ + id: String(index), + label: basename(child.path), + value: nodeSize(child), + tone: Math.min(1, Math.sqrt(nodeSize(child) / biggest)), + })); + if (workspace.node.folded > 0 && nodeSize(workspace.node) - visibleShare > 0) { + cells.push({ + id: "rest", + label: t("Other folders", "其他文件夹"), + value: nodeSize(workspace.node) - visibleShare, + tone: 0.08, + }); + } + return cells; + }, [children, t, visibleShare, workspace.node]); + const explore = (path?: string | null) => { setManualPath(false); void workspace.explore(path); @@ -240,6 +275,25 @@ export function StoragePage({ bootstrap }: { bootstrap: Bootstrap }) { {children.length > 0 ? ( <> +
+ + + + {t("Sunburst coming later", "旭日图(后期)")} + +
{children.map((child, index) => ( ) : null} + {view === "map" ? ( +
+ { + const child = children.find((_, index) => String(index) === id); + if (child?.isDir) drill(child); + }} + /> +

+ {t( + "Click a block to drill into that folder (shares the same measurement cache; nothing re-scans). Darker = bigger share.", + "点击矩形 = 下钻该目录(与列表共用同一份测量缓存,不重新扫描);颜色越深占比越大。", + )} +

+
+ ) : (
{children.map((child, index) => { const share = percent(nodeSize(child), nodeTotal); @@ -340,6 +413,7 @@ export function StoragePage({ bootstrap }: { bootstrap: Bootstrap }) {
) : null}
+ )} ) : (
diff --git a/src/styles.css b/src/styles.css index 8d978c8..287a06c 100644 --- a/src/styles.css +++ b/src/styles.css @@ -6868,3 +6868,656 @@ html.widget-mode body { background: rgba(150, 110, 170, 0.08); color: #8a6a99; } + +/* ---- duplicate files (重复文件) ---------------------------------------- */ + +.dup-config { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 8px; + padding: 12px 14px; + border: 1px solid var(--line); + border-radius: 14px; + background: var(--card, #fffdf8); +} + +.dup-config-label { + color: #8b94a0; + font-size: var(--nex-text-3xs); + font-weight: var(--nex-weight-semibold); +} + +.dup-config-spacer { + flex: 1 1 auto; +} + +.dup-root-chip { + display: inline-flex; + align-items: center; + gap: 5px; + padding: 3px 9px; + border: 1px solid #e6d9c8; + border-radius: 99px; + background: rgba(224, 95, 33, 0.05); + color: #6d5b48; + font-size: var(--nex-text-3xs); + max-width: 340px; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.dup-root-chip.is-static { + border-style: dashed; + color: #8b94a0; + background: none; +} + +.dup-root-chip button { + border: 0; + background: none; + color: #b3a08d; + cursor: pointer; + display: inline-flex; + padding: 0; +} + +.dup-root-add { + display: inline-flex; + align-items: center; + gap: 4px; + padding: 3px 10px; + border: 1px dashed #d9c6ae; + border-radius: 99px; + background: none; + color: #a4826a; + font-size: var(--nex-text-3xs); + cursor: pointer; +} + +.dup-root-add:hover { + border-color: var(--nex-accent, #e05f21); + color: var(--nex-accent, #e05f21); +} + +.dup-seg { + display: inline-flex; + overflow: hidden; + border: 1px solid var(--line); + border-radius: 9px; +} + +.dup-seg button { + padding: 4px 11px; + border: 0; + border-right: 1px solid var(--line); + background: #fffdf8; + color: #6d7683; + font-size: var(--nex-text-3xs); + cursor: pointer; + display: inline-flex; + align-items: center; + gap: 4px; +} + +.dup-seg button:last-child { + border-right: 0; +} + +.dup-seg button.is-active { + background: var(--nex-accent, #e05f21); + color: #fff; + font-weight: var(--nex-weight-semibold); +} + +.dup-funnel { + margin-top: 12px; + padding: 12px 14px; + border: 1px solid #f0e3d0; + border-radius: 14px; + background: linear-gradient(135deg, rgba(224, 95, 33, 0.05), rgba(224, 95, 33, 0.015)); +} + +.dup-funnel-row { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 8px; +} + +.dup-funnel-row > i { + color: #cbb79f; + font-style: normal; +} + +.dup-stage { + display: flex; + flex-direction: column; + padding: 6px 14px; + border: 1px solid #eadfcf; + border-radius: 11px; + background: #fffdf8; + text-align: center; +} + +.dup-stage b { + color: #b8531c; + font-size: var(--nex-text-2xs); + font-variant-numeric: tabular-nums; +} + +.dup-stage span { + color: #8b94a0; + font-size: var(--nex-text-4xs, 10px); +} + +.dup-stage.is-hot { + border-color: var(--nex-accent, #e05f21); + box-shadow: 0 0 0 2px rgba(224, 95, 33, 0.12); +} + +.dup-funnel-total { + margin-left: auto; + color: #6d5b48; + font-size: var(--nex-text-3xs); +} + +.dup-funnel-total b { + color: #b8531c; +} + +.dup-funnel-current { + margin-top: 8px; + overflow: hidden; + color: #97826c; + font-size: var(--nex-text-3xs); + text-overflow: ellipsis; + white-space: nowrap; +} + +.dup-toolbar { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 8px; + margin-top: 14px; + padding: 10px 14px; + border: 1px solid var(--line); + border-radius: 14px; + background: var(--card, #fffdf8); +} + +.dup-toolbar button { + display: inline-flex; + align-items: center; + gap: 5px; + padding: 4px 12px; + border: 1px solid #e6d9c8; + border-radius: 9px; + background: #fffdf8; + color: #6d5b48; + font-size: var(--nex-text-3xs); + cursor: pointer; +} + +.dup-toolbar button:hover { + border-color: var(--nex-accent, #e05f21); + color: var(--nex-accent, #e05f21); +} + +.dup-toolbar .dup-smart { + border-color: rgba(224, 95, 33, 0.4); + color: #b8531c; +} + +.dup-toolbar-sum { + flex: 1 1 auto; + color: #8b94a0; + font-size: var(--nex-text-3xs); + text-align: right; +} + +.dup-toolbar .dup-clean { + border-color: #d67358 !important; + color: #c25438 !important; +} + +.dup-confirm { + display: flex; + align-items: center; + gap: 10px; + margin-top: 10px; + padding: 10px 14px; + border: 1px solid #e9c9a8; + border-radius: 12px; + background: rgba(224, 95, 33, 0.06); + color: #6d4b2f; +} + +.dup-confirm > svg { + flex: 0 0 auto; + color: #c2762f; +} + +.dup-confirm > div { + flex: 1 1 auto; + min-width: 0; +} + +.dup-confirm b { + display: block; + font-size: var(--nex-text-2xs); +} + +.dup-confirm small { + color: #97826c; + font-size: var(--nex-text-3xs); +} + +.dup-groups { + display: flex; + flex-direction: column; + gap: 10px; + margin-top: 12px; +} + +.dup-group { + border: 1px solid var(--line); + border-radius: 14px; + background: var(--card, #fffdf8); + overflow: hidden; +} + +.dup-group.is-personal { + border-color: #e6d3ae; +} + +.dup-group-head { + display: flex; + align-items: center; + gap: 8px; + padding: 9px 13px; + border-bottom: 1px solid #f2eade; + background: rgba(224, 95, 33, 0.025); +} + +.dup-group-title { + display: flex; + align-items: center; + gap: 8px; + min-width: 0; + flex: 1 1 auto; + color: #55493a; + font-size: var(--nex-text-2xs); +} + +.dup-group-title b { + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.dup-group-count { + flex: 0 0 auto; + color: #b8531c; + font-weight: var(--nex-weight-semibold); +} + +.dup-waste-chip { + flex: 0 0 auto; + padding: 1px 8px; + border: 1px solid #ecd3bd; + border-radius: 99px; + background: rgba(224, 95, 33, 0.07); + color: #b8531c; + font-size: var(--nex-text-3xs); +} + +.dup-personal-chip { + display: inline-flex; + align-items: center; + gap: 3px; + flex: 0 0 auto; + padding: 1px 8px; + border: 1px solid #e2c793; + border-radius: 99px; + background: rgba(197, 145, 47, 0.08); + color: #9a6f1d; + font-size: var(--nex-text-3xs); +} + +.dup-group-size { + flex: 0 0 auto; + color: #55493a; + font-size: var(--nex-text-2xs); + font-weight: var(--nex-weight-semibold); + font-variant-numeric: tabular-nums; +} + +.dup-group-dismiss { + flex: 0 0 auto; + display: inline-flex; + padding: 3px; + border: 0; + border-radius: 6px; + background: none; + color: #b3a08d; + cursor: pointer; +} + +.dup-group-dismiss:hover { + background: rgba(224, 95, 33, 0.1); + color: #b8531c; +} + +.dup-copies { + margin: 0; + padding: 4px 0; + list-style: none; +} + +.dup-copy { + display: flex; + align-items: center; + gap: 8px; + padding: 5px 13px; + font-size: var(--nex-text-3xs); +} + +.dup-copy.is-picked { + background: rgba(224, 95, 33, 0.045); +} + +.dup-copy.is-keep { + color: #4b8a55; +} + +.dup-keep-chip { + flex: 0 0 auto; + padding: 1px 8px; + border: 1px solid #bfe0c4; + border-radius: 99px; + background: rgba(88, 170, 98, 0.09); + color: #4b8a55; + font-size: var(--nex-text-3xs); + font-weight: var(--nex-weight-semibold); +} + +.dup-lock-chip { + display: inline-flex; + align-items: center; + gap: 3px; + flex: 0 0 auto; + color: #9a6f1d; +} + +.dup-copy-path { + flex: 1 1 auto; + min-width: 0; + overflow: hidden; + color: #6d7683; + text-overflow: ellipsis; + white-space: nowrap; + direction: rtl; + text-align: left; +} + +.dup-copy.is-keep .dup-copy-path { + color: #4b8a55; +} + +.dup-copy-age { + flex: 0 0 auto; + color: #aab4c0; + font-variant-numeric: tabular-nums; +} + +.dup-copy-reveal { + flex: 0 0 auto; + display: inline-flex; + align-items: center; + gap: 3px; + padding: 2px 7px; + border: 0; + border-radius: 7px; + background: none; + color: #3f6bbd; + font-size: var(--nex-text-3xs); + cursor: pointer; + opacity: 0; +} + +.dup-copy:hover .dup-copy-reveal, +.bigfile-row:hover .dup-copy-reveal { + opacity: 1; +} + +/* ---- large files (大文件) ---------------------------------------------- */ + +.bigfiles-config { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 8px; + padding: 12px 14px; + border: 1px solid var(--line); + border-radius: 14px; + background: var(--card, #fffdf8); +} + +.bigfiles-list-head { + display: flex; + align-items: center; + gap: 12px; + margin-top: 14px; + padding: 10px 14px; + border: 1px solid var(--line); + border-radius: 14px; + background: var(--card, #fffdf8); +} + +.bigfiles-list-head > div { + flex: 1 1 auto; + min-width: 0; +} + +.bigfiles-list-head b { + display: block; + color: #55493a; + font-size: var(--nex-text-2xs); +} + +.bigfiles-list-head b .is-accent { + color: #b8531c; +} + +.bigfiles-list-head small { + color: #8b94a0; + font-size: var(--nex-text-3xs); +} + +.bigfiles-hide-critical { + display: inline-flex; + align-items: center; + gap: 6px; + color: #6d7683; + font-size: var(--nex-text-3xs); + cursor: pointer; +} + +.bigfiles-list { + margin: 10px 0 0; + padding: 0; + list-style: none; + border: 1px solid var(--line); + border-radius: 14px; + background: var(--card, #fffdf8); + overflow: hidden; +} + +.bigfile-row { + display: flex; + align-items: center; + gap: 9px; + padding: 8px 13px; + border-bottom: 1px solid #f2eade; + font-size: var(--nex-text-3xs); +} + +.bigfile-row:last-child { + border-bottom: 0; +} + +.bigfile-row.is-picked { + background: rgba(224, 95, 33, 0.045); +} + +.bigfile-index { + flex: 0 0 auto; + color: #c9bfae; + font-variant-numeric: tabular-nums; +} + +.bigfile-icon { + flex: 0 0 auto; + display: inline-flex; + padding: 5px; + border-radius: 8px; + background: rgba(224, 95, 33, 0.08); + color: #b8531c; +} + +.bigfile-main { + flex: 1 1 auto; + min-width: 0; +} + +.bigfile-main b { + display: block; + color: #55493a; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.bigfile-path { + display: block; + color: #9aa4af; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + direction: rtl; + text-align: left; +} + +.bigfile-cloud-chip { + display: inline-flex; + align-items: center; + gap: 3px; + flex: 0 0 auto; + padding: 1px 8px; + border: 1px solid #bcd2ea; + border-radius: 99px; + background: rgba(63, 107, 189, 0.07); + color: #3f6bbd; + font-size: var(--nex-text-3xs); +} + +.bigfile-size { + flex: 0 0 auto; + color: #55493a; + font-weight: var(--nex-weight-semibold); + font-variant-numeric: tabular-nums; +} + +/* ---- storage treemap (矩形图) ------------------------------------------- */ + +.storage-viewseg { + display: flex; + align-items: center; + gap: 6px; + margin: 10px 0 4px; +} + +.storage-viewseg button { + padding: 4px 13px; + border: 1px solid var(--line); + border-radius: 9px; + background: #fffdf8; + color: #6d7683; + font-size: var(--nex-text-3xs); + cursor: pointer; +} + +.storage-viewseg button.is-active { + border-color: var(--nex-accent, #e05f21); + background: rgba(224, 95, 33, 0.09); + color: #b8531c; + font-weight: var(--nex-weight-semibold); +} + +.storage-viewseg-note { + color: #b8b0a4; + font-size: var(--nex-text-3xs); +} + +.storage-treemap { + position: relative; + width: 100%; +} + +.treemap { + position: relative; + margin-top: 6px; + border-radius: 12px; + overflow: hidden; +} + +.treemap-cell { + position: absolute; + display: flex; + align-items: flex-end; + padding: 6px 8px; + border: 0; + border-radius: 8px; + cursor: pointer; + text-align: left; + overflow: hidden; + transition: filter 0.12s ease; +} + +.treemap-cell:hover { + filter: brightness(0.94); +} + +.treemap-label { + display: flex; + flex-direction: column; + min-width: 0; +} + +.treemap-label b { + font-size: var(--nex-text-2xs); + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.treemap-label small { + font-size: var(--nex-text-3xs); + opacity: 0.85; +} + +.treemap-label.is-tiny { + font-size: 10px; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.storage-treemap-hint { + margin: 8px 0 0; + color: #97826c; + font-size: var(--nex-text-3xs); +} diff --git a/src/types.ts b/src/types.ts index 8ae38b7..4cb2323 100644 --- a/src/types.ts +++ b/src/types.ts @@ -6,7 +6,12 @@ export type PageId = | "permissions" | "widget" | "storage" + | "duplicates" + | "large-files" | "system" + | "maintenance" + | "privacy" + | "optimization" | "history" | "settings"; @@ -21,7 +26,10 @@ export type Category = | "trash" | "language-packs" | "leftovers" - | "update-installers"; + | "update-installers" + | "duplicates" + | "ai-tools" + | "privacy"; export type ItemKind = "path" | "contents" | "file"; export type LockReason = | "app-running" @@ -74,7 +82,15 @@ export interface DeleteResult { export interface JobProgress { jobId: string; kind: string; - event: "phase" | "tick" | "note" | "warning" | "deleted" | "bucket" | "metered"; + event: + | "phase" + | "tick" + | "note" + | "warning" + | "deleted" + | "bucket" + | "metered" + | "group"; phase: string | null; detail: string | null; done: number | null; @@ -293,6 +309,55 @@ export interface LargestFile { modified_ms: number | null; } +// ---- duplicate files (重复文件) ------------------------------------------ + +export interface DupCopy { + /** Display spelling; `~` folded for the home folder. */ + path: string; + mtimeMs: number; + /** Why this copy may not be deleted (protected user asset), when it may not. */ + locked: string | null; +} + +export interface DupGroup { + size: number; + copies: DupCopy[]; + /** Index the UI marks 「保留」 by default. */ + keep: number; + /** At least one copy sits in a protected personal folder. */ + personal: boolean; +} + +export interface DupReport { + groups: DupGroup[]; + walked: number; + sameSize: number; + sampleHits: number; + confirmedGroups: number; + confirmedFiles: number; + wasted: number; +} + +export interface DupsResult { + scanId: string; + report: DupReport; + elapsedMs: number; +} + +// ---- large files (大文件) ------------------------------------------------- + +export interface LargeFile { + path: string; + displayPath: string; + size: number; + modifiedMs: number; + class: "video" | "archive" | "installer" | "image" | "other"; + /** A cloud-sync folder sits above this file — there may be a copy online. */ + cloudHint: boolean; + /** Disk image: something (Hyper-V/WSL) may hold it open. */ + maybeMounted: boolean; +} + export interface LedgerEntry { path: string; kind: ItemKind;