From 2e705632440ba02f50f41bce817b816fda285bea Mon Sep 17 00:00:00 2001 From: TheKillerMax <70108066+TheKillerMax@users.noreply.github.com> Date: Fri, 9 Oct 2026 14:50:07 -0300 Subject: [PATCH] Verify WOF savings and add thorough analysis Retain compression only when measured allocation savings meet policy. Protect file identity and scope, fix cancellation and cache persistence, and add explicit Windows/NTFS integration coverage. --- .github/workflows/release.yml | 15 +- .github/workflows/rust.yml | 12 +- CHANGELOG.md | 28 + Cargo.lock | 16 +- Cargo.toml | 4 +- README.md | 57 +- build.rs | 16 +- docs/TESTING.md | 94 +++ docs/compression-policy.md | 115 ++++ hashfilter/src/lib.rs | 290 ++++++++- src/backend.rs | 1050 +++++++++++++++++---------------- src/background.rs | 122 ++-- src/compact.rs | 597 ++++++++++++++++--- src/compression.rs | 717 +++++++++++++++++++--- src/config.rs | 301 +++++++++- src/directstorage.rs | 105 +++- src/folder.rs | 368 ++++++------ src/gui.rs | 193 +++--- src/main.rs | 1 + src/persistence.rs | 108 +++- src/policy.rs | 127 ++++ src/ui/app.js | 252 ++++++-- src/ui/index.html | 60 +- src/ui/style.css | 70 +++ tests/ui.test.cjs | 512 ++++++++++++++++ 25 files changed, 4052 insertions(+), 1178 deletions(-) create mode 100644 docs/TESTING.md create mode 100644 docs/compression-policy.md create mode 100644 src/policy.rs create mode 100644 tests/ui.test.cjs diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 40f22c3..40575b2 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -54,6 +54,7 @@ jobs: uses: dtolnay/rust-toolchain@stable with: targets: x86_64-pc-windows-msvc + components: rustfmt - name: Read release version shell: pwsh @@ -101,11 +102,23 @@ jobs: Set-Content -Path release-notes.md -Value $notes -Encoding utf8 + - name: Check Rust formatting + run: cargo fmt --all -- --check + + - name: Validate embedded JavaScript + run: node --check src/ui/app.js + + - name: Test interface behavior + run: node --test tests/ui.test.cjs + - name: Build release x64 run: cargo build --release --locked --target x86_64-pc-windows-msvc - name: Run tests - run: cargo test --release --locked --target x86_64-pc-windows-msvc + run: cargo test --workspace --release --locked --target x86_64-pc-windows-msvc + + - name: Verify native WOF round trips on NTFS + run: cargo test --release --locked --target x86_64-pc-windows-msvc -- --ignored --test-threads=1 - name: Create tag shell: pwsh diff --git a/.github/workflows/rust.yml b/.github/workflows/rust.yml index d4207f2..176107e 100644 --- a/.github/workflows/rust.yml +++ b/.github/workflows/rust.yml @@ -25,15 +25,25 @@ jobs: uses: dtolnay/rust-toolchain@stable with: targets: x86_64-pc-windows-msvc + components: rustfmt + + - name: Check Rust formatting + run: cargo fmt --all -- --check - name: Validate embedded JavaScript run: node --check src/ui/app.js + - name: Test interface behavior + run: node --test tests/ui.test.cjs + - name: Build release x64 run: cargo build --release --locked --target x86_64-pc-windows-msvc - name: Run tests - run: cargo test --release --locked --target x86_64-pc-windows-msvc + run: cargo test --workspace --release --locked --target x86_64-pc-windows-msvc + + - name: Verify native WOF round trips on NTFS + run: cargo test --release --locked --target x86_64-pc-windows-msvc -- --ignored --test-threads=1 - name: Upload Compactor x64 uses: actions/upload-artifact@v7 diff --git a/CHANGELOG.md b/CHANGELOG.md index 49952c6..9c38281 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,34 @@ ## Unreleased +### Added + +- Optional Thorough analysis, which tries the selected WOF algorithm on every eligible, uncached file instead of rejecting candidates through a generic sample. Existing settings continue to use Sampled mode; LZX remains the default algorithm. +- A measured retention policy: require the configured percentage reduction and at least one NTFS cluster of savings, otherwise restore the newly compressed file. Report failed measurements and restoration failures explicitly. +- File-identity-aware WOF inspection, guarded normal-view allocation queries, canonical-root containment checks, hardlink protection and cooperative per-file locking between Compactor instances. +- Persistent operation reports, bounded error details, behaviour tests for the embedded UI and explicit native Windows/NTFS integration tests. +- Support for checking Windows sources with a real MinGW cross-toolchain, without bypassing resource compilation. + +### Fixed + +- Recognise actual WOF backing before rejecting sparse/reparse metadata. Do not infer the compression format from a size comparison. +- Validate Windows API response lengths, versions, providers and algorithm identifiers; accept the existing XPRESS4K setting consistently. +- Scope the incompressible cache to file fingerprint, algorithm, mode, threshold and cluster size; cache only measured negative results from the protected identity. +- Preserve pending cache entries after write/flush/sync failures and recover from truncated or missing cache files. +- Stop scheduling work when the GUI closes, including while paused. Prioritise cancellation over an already-ready analysis/preflight result. +- Process each original decompression candidate at most once per run, retaining failed WOF files for inspection and a later retry. +- Invalidate stale analyses after settings changes and require new analysis after decompression or errors. +- Detect DirectStorage signals independently of compression exclusions, support cancelling the preflight and refuse to compress after an incomplete check. +- Save configuration atomically and validate it on load. Preserve invalid configuration bytes until the user saves a corrected configuration. +- Escape automatically added folder exclusions, reject invalid numeric settings, reset empty charts and refresh displayed units and file/folder views correctly. + +### Changed + +- Update `crossbeam-channel` from 0.5.0 to 0.5.17 and its `crossbeam-utils` dependency from 0.8.1 to 0.8.23, with the resolved versions recorded in Cargo.lock. +- Removed uncalibrated algorithm-specific estimate multipliers; estimates are explicitly generic and provisional. +- Native WOF tests use temporary fixtures instead of modifying Cargo.lock or scanning a user's C:\Games directory. +- CI and release workflows run interface tests, workspace tests and explicit WOF round-trip checks before publishing artifacts. + ## [0.11.5] - 2026-09-14 ### Added diff --git a/Cargo.lock b/Cargo.lock index 6e283d1..a44d3fc 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1,5 +1,7 @@ # This file is automatically @generated by Cargo. # It is not intended for manual editing. +version = 4 + [[package]] name = "addr2line" version = "0.14.0" @@ -196,24 +198,18 @@ checksum = "245097e9a4535ee1e3e3931fcfcd55a796a44c643e8596ff6566d68f09b87bbc" [[package]] name = "crossbeam-channel" -version = "0.5.0" +version = "0.5.17" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dca26ee1f8d361640700bde38b2c37d8c22b3ce2d360e1fc1c74ea4b0aa7d775" +checksum = "98b0cc327b5bc766e7fda9c9260cc0fa81b43a8e240440422dff70788e3f9ef1" dependencies = [ - "cfg-if 1.0.0", "crossbeam-utils", ] [[package]] name = "crossbeam-utils" -version = "0.8.1" +version = "0.8.23" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "02d96d1e189ef58269ebe5b97953da3274d83a93af647c2ddd6f9dab28cedb8d" -dependencies = [ - "autocfg", - "cfg-if 1.0.0", - "lazy_static", -] +checksum = "a31eee39dddec8330830986fcd7625edb5a24ec90ea038215273bbc3adb08ac6" [[package]] name = "ctrlc" diff --git a/Cargo.toml b/Cargo.toml index edae987..39ca753 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -12,7 +12,7 @@ license = "MIT" #pango = { git = "https://github.com/gtk-rs/gtk-rs-core.git", package = "pango" } backtrace = "0.3.32" compresstimator = { git = "https://github.com/Freaky/compresstimator.git", rev = "26ddd3f499bc46f2c8b3ce814e9723ed41b47919" } -crossbeam-channel = "0.5" +crossbeam-channel = "0.5.17" ctrlc = "3.1" directories = "2.0.1" dirs-sys = "0.3.3" @@ -30,7 +30,7 @@ serde_json = "1.0" siphasher = "0.3.0" walkdir = "2.3" web-view = { git = "https://github.com/Freaky/web-view", branch = "blocking-step" } -winapi = { version = "0.3.7", features = [ "combaseapi", "fileapi", "ioapiset", "knownfolders", "processthreadsapi", "shellscalingapi", "shlobj", "shtypes", "sysinfoapi", "winbase", "winerror", "winioctl", "winver"] } +winapi = { version = "0.3.7", features = [ "combaseapi", "fileapi", "handleapi", "synchapi", "ioapiset", "knownfolders", "processthreadsapi", "shellscalingapi", "shlobj", "shtypes", "sysinfoapi", "winbase", "winerror", "winioctl", "winver"] } filetime = "0.2.8" tinyfiledialogs = "3.3.10" wfd = "0.1.6" diff --git a/README.md b/README.md index 8a825ec..ffef9e3 100644 --- a/README.md +++ b/README.md @@ -10,9 +10,9 @@ This repository is a maintained fork of [Freaky/Compactor](https://github.com/Fr - XPRESS4K, XPRESS8K, XPRESS16K, and LZX compression - LZX as the default compression mode -- Sampled compressibility analysis before compression -- Configurable minimum estimated savings threshold, defaulting to 1% -- Estimated post-compression size and additional savings during analysis +- Fast sampled analysis or optional Thorough analysis for maximum coverage +- Configurable minimum measured savings to retain compression, defaulting to 1% and at least one NTFS cluster +- Clearly labelled generic sample estimates, followed by measurements from the protected file handle - Storage-aware multithreaded analysis, compression, and decompression on SSDs - Conservative physical-core-aware LZX Auto concurrency with manual override - Single-threaded HDD operation by default @@ -23,32 +23,37 @@ This repository is a maintained fork of [Freaky/Compactor](https://github.com/Fr - WOF availability checks before file transformations begin - The system is kept awake during compression/decompression while the display may still turn off - Local-NTFS target validation and protection for Windows-managed paths -- In-app searchable viewer for folders containing WOF-compressed files +- In-app searchable viewer for WOF-compressed files and the folders containing them - Pause, resume, and stop controls - Timestamp preservation after compression and decompression - Automatic retry of previously incompressible files after they change - Case-insensitive exclusion patterns with blank-entry filtering -- Safe handling of encrypted, sparse, offline, reparse-point, and NTFS-compressed files +- Native WOF detection, with protection for other reparse points, hardlinks, encrypted, offline, sparse and NTFS-compressed files +- Persistent operation reports with separate success, low-benefit, skipped and error counts +- Reanalysis after settings changes, safe shutdown while paused, and atomic configuration writes - No default file-extension exclusions ## Defaults - Compression: `LZX` -- Minimum estimated savings: `1%` +- Analysis: `Sampled` (choose `Thorough` for maximum coverage) +- Minimum measured savings: `1%` and at least one NTFS cluster - Maximum threads: `Auto` - Compression priority: `Below Normal` - HDDs only use 1 thread: enabled - Protect DirectStorage games: enabled - Excluded paths: - - `*:\\Windows*` - - `*:\\System Volume Information*` - - `*:\\$*` + - `*:\Windows*` + - `*:\System Volume Information*` + - `*:\$*` -`Auto` is storage- and workload-aware. On SSDs it uses up to eight workers for analysis. XPRESS compression can use up to 16 logical-CPU workers. LZX Auto uses one outer worker on CPUs with four or fewer physical cores and at most two on larger CPUs because LZX WOF operations can be CPU-intensive. A manual limit from 1 to 16 is treated as an explicit override and is respected for LZX as well. Auto decompression uses storage-aware parallelism up to eight workers. HDDs still use one worker by default when the HDD safeguard is enabled, and unknown storage is handled conservatively with one worker. Compression reuses a valid analysis estimate when the file has not changed, avoiding duplicate sampling before WOF compression. +`Auto` is storage- and workload-aware. On SSDs it uses up to eight workers for analysis. XPRESS compression can use up to 16 logical-CPU workers. LZX Auto uses one outer worker on CPUs with four or fewer physical cores and at most two on larger CPUs because LZX WOF operations can be CPU-intensive. A manual limit from 1 to 16 is treated as an explicit override and is respected for LZX as well. Auto decompression uses storage-aware parallelism up to eight workers. HDDs still use one worker by default when the HDD safeguard is enabled, and unknown storage is handled conservatively with one worker. In Sampled mode, compression reuses a valid analysis estimate when the file has not changed, avoiding duplicate sampling before WOF compression. Compression/decompression worker priority can be set to Lowest, Below Normal, Normal, Above Normal, or Highest. Only the worker threads are affected; the GUI and analysis threads remain at normal priority. Below Normal is the default so idle CPU capacity can still be used while foreground work gets preference when the system is busy. -File extensions are not used to decide whether a file should be compressed. Eligible files are sampled and compared against the configured savings threshold. +File extensions are not used to decide whether a file should be compressed. In **Sampled** mode, a fast generic estimator chooses candidates; it can miss files that the selected WOF algorithm would compress. In **Thorough** mode, the estimate is advisory and every otherwise eligible, uncached file is tried with the selected algorithm. Both modes retain compression only when the measured allocation reduction meets the percentage threshold and saves at least one NTFS cluster. A result below that threshold is expanded again; any failure to restore is reported explicitly. + +For the greatest coverage, choose **LZX + Thorough**. LZX is the most compact algorithm listed by Windows for this compression model; Thorough changes which files are attempted, not the format. It does not promise a fixed improvement and can cost substantially more CPU time and writes, particularly on already compressed archives or media. **LZX + Sampled** remains the default to preserve the existing performance tradeoff. See [compression policy and limitations](docs/compression-policy.md). ## Installation @@ -60,23 +65,25 @@ Compactor is portable and does not require an installer or background service. 1. Choose a folder. 2. Wait for analysis to complete. -3. Review current disk usage and estimated savings. -4. Change the compression mode, savings threshold, thread limit, worker priority, or DirectStorage protection in Settings if required. -5. Select Compress. +3. Review current disk usage and, in Sampled mode, the generic savings estimate. +4. Choose the algorithm, analysis mode, savings threshold, thread limit, worker priority and DirectStorage protection in Settings. Analyse again after saving changes. +5. Select Compress, then review the persistent operation report. The final savings count uses measurements taken around successful file operations, not the earlier analysis snapshot. -Use Decompress to remove WOF backing from files previously compressed with Compactor. Use **Decompress + exclude** when you also want the selected folder added to File exclusions so it will not be compressed again on later runs. After analysis, select View beside the compressed count to browse folders containing WOF-compressed files inside Compactor. The viewer includes path filtering and pagination for large scans. +Use Decompress to remove supported WOF file backing, including files compressed by another WOF tool. The operation needs free space to materialise the contents and reports any file that cannot be expanded. After decompression, Analyse again before compressing. Use **Decompress + exclude** when you also want the selected folder added to File exclusions after all remaining WOF files have been successfully expanded. Literal folder names containing brackets or braces are handled correctly. After analysis, select View beside the compressed count to browse WOF-compressed files or their containing folders inside Compactor. The viewer includes a Files/Folders selector, path filtering and pagination for large scans. ## Notes Compactor is best suited to applications and game files that change infrequently. Modifying a WOF-compressed file causes Windows to materialise it again, so updated folders may need to be analysed and compressed again. -Compression and decompression hold each active file against concurrent writers and deleters while still allowing readers. This reduces the risk of racing an application or game update in the middle of a WOF operation. Files that change between analysis and compression are re-estimated instead of reusing stale analysis results. +Compression and decompression hold each active file against concurrent content writers and deleters while still allowing readers. Attributes, backing format, hardlinks and final path are checked again after opening. A file redirected outside the scan's canonical root is refused. A mutex keyed by file identity prevents cooperating Compactor instances from transforming the same file concurrently. This does not coordinate with unrelated compression tools. + +In Sampled mode, files that change between analysis and compression are re-estimated. Cache entries are tied to the fingerprint observed under the protected handle, algorithm, analysis mode, savings threshold and cluster size; sampled rejections and I/O errors are not recorded as measured compression failures. -If a selected tree contains `dstorage.dll` or `dstoragecore.dll`, Compactor identifies the likely game/install root using common game-library layouts and Unreal Engine DirectStorage layouts. With **Protect DirectStorage games** enabled, files under those detected roots are removed from the compression queue before WOF is applied. The setting can be disabled when you deliberately want to compress such files. Detection is conservative and based on the presence/layout of the DirectStorage runtime; it cannot prove that every detected game is actively using BypassIO at that moment. +Before a compression run, Compactor searches independently of compression exclusions for `dstorage.dll` or `dstoragecore.dll`. When these are found, Compactor identifies the likely game/install root using common game-library layouts and Unreal Engine DirectStorage layouts. With **Protect DirectStorage games** enabled, files under those detected roots are removed from the compression queue before WOF is applied. The setting can be disabled when you deliberately want to compress such files. Detection is conservative and based on the presence/layout of the DirectStorage runtime; it cannot prove that every detected game is actively using BypassIO or find every possible runtime layout. The preflight is cancellable and stops compression if it cannot complete the traversal. Before compression or decompression starts, Compactor also checks that Windows reports WOF support and probes the target volume using available files. If WOF is explicitly unavailable, the operation is stopped with a clear error instead of failing repeatedly file by file. -Do not run Compactor blindly across an entire system drive. Whole-drive roots, network/UNC targets, non-NTFS filesystems, the active Windows directory, `System Volume Information`, root `$*` directories, and the root `Recovery` directory are rejected. User-selected folders can still contain databases, virtual machines, active logs, or other write-heavy files that are poor candidates for WOF compression. +Do not run Compactor blindly across an entire system drive. Whole-drive roots, network/UNC targets, non-NTFS filesystems, the active Windows directory, `System Volume Information`, root `$*` directories, and the root `Recovery` directory are rejected. Folder aliases through junctions, symbolic links or mount points are rejected; select the actual local NTFS folder. User-selected folders can still contain databases, virtual machines, active logs, or other write-heavy files that are poor candidates for WOF compression. Compactor does not elevate itself through UAC. Protected files may require running the program with appropriate permissions. @@ -91,8 +98,8 @@ This fork includes the following changes: - Required read-data/write-attributes access for WOF operations - File handles that block concurrent writers/deleters during active WOF operations - Case-insensitive exclusions and blank-entry filtering -- Explicit skipping of encrypted, sparse, offline, reparse-point, and NTFS-compressed files -- Incompressible-cache keys based on path, file size, and modification time +- Skipping of encrypted, offline and legacy NTFS-compressed files, with explicit WOF-aware handling of sparse/reparse metadata +- Incompressible-cache keys scoped to the file fingerprint and selected compression policy - Zero-safe progress calculations and saturating size arithmetic - Byte-aware compression progress - Configurable savings thresholds @@ -112,7 +119,7 @@ This fork includes the following changes: - Reduced-seek HDD analysis sampling - Lower scan memory usage for large excluded trees and bounded parallel estimation batches - More accurate post-decompression on-disk accounting -- In-app compressed-folder viewer with filtering and pagination +- In-app compressed file/folder viewer with filtering and pagination - Windows x64 CI on stable Rust See [CHANGELOG.md](CHANGELOG.md) for the full change history. @@ -134,7 +141,7 @@ cargo build --release The executable is written to: ```text -target\\release\\Compactor.exe +target\release\Compactor.exe ``` ## Technical details @@ -143,7 +150,11 @@ Compactor is primarily written in [Rust](https://www.rust-lang.org/) and uses a WOF compression is applied through [`FSCTL_SET_EXTERNAL_BACKING`](https://learn.microsoft.com/windows-hardware/drivers/ifs/fsctl-set-external-backing) and removed through [`FSCTL_DELETE_EXTERNAL_BACKING`](https://learn.microsoft.com/windows-hardware/drivers/ifs/fsctl-delete-external-backing). -Compressibility sampling uses Thomas Hurst's [compresstimator](https://github.com/Freaky/compresstimator) project. SSD analysis uses distributed sampling, while HDD analysis uses a small number of contiguous sample windows to reduce seek overhead. Estimates are sampling results and are not exact predictions of final WOF size; the displayed projection is also adjusted for the selected WOF algorithm and rounded to the target volume's NTFS cluster size. +Compressibility sampling uses Thomas Hurst's [compresstimator](https://github.com/Freaky/compresstimator) project. SSD analysis uses distributed sampling, while HDD analysis uses a small number of contiguous sample windows to reduce seek overhead. Estimates are rounded to the volume's NTFS cluster size. They are generic sampling results, not measurements of the selected WOF codec; uncalibrated per-codec multipliers have been removed. Thorough mode does not present that estimate as its final savings prediction. + +WOF state is queried explicitly. Measurements use `GetFileInformationByHandleEx(FileCompressionInfo)` through a protected file identity and an identity-checked normal WOF view. Unsupported backing formats are left unchanged; malformed API responses and ambiguous allocations are reported as errors. These cases are never counted as successful compression. Existing WOF files are preserved by Compress; the program does not automatically cycle through algorithms or expand an existing compressed installation to try LZX. + +See [testing and Windows verification](docs/TESTING.md) for reproducible checks, including real WOF round trips on isolated NTFS fixtures. Windows storage-property queries are used to distinguish storage with and without seek penalties. If storage type cannot be determined, Compactor uses one worker thread. Windows processor-topology information is used to choose the conservative LZX Auto worker count; explicit manual thread limits override that Auto policy. diff --git a/build.rs b/build.rs index 1d7c557..e9eff64 100644 --- a/build.rs +++ b/build.rs @@ -6,5 +6,19 @@ fn main() { let mut res = winres::WindowsResource::new(); res.set_icon("compact.ico"); - res.compile().unwrap(); + // winres 0.1 defaults to a Windows root directory and *.exe tools even + // when its build script runs on Linux. Keep the normal MSVC path and also + // support cross-checking the Windows sources with a real MinGW toolchain. + if std::env::var("CARGO_CFG_TARGET_ENV").as_deref() == Ok("gnu") + && std::env::var("HOST").ok() != std::env::var("TARGET").ok() + { + let architecture = match std::env::var("CARGO_CFG_TARGET_ARCH").as_deref() { + Ok("x86") => "i686", + _ => "x86_64", + }; + res.set_toolkit_path("."); + res.set_windres_path(&format!("{}-w64-mingw32-windres", architecture)); + res.set_ar_path(&format!("{}-w64-mingw32-ar", architecture)); + } + res.compile().expect("Unable to compile Windows resources"); } diff --git a/docs/TESTING.md b/docs/TESTING.md new file mode 100644 index 0000000..975898a --- /dev/null +++ b/docs/TESTING.md @@ -0,0 +1,94 @@ +# Testing and native Windows verification + +## Before merging + +Use Windows 10/11 (or a supported Windows CI image), a **local NTFS temporary +directory**, stable Rust MSVC x64, Microsoft C++ build tools and Node.js 18 or +newer. The CI workflow runs the following gates: + +```powershell +cargo fmt --all -- --check +node --check src/ui/app.js +node --test tests/ui.test.cjs +cargo build --release --locked --target x86_64-pc-windows-msvc +cargo test --workspace --release --locked --target x86_64-pc-windows-msvc +cargo test --release --locked --target x86_64-pc-windows-msvc -- --ignored --test-threads=1 +``` + +The final command is essential. Tests marked `ignore` require actual WOF and +NTFS; they are not equivalent to the ordinary unit tests. The CI and release +workflows explicitly run them and **fail when a native support probe or an +assertion fails**. +They use their own temporary files and do not modify Cargo.lock, a game +installation, or user-selected files. + +The native fixtures cover all four codecs, backing detection and scan +classification, unchanged bytes and modification times, before/after allocation versus +`GetCompressedFileSizeW`, decompression, Thorough bypass of a pessimistic +sample, threshold restoration, already-compressed preservation, active writer +conflicts, hardlink protection and canonical-root containment. A separate +Windows unit test exercises cooperative locking from different threads using +independent mutex handles. + +## Portable checks + +These can be run without Windows, with the stated scope: + +```sh +node --test tests/ui.test.cjs +cargo test -p hashfilter --locked +rustc --edition 2018 --test src/policy.rs -o policy-tests +./policy-tests +``` + +The Node tests execute the actual embedded JavaScript and its messages using a +minimal DOM adapter. They verify behaviour and safe text handling; they do not +run the MSHTML engine. The pure Rust policy tests cover thresholds, invalid +values, cluster rounding and overflow boundaries. Hashfilter tests exercise +real files and controlled write/flush/sync failures. + +The Windows Rust sources can also be type-checked from Linux with the +`x86_64-pc-windows-gnu` Rust target and a compatible GCC/MinGW toolchain: + +```sh +cargo check --locked --target x86_64-pc-windows-gnu --tests +cargo test --workspace --no-run --locked --target x86_64-pc-windows-gnu +``` + +The second command also compiles and links every workspace test executable, +without running it. Add `--offline` when the dependencies are already cached. +Resource compilation remains enabled. The legacy embedded C dependencies need +a compatible compiler. Neither command executes WOF or native MSHTML, and +neither replaces the Windows MSVC build and integration gate. Native Windows +execution must be verified separately; cross-compilation does not establish +that those tests passed. + +## Manual checks on Windows + +1. Copy a representative, inactive folder into an isolated test location. Record + its contents and allocation. Compare LZX + Sampled with LZX + Thorough on + separate identical copies: total allocated bytes, elapsed time, CPU impact, + report counts and application loading behaviour. Do not extrapolate a + saving from the sample or from another user's dataset. +2. Set a high minimum percentage and confirm low-benefit files are restored. + Review failures if free space is tight; do not assume restoration succeeded + just because it was requested. +3. Analyse, change exclusions or the analysis mode, then confirm compression + requires a new analysis. Check a literal folder such as `Title [2024]`. +4. Pause, resume and stop both transformations. Close the window while paused + and while a file is active. Active native calls can finish; no new files + should be scheduled and the process should then exit. +5. Include a known DirectStorage runtime under an excluded `bin` directory. + Confirm the game root is protected. Cancel the preflight and confirm no file + is transformed. +6. Decompress a folder containing a file that cannot be expanded. Confirm a + single attempt, a visible error and retained WOF classification. The + `Decompress + exclude` action must not claim full restoration or add the + exclusion while WOF files remain. +7. Check the settings, file/folder viewer, empty summary and operation report at + common Windows display scales. Test cancelling the folder picker and + attempting invalid numeric settings. + +Keep the native CI result and any workload measurements with the PR. A source +diff, formatting pass, cross-check or mocked UI test alone is not evidence that +native WOF operations passed. diff --git a/docs/compression-policy.md b/docs/compression-policy.md new file mode 100644 index 0000000..47bd67e --- /dev/null +++ b/docs/compression-policy.md @@ -0,0 +1,115 @@ +# Compression policy + +## Choose the amount of work, then the codec + +Compactor keeps files directly usable through Windows Overlay Filter (WOF). +The supported FILE provider formats remain XPRESS4K, XPRESS8K, XPRESS16K and +LZX. Microsoft describes LZX as the most compact choice in `compact /EXE`. +This is a reason to offer LZX for maximum space savings, not a guarantee that +every file or workload benefits equally. + +| Setting | Candidate selection | Tradeoff | +| --- | --- | --- | +| Sampled (default) | A generic 8 KiB sampler chooses potentially worthwhile files | Less work, but can miss savings that the selected codec could achieve | +| Thorough | All otherwise eligible files are attempted unless the same policy already measured them as not worthwhile | Maximum coverage with the selected codec, at the cost of more CPU time and writes | + +LZX + Thorough is the option for users who want to spend more work looking for +additional savings. The choice does not introduce a new compression format, +change file names, or convert working files into archives. Both modes keep the +existing HDD and LZX worker limits, DirectStorage safeguard and worker priority. + +No data-dependent benchmark has been run on the user's files. No fixed savings +percentage or improvement over the previous version is claimed. The generic +sample is not a native XPRESS/LZX benchmark. In particular, an arbitrary 10% +LZX projection improvement has been removed. + +## What qualifies as worthwhile + +For each new compression operation, the worker records the allocation before +and after compression under a protected file identity. Compression is retained +only when: + +1. The selected WOF algorithm is actually present after the operation. +2. The logical file length is unchanged. +3. The allocation reduction meets the configured percentage of the **initial + allocation**, rounded up to a whole byte. +4. At least one allocation unit (the target NTFS cluster size) is saved. + +The default percentage is 1%. Setting it to zero still requires a positive +saving of one cluster; it never means retaining a file that grew. +`ERROR_COMPRESSION_NOT_BENEFICIAL` is a normal negative result. + +If a newly compressed file does not meet the threshold, Compactor requests +restoration to uncompressed form and verifies the backing state afterwards. +Restoration can need temporary free space for the entire logical stream. The +space check is a snapshot, not a reservation; another process can still consume +space. If a measurement, operation or restoration fails, the error report says +so and a rescan is required. A failure is never silently recorded as success. + +The allocation query uses `FileCompressionInfo`, not the allocation of the +underlying sparse stream. For WOF it opens a normal view while retaining the +protected handle and compares volume/file identity before using it. It does +not enumerate or add the hidden WOF data stream. A nonempty WOF file with an +ambiguous zero allocation is rejected as unmeasurable. Native Windows tests +must pass the comparison with `GetCompressedFileSizeW` before this change is +merged or released. + +## Files and operations that are protected + +- Compress preserves existing WOF compression. It does not automatically expand + XPRESS files or try multiple algorithms in sequence. There is no dependency + on an undocumented in-place algorithm migration contract. +- Users can explicitly Decompress, Analyse and then Compress with another + method. Expansion requires free space and the usual file access rights. +- Whole-drive roots, network targets, non-NTFS targets, protected Windows paths + and folder aliases through reparse points are refused. +- Every worker checks the final opened path against the canonical root captured + for the scan. Replacing a nested directory with a junction cannot redirect a + queued operation outside that root. +- Unsupported providers and versions are left unchanged. Malformed API + responses and failed inspections are reported as errors. +- Other reparse points, sparse files without supported WOF backing, encrypted, + offline, legacy NTFS-compressed, system, temporary and read-only files are + skipped. Hardlinks are not transformed because another name can lie outside + the selected tree and accounting would otherwise count the same storage twice. +- Active content writers/deleters conflict with the file sharing mode. A + per-identity mutex coordinates cooperating Compactor instances. Unrelated + tools that change WOF attributes do not participate in that mutex. +- DirectStorage protection searches independently of compression exclusions. + An excluded `bin` folder therefore cannot hide a known runtime signal from + the protection pass. The heuristic cannot detect every application or layout; + disabling it is an explicit user choice. + +These checks reduce known problems; they do not establish that arbitrary +applications perform equally with every codec. Write-heavy databases, VM +images, active logs and installations being updated are poor candidates for +this kind of filesystem compression. + +## Cache and operation reports + +The v3 cache contains only measured negative results. Its key includes path, +logical length, modification time, codec, analysis mode, threshold and cluster +size. A Sampled rejection is not proof of incompressibility and is not cached. +The fingerprint is metadata-based, not a cryptographic content hash. +Changing the relevant policy or metadata reconsiders the file; v2 entries do +not suppress new attempts. + +Each run reports changed files, below-threshold results, skips and failures. +Error details are limited to the first 20 entries while the count includes all +errors. Reported operation savings use the before/after measurements of +completed files. They do not compare a stale analysis snapshot with the final +folder or conceal failed files inside a success count. + +## Primary references + +- [Microsoft: compact](https://learn.microsoft.com/windows-server/administration/windows-commands/compact) +- [Microsoft: WOF_FILE_COMPRESSION_INFO_V1](https://learn.microsoft.com/windows/win32/api/wofapi/ns-wofapi-wof_file_compression_info_v1) +- [Microsoft: WofSetFileDataLocation](https://learn.microsoft.com/windows/win32/api/wofapi/nf-wofapi-wofsetfiledatalocation) +- [Microsoft: WofIsExternalFile and buffer sizing](https://learn.microsoft.com/windows/win32/api/wofapi/nf-wofapi-wofisexternalfile) +- [Microsoft: FSCTL_GET_EXTERNAL_BACKING](https://learn.microsoft.com/windows-hardware/drivers/ifs/fsctl-get-external-backing) +- [Microsoft: FSCTL_DELETE_EXTERNAL_BACKING](https://learn.microsoft.com/windows-hardware/drivers/ifs/fsctl-delete-external-backing) +- [Microsoft: FILE_COMPRESSION_INFO](https://learn.microsoft.com/windows/win32/api/winbase/ns-winbase-file_compression_info) +- [Microsoft: GetCompressedFileSizeW](https://learn.microsoft.com/windows/win32/api/fileapi/nf-fileapi-getcompressedfilesizew) + +References checked on 2026-10-09. See [TESTING.md](TESTING.md) for the required +native verification and manual workload checks. diff --git a/hashfilter/src/lib.rs b/hashfilter/src/lib.rs index 9883796..c987b09 100644 --- a/hashfilter/src/lib.rs +++ b/hashfilter/src/lib.rs @@ -27,6 +27,16 @@ impl HashFilter { pub fn set_backing>(&mut self, path: P) { self.path = Some(path.as_ref().to_owned()); self.last_offset = 0; + self.filter.clear(); + self.pending.clear(); + } + + fn reset_loaded(&mut self) { + self.last_offset = 0; + self.filter.clear(); + // Local inserts are still useful and must survive replacement or + // truncation of this disposable, append-only cache. + self.filter.extend(self.pending.iter().copied()); } pub fn load(&mut self) -> io::Result<()> { @@ -36,10 +46,19 @@ impl HashFilter { let mut file = match File::open(self.path.as_ref().unwrap()) { Ok(file) => file, - Err(ref e) if e.kind() == io::ErrorKind::NotFound => return Ok(()), + Err(ref e) if e.kind() == io::ErrorKind::NotFound => { + self.reset_loaded(); + return Ok(()); + } Err(e) => return Err(e), }; - file.lock_shared()?; + FileExt::lock_shared(&file)?; + + let end = file.metadata()?.len(); + let complete_end = end - end % 16; + if complete_end < self.last_offset { + self.reset_loaded(); + } if self.last_offset > 0 { file.seek(SeekFrom::Start(self.last_offset))?; @@ -47,15 +66,15 @@ impl HashFilter { let mut file = BufReader::new(file); let mut buf = [0; 16]; - loop { - match file.read_exact(&mut buf) { - Ok(()) => self.filter.insert(u128::from_le_bytes(buf)), - Err(ref e) if e.kind() == io::ErrorKind::UnexpectedEof => return Ok(()), - Err(e) => return Err(e), - }; - + // A crashed append can leave an incomplete final record. Do not read + // it, but propagate an unexpected EOF within the known complete data. + while self.last_offset < complete_end { + file.read_exact(&mut buf)?; + self.filter.insert(u128::from_le_bytes(buf)); self.last_offset += 16; } + + Ok(()) } pub fn save(&mut self) -> io::Result<()> { @@ -70,26 +89,52 @@ impl HashFilter { let mut file = OpenOptions::new() .write(true) .create(true) + .truncate(false) .open(self.path.as_ref().unwrap())?; - file.lock_exclusive()?; + FileExt::lock_exclusive(&file)?; let end = file.metadata()?.len(); - if end % 16 != 0 { - file.set_len(end - (end % 16))?; + let complete_end = end - end % 16; + if complete_end != end { + file.set_len(complete_end)?; + } + if complete_end < self.last_offset { + self.reset_loaded(); } file.seek(SeekFrom::End(0))?; + let new_end = (self.pending.len() as u64) + .checked_mul(16) + .and_then(|bytes| complete_end.checked_add(bytes)) + .ok_or_else(|| { + io::Error::new(io::ErrorKind::InvalidInput, "Hash cache is too large") + })?; + let can_advance = complete_end == self.last_offset; let mut file = BufWriter::new(file); - while let Some(key) = self.pending.pop() { - file.write_all(&key.to_le_bytes())?; - } + self.write_pending(&mut file, |writer| writer.get_ref().sync_all())?; - if end == self.last_offset { - self.last_offset = file.seek(SeekFrom::End(0))?; + if can_advance { + self.last_offset = new_end; } - file.into_inner()?.sync_all()?; + Ok(()) + } + + fn write_pending(&mut self, writer: &mut W, sync: F) -> io::Result<()> + where + W: Write, + F: FnOnce(&mut W) -> io::Result<()>, + { + for key in &self.pending { + writer.write_all(&key.to_le_bytes())?; + } + writer.flush()?; + sync(writer)?; + // Do not forget records until they reach durable storage. A failed + // append may leave valid duplicate records on retry; HashSet loading + // makes those harmless, and save() repairs a partial trailing record. + self.pending.clear(); Ok(()) } @@ -118,7 +163,7 @@ impl HashFilter { } #[test] -fn it_seems_to_work() { +fn persists_and_merges_appends_from_other_instances() { let dir = tempdir::TempDir::new("hashfilter-test").unwrap(); let db = dir.path().join("test.dat"); let mut hf = HashFilter::open(&db); @@ -155,3 +200,210 @@ fn it_seems_to_work() { hf.load().unwrap(); assert!(hf.contains(PathBuf::from("/path/to/some/file10"))); } + +#[cfg(test)] +mod tests { + use super::*; + use std::io::Cursor; + + #[test] + fn switching_backing_drops_keys_from_the_previous_cache() { + let dir = tempdir::TempDir::new("hashfilter-switch").unwrap(); + let first = dir.path().join("first.dat"); + let second = dir.path().join("second.dat"); + let mut filter = HashFilter::open(&first); + filter.insert("persisted in first"); + filter.save().unwrap(); + filter.insert("pending in first"); + + let mut other = HashFilter::open(&second); + other.insert("persisted in second"); + other.save().unwrap(); + + filter.set_backing(&second); + filter.load().unwrap(); + assert!(!filter.contains("persisted in first")); + assert!(!filter.contains("pending in first")); + assert!(filter.contains("persisted in second")); + assert!(filter.pending.is_empty()); + } + + #[test] + fn truncation_reloads_retained_records_and_preserves_local_inserts() { + let dir = tempdir::TempDir::new("hashfilter-truncate").unwrap(); + let path = dir.path().join("cache.dat"); + let mut filter = HashFilter::open(&path); + filter.insert("retained"); + filter.insert("discarded"); + filter.save().unwrap(); + filter.insert("pending"); + + OpenOptions::new() + .write(true) + .open(&path) + .unwrap() + .set_len(16) + .unwrap(); + filter.load().unwrap(); + assert!(filter.contains("retained")); + assert!(!filter.contains("discarded")); + assert!(filter.contains("pending")); + filter.save().unwrap(); + + let mut reloaded = HashFilter::open(&path); + reloaded.load().unwrap(); + assert!(reloaded.contains("retained")); + assert!(reloaded.contains("pending")); + assert!(!reloaded.contains("discarded")); + } + + #[test] + fn save_also_detects_truncation_without_an_intervening_load() { + let dir = tempdir::TempDir::new("hashfilter-save-truncate").unwrap(); + let path = dir.path().join("cache.dat"); + let mut filter = HashFilter::open(&path); + filter.insert("old"); + filter.save().unwrap(); + filter.insert("pending"); + File::create(&path).unwrap(); + + filter.save().unwrap(); + assert!(!filter.contains("old")); + assert!(filter.contains("pending")); + assert_eq!(16, std::fs::metadata(&path).unwrap().len()); + } + + #[test] + fn removed_cache_does_not_leave_stale_persisted_keys() { + let dir = tempdir::TempDir::new("hashfilter-removed").unwrap(); + let path = dir.path().join("cache.dat"); + let mut filter = HashFilter::open(&path); + filter.insert("old"); + filter.save().unwrap(); + filter.insert("pending"); + std::fs::remove_file(&path).unwrap(); + + filter.load().unwrap(); + assert!(!filter.contains("old")); + assert!(filter.contains("pending")); + filter.save().unwrap(); + let mut reloaded = HashFilter::open(&path); + reloaded.load().unwrap(); + assert!(reloaded.contains("pending")); + assert!(!reloaded.contains("old")); + } + + #[test] + fn partial_trailing_record_is_ignored_then_repaired() { + let dir = tempdir::TempDir::new("hashfilter-partial").unwrap(); + let path = dir.path().join("cache.dat"); + let mut filter = HashFilter::open(&path); + filter.insert("complete"); + filter.save().unwrap(); + OpenOptions::new() + .append(true) + .open(&path) + .unwrap() + .write_all(&HashFilter::key_for("partial").to_le_bytes()[..7]) + .unwrap(); + + let mut reloaded = HashFilter::open(&path); + reloaded.load().unwrap(); + assert!(reloaded.contains("complete")); + assert!(!reloaded.contains("partial")); + reloaded.insert("after partial"); + reloaded.save().unwrap(); + assert_eq!(32, std::fs::metadata(&path).unwrap().len()); + filter.load().unwrap(); + assert!(filter.contains("after partial")); + assert!(!filter.contains("partial")); + } + + struct FailingWriter { + bytes: Vec, + fail_after: Option, + fail_flush: bool, + } + + impl Write for FailingWriter { + fn write(&mut self, bytes: &[u8]) -> io::Result { + let count = match self.fail_after { + Some(limit) if self.bytes.len() >= limit => { + return Err(io::Error::new( + io::ErrorKind::Other, + "Injected write failure", + )); + } + Some(limit) => bytes.len().min(limit - self.bytes.len()), + None => bytes.len(), + }; + self.bytes.extend_from_slice(&bytes[..count]); + Ok(count) + } + + fn flush(&mut self) -> io::Result<()> { + if self.fail_flush { + Err(io::Error::new( + io::ErrorKind::Other, + "Injected flush failure", + )) + } else { + Ok(()) + } + } + } + + #[test] + fn write_flush_and_sync_failures_all_preserve_pending_for_retry() { + for failure in 0..3 { + let mut filter = HashFilter::default(); + filter.insert("first"); + filter.insert("second"); + let mut writer = FailingWriter { + bytes: Vec::new(), + fail_after: if failure == 0 { Some(19) } else { None }, + fail_flush: failure == 1, + }; + let result = filter.write_pending(&mut writer, |_| { + if failure == 2 { + Err(io::Error::new( + io::ErrorKind::Other, + "Injected sync failure", + )) + } else { + Ok(()) + } + }); + assert!(result.is_err()); + assert_eq!(2, filter.pending.len()); + assert!(filter.contains("first")); + assert!(filter.contains("second")); + + let mut retry = Cursor::new(Vec::new()); + filter.write_pending(&mut retry, |_| Ok(())).unwrap(); + assert!(filter.pending.is_empty()); + let expected: Vec = ["first", "second"] + .iter() + .flat_map(|value| HashFilter::key_for(value).to_le_bytes().to_vec()) + .collect(); + assert_eq!(expected, retry.into_inner()); + } + } + + #[test] + fn failed_save_can_be_retried_after_fixing_the_backing_path() { + let dir = tempdir::TempDir::new("hashfilter-retry").unwrap(); + let path = dir.path().join("cache.dat"); + std::fs::create_dir(&path).unwrap(); + let mut filter = HashFilter::open(&path); + filter.insert("pending"); + assert!(filter.save().is_err()); + assert_eq!(1, filter.pending.len()); + + std::fs::remove_dir(&path).unwrap(); + filter.save().unwrap(); + let mut reloaded = HashFilter::open(&path); + reloaded.load().unwrap(); + assert!(reloaded.contains("pending")); + } +} diff --git a/src/backend.rs b/src/backend.rs index cf8970a..58c4add 100644 --- a/src/backend.rs +++ b/src/backend.rs @@ -3,15 +3,16 @@ use std::io; use std::path::{Path, PathBuf}; use std::time::{Duration, Instant}; -use crossbeam_channel::{bounded, Receiver, RecvTimeoutError}; +use crossbeam_channel::{bounded, Receiver, RecvTimeoutError, TryRecvError}; use filesize::PathExt; use winapi::um::winbase::SetThreadExecutionState; use winapi::um::winnt::{ES_CONTINUOUS, ES_SYSTEM_REQUIRED}; use crate::background::BackgroundHandle; use crate::compact::{self, Compression}; -use crate::compression::{BackgroundCompactor, CompressionJob}; -use crate::directstorage::{discover_direct_storage_roots, is_under}; +use crate::compression::{BackgroundCompactor, CompressionJob, FileDisposition, FileOutcome}; +use crate::config::Config; +use crate::directstorage::{is_under, DirectStorageScan}; use crate::folder::{ compression_worker_count_for_path, validate_target_path, FileInfo, FileKind, FolderInfo, FolderScan, @@ -27,6 +28,7 @@ pub struct Backend { gui: GuiWrapper, msg: Receiver, info: Option, + analysis_valid: bool, } struct SystemAwakeGuard; @@ -113,8 +115,126 @@ fn protect_direct_storage_candidates(folder: &mut FolderInfo, roots: &[PathBuf]) protected } +fn literal_exclusion(path: &Path) -> String { + let mut pattern = String::new(); + for ch in path.to_string_lossy().chars() { + match ch { + '*' => pattern.push_str("[*]"), + '?' => pattern.push_str("[?]"), + '[' => pattern.push_str("[[]"), + ']' => pattern.push_str("[]]"), + '{' => pattern.push_str("[{]"), + '}' => pattern.push_str("[}]"), + _ => pattern.push(ch), + } + } + pattern +} + +#[derive(Default)] +struct OperationTotals { + changed: usize, + not_beneficial: usize, + skipped: usize, + failed: usize, + errors: Vec, + measured_before: u64, + measured_after: u64, +} + +impl OperationTotals { + fn error(&mut self, path: &Path, message: impl std::fmt::Display) { + self.failed += 1; + // Keep memory and GUI messages bounded even for millions of errors. + if self.errors.len() < 20 { + self.errors.push(format!("{}: {}", path.display(), message)); + } + } +} + +fn record_file_result( + folder: &mut FolderInfo, + mut file: FileInfo, + path: &Path, + result: io::Result, + totals: &mut OperationTotals, + cache: &mut hashfilter::HashFilter, + settings: &Config, +) { + file.estimate_valid = false; + match result { + Ok(outcome) => { + totals.measured_before = totals + .measured_before + .saturating_add(outcome.original_physical_size); + totals.measured_after = totals.measured_after.saturating_add(outcome.physical_size); + file.content_len = outcome.content_len; + file.logical_size = outcome.content_len; + file.modified_time = outcome.modified_time; + file.physical_size = outcome.physical_size; + file.compression = outcome.compression; + match outcome.disposition { + FileDisposition::Compressed | FileDisposition::Decompressed => totals.changed += 1, + FileDisposition::NotBeneficial => { + totals.not_beneficial += 1; + // Cache only a measured outcome and the fingerprint captured + // under the protected handle, never later metadata by path. + cache.insert(incompressible_key( + path, + outcome.content_len, + outcome.modified_time, + settings.compression, + settings.analysis_mode, + settings.min_savings_percent, + folder.cluster_size, + )); + } + FileDisposition::Skipped => totals.skipped += 1, + } + } + Err(error) => { + totals.error(path, error); + // A failed rollback may leave valid WOF backing. Refresh for the + // viewer/decompress action rather than silently losing that file. + if let Ok(metadata) = std::fs::metadata(path) { + use std::os::windows::fs::MetadataExt; + file.content_len = metadata.len(); + file.logical_size = metadata.len(); + file.modified_time = metadata.last_write_time(); + } + if let Ok(size) = path.size_on_disk() { + file.physical_size = size; + } + if let Ok(backing) = compact::detect_compression(path) { + file.compression = backing; + } + } + } + file.estimated_physical_size = file.physical_size; + folder.push( + if file.compression.is_some() { + FileKind::Compressed + } else { + FileKind::Skipped + }, + file, + ); +} + +fn take_queued_file( + folder: &mut FolderInfo, + remaining: &mut usize, + kind: FileKind, +) -> Option { + if *remaining == 0 { + return None; + } + *remaining -= 1; + folder.pop(kind) +} + fn add_folder_exclusion(path: &Path) -> Result { - let display = path.to_string_lossy().to_string(); + let display = literal_exclusion(path); let c = config(); let mut c = c.write().unwrap(); let mut current = c.current(); @@ -129,8 +249,7 @@ fn add_folder_exclusion(path: &Path) -> Result { current.excludes.push(display); current.validate()?; - c.replace(current); - c.save() + c.update(current) .map_err(|err| format!("Unable to save exclusions: {}", err))?; Ok(true) } @@ -229,6 +348,7 @@ impl Backend { gui, msg, info: None, + analysis_valid: false, } } @@ -301,8 +421,13 @@ impl Backend { if self.target_is_valid(&path) { self.gui.folder(&path); self.scan_loop(path); + continue; } } + self.gui.scanned(); + if !self.analysis_valid { + self.gui.send(&GuiResponse::AnalysisInvalidated); + } } Ok(GuiRequest::Analyse) if self.info.is_some() => { let path = self.info.as_ref().unwrap().path.clone(); @@ -315,7 +440,22 @@ impl Backend { Ok(GuiRequest::ViewCompressed { view, query, page }) if self.info.is_some() => { self.view_compressed(view, query, page); } + Ok(GuiRequest::SettingsChanged) => { + self.analysis_valid = false; + if self.info.is_some() { + self.gui.send(&GuiResponse::AnalysisInvalidated); + } + } + Ok(GuiRequest::Quit) => break, Ok(GuiRequest::Compress) if self.info.is_some() => { + if !self.analysis_valid { + self.gui.send(&GuiResponse::AnalysisInvalidated); + self.gui.error( + "Analysis required", + "Analyse the folder with the current settings before compressing.", + ); + continue; + } let path = self.info.as_ref().unwrap().path.clone(); if self.target_is_valid(&path) { self.compress_loop(); @@ -333,6 +473,15 @@ impl Backend { self.uncompress_loop(true); } } + Ok(GuiRequest::Analyse) + | Ok(GuiRequest::Compress) + | Ok(GuiRequest::Decompress) + | Ok(GuiRequest::DecompressAndExclude) => { + self.gui + .error("Folder required", "Choose and analyse a folder first."); + self.gui.scanned(); + self.gui.send(&GuiResponse::AnalysisInvalidated); + } Ok(msg) => { eprintln!("Backend: Ignored message: {:?}", msg); } @@ -345,20 +494,20 @@ impl Backend { } fn scan_loop(&mut self, path: PathBuf) { + self.info = None; + self.analysis_valid = false; let current = config().read().unwrap().current(); - let excludes = current.globset().expect("globs"); - let ratio_limit = current.ratio_limit(); - - let scanner = FolderScan::new( - path, - excludes, - ratio_limit, - current.compression, - current.max_threads, - current.hdd_single_thread, - ); + let scanner = match FolderScan::new(&path, ¤t) { + Ok(scanner) => scanner, + Err(message) => { + self.gui.error("Settings error", message); + self.gui.stopped(); + return; + } + }; let task = BackgroundHandle::spawn(scanner); let start = Instant::now(); + let mut cancelled = false; self.gui.status("Analysing", None); loop { @@ -375,7 +524,11 @@ impl Backend { self.gui.status("Analysing", None); self.gui.resumed(); } - Ok(GuiRequest::Stop) | Err(RecvTimeoutError::Disconnected) => { + Ok(GuiRequest::Stop) + | Ok(GuiRequest::Quit) + | Ok(GuiRequest::SettingsChanged) + | Err(RecvTimeoutError::Disconnected) => { + cancelled = true; task.cancel(); } Ok(msg) => { @@ -385,21 +538,35 @@ impl Backend { } match task.wait_timeout(Duration::from_millis(25)) { - Some(Ok(info)) => { - self.gui - .status(format!("Analysed in {:.2?}", start.elapsed()), Some(1.0)); - self.gui.summary(info.summary()); - self.gui.scanned(); - self.info = Some(info); - break; - } - Some(Err(info)) => { - self.gui.status( - format!("Analysis stopped after {:.2?}", start.elapsed()), - Some(0.5), - ); - self.gui.summary(info.summary()); - self.gui.stopped(); + Some(result) => { + let complete = result.is_ok() && !cancelled; + let info = match result { + Ok(info) | Err(info) => info, + }; + self.analysis_valid = complete; + if complete { + self.gui.status( + format!( + "Analysed in {:.2?}; {} scan/read errors", + start.elapsed(), + info.scan_errors + ), + Some(1.0), + ); + self.gui.summary(info.summary()); + self.gui.scanned(); + } else { + self.gui.status( + format!( + "Analysis stopped after {:.2?}; analyse again before compressing", + start.elapsed() + ), + Some(0.0), + ); + self.gui.summary(info.summary()); + self.gui.stopped(); + self.gui.send(&GuiResponse::AnalysisInvalidated); + } self.info = Some(info); break; } @@ -449,554 +616,379 @@ impl Backend { } fn compress_loop(&mut self) { - let current = config().read().unwrap().current(); - let compression = Some(current.compression); - let mut folder = self.info.take().expect("fileinfo"); - - if current.protect_direct_storage && folder.direct_storage { - self.gui.status("Checking DirectStorage protection", None); - let roots = discover_direct_storage_roots(&folder.path); - let protected = protect_direct_storage_candidates(&mut folder, &roots); - if protected > 0 { - self.gui.status( - format!( - "Protected {} files in {} DirectStorage game{}", - protected, - roots.len(), - if roots.len() == 1 { "" } else { "s" } - ), - Some(0.0), - ); - self.gui.summary(folder.summary()); - } - } - - if folder.len(FileKind::Compressible) == 0 { - self.gui.status("Nothing to compact", Some(1.0)); - self.gui.summary(folder.summary()); - self.gui.scanned(); - self.info = Some(folder); - return; - } - - if !self.wof_preflight(&folder, FileKind::Compressible) { - self.gui.summary(folder.summary()); - self.gui.scanned(); - self.info = Some(folder); - return; - } - - let _awake = SystemAwakeGuard::new(); - let worker_count = compression_worker_count_for_path( - &folder.path, - current.compression, - current.max_threads, - current.hdd_single_thread, - ); - - let (send_file, send_file_rx) = bounded::(worker_count); - let (recv_result_tx, recv_result) = bounded::<(PathBuf, io::Result)>(worker_count); - let mut tasks = Vec::with_capacity(worker_count); - - for _ in 0..worker_count { - let compactor = BackgroundCompactor::new( - compression, - current.ratio_limit(), - send_file_rx.clone(), - recv_result_tx.clone(), - ); - tasks.push(BackgroundHandle::spawn(compactor)); - } - - drop(send_file_rx); - drop(recv_result_tx); - - let start = Instant::now(); - let summary = folder.summary(); - let total_files = folder.len(FileKind::Compressible); - let total_bytes = summary.compressible.logical_size; - let compressible_size = summary.compressible.physical_size; - let mut done_files = 0usize; - let mut done_bytes = 0u64; - let mut pending: HashMap = HashMap::with_capacity(worker_count); - let mut no_more_files = false; - - let mut last_update = Instant::now(); - let mut last_write = Instant::now(); - let mut paused = false; - let mut stopped = false; - - let old_size = folder.physical_size; - - let incompressible = pathdb(); - let mut incompressible = incompressible.write().unwrap(); - let _ = incompressible.load(); + self.transform_loop(false, false); + } - self.gui.compacting(); - self.gui.status("Compacting", Some(0.0)); + fn uncompress_loop(&mut self, exclude_after: bool) { + self.transform_loop(true, exclude_after); + } + fn direct_storage_roots(&self, path: &Path) -> io::Result> { + self.gui.status("Checking DirectStorage protection", None); + let task = BackgroundHandle::spawn(DirectStorageScan { + path: path.to_path_buf(), + }); + let mut cancelled = false; loop { - while !paused && !stopped && pending.len() < worker_count && !no_more_files { - if let Some(fi) = folder.pop(FileKind::Compressible) { - let path = folder.path.join(&fi.path); - let job = CompressionJob { - path: path.clone(), - content_len: fi.content_len, - modified_time: fi.modified_time, - estimate_valid: fi.estimate_valid, - estimated_ratio: fi.estimated_ratio, - }; - - if send_file.send(job).is_err() { - folder.push(FileKind::Compressible, fi); - stopped = true; - break; - } - - pending.insert(path, fi); - } else { - no_more_files = true; - } - } - - if (no_more_files || stopped) && pending.is_empty() { - break; - } - - if last_write.elapsed() > Duration::from_secs(60) { - let _ = incompressible.save(); - last_write = Instant::now(); - } - - loop { - match self.msg.try_recv() { - Ok(GuiRequest::Pause) if !paused && !stopped => { - paused = true; - self.gui.paused(); - self.gui.status( - if pending.is_empty() { - "Paused" - } else { - "Pausing after active files finish" - }, - Some(progress(done_bytes, total_bytes)), - ); - } - Ok(GuiRequest::Resume) if paused && !stopped => { - paused = false; - self.gui.resumed(); - self.gui - .status("Compacting", Some(progress(done_bytes, total_bytes))); - } - Ok(GuiRequest::Stop) if !stopped => { - stopped = true; - self.gui.status( - if pending.is_empty() { - "Stopping" - } else { - "Stopping after active files finish" - }, - Some(progress(done_bytes, total_bytes)), - ); - } - Ok(_) => (), - Err(_) => break, - } - } - - match recv_result.recv_timeout(Duration::from_millis(25)) { - Ok((path, result)) => { - let Some(mut fi) = pending.remove(&path) else { - continue; - }; - let logical_size = fi.logical_size; - let display_path = fi.path.clone(); - done_files += 1; - done_bytes = done_bytes.saturating_add(logical_size); - - match result { - Ok(true) => { - fi.physical_size = path.size_on_disk().unwrap_or(fi.physical_size); - fi.estimated_physical_size = fi.physical_size; - fi.estimate_valid = false; - if let Ok(metadata) = std::fs::metadata(&path) { - use std::os::windows::fs::MetadataExt; - fi.content_len = metadata.len(); - fi.logical_size = metadata.len(); - fi.modified_time = metadata.last_write_time(); - } - - if fi.physical_size >= fi.logical_size { - if let Ok(metadata) = std::fs::metadata(&path) { - incompressible.insert(incompressible_key(&path, &metadata)); - } - folder.push(FileKind::Skipped, fi); - } else { - folder.push(FileKind::Compressed, fi); - } - } - Ok(false) => { - fi.estimated_physical_size = fi.physical_size; - fi.estimate_valid = false; - if let Ok(metadata) = std::fs::metadata(&path) { - incompressible.insert(incompressible_key(&path, &metadata)); - } - folder.push(FileKind::Skipped, fi); - } - Err(err) => { - fi.estimated_physical_size = fi.physical_size; - self.gui.status( - format!("Error: {}, {}", err, display_path.display()), - Some(progress(done_bytes, total_bytes)), - ); - folder.push(FileKind::Skipped, fi); - } - } - - if last_update.elapsed() > Duration::from_millis(50) { - last_update = Instant::now(); - self.gui.status( - if paused { - if pending.is_empty() { - "Paused".to_string() - } else { - "Pausing after active files finish".to_string() - } - } else if stopped { - if pending.is_empty() { - "Stopping".to_string() - } else { - "Stopping after active files finish".to_string() - } - } else { - format!("Compacting: {}", display_path.display()) - }, - Some(progress(done_bytes, total_bytes)), - ); - - if pending.is_empty() { - self.gui.summary(folder.summary()); - } - } + match self.msg.recv_timeout(Duration::from_millis(25)) { + Ok(GuiRequest::Pause) => { + task.pause(); + self.gui.paused(); } - Err(RecvTimeoutError::Timeout) => { - if paused - && pending.is_empty() - && last_update.elapsed() > Duration::from_millis(50) - { - last_update = Instant::now(); - self.gui - .status("Paused", Some(progress(done_bytes, total_bytes))); - self.gui.summary(folder.summary()); - } + Ok(GuiRequest::Resume) => { + task.resume(); + self.gui.resumed(); } - Err(RecvTimeoutError::Disconnected) => { - stopped = true; - break; + Ok(GuiRequest::Stop) + | Ok(GuiRequest::Quit) + | Ok(GuiRequest::SettingsChanged) + | Err(RecvTimeoutError::Disconnected) => { + cancelled = true; + task.cancel(); } + _ => {} + } + if let Some(result) = task.wait_timeout(Duration::from_millis(25)) { + return if cancelled { + Err(io::Error::new( + io::ErrorKind::Interrupted, + "DirectStorage check stopped", + )) + } else { + result + }; } } - - drop(send_file); - for task in tasks { - task.wait(); - } - let _ = incompressible.save(); - - let new_size = folder.physical_size; - let decimal = config().read().unwrap().current().decimal; - let saved = old_size.saturating_sub(new_size); - - let msg = if stopped { - format!( - "Stopped after {} of {} files, saving {} in {:.2?}", - done_files, - total_files, - format_size(saved, decimal), - start.elapsed() - ) - } else { - format!( - "Compacted {} in {} files, saving {} in {:.2?}", - format_size(compressible_size, decimal), - done_files, - format_size(saved, decimal), - start.elapsed() - ) - }; - - self.gui - .status(msg, Some(progress(done_bytes, total_bytes))); - self.gui.summary(folder.summary()); - if stopped { - self.gui.stopped(); - } else { - self.gui.scanned(); - } - - self.info = Some(folder); } - fn uncompress_loop(&mut self, exclude_after: bool) { + fn transform_loop(&mut self, decompress: bool, exclude_after: bool) { let current = config().read().unwrap().current(); let mut folder = self.info.take().expect("fileinfo"); + let kind = if decompress { + FileKind::Compressed + } else { + FileKind::Compressible + }; + let operation = if decompress { + "Decompression" + } else { + "Compression" + }; + let verb = if decompress { + "Expanding" + } else { + "Compacting" + }; + let mut totals = OperationTotals::default(); + self.gui.compacting(); - if folder.len(FileKind::Compressed) == 0 { - self.gui.status("Nothing to decompress", Some(1.0)); - self.gui.scanned(); - self.info = Some(folder); - return; + // Run independently of compression exclusions: a runtime DLL hidden in + // an excluded bin directory must still protect the rest of its game. + if !decompress && current.protect_direct_storage { + match self.direct_storage_roots(&folder.path) { + Ok(roots) => { + folder.direct_storage = !roots.is_empty(); + totals.skipped += protect_direct_storage_candidates(&mut folder, &roots); + } + Err(error) => { + self.analysis_valid = false; + self.gui + .status(format!("Compression not started: {}", error), Some(0.0)); + if error.kind() != io::ErrorKind::Interrupted { + self.gui.error("DirectStorage check incomplete", format!( + "No files were compressed. {}. Review access to the selected folder and analyse again.", error, + )); + } + self.gui.summary(folder.summary()); + self.gui.stopped(); + self.gui.send(&GuiResponse::AnalysisInvalidated); + self.info = Some(folder); + return; + } + } } - if !self.wof_preflight(&folder, FileKind::Compressed) { + let total_files = folder.len(kind); + if total_files > 0 && !self.wof_preflight(&folder, kind) { self.gui.summary(folder.summary()); self.gui.scanned(); self.info = Some(folder); return; } - let _awake = SystemAwakeGuard::new(); - let worker_count = decompression_worker_count_for_path( - &folder.path, - current.max_threads, - current.hdd_single_thread, - ); - let (send_file, send_file_rx) = bounded::(worker_count); - let (recv_result_tx, recv_result) = bounded::<(PathBuf, io::Result)>(worker_count); + let worker_count = if decompress { + decompression_worker_count_for_path( + &folder.path, + current.max_threads, + current.hdd_single_thread, + ) + } else { + compression_worker_count_for_path( + &folder.path, + current.compression, + current.max_threads, + current.hdd_single_thread, + ) + } + .min(total_files.max(1)); + let (send_file, jobs) = bounded::(worker_count); + let (results, recv_result) = bounded::<(PathBuf, io::Result)>(worker_count); let mut tasks = Vec::with_capacity(worker_count); - - for _ in 0..worker_count { - let compactor = BackgroundCompactor::new( - None, - 0.0, - send_file_rx.clone(), - recv_result_tx.clone(), - ); - tasks.push(BackgroundHandle::spawn(compactor)); + if total_files > 0 { + for _ in 0..worker_count { + tasks.push(BackgroundHandle::spawn(BackgroundCompactor::new( + if decompress { + None + } else { + Some(current.compression) + }, + current.min_savings_percent, + current.analysis_mode, + folder.cluster_size, + jobs.clone(), + results.clone(), + ))); + } } - - drop(send_file_rx); - drop(recv_result_tx); + drop(jobs); + drop(results); let start = Instant::now(); - let summary = folder.summary(); - let total_files = folder.len(FileKind::Compressed); - let total_bytes = summary.compressed.logical_size; - let mut expanded_files = 0usize; + let total_bytes = if decompress { + folder.compressed.logical_size + } else { + folder.compressible.logical_size + }; + let mut done_files = 0usize; let mut done_bytes = 0u64; let mut pending: HashMap = HashMap::with_capacity(worker_count); - let mut failed = Vec::new(); - let mut no_more_files = false; - - let mut last_update = Instant::now(); let mut paused = false; let mut stopped = false; - let old_size = folder.physical_size; - - self.gui.compacting(); - self.gui.status("Expanding", Some(0.0)); + let mut exhausted = total_files == 0; + let mut remaining_to_dispatch = total_files; + let mut last_update = Instant::now(); + let mut last_write = Instant::now(); + let mut cache = pathdb().write().unwrap(); + let _ = cache.load(); + self.gui.status(verb, Some(0.0)); loop { - while !paused && !stopped && pending.len() < worker_count && !no_more_files { - if let Some(fi) = folder.pop(FileKind::Compressed) { - let path = folder.path.join(&fi.path); - let job = CompressionJob { - path: path.clone(), - content_len: fi.content_len, - modified_time: fi.modified_time, - estimate_valid: fi.estimate_valid, - estimated_ratio: fi.estimated_ratio, - }; - - if send_file.send(job).is_err() { - folder.push(FileKind::Compressed, fi); - stopped = true; - break; - } - - pending.insert(path, fi); - } else { - no_more_files = true; - } - } - - if (no_more_files || stopped) && pending.is_empty() { - break; - } - + // Consume controls before dispatching so closing a paused or idle + // window stops scheduling work instead of leaving a stranded loop. loop { match self.msg.try_recv() { - Ok(GuiRequest::Pause) if !paused && !stopped => { + Ok(GuiRequest::Pause) if !stopped => { paused = true; self.gui.paused(); self.gui.status( - if pending.is_empty() { - "Paused" - } else { - "Pausing after active files finish" - }, + "Pausing after active files finish", Some(progress(done_bytes, total_bytes)), ); } - Ok(GuiRequest::Resume) if paused && !stopped => { + Ok(GuiRequest::Resume) if !stopped => { paused = false; self.gui.resumed(); - self.gui - .status("Expanding", Some(progress(done_bytes, total_bytes))); } - Ok(GuiRequest::Stop) if !stopped => { + Ok(GuiRequest::SettingsChanged) => { + self.analysis_valid = false; stopped = true; - self.gui.status( - if pending.is_empty() { - "Stopping" - } else { - "Stopping after active files finish" - }, - Some(progress(done_bytes, total_bytes)), - ); } - Ok(_) => (), - Err(_) => break, + Ok(GuiRequest::Stop) | Ok(GuiRequest::Quit) => stopped = true, + Err(TryRecvError::Disconnected) => { + stopped = true; + break; + } + Err(TryRecvError::Empty) => break, + _ => {} } } - match recv_result.recv_timeout(Duration::from_millis(25)) { - Ok((path, result)) => { - let Some(mut fi) = pending.remove(&path) else { - continue; - }; - let logical_size = fi.logical_size; - let display_path = fi.path.clone(); - done_bytes = done_bytes.saturating_add(logical_size); - - match result { - Ok(_) => { - expanded_files += 1; - fi.physical_size = path.size_on_disk().unwrap_or(fi.logical_size); - fi.estimated_physical_size = fi.physical_size; - fi.estimate_valid = false; - if let Ok(metadata) = std::fs::metadata(&path) { - use std::os::windows::fs::MetadataExt; - fi.content_len = metadata.len(); - fi.logical_size = metadata.len(); - fi.modified_time = metadata.last_write_time(); - } - folder.push(FileKind::Compressible, fi); - } - Err(err) => { - fi.estimated_physical_size = fi.physical_size; - fi.estimate_valid = false; - self.gui.status( - format!("Error: {}, {}", err, display_path.display()), - Some(progress(done_bytes, total_bytes)), - ); - failed.push(fi); + while !paused && !stopped && !exhausted && pending.len() < worker_count { + match take_queued_file(&mut folder, &mut remaining_to_dispatch, kind) { + Some(file) => { + let path = folder.path.join(&file.path); + let job = CompressionJob { + path: path.clone(), + root: folder.canonical_root.clone(), + expected_path: folder.canonical_root.join(&file.path), + content_len: file.content_len, + modified_time: file.modified_time, + estimate_valid: file.estimate_valid, + estimated_ratio: file.estimated_ratio, + }; + if send_file.send(job).is_err() { + folder.push(kind, file); + stopped = true; + break; } + pending.insert(path, file); } + None => exhausted = true, + } + } + if (exhausted || stopped) && pending.is_empty() { + break; + } - if last_update.elapsed() > Duration::from_millis(50) { - last_update = Instant::now(); - self.gui.status( - if paused { - if pending.is_empty() { - "Paused".to_string() - } else { - "Pausing after active files finish".to_string() - } - } else if stopped { - if pending.is_empty() { - "Stopping".to_string() - } else { - "Stopping after active files finish".to_string() - } - } else { - format!("Expanding: {}", display_path.display()) - }, - Some(progress(done_bytes, total_bytes)), + match recv_result.recv_timeout(Duration::from_millis(25)) { + Ok((path, result)) => { + if let Some(file) = pending.remove(&path) { + done_files += 1; + done_bytes = done_bytes.saturating_add(file.logical_size); + record_file_result( + &mut folder, + file, + &path, + result, + &mut totals, + &mut cache, + ¤t, ); - - if pending.is_empty() { - self.gui.summary(folder.summary()); - } - } - } - Err(RecvTimeoutError::Timeout) => { - if paused - && pending.is_empty() - && last_update.elapsed() > Duration::from_millis(50) - { - last_update = Instant::now(); - self.gui - .status("Paused", Some(progress(done_bytes, total_bytes))); - self.gui.summary(folder.summary()); } } Err(RecvTimeoutError::Disconnected) => { stopped = true; break; } + Err(RecvTimeoutError::Timeout) => {} + } + // A panicked worker cannot report its active file. Do not wait + // forever for that missing result; drain the other workers below. + if tasks.iter().any(|task| task.is_finished()) { + stopped = true; + break; + } + if last_update.elapsed() >= Duration::from_millis(100) { + let state = if stopped { + "Stopping after active files finish" + } else if paused && pending.is_empty() { + "Paused" + } else if paused { + "Pausing after active files finish" + } else { + verb + }; + self.gui.status( + format!( + "{}: {} / {} files; {} errors", + state, done_files, total_files, totals.failed + ), + Some(progress(done_bytes, total_bytes)), + ); + if pending.is_empty() { + self.gui.summary(folder.summary()); + } + last_update = Instant::now(); + } + if last_write.elapsed() >= Duration::from_secs(60) { + if let Err(error) = cache.save() { + eprintln!("Unable to save compression cache: {}", error); + } + last_write = Instant::now(); } } drop(send_file); for task in tasks { - task.wait(); + if task.wait_result().is_err() { + stopped = true; + } } - - for fi in failed { - folder.push(FileKind::Compressed, fi); + // At most worker_count files were active; the equally-sized result + // channel can hold all remaining responses while the workers finish. + for (path, result) in recv_result.try_iter() { + if let Some(file) = pending.remove(&path) { + done_bytes = done_bytes.saturating_add(file.logical_size); + record_file_result( + &mut folder, + file, + &path, + result, + &mut totals, + &mut cache, + ¤t, + ); + } + } + for (path, file) in pending { + record_file_result( + &mut folder, + file, + &path, + Err(io::Error::new( + io::ErrorKind::Other, + "Worker exited before reporting this file; analyse again", + )), + &mut totals, + &mut cache, + ¤t, + ); } + if let Err(error) = cache.save() { + eprintln!("Unable to save compression cache: {}", error); + } + drop(cache); - let mut exclusion_active = false; - if exclude_after && !stopped { + let mut excluded = false; + if exclude_after && !stopped && totals.failed == 0 && folder.compressed.count == 0 { match add_folder_exclusion(&folder.path) { - Ok(added) => { - exclusion_active = true; + Ok(_) => { + excluded = true; move_compressible_to_skipped(&mut folder); - if added { - self.gui.config(); - } + self.gui.config(); } - Err(err) => self.gui.error("Unable to add exclusion", err), + Err(error) => self.gui.error("Unable to add exclusion", error), } + } else if exclude_after && !stopped { + self.gui.error("Folder was not excluded", "Some files could not be decompressed. Review the operation report, fix the errors and try again."); } - let new_size = folder.physical_size; - let decimal = config().read().unwrap().current().decimal; - let wasted = new_size.saturating_sub(old_size); - - let msg = if stopped { - format!( - "Stopped after expanding {} of {} files in {:.2?}", - expanded_files, - total_files, - start.elapsed() - ) - } else if exclude_after && exclusion_active { - format!( - "Expanded {} files using {} more space and excluded this folder in {:.2?}", - expanded_files, - format_size(wasted, decimal), - start.elapsed() - ) + let decimal = current.decimal; + let size_change = if decompress { + totals.measured_after.saturating_sub(totals.measured_before) } else { - format!( - "Expanded {} files using {} more space in {:.2?}", - expanded_files, - format_size(wasted, decimal), - start.elapsed() - ) + totals.measured_before.saturating_sub(totals.measured_after) }; - - self.gui - .status(msg, Some(progress(done_bytes, total_bytes))); + self.gui.status( + format!( + "{}{}: {} changed, {} below threshold, {} skipped, {} errors; {} {} in {:.2?}{}", + if stopped { "Stopped — " } else { "" }, + operation, + totals.changed, + totals.not_beneficial, + totals.skipped, + totals.failed, + format_size(size_change, decimal), + if decompress { + "additional space in completed files" + } else { + "saved in completed files" + }, + start.elapsed(), + if excluded { "; folder excluded" } else { "" }, + ), + Some(progress(done_bytes, total_bytes)), + ); + self.gui.send(&GuiResponse::OperationSummary { + operation: operation.to_string(), + changed: totals.changed, + not_beneficial: totals.not_beneficial, + skipped: totals.skipped, + failed: totals.failed, + errors: totals.errors, + }); self.gui.summary(folder.summary()); if stopped { self.gui.stopped(); } else { self.gui.scanned(); } - + // Expanded files have not been analysed against exclusions or the + // current algorithm. Errors can also leave changed backing metadata. + if decompress || totals.failed > 0 || !self.analysis_valid { + self.analysis_valid = false; + self.gui.send(&GuiResponse::AnalysisInvalidated); + } self.info = Some(folder); } } @@ -1028,6 +1020,7 @@ mod tests { logical_size, physical_size, estimated_physical_size: physical_size, + compression: Some(Compression::Lzx), }, ); } @@ -1035,6 +1028,45 @@ mod tests { folder } + #[test] + fn automatically_excluded_folder_names_are_literal_globs() { + let path = Path::new(r"C:\Games\Title [2024] {demo}"); + let mut config = Config::default(); + config.excludes = vec![literal_exclusion(path)]; + let excludes = config.globset().unwrap(); + assert!(excludes.is_match(path)); + assert!(!excludes.is_match(r"C:\Games\Title 2 demo")); + } + + #[test] + fn failed_decompression_files_are_retained_without_requeueing_in_the_same_run() { + let mut folder = sample_compressed_folder(); + let mut remaining = folder.compressed.count; + let mut attempted = std::collections::HashSet::new(); + while let Some(file) = take_queued_file(&mut folder, &mut remaining, FileKind::Compressed) { + assert!( + attempted.insert(file.path.clone()), + "file retried in the same run" + ); + // Failure keeps WOF backing in the viewer and available to retry + // during a later operation, never in this operation's work budget. + folder.push(FileKind::Compressed, file); + } + assert_eq!(3, attempted.len()); + assert_eq!(3, folder.compressed.count); + assert_eq!(0, remaining); + } + + #[test] + fn operation_errors_are_counted_but_details_are_bounded() { + let mut totals = OperationTotals::default(); + for _ in 0..100 { + totals.error(Path::new("test.bin"), "denied"); + } + assert_eq!(100, totals.failed); + assert_eq!(20, totals.errors.len()); + } + #[test] fn compressed_file_view_filters_paths() { let folder = sample_compressed_folder(); @@ -1110,18 +1142,20 @@ mod tests { logical_size: 8192, physical_size: 8192, estimated_physical_size: 4096, + compression: None, }, ); } - let protected = protect_direct_storage_candidates( - &mut folder, - &[PathBuf::from(r"D:\Games\Foo")], - ); + let protected = + protect_direct_storage_candidates(&mut folder, &[PathBuf::from(r"D:\Games\Foo")]); assert_eq!(1, protected); assert_eq!(1, folder.compressible.count); assert_eq!(1, folder.skipped.count); - assert_eq!(PathBuf::from(r"Bar\data.bin"), folder.compressible.files[0].path); + assert_eq!( + PathBuf::from(r"Bar\data.bin"), + folder.compressible.files[0].path + ); } #[test] @@ -1133,4 +1167,4 @@ mod tests { decompression_worker_count_for_path(Path::new(r"Z:\unknown"), 0, true) ); } -} \ No newline at end of file +} diff --git a/src/background.rs b/src/background.rs index c622e10..69097db 100644 --- a/src/background.rs +++ b/src/background.rs @@ -1,6 +1,4 @@ use crossbeam_channel::{Receiver, RecvTimeoutError}; -#[cfg(test)] -use crossbeam_channel::TryRecvError; use std::panic::{catch_unwind, UnwindSafe}; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::Arc; @@ -123,15 +121,6 @@ impl BackgroundHandle { } } - #[cfg(test)] - pub fn poll(&self) -> Option { - match self.result.try_recv() { - Ok(value) => Some(value.unwrap()), - Err(TryRecvError::Empty) => None, - Err(e) => panic!("{:?}", e), - } - } - pub fn wait_timeout(&self, wait: Duration) -> Option { match self.result.recv_timeout(wait) { Ok(value) => Some(value.unwrap()), @@ -140,11 +129,16 @@ impl BackgroundHandle { } } - pub fn wait(self) -> T { - match self.result.recv() { - Ok(value) => value.unwrap(), - Err(e) => panic!("{:?}", e), - } + /// Inspect completion without consuming it, so coordinators can detect a + /// worker that exited before reporting its active file. + pub fn is_finished(&self) -> bool { + !self.result.is_empty() + } + + pub fn wait_result(self) -> std::thread::Result { + self.result + .recv() + .unwrap_or_else(|_| Err(Box::new("Background worker disconnected before returning"))) } pub fn cancel(&self) { @@ -184,74 +178,66 @@ mod tests { use super::*; use std::time::Duration; - #[derive(Debug, Clone, Copy)] - pub struct Tick; + struct Stepped { + steps: Receiver<()>, + events: crossbeam_channel::Sender, + } - impl Background for Tick { + impl Background for Stepped { type Output = Result; type Status = u32; fn run(self, control: &ControlToken) -> Self::Output { - let mut ticks = 0; - - while ticks < 100 && !control.is_cancelled_with_pause() { - ticks += 1; - control.set_status(ticks); - - thread::sleep(Duration::from_millis(10)); + let mut count = 0; + while !control.is_cancelled_with_pause() { + match self.steps.recv_timeout(Duration::from_millis(10)) { + Ok(()) => { + if control.is_cancelled_with_pause() { + break; + } + count += 1; + control.set_status(count); + self.events.send(count).unwrap(); + } + Err(RecvTimeoutError::Timeout) => {} + Err(RecvTimeoutError::Disconnected) => break, + } } - - control.result().map(|_| ticks).map_err(|_| ticks) + control.result().map(|_| count).map_err(|_| count) } } #[test] - fn it_cancels() { - let task = Tick; - - let handle = BackgroundHandle::spawn(task); - - for _ in 0..10 { - thread::sleep(Duration::from_millis(10)); - let got = handle.poll(); - assert!(got.is_none()); - } - + fn cancellation_finishes_after_the_acknowledged_step() { + let (send, steps) = crossbeam_channel::unbounded(); + let (events, receive) = crossbeam_channel::unbounded(); + let handle = BackgroundHandle::spawn(Stepped { steps, events }); + send.send(()).unwrap(); + assert_eq!(1, receive.recv_timeout(Duration::from_secs(2)).unwrap()); handle.cancel(); - - let ret = handle.wait(); - assert!(ret.is_err()); - let ticks = ret.unwrap_err(); - assert!(9 <= ticks && ticks <= 12); + assert_eq!(Some(Err(1)), handle.wait_timeout(Duration::from_secs(2))); } #[test] - fn it_pauses() { - let task = Tick; - - let handle = BackgroundHandle::spawn(task); - + fn pause_stops_work_and_cancel_wakes_a_paused_task() { + let (send, steps) = crossbeam_channel::unbounded(); + let (events, receive) = crossbeam_channel::unbounded(); + let handle = BackgroundHandle::spawn(Stepped { steps, events }); handle.pause(); - - for _ in 0..10 { - thread::sleep(Duration::from_millis(10)); - let got = handle.poll(); - assert!(got.is_none()); - } - + send.send(()).unwrap(); + assert!(matches!( + receive.recv_timeout(Duration::from_millis(100)), + Err(RecvTimeoutError::Timeout) + )); handle.resume(); - - for _ in 0..10 { - thread::sleep(Duration::from_millis(10)); - let got = handle.poll(); - assert!(got.is_none()); - } - + assert_eq!(1, receive.recv_timeout(Duration::from_secs(2)).unwrap()); + handle.pause(); + send.send(()).unwrap(); + assert!(matches!( + receive.recv_timeout(Duration::from_millis(100)), + Err(RecvTimeoutError::Timeout) + )); handle.cancel(); - - let ret = handle.wait(); - assert!(ret.is_err()); - let ticks = ret.unwrap_err(); - assert!(9 <= ticks && ticks <= 12); + assert_eq!(Some(Err(1)), handle.wait_timeout(Duration::from_secs(2))); } } diff --git a/src/compact.rs b/src/compact.rs index a746665..859f217 100644 --- a/src/compact.rs +++ b/src/compact.rs @@ -1,26 +1,49 @@ #![allow(non_camel_case_types, non_snake_case, dead_code)] use std::convert::TryFrom; -use std::ffi::{CString, OsStr}; +use std::ffi::{CString, OsStr, OsString}; use std::io; -use std::os::windows::ffi::OsStrExt; +use std::os::windows::ffi::{OsStrExt, OsStringExt}; use std::os::windows::fs::OpenOptionsExt; use std::os::windows::io::AsRawHandle; -use std::path::Path; +use std::path::{Path, PathBuf}; use std::str::FromStr; use serde_derive::{Deserialize, Serialize}; use winapi::shared::minwindef::{BOOL, DWORD, PBOOL, PULONG, ULONG}; use winapi::shared::ntdef::PVOID; -use winapi::shared::winerror::{HRESULT_CODE, SUCCEEDED}; +use winapi::shared::winerror::{HRESULT_CODE, SUCCEEDED, WAIT_TIMEOUT}; +use winapi::um::fileapi::{ + GetFileInformationByHandle, GetFinalPathNameByHandleW, BY_HANDLE_FILE_INFORMATION, + FILE_COMPRESSION_INFO, +}; +use winapi::um::handleapi::CloseHandle; use winapi::um::ioapiset::DeviceIoControl; -use winapi::um::winioctl::{FSCTL_DELETE_EXTERNAL_BACKING, FSCTL_SET_EXTERNAL_BACKING}; +use winapi::um::minwinbase::{FileAttributeTagInfo, FileCompressionInfo}; +use winapi::um::synchapi::{CreateMutexW, ReleaseMutex, WaitForSingleObject}; +use winapi::um::winbase::{ + GetFileInformationByHandleEx, FILE_FLAG_OPEN_REPARSE_POINT, WAIT_ABANDONED, WAIT_FAILED, + WAIT_OBJECT_0, +}; +use winapi::um::winioctl::{ + FSCTL_DELETE_EXTERNAL_BACKING, FSCTL_GET_EXTERNAL_BACKING, FSCTL_SET_EXTERNAL_BACKING, +}; use winapi::um::winnt::{ - FILE_READ_DATA, FILE_SHARE_READ, FILE_WRITE_ATTRIBUTES, HANDLE, HRESULT, LPCWSTR, + FILE_ATTRIBUTE_REPARSE_POINT, FILE_READ_ATTRIBUTES, FILE_READ_DATA, FILE_SHARE_READ, + FILE_WRITE_ATTRIBUTES, HANDLE, HRESULT, LPCWSTR, }; use winapi::um::winver::{GetFileVersionInfoA, GetFileVersionInfoSizeA, VerQueryValueA}; +// winapi 0.3.9 names the first FILE_ATTRIBUTE_TAG_INFO member +// NextEntryOffset by mistake. Define the documented two-DWORD layout locally +// so its meaning stays explicit when validating reparse tags. +#[repr(C)] +struct AttributeTagInfo { + file_attributes: DWORD, + reparse_tag: DWORD, +} + #[repr(C)] #[derive(Copy, Clone)] struct _WOF_FILE_COMPRESSION_INFO_V1 { @@ -62,25 +85,20 @@ struct VS_FIXEDFILEINFO { } const VS_FIXEDFILEINFO_SIGNATURE: DWORD = 0xFEEF_04BD; - const FILE_PROVIDER_COMPRESSION_XPRESS4K: ULONG = 0; const FILE_PROVIDER_COMPRESSION_LZX: ULONG = 1; const FILE_PROVIDER_COMPRESSION_XPRESS8K: ULONG = 2; const FILE_PROVIDER_COMPRESSION_XPRESS16K: ULONG = 3; - +const ERROR_OBJECT_NOT_EXTERNALLY_BACKED: i32 = 342; const ERROR_COMPRESSION_NOT_BENEFICIAL: i32 = 344; - +const IO_REPARSE_TAG_WOF: DWORD = 0x8000_0017; const FILE_PROVIDER_CURRENT_VERSION: ULONG = 1; const WOF_CURRENT_VERSION: ULONG = 1; const WOF_PROVIDER_FILE: ULONG = 2; impl Default for _FILE_PROVIDER_EXTERNAL_INFO_V1 { fn default() -> Self { - Self { - Version: FILE_PROVIDER_CURRENT_VERSION, - Algorithm: Compression::default().into(), - Flags: 0, - } + Self::from(Compression::default()) } } @@ -119,12 +137,12 @@ impl Default for Compression { impl std::fmt::Display for Compression { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - match self { - Compression::Xpress4k => write!(f, "XPRESS4k"), - Compression::Xpress8k => write!(f, "XPRESS8K"), - Compression::Xpress16k => write!(f, "XPRESS16K"), - Compression::Lzx => write!(f, "LZX"), - } + f.write_str(match self { + Compression::Xpress4k => "XPRESS4K", + Compression::Xpress8k => "XPRESS8K", + Compression::Xpress16k => "XPRESS16K", + Compression::Lzx => "LZX", + }) } } @@ -132,7 +150,7 @@ impl FromStr for Compression { type Err = (); fn from_str(s: &str) -> Result { - match s { + match s.trim().to_ascii_uppercase().as_str() { "XPRESS4K" => Ok(Compression::Xpress4k), "XPRESS8K" => Ok(Compression::Xpress8k), "XPRESS16K" => Ok(Compression::Xpress16k), @@ -167,61 +185,138 @@ impl From for ULONG { } } +/// Unknown providers, versions and reparse tags must never be treated as plain +/// data: WIM-backed files, links and future WOF formats are outside our scope. +#[derive(Debug, Copy, Clone, PartialEq, Eq)] +pub enum BackingState { + None, + Wof(Compression), + Unsupported, +} + +#[derive(Debug, Copy, Clone, PartialEq, Eq)] +pub struct FileIdentity { + pub volume_serial: DWORD, + pub file_index: u64, + pub links: DWORD, +} + +/// Cooperative exclusion for Compactor instances across Windows sessions. +/// File sharing alone does not exclude handles that request WRITE_ATTRIBUTES, +/// which is sufficient for another WOF operation. The raw HANDLE also makes +/// this guard non-Send: mutex ownership must be released on the acquiring thread. +#[derive(Debug)] +pub struct WofIdentityLock(HANDLE); + +impl Drop for WofIdentityLock { + fn drop(&mut self) { + unsafe { + let _ = ReleaseMutex(self.0); + let _ = CloseHandle(self.0); + } + } +} + +pub fn lock_wof_identity(identity: &FileIdentity) -> io::Result { + // Global named mutexes do not require SeCreateGlobalPrivilege; that check + // applies to creating global file-mapping and symbolic-link objects. + let name = format!( + r"Global\Compactor.WOF.{:08x}.{:016x}", + identity.volume_serial, identity.file_index + ); + let name: Vec = name.encode_utf16().chain(std::iter::once(0)).collect(); + let mutex = unsafe { CreateMutexW(std::ptr::null_mut(), 0, name.as_ptr()) }; + if mutex.is_null() { + return Err(io::Error::last_os_error()); + } + match unsafe { WaitForSingleObject(mutex, 0) } { + WAIT_OBJECT_0 | WAIT_ABANDONED => { + // Abandonment transfers ownership. The caller always re-queries + // current backing and metadata after acquiring this guard. + Ok(WofIdentityLock(mutex)) + } + status => { + let error = if status == WAIT_TIMEOUT { + io::Error::new( + io::ErrorKind::WouldBlock, + "Another Compactor operation is already working on this file", + ) + } else if status == WAIT_FAILED { + io::Error::last_os_error() + } else { + io::Error::new( + io::ErrorKind::Other, + "Unexpected result while acquiring the file operation mutex", + ) + }; + unsafe { + let _ = CloseHandle(mutex); + } + Err(error) + } + } +} + +pub fn file_identity_handle(file: &std::fs::File) -> io::Result { + let mut info: BY_HANDLE_FILE_INFORMATION = unsafe { std::mem::zeroed() }; + let ret = unsafe { GetFileInformationByHandle(file.as_raw_handle() as HANDLE, &mut info) }; + if ret == 0 { + return Err(io::Error::last_os_error()); + } + Ok(FileIdentity { + volume_serial: info.dwVolumeSerialNumber, + file_index: ((info.nFileIndexHigh as u64) << 32) | info.nFileIndexLow as u64, + links: info.nNumberOfLinks, + }) +} + pub fn system_supports_compression() -> io::Result { let dll = CString::new("WofUtil.dll").unwrap(); let path = CString::new("\\").unwrap(); let mut handle = 0; - let len = unsafe { GetFileVersionInfoSizeA(dll.as_ptr(), &mut handle) }; - if len == 0 { return Err(io::Error::last_os_error()); } - let mut buf = vec![0u8; len as usize]; - - let ret = unsafe { - GetFileVersionInfoA( - dll.as_ptr(), - handle, - len, - buf.as_mut_ptr() as *mut _ as PVOID, - ) - }; - + let ret = unsafe { GetFileVersionInfoA(dll.as_ptr(), handle, len, buf.as_mut_ptr() as PVOID) }; if ret == 0 { return Err(io::Error::last_os_error()); } - let mut pinfo: PVOID = std::ptr::null_mut(); let mut pinfo_size = 0; - let ret = unsafe { VerQueryValueA( - buf.as_mut_ptr() as *mut _ as PVOID, + buf.as_mut_ptr() as PVOID, path.as_ptr(), &mut pinfo, &mut pinfo_size, ) }; - if ret == 0 { return Err(io::Error::last_os_error()); } - - assert!(pinfo_size as usize >= std::mem::size_of::()); - assert!(!pinfo.is_null()); - - let pinfo: &VS_FIXEDFILEINFO = unsafe { &*(pinfo as *const VS_FIXEDFILEINFO) }; - assert!(pinfo.dwSignature == VS_FIXEDFILEINFO_SIGNATURE); - + if pinfo.is_null() || (pinfo_size as usize) < std::mem::size_of::() { + return Err(io::Error::new( + io::ErrorKind::InvalidData, + "Invalid WofUtil version information", + )); + } + // VerQueryValue returns storage inside a byte buffer; that buffer does not + // promise the alignment required for a Rust reference to VS_FIXEDFILEINFO. + let pinfo = unsafe { std::ptr::read_unaligned(pinfo as *const VS_FIXEDFILEINFO) }; + if pinfo.dwSignature != VS_FIXEDFILEINFO_SIGNATURE { + return Err(io::Error::new( + io::ErrorKind::InvalidData, + "Invalid WofUtil version signature", + )); + } Ok((pinfo.dwFileVersionMS >> 16) & 0xffff >= 10) } pub fn file_supports_compression>(path: P) -> io::Result { let file = std::fs::File::open(path)?; let mut version: ULONG = 0; - let ret = unsafe { WofGetDriverVersion( file.as_raw_handle() as HANDLE, @@ -229,23 +324,114 @@ pub fn file_supports_compression>(path: P) -> io::Result { &mut version, ) }; - - if SUCCEEDED(ret) && version > 0 { - Ok(true) - } else { + if SUCCEEDED(ret) { + Ok(version > 0) + } else if HRESULT_CODE(ret) == 1 { + // WofGetDriverVersion documents ERROR_INVALID_FUNCTION when no WOF + // driver is attached for this volume/provider. Ok(false) + } else { + Err(io::Error::from_raw_os_error(HRESULT_CODE(ret))) + } +} + +fn decode_external_backing(data: &[u8]) -> io::Result { + if data.len() < 8 { + return Err(io::Error::new( + io::ErrorKind::InvalidData, + "Truncated WOF backing information", + )); + } + let field = |offset| { + ULONG::from_le_bytes([ + data[offset], + data[offset + 1], + data[offset + 2], + data[offset + 3], + ]) + }; + if field(0) != WOF_CURRENT_VERSION || field(4) != WOF_PROVIDER_FILE { + return Ok(BackingState::Unsupported); + } + if data.len() < 20 { + return Err(io::Error::new( + io::ErrorKind::InvalidData, + "Truncated WOF file-provider information", + )); + } + if field(8) != FILE_PROVIDER_CURRENT_VERSION || field(16) != 0 { + return Ok(BackingState::Unsupported); + } + Ok(match Compression::try_from(field(12)) { + Ok(compression) => BackingState::Wof(compression), + Err(_) => BackingState::Unsupported, + }) +} + +pub fn detect_backing_handle(file: &std::fs::File) -> io::Result { + let mut tag: AttributeTagInfo = unsafe { std::mem::zeroed() }; + let ret = unsafe { + GetFileInformationByHandleEx( + file.as_raw_handle() as HANDLE, + FileAttributeTagInfo, + &mut tag as *mut _ as PVOID, + std::mem::size_of::() as DWORD, + ) + }; + if ret == 0 { + return Err(io::Error::last_os_error()); + } + if tag.file_attributes & FILE_ATTRIBUTE_REPARSE_POINT != 0 + && tag.reparse_tag != IO_REPARSE_TAG_WOF + { + return Ok(BackingState::Unsupported); + } + + // Large enough for the documented WIM and file-provider structures. Parse + // byte fields explicitly instead of assuming the output is aligned. + let mut data = [0u8; 4096]; + let mut returned: DWORD = 0; + let ret = unsafe { + DeviceIoControl( + file.as_raw_handle() as HANDLE, + FSCTL_GET_EXTERNAL_BACKING, + std::ptr::null_mut(), + 0, + data.as_mut_ptr() as PVOID, + data.len() as DWORD, + &mut returned, + std::ptr::null_mut(), + ) + }; + if ret == 0 { + let err = io::Error::last_os_error(); + if err.raw_os_error() == Some(ERROR_OBJECT_NOT_EXTERNALLY_BACKED) { + // An unexplained WOF reparse point is not a safe plain-file target. + return Ok(if tag.file_attributes & FILE_ATTRIBUTE_REPARSE_POINT == 0 { + BackingState::None + } else { + BackingState::Unsupported + }); + } + return Err(err); } + if returned as usize > data.len() { + return Err(io::Error::new( + io::ErrorKind::InvalidData, + "Invalid WOF response length", + )); + } + decode_external_backing(&data[..returned as usize]) } pub fn detect_compression>(path: P) -> io::Result> { let mut p: Vec = path.as_ref().encode_wide().collect(); p.push(0); - let mut is_external: BOOL = 0; let mut provider: ULONG = 0; let mut file_info: _WOF_FILE_COMPRESSION_INFO_V1 = unsafe { std::mem::zeroed() }; - let mut len: ULONG = std::mem::size_of::<_WOF_FILE_COMPRESSION_INFO_V1>() as ULONG; - + let expected = std::mem::size_of::<_WOF_FILE_COMPRESSION_INFO_V1>() as ULONG; + let mut len = expected; let ret = unsafe { WofIsExternalFile( p.as_ptr(), @@ -255,15 +441,123 @@ pub fn detect_compression>(path: P) -> io::Result 0 && provider == WOF_PROVIDER_FILE { - Ok(Compression::try_from(file_info.Algorithm).ok()) - } else { - Ok(None) +pub fn final_path_handle(file: &std::fs::File) -> io::Result { + let mut buffer = vec![0u16; 512]; + loop { + // Flags 0 request a normalized DOS-volume path, normally with a \\?\ + // prefix. Keep that prefix to support long names when reopening. + let len = unsafe { + GetFinalPathNameByHandleW( + file.as_raw_handle() as HANDLE, + buffer.as_mut_ptr(), + buffer.len() as DWORD, + 0, + ) + }; + if len == 0 { + return Err(io::Error::last_os_error()); + } + if (len as usize) < buffer.len() { + return Ok(PathBuf::from(OsString::from_wide(&buffer[..len as usize]))); + } + if len > 32_768 { + return Err(io::Error::new( + io::ErrorKind::InvalidData, + "Invalid final path length", + )); + } + buffer.resize(len as usize + 1, 0); + } +} + +/// Reopen the normal WOF view only after its backing was identified. The caller +/// keeps the original share-denying handle open; file identity is checked even +/// if an ancestor was renamed between resolving and opening the final path. +pub fn reopen_wof_handle(file: &std::fs::File) -> io::Result { + if !matches!(detect_backing_handle(file)?, BackingState::Wof(_)) { + return Err(io::Error::new( + io::ErrorKind::InvalidInput, + "The file is not a supported WOF file", + )); + } + let before = file_identity_handle(file)?; + let reopened = std::fs::OpenOptions::new() + .access_mode(FILE_READ_DATA | FILE_READ_ATTRIBUTES | FILE_WRITE_ATTRIBUTES) + .share_mode(FILE_SHARE_READ) + .open(final_path_handle(file)?)?; + let after = file_identity_handle(&reopened)?; + if before.volume_serial != after.volume_serial || before.file_index != after.file_index { + return Err(io::Error::new( + io::ErrorKind::Other, + "The file identity changed while reopening the WOF view", + )); + } + Ok(reopened) +} + +fn query_allocated_size(file: &std::fs::File) -> io::Result { + let mut info: FILE_COMPRESSION_INFO = unsafe { std::mem::zeroed() }; + let ret = unsafe { + GetFileInformationByHandleEx( + file.as_raw_handle() as HANDLE, + FileCompressionInfo, + &mut info as *mut _ as PVOID, + std::mem::size_of::() as DWORD, + ) + }; + if ret == 0 { + return Err(io::Error::last_os_error()); + } + let size = unsafe { *info.CompressedFileSize.QuadPart() }; + if size < 0 { + return Err(io::Error::new( + io::ErrorKind::InvalidData, + "Windows returned a negative allocated file size", + )); + } + Ok(size as u64) +} + +/// Query FileCompressionInfo on the normal file-system view. AllocationSize on +/// the underlying sparse stream is not a substitute for WOF storage usage, and +/// its hidden backing stream must not be added a second time. +pub fn allocated_size_handle(file: &std::fs::File) -> io::Result { + if matches!(detect_backing_handle(file)?, BackingState::Wof(_)) { + let view = reopen_wof_handle(file)?; + let size = query_allocated_size(&view)?; + if size == 0 && view.metadata()?.len() > 0 { + return Err(io::Error::new( + io::ErrorKind::InvalidData, + "Windows did not expose a measurable WOF allocation", + )); } + Ok(size) } else { - Err(io::Error::from_raw_os_error(HRESULT_CODE(ret))) + query_allocated_size(file) } } @@ -271,10 +565,11 @@ unsafe fn as_byte_slice(p: &T) -> &[u8] { std::slice::from_raw_parts((p as *const T) as *const u8, std::mem::size_of::()) } -fn open_for_wof>(path: P) -> io::Result { +pub fn open_for_wof>(path: P) -> io::Result { std::fs::OpenOptions::new() - .access_mode(FILE_READ_DATA | FILE_WRITE_ATTRIBUTES) + .access_mode(FILE_READ_DATA | FILE_READ_ATTRIBUTES | FILE_WRITE_ATTRIBUTES) .share_mode(FILE_SHARE_READ) + .custom_flags(FILE_FLAG_OPEN_REPARSE_POINT) .open(path) } @@ -284,9 +579,13 @@ pub fn compress_file>(path: P, compression: Compression) -> io::R } pub fn compress_file_handle(file: &std::fs::File, compression: Compression) -> io::Result { + if detect_backing_handle(file)? != BackingState::None { + // Converting an existing WOF/WIM representation is intentionally not an + // implicit side effect of a compression request. + return Ok(false); + } const LEN: usize = std::mem::size_of::<_WOF_EXTERNAL_INFO>() + std::mem::size_of::<_FILE_PROVIDER_EXTERNAL_INFO_V1>(); - let mut data = [0u8; LEN]; let (wof, inf) = data.split_at_mut(std::mem::size_of::<_WOF_EXTERNAL_INFO>()); unsafe { @@ -295,14 +594,12 @@ pub fn compress_file_handle(file: &std::fs::File, compression: Compression) -> i compression, ))); } - let mut bytes_returned: DWORD = 0; - let ret = unsafe { DeviceIoControl( file.as_raw_handle() as HANDLE, FSCTL_SET_EXTERNAL_BACKING, - &mut data as *mut _ as PVOID, + data.as_mut_ptr() as PVOID, data.len() as DWORD, std::ptr::null_mut(), 0, @@ -310,7 +607,6 @@ pub fn compress_file_handle(file: &std::fs::File, compression: Compression) -> i std::ptr::null_mut(), ) }; - // DeviceIoControl returns a Win32 BOOL, not an HRESULT. if ret != 0 { Ok(true) @@ -330,11 +626,21 @@ pub fn uncompress_file>(path: P) -> io::Result<()> { } pub fn uncompress_file_handle(file: &std::fs::File) -> io::Result<()> { + match detect_backing_handle(file)? { + BackingState::None => return Ok(()), + BackingState::Unsupported => { + return Err(io::Error::new( + io::ErrorKind::InvalidInput, + "Unsupported external backing will not be removed", + )); + } + BackingState::Wof(_) => {} + } + let view = reopen_wof_handle(file)?; let mut bytes_returned: DWORD = 0; - let ret = unsafe { DeviceIoControl( - file.as_raw_handle() as HANDLE, + view.as_raw_handle() as HANDLE, FSCTL_DELETE_EXTERNAL_BACKING, std::ptr::null_mut(), 0, @@ -344,7 +650,6 @@ pub fn uncompress_file_handle(file: &std::fs::File) -> io::Result<()> { std::ptr::null_mut(), ) }; - if ret != 0 { Ok(()) } else { @@ -352,14 +657,16 @@ pub fn uncompress_file_handle(file: &std::fs::File) -> io::Result<()> { } } -#[link(name = "WofUtil")] +// The Windows SDK uses WofUtil.lib; MinGW installs libwofutil.a. On a +// case-sensitive cross-build host the library spelling must match exactly. +#[cfg_attr(target_env = "msvc", link(name = "WofUtil"))] +#[cfg_attr(target_env = "gnu", link(name = "wofutil"))] extern "system" { pub fn WofGetDriverVersion( file_or_volume_handle: HANDLE, provider: ULONG, version: PULONG, ) -> HRESULT; - pub fn WofIsExternalFile( file_path: LPCWSTR, is_external_file: PBOOL, @@ -367,29 +674,141 @@ extern "system" { external_file_info: PVOID, length: PULONG, ) -> HRESULT; - - // This is a slightly simpler way of setting file backing. - pub fn WofSetFileDataLocation( - file_handle: HANDLE, - provider: ULONG, - external_file_info: PVOID, - length: ULONG, - ) -> HRESULT; } -#[test] -fn compact_works_i_guess() { - let path = std::path::PathBuf::from("Cargo.lock"); +#[cfg(test)] +mod tests { + use super::*; + use crate::background::{Background, ControlToken}; + use crate::config::Config; + use crate::folder::FolderScan; + use filesize::PathExt; + + fn backing_data( + version: u32, + provider: u32, + file_version: u32, + algorithm: u32, + flags: u32, + ) -> Vec { + [version, provider, file_version, algorithm, flags] + .iter() + .flat_map(|value| value.to_le_bytes()) + .collect() + } - let supported = system_supports_compression().expect("system_supports_compression"); + #[test] + fn algorithms_round_trip_ui_and_windows_values() { + for algorithm in [ + Compression::Xpress4k, + Compression::Xpress8k, + Compression::Xpress16k, + Compression::Lzx, + ] { + assert_eq!(Ok(algorithm), algorithm.to_string().parse()); + assert_eq!(Ok(algorithm), algorithm.to_string().to_lowercase().parse()); + assert_eq!(Ok(algorithm), Compression::try_from(ULONG::from(algorithm))); + } + assert!("LZMS".parse::().is_err()); + assert!(Compression::try_from(4).is_err()); + } - if supported && file_supports_compression(&path).expect("file_supports_compression") { - uncompress_file(&path).expect("uncompress_file"); - assert_eq!(None, detect_compression(&path).expect("detect_compression")); - compress_file(&path, Compression::default()).expect("compress_file"); + #[test] + fn backing_parser_rejects_truncated_and_unknown_structures() { + let valid = backing_data(1, 2, 1, 1, 0); assert_eq!( - Some(Compression::default()), - detect_compression(&path).expect("detect_compression") + BackingState::Wof(Compression::Lzx), + decode_external_backing(&valid).unwrap() ); + for len in 0..20 { + assert!(decode_external_backing(&valid[..len]).is_err()); + } + for unsupported in [ + backing_data(2, 2, 1, 1, 0), + backing_data(1, 1, 1, 1, 0), + backing_data(1, 2, 2, 1, 0), + backing_data(1, 2, 1, 99, 0), + backing_data(1, 2, 1, 1, 1), + ] { + assert_eq!( + BackingState::Unsupported, + decode_external_backing(&unsupported).unwrap() + ); + } + } + + #[test] + fn identity_lock_excludes_other_threads_and_releases_on_drop() { + let dir = tempdir::TempDir::new("compactor-file-mutex").unwrap(); + let path = dir.path().join("fixture.bin"); + std::fs::write(&path, b"mutex fixture").unwrap(); + let file = open_for_wof(&path).unwrap(); + let identity = file_identity_handle(&file).unwrap(); + let guard = lock_wof_identity(&identity).unwrap(); + // Named Windows mutexes are reentrant for the same thread. Compete + // from another thread so this exercises actual mutual exclusion. + let blocked = std::thread::spawn(move || lock_wof_identity(&identity).map(|_| ())) + .join() + .unwrap() + .unwrap_err(); + assert_eq!(io::ErrorKind::WouldBlock, blocked.kind()); + drop(guard); + std::thread::spawn(move || lock_wof_identity(&identity).map(|_| ())) + .join() + .unwrap() + .unwrap(); + } + + #[test] + #[ignore = "Requires Windows 10+ and a local NTFS temporary directory; run with --ignored"] + fn wof_round_trip_preserves_bytes_and_reports_real_storage_for_all_algorithms() { + assert!(system_supports_compression().expect("WOF version probe")); + let dir = tempdir::TempDir::new("compactor-wof-round-trip").unwrap(); + let data = + b"Compactor WOF integration fixture: verify every decompressed byte.\r\n".repeat(32768); + for algorithm in [ + Compression::Xpress4k, + Compression::Xpress8k, + Compression::Xpress16k, + Compression::Lzx, + ] { + let path = dir.path().join(format!("{}.bin", algorithm)); + std::fs::write(&path, &data).unwrap(); + assert!(file_supports_compression(&path).expect("NTFS WOF probe")); + let guard = open_for_wof(&path).unwrap(); + let before = allocated_size_handle(&guard).unwrap(); + assert_eq!(BackingState::None, detect_backing_handle(&guard).unwrap()); + assert!(compress_file_handle(&guard, algorithm).unwrap()); + assert_eq!( + BackingState::Wof(algorithm), + detect_backing_handle(&guard).unwrap() + ); + assert_eq!( + Some(algorithm), + detect_compression(path.as_os_str()).unwrap() + ); + let compressed = allocated_size_handle(&guard).unwrap(); + assert!(compressed > 0 && compressed < before); + assert_eq!(compressed, path.size_on_disk().unwrap()); + assert_eq!(data, std::fs::read(&path).unwrap()); + // Regression: native WOF sparse/reparse attributes must remain + // visible to the scanner as decompressible WOF files. + let scanned = FolderScan::new(dir.path(), &Config::default()) + .unwrap() + .run(&ControlToken::new()) + .unwrap(); + assert_eq!(1, scanned.compressed.count); + assert_eq!(Some(algorithm), scanned.compressed.files[0].compression); + // A second request must preserve the representation already in use. + assert!(!compress_file_handle(&guard, Compression::Lzx).unwrap()); + assert_eq!( + BackingState::Wof(algorithm), + detect_backing_handle(&guard).unwrap() + ); + uncompress_file_handle(&guard).unwrap(); + assert_eq!(BackingState::None, detect_backing_handle(&guard).unwrap()); + assert_eq!(data, std::fs::read(&path).unwrap()); + assert_eq!(before, allocated_size_handle(&guard).unwrap()); + } } } diff --git a/src/compression.rs b/src/compression.rs index 5f64e25..7828835 100644 --- a/src/compression.rs +++ b/src/compression.rs @@ -1,51 +1,83 @@ use std::io; -use std::os::windows::fs::{MetadataExt, OpenOptionsExt}; +use std::os::windows::fs::MetadataExt; use std::path::PathBuf; use compresstimator::Compresstimator; use crossbeam_channel::{Receiver, Sender}; use filetime::FileTime; -use fs2::FileExt; use winapi::um::processthreadsapi::{GetCurrentThread, SetThreadPriority}; use winapi::um::winbase::{ THREAD_PRIORITY_ABOVE_NORMAL, THREAD_PRIORITY_BELOW_NORMAL, THREAD_PRIORITY_HIGHEST, THREAD_PRIORITY_LOWEST, THREAD_PRIORITY_NORMAL, }; -use winapi::um::winnt::{FILE_READ_DATA, FILE_SHARE_READ, FILE_WRITE_ATTRIBUTES}; +use winapi::um::winnt::{ + FILE_ATTRIBUTE_COMPRESSED, FILE_ATTRIBUTE_ENCRYPTED, FILE_ATTRIBUTE_OFFLINE, + FILE_ATTRIBUTE_READONLY, FILE_ATTRIBUTE_REPARSE_POINT, FILE_ATTRIBUTE_SPARSE_FILE, + FILE_ATTRIBUTE_SYSTEM, FILE_ATTRIBUTE_TEMPORARY, +}; -use crate::background::Background; -use crate::background::ControlToken; -use crate::compact::{self, Compression}; -use crate::config::CompressionPriority; +use crate::background::{Background, ControlToken}; +use crate::compact::{self, BackingState, Compression}; +use crate::config::{AnalysisMode, CompressionPriority}; use crate::persistence::config; +use crate::policy::{round_up_to_cluster, sample_is_candidate, savings_worthwhile}; #[derive(Debug, Clone)] pub struct CompressionJob { pub path: PathBuf, + pub root: PathBuf, + pub expected_path: PathBuf, pub content_len: u64, pub modified_time: u64, pub estimate_valid: bool, pub estimated_ratio: f32, } +#[derive(Debug, Copy, Clone, PartialEq, Eq)] +pub enum FileDisposition { + Compressed, + Decompressed, + NotBeneficial, + Skipped, +} + +/// Measurements and the final fingerprint come from the protected file handle. +/// In particular, the caller must not attach a failed attempt to a replacement +/// file by rereading its path after this worker releases the handle. +#[derive(Debug, Clone)] +pub struct FileOutcome { + pub disposition: FileDisposition, + pub original_physical_size: u64, + pub physical_size: u64, + pub content_len: u64, + pub modified_time: u64, + pub compression: Option, +} + #[derive(Debug)] pub struct BackgroundCompactor { compression: Option, - ratio_limit: f32, + min_savings_percent: f32, + analysis_mode: AnalysisMode, + cluster_size: u64, files_in: Receiver, - files_out: Sender<(PathBuf, io::Result)>, + files_out: Sender<(PathBuf, io::Result)>, } impl BackgroundCompactor { pub fn new( compression: Option, - ratio_limit: f32, + min_savings_percent: f32, + analysis_mode: AnalysisMode, + cluster_size: u64, files_in: Receiver, - files_out: Sender<(PathBuf, io::Result)>, + files_out: Sender<(PathBuf, io::Result)>, ) -> Self { Self { compression, - ratio_limit, + min_savings_percent, + analysis_mode, + cluster_size: cluster_size.max(1), files_in, files_out, } @@ -67,6 +99,7 @@ fn reuse_estimate(job: &CompressionJob, content_len: u64, modified_time: u64) -> && job.content_len == content_len && job.modified_time == modified_time && job.estimated_ratio.is_finite() + && (0.0..=1.0).contains(&job.estimated_ratio) { Some(job.estimated_ratio) } else { @@ -74,54 +107,343 @@ fn reuse_estimate(job: &CompressionJob, content_len: u64, modified_time: u64) -> } } +fn unsafe_file(attributes: u32, is_file: bool, links: u32, backing: BackingState) -> bool { + let always_excluded = FILE_ATTRIBUTE_COMPRESSED + | FILE_ATTRIBUTE_ENCRYPTED + | FILE_ATTRIBUTE_OFFLINE + | FILE_ATTRIBUTE_READONLY + | FILE_ATTRIBUTE_SYSTEM + | FILE_ATTRIBUTE_TEMPORARY; + !is_file + || links != 1 + || attributes & always_excluded != 0 + || backing == BackingState::Unsupported + || (backing == BackingState::None + && attributes & (FILE_ATTRIBUTE_SPARSE_FILE | FILE_ATTRIBUTE_REPARSE_POINT) != 0) +} + +fn known_compression(backing: BackingState) -> Option { + match backing { + BackingState::Wof(algorithm) => Some(algorithm), + _ => None, + } +} + +/// A WOF expansion can need room for the entire uncompressed stream before the +/// compressed backing is released. This conservative check avoids starting an +/// expansion already known not to fit. It is a snapshot, not a reservation; +/// unrelated processes can still exhaust the volume while Windows works. +fn check_expansion_space( + file: &std::fs::File, + content_len: u64, + cluster_size: u64, +) -> io::Result<()> { + let path = compact::final_path_handle(file)?; + let parent = path.parent().ok_or_else(|| { + io::Error::new( + io::ErrorKind::InvalidInput, + "Unable to locate the file's volume", + ) + })?; + let available = fs2::available_space(parent)?; + let required = round_up_to_cluster(content_len, cluster_size); + if available < required { + return Err(io::Error::new( + io::ErrorKind::Other, + format!( + "Restoring the uncompressed file needs up to {} free bytes; Windows reports {}. The file remains WOF compressed", + required, available + ), + )); + } + Ok(()) +} + +fn restore_uncompressed( + file: &std::fs::File, + content_len: u64, + cluster_size: u64, +) -> io::Result { + match compact::detect_backing_handle(file)? { + BackingState::Wof(_) => { + check_expansion_space(file, content_len, cluster_size)?; + compact::uncompress_file_handle(file)?; + } + BackingState::None => {} + BackingState::Unsupported => { + return Err(io::Error::new( + io::ErrorKind::Other, + "Unexpected external backing; restoration was not attempted", + )); + } + } + if compact::detect_backing_handle(file)? != BackingState::None { + return Err(io::Error::new( + io::ErrorKind::Other, + "Windows did not remove WOF backing during restoration", + )); + } + if file.metadata()?.len() != content_len { + return Err(io::Error::new( + io::ErrorKind::InvalidData, + "The logical file length changed during restoration; inspect this file before retrying", + )); + } + compact::allocated_size_handle(file) +} + +fn failed_with_restoration( + file: &std::fs::File, + content_len: u64, + cluster_size: u64, + cause: io::Error, +) -> io::Error { + match restore_uncompressed(file, content_len, cluster_size) { + Ok(_) => io::Error::new(cause.kind(), format!("{}; the file was restored to uncompressed form", cause)), + Err(restore_error) => io::Error::new( + io::ErrorKind::Other, + format!( + "{}; restoring the uncompressed file also failed: {}. The file may still be WOF compressed; rescan before retrying", + cause, restore_error + ), + ), + } +} + +fn compact_and_measure( + file: &std::fs::File, + compression: Compression, + before: u64, + content_len: u64, + min_savings_percent: f32, + cluster_size: u64, +) -> io::Result<(FileDisposition, u64, Option)> { + let attempt = compact::compress_file_handle(file, compression); + // Inspect the state even when the API reports failure. Returning a bare + // error must not hide a representation that Windows already changed. + let backing = compact::detect_backing_handle(file).map_err(|error| { + io::Error::new( + error.kind(), + format!("Unable to verify file backing after compression: {}. Its state is uncertain; rescan before retrying", error), + ) + })?; + match backing { + BackingState::None => { + return match attempt { + Ok(false) => Ok(( + FileDisposition::NotBeneficial, + compact::allocated_size_handle(file)?, + None, + )), + Ok(true) => Err(io::Error::new( + io::ErrorKind::Other, + "Windows reported compression success but the file has no WOF backing", + )), + Err(error) => Err(error), + }; + } + BackingState::Unsupported => { + return Err(io::Error::new(io::ErrorKind::Other, "Unexpected external backing after compression; the file was left untouched for inspection")); + } + BackingState::Wof(actual) if actual != compression => { + let error = io::Error::new( + io::ErrorKind::Other, + "Windows applied a different compression algorithm than requested", + ); + return Err(failed_with_restoration( + file, + content_len, + cluster_size, + error, + )); + } + BackingState::Wof(_) => {} + } + if let Err(error) = attempt { + return Err(failed_with_restoration( + file, + content_len, + cluster_size, + error, + )); + } + let after = match compact::allocated_size_handle(file) { + Ok(size) => size, + Err(error) => { + return Err(failed_with_restoration( + file, + content_len, + cluster_size, + error, + )) + } + }; + let after_metadata = match file.metadata() { + Ok(metadata) => metadata, + Err(error) => { + return Err(failed_with_restoration( + file, + content_len, + cluster_size, + error, + )) + } + }; + if after_metadata.len() != content_len { + let error = io::Error::new( + io::ErrorKind::InvalidData, + "The logical file length changed during compression", + ); + return Err(failed_with_restoration( + file, + content_len, + cluster_size, + error, + )); + } + if savings_worthwhile(before, after, min_savings_percent, cluster_size) { + Ok((FileDisposition::Compressed, after, Some(compression))) + } else { + match restore_uncompressed(file, content_len, cluster_size) { + Ok(restored) => Ok((FileDisposition::NotBeneficial, restored, None)), + Err(error) => Err(io::Error::new( + io::ErrorKind::Other, + format!( + "The measured saving ({} to {} bytes) did not meet the retention threshold, but restoration failed: {}. The file may still be WOF compressed; rescan before retrying", + before, after, error + ), + )), + } + } +} + fn handle_file( job: &CompressionJob, compression: Option, - ratio_limit: f32, -) -> io::Result { - let handle = std::fs::OpenOptions::new() - .access_mode(FILE_WRITE_ATTRIBUTES | FILE_READ_DATA) - // Allow readers, but deny concurrent writers/deleters while a WOF - // operation is in flight. This avoids racing game/app updates. - .share_mode(FILE_SHARE_READ) - .open(&job.path)?; - - handle.try_lock_exclusive()?; - - // Read the fingerprint from the opened, protected handle. Reading metadata - // by path before opening left a small race where an updater could replace - // or modify the file between the metadata check and the share-denying open. + min_savings_percent: f32, + analysis_mode: AnalysisMode, + cluster_size: u64, +) -> io::Result { + if !min_savings_percent.is_finite() || !(0.0..=100.0).contains(&min_savings_percent) { + return Err(io::Error::new( + io::ErrorKind::InvalidInput, + "Minimum savings must be between 0 and 100%", + )); + } + let cluster_size = cluster_size.max(1); + // OPEN_REPARSE_POINT prevents following a last-component link. Denying + // FILE_SHARE_WRITE and FILE_SHARE_DELETE excludes writers and replacements + // while we inspect and transform this identity. An additional Windows + // byte-range lock would also block our own second handle to the WOF view. + let handle = compact::open_for_wof(&job.path)?; + // A parent directory can become a junction after analysis. Validate the + // opened identity against the canonical root and exact path captured during + // that scan. A redirect within the same root can still lead to an excluded + // or DirectStorage-protected subtree, so containment alone is insufficient. + let final_path = compact::final_path_handle(&handle)?; + if !crate::directstorage::is_under(&final_path, &job.root) { + return Err(io::Error::new( + io::ErrorKind::PermissionDenied, + "The opened file is outside the folder that was analysed; no compression change was attempted", + )); + } + if !crate::directstorage::same_path(&final_path, &job.expected_path) { + return Err(io::Error::new( + io::ErrorKind::PermissionDenied, + "The opened file no longer matches the path that was analysed; no compression change was attempted", + )); + } + let identity = compact::file_identity_handle(&handle)?; + let _operation_lock = compact::lock_wof_identity(&identity)?; + // Link count is metadata too; refresh it after cooperative exclusion. + let identity = compact::file_identity_handle(&handle)?; let meta = handle.metadata()?; + let backing = compact::detect_backing_handle(&handle)?; + let before = compact::allocated_size_handle(&handle)?; + let ratio_limit = 1.0 - min_savings_percent / 100.0; - let ret = match compression { - Some(compression) => match reuse_estimate(job, meta.len(), meta.last_write_time()) { - Some(ratio) if ratio < ratio_limit => { - compact::compress_file_handle(&handle, compression) + let operation = (|| -> io::Result<(FileDisposition, u64, Option)> { + if unsafe_file( + meta.file_attributes(), + meta.is_file(), + identity.links, + backing, + ) { + return Ok((FileDisposition::Skipped, before, known_compression(backing))); + } + match compression { + Some(algorithm) => { + if backing != BackingState::None + || meta.len() <= cluster_size + || before <= cluster_size + { + return Ok((FileDisposition::Skipped, before, known_compression(backing))); + } + if analysis_mode == AnalysisMode::Sampled { + let ratio = match reuse_estimate(job, meta.len(), meta.last_write_time()) { + Some(ratio) => ratio, + None => Compresstimator::with_block_size(8192) + .compresstimate(&handle, meta.len())?, + }; + if !sample_is_candidate(ratio, ratio_limit) { + // A sample is not proof that the selected WOF algorithm + // cannot save space. Do not persist this as a failed WOF + // attempt, especially when the file changed after scan. + return Ok((FileDisposition::Skipped, before, None)); + } + } + compact_and_measure( + &handle, + algorithm, + before, + meta.len(), + min_savings_percent, + cluster_size, + ) } - Some(_) => Ok(false), None => { - let est = Compresstimator::with_block_size(8192); - match est.compresstimate(&handle, meta.len()) { - Ok(ratio) if ratio < ratio_limit => { - compact::compress_file_handle(&handle, compression) - } - Ok(_) => Ok(false), - Err(e) => Err(e), + if !matches!(backing, BackingState::Wof(_)) { + return Ok((FileDisposition::Skipped, before, None)); } + let restored = restore_uncompressed(&handle, meta.len(), cluster_size)?; + Ok((FileDisposition::Decompressed, restored, None)) } - }, - None => compact::uncompress_file_handle(&handle).map(|_| true), - }; + } + })(); - let _ = filetime::set_file_handle_times( + // Restore timestamps through the same protected identity, including failed + // attempts and rollbacks. A failure here is visible instead of silently + // claiming that metadata preservation succeeded. + let restored_times = filetime::set_file_handle_times( &handle, Some(FileTime::from_last_access_time(&meta)), Some(FileTime::from_last_modification_time(&meta)), ); - - handle.unlock()?; - - ret + let (disposition, physical_size, final_compression) = match (operation, restored_times) { + (Ok(value), Ok(())) => value, + (Err(error), Ok(())) => return Err(error), + (Ok(_), Err(error)) => { + return Err(io::Error::new(error.kind(), format!("The file operation finished, but restoring timestamps failed: {}. Rescan to inspect its current state", error))); + } + (Err(error), Err(time_error)) => { + return Err(io::Error::new( + error.kind(), + format!( + "{}; restoring timestamps also failed: {}", + error, time_error + ), + )); + } + }; + let final_meta = handle.metadata()?; + Ok(FileOutcome { + disposition, + original_physical_size: before, + physical_size, + content_len: final_meta.len(), + modified_time: final_meta.last_write_time(), + compression: final_compression, + }) } impl Background for BackgroundCompactor { @@ -129,21 +451,24 @@ impl Background for BackgroundCompactor { type Status = (); fn run(self, control: &ControlToken) -> Self::Output { - // Apply priority only to the compression/decompression worker. The GUI - // and analysis threads keep their normal scheduling priority. Failure - // to change the Windows thread priority is non-fatal. + // Only this worker changes priority; analysis and the GUI stay at their + // normal priority. Failure to change scheduling is non-fatal. let priority = config().read().unwrap().current().compression_priority; unsafe { let _ = SetThreadPriority(GetCurrentThread(), thread_priority_value(priority)); } - for job in &self.files_in { if control.is_cancelled_with_pause() { break; } - let path = job.path.clone(); - let ret = handle_file(&job, self.compression, self.ratio_limit); + let ret = handle_file( + &job, + self.compression, + self.min_savings_percent, + self.analysis_mode, + self.cluster_size, + ); if self.files_out.send((path, ret)).is_err() { break; } @@ -151,54 +476,250 @@ impl Background for BackgroundCompactor { } } -#[test] -fn estimate_reuse_requires_matching_fingerprint() { - let job = CompressionJob { - path: PathBuf::from("test.bin"), - content_len: 8192, - modified_time: 1234, - estimate_valid: true, - estimated_ratio: 0.5, - }; +#[cfg(test)] +mod tests { + use super::*; - assert_eq!(Some(0.5), reuse_estimate(&job, 8192, 1234)); - assert_eq!(None, reuse_estimate(&job, 4096, 1234)); - assert_eq!(None, reuse_estimate(&job, 8192, 5678)); -} + fn job_for(path: PathBuf, ratio: f32) -> CompressionJob { + let meta = std::fs::metadata(&path).unwrap(); + CompressionJob { + root: path.parent().unwrap().canonicalize().unwrap(), + expected_path: path.canonicalize().unwrap(), + path, + content_len: meta.len(), + modified_time: meta.last_write_time(), + estimate_valid: true, + estimated_ratio: ratio, + } + } -#[test] -fn invalid_estimate_is_not_reused() { - let job = CompressionJob { - path: PathBuf::from("test.bin"), - content_len: 8192, - modified_time: 1234, - estimate_valid: false, - estimated_ratio: 0.5, - }; + #[test] + fn estimate_reuse_requires_matching_fingerprint_and_valid_ratio() { + let mut job = CompressionJob { + path: PathBuf::from("test.bin"), + root: PathBuf::from(r"C:\Games"), + expected_path: PathBuf::from("test.bin"), + content_len: 8192, + modified_time: 1234, + estimate_valid: true, + estimated_ratio: 0.5, + }; + assert_eq!(Some(0.5), reuse_estimate(&job, 8192, 1234)); + assert_eq!(None, reuse_estimate(&job, 4096, 1234)); + assert_eq!(None, reuse_estimate(&job, 8192, 5678)); + job.estimate_valid = false; + assert_eq!(None, reuse_estimate(&job, 8192, 1234)); + job.estimate_valid = true; + for ratio in [f32::NAN, f32::INFINITY, -0.5, 1.01] { + job.estimated_ratio = ratio; + assert_eq!(None, reuse_estimate(&job, 8192, 1234)); + } + } - assert_eq!(None, reuse_estimate(&job, 8192, 1234)); -} + #[test] + fn native_wof_is_distinguished_from_other_special_files_and_hardlinks() { + let wof = BackingState::Wof(Compression::Lzx); + let sparse_reparse = FILE_ATTRIBUTE_SPARSE_FILE | FILE_ATTRIBUTE_REPARSE_POINT; + assert!(!unsafe_file(sparse_reparse, true, 1, wof)); + assert!(unsafe_file(sparse_reparse, true, 1, BackingState::None)); + assert!(unsafe_file( + sparse_reparse, + true, + 1, + BackingState::Unsupported + )); + assert!(unsafe_file(0, false, 1, BackingState::None)); + assert!(unsafe_file(0, true, 2, BackingState::None)); + assert!(unsafe_file(0, true, 0, BackingState::None)); + for attribute in [ + FILE_ATTRIBUTE_COMPRESSED, + FILE_ATTRIBUTE_ENCRYPTED, + FILE_ATTRIBUTE_OFFLINE, + FILE_ATTRIBUTE_READONLY, + FILE_ATTRIBUTE_SYSTEM, + FILE_ATTRIBUTE_TEMPORARY, + ] { + assert!(unsafe_file(attribute, true, 1, BackingState::None)); + assert!(unsafe_file(attribute | sparse_reparse, true, 1, wof)); + } + } -#[test] -fn compression_priority_maps_to_safe_windows_levels() { - assert_eq!( - THREAD_PRIORITY_LOWEST as i32, - thread_priority_value(CompressionPriority::Lowest) - ); - assert_eq!( - THREAD_PRIORITY_BELOW_NORMAL as i32, - thread_priority_value(CompressionPriority::BelowNormal) - ); - assert_eq!( - THREAD_PRIORITY_NORMAL as i32, - thread_priority_value(CompressionPriority::Normal) - ); - assert_eq!( - THREAD_PRIORITY_ABOVE_NORMAL as i32, - thread_priority_value(CompressionPriority::AboveNormal) - ); - assert_eq!( - THREAD_PRIORITY_HIGHEST as i32, - thread_priority_value(CompressionPriority::Highest) - ); + #[test] + fn compression_priority_maps_to_safe_windows_levels() { + for (priority, expected) in [ + (CompressionPriority::Lowest, THREAD_PRIORITY_LOWEST), + ( + CompressionPriority::BelowNormal, + THREAD_PRIORITY_BELOW_NORMAL, + ), + (CompressionPriority::Normal, THREAD_PRIORITY_NORMAL), + ( + CompressionPriority::AboveNormal, + THREAD_PRIORITY_ABOVE_NORMAL, + ), + (CompressionPriority::Highest, THREAD_PRIORITY_HIGHEST), + ] { + assert_eq!(expected as i32, thread_priority_value(priority)); + } + } + + #[test] + #[ignore = "Requires Windows 10+ and a local NTFS temporary directory; run with --ignored"] + fn thorough_mode_bypasses_the_sample_and_retention_uses_measured_savings() { + let dir = tempdir::TempDir::new("compactor-measured-retention").unwrap(); + let path = dir.path().join("fixture.bin"); + let data = + b"A repeatable WOF compression fixture with enough repeated content.\n".repeat(32768); + std::fs::write(&path, &data).unwrap(); + assert!(compact::file_supports_compression(&path).unwrap()); + let time = FileTime::from_unix_time(1_600_000_000, 123_400_000); + filetime::set_file_mtime(&path, time).unwrap(); + let job = job_for(path.clone(), 1.0); + let before = + compact::allocated_size_handle(&compact::open_for_wof(&path).unwrap()).unwrap(); + + let sampled = handle_file( + &job, + Some(Compression::Lzx), + 1.0, + AnalysisMode::Sampled, + 4096, + ) + .unwrap(); + assert_eq!(FileDisposition::Skipped, sampled.disposition); + assert_eq!(None, sampled.compression); + assert_eq!(before, sampled.physical_size); + + let thorough = handle_file( + &job, + Some(Compression::Lzx), + 1.0, + AnalysisMode::Thorough, + 4096, + ) + .unwrap(); + assert_eq!(FileDisposition::Compressed, thorough.disposition); + assert_eq!(Some(Compression::Lzx), thorough.compression); + assert!(savings_worthwhile( + before, + thorough.physical_size, + 1.0, + 4096 + )); + assert_eq!(job.modified_time, thorough.modified_time); + assert_eq!(data, std::fs::read(&path).unwrap()); + + let existing = handle_file( + &job_for(path.clone(), 0.1), + Some(Compression::Xpress4k), + 0.0, + AnalysisMode::Thorough, + 4096, + ) + .unwrap(); + assert_eq!(FileDisposition::Skipped, existing.disposition); + assert_eq!(Some(Compression::Lzx), existing.compression); + assert_eq!(thorough.physical_size, existing.physical_size); + + let restored = handle_file( + &job_for(path.clone(), 0.1), + None, + 1.0, + AnalysisMode::Thorough, + 4096, + ) + .unwrap(); + assert_eq!(FileDisposition::Decompressed, restored.disposition); + assert_eq!(before, restored.physical_size); + assert_eq!(data, std::fs::read(&path).unwrap()); + assert_eq!(job.modified_time, restored.modified_time); + + // No nonempty file can save 100%. Force the real compress/measure/ + // restore path and prove it returns to the original allocation. + let rejected = handle_file( + &job_for(path.clone(), 0.0), + Some(Compression::Lzx), + 100.0, + AnalysisMode::Thorough, + 4096, + ) + .unwrap(); + assert_eq!(FileDisposition::NotBeneficial, rejected.disposition); + assert_eq!(None, rejected.compression); + assert_eq!(before, rejected.physical_size); + assert_eq!(job.modified_time, rejected.modified_time); + assert_eq!(data, std::fs::read(&path).unwrap()); + } + + #[test] + #[ignore = "Requires Windows 10+ and a local NTFS temporary directory; run with --ignored"] + fn out_of_scope_files_active_writers_and_hardlinks_are_not_transformed() { + let dir = tempdir::TempDir::new("compactor-protected-files").unwrap(); + let path = dir.path().join("fixture.bin"); + let data = vec![b'x'; 65536]; + std::fs::write(&path, &data).unwrap(); + assert!(compact::file_supports_compression(&path).unwrap()); + let job = job_for(path.clone(), 0.0); + let other_root = tempdir::TempDir::new("compactor-unrelated-root").unwrap(); + let mut outside = job.clone(); + outside.root = other_root.path().canonicalize().unwrap(); + let scope_error = handle_file( + &outside, + Some(Compression::Lzx), + 1.0, + AnalysisMode::Thorough, + 4096, + ) + .unwrap_err(); + assert_eq!(io::ErrorKind::PermissionDenied, scope_error.kind()); + assert_eq!(None, compact::detect_compression(path.as_os_str()).unwrap()); + assert_eq!(data, std::fs::read(&path).unwrap()); + let other_path = dir.path().join("another-subtree-file.bin"); + std::fs::write(&other_path, b"preserve the other path").unwrap(); + let mut redirected_within_root = job.clone(); + redirected_within_root.expected_path = other_path.canonicalize().unwrap(); + let redirect_error = handle_file( + &redirected_within_root, + Some(Compression::Lzx), + 1.0, + AnalysisMode::Thorough, + 4096, + ) + .unwrap_err(); + assert_eq!(io::ErrorKind::PermissionDenied, redirect_error.kind()); + assert_eq!(None, compact::detect_compression(path.as_os_str()).unwrap()); + assert_eq!(data, std::fs::read(&path).unwrap()); + assert_eq!( + b"preserve the other path".to_vec(), + std::fs::read(&other_path).unwrap() + ); + let writer = std::fs::OpenOptions::new() + .read(true) + .write(true) + .open(&path) + .unwrap(); + assert!(handle_file( + &job, + Some(Compression::Lzx), + 1.0, + AnalysisMode::Thorough, + 4096 + ) + .is_err()); + drop(writer); + let alias = dir.path().join("alias.bin"); + std::fs::hard_link(&path, &alias).unwrap(); + let skipped = handle_file( + &job, + Some(Compression::Lzx), + 1.0, + AnalysisMode::Thorough, + 4096, + ) + .unwrap(); + assert_eq!(FileDisposition::Skipped, skipped.disposition); + assert_eq!(None, skipped.compression); + assert_eq!(data, std::fs::read(&path).unwrap()); + assert_eq!(data, std::fs::read(&alias).unwrap()); + } } diff --git a/src/config.rs b/src/config.rs index 883388c..5a71054 100644 --- a/src/config.rs +++ b/src/config.rs @@ -1,13 +1,45 @@ use std::fmt; use std::io; +use std::io::Write; use std::path::{Path, PathBuf}; use std::str::FromStr; +use std::sync::atomic::{AtomicUsize, Ordering}; use globset::{GlobBuilder, GlobSet, GlobSetBuilder}; use serde_derive::{Deserialize, Serialize}; use crate::compact::Compression; +/// Sampling is fast, while thorough analysis lets Windows measure every +/// eligible file. Neither mode changes the selected WOF compression format. +#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq, Eq, Hash)] +pub enum AnalysisMode { + #[default] + Sampled, + Thorough, +} + +impl fmt::Display for AnalysisMode { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(match self { + Self::Sampled => "Sampled", + Self::Thorough => "Thorough", + }) + } +} + +impl FromStr for AnalysisMode { + type Err = (); + + fn from_str(value: &str) -> Result { + match value.trim().to_ascii_lowercase().as_str() { + "sampled" => Ok(Self::Sampled), + "thorough" => Ok(Self::Thorough), + _ => Err(()), + } + } +} + fn default_min_savings_percent() -> f32 { 1.0 } @@ -74,12 +106,15 @@ impl FromStr for CompressionPriority { pub struct ConfigFile { backing: Option, config: Config, + load_error: Option, } #[derive(Debug, Clone, Serialize, Deserialize)] pub struct Config { pub decimal: bool, pub compression: Compression, + #[serde(default)] + pub analysis_mode: AnalysisMode, #[serde(default = "default_min_savings_percent")] pub min_savings_percent: f32, #[serde(default = "default_max_threads")] @@ -98,59 +133,159 @@ impl Default for Config { Self { decimal: false, compression: Compression::Lzx, + analysis_mode: AnalysisMode::default(), min_savings_percent: default_min_savings_percent(), max_threads: default_max_threads(), hdd_single_thread: default_hdd_single_thread(), protect_direct_storage: default_protect_direct_storage(), compression_priority: default_compression_priority(), - excludes: vec![ - "*:\\Windows*", - "*:\\System Volume Information*", - "*:\\$*", - ] - .into_iter() - .map(String::from) - .collect(), + excludes: vec!["*:\\Windows*", "*:\\System Volume Information*", "*:\\$*"] + .into_iter() + .map(String::from) + .collect(), } } } impl ConfigFile { pub fn new>(path: P) -> Self { + let path = path.as_ref().to_owned(); + let loaded = std::fs::read(&path).and_then(|data| { + let config = serde_json::from_slice::(&data) + .map_err(|err| io::Error::new(io::ErrorKind::InvalidData, err))?; + config + .validate() + .map_err(|err| io::Error::new(io::ErrorKind::InvalidData, err))?; + Ok(config) + }); + let (config, load_error) = match loaded { + Ok(config) => (config, None), + Err(err) if err.kind() == io::ErrorKind::NotFound => (Config::default(), None), + Err(err) => ( + Config::default(), + Some(format!("Unable to load {}: {}", path.display(), err)), + ), + }; + Self { - backing: Some(path.as_ref().to_owned()), - config: std::fs::read(path) - .and_then(|data| { - serde_json::from_slice::(&data) - .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e)) - }) - .unwrap_or_default(), + backing: Some(path), + config, + load_error, } } - pub fn save(&self) -> io::Result<()> { + fn write_config(&self, config: &Config) -> io::Result<()> { + config + .validate() + .map_err(|err| io::Error::new(io::ErrorKind::InvalidInput, err))?; match &self.backing { Some(path) => { - if let Some(dir) = path.parent() { - std::fs::create_dir_all(dir)?; - } - - let data = serde_json::to_string_pretty(&self.config).expect("Serialize"); - std::fs::write(path, &data) + let data = serde_json::to_vec_pretty(config) + .map_err(|err| io::Error::new(io::ErrorKind::InvalidData, err))?; + atomic_write(path, &data) } None => Ok(()), } } + /// Persist first, so a failed write cannot silently change active settings. + pub fn update(&mut self, config: Config) -> io::Result<()> { + self.write_config(&config)?; + self.config = config; + self.load_error = None; + Ok(()) + } + + pub fn load_error(&self) -> Option<&str> { + self.load_error.as_deref() + } + pub fn current(&self) -> Config { self.config.clone() } +} + +fn atomic_write(path: &Path, data: &[u8]) -> io::Result<()> { + static NEXT_TEMP: AtomicUsize = AtomicUsize::new(0); + + let parent = path + .parent() + .filter(|dir| !dir.as_os_str().is_empty()) + .unwrap_or_else(|| Path::new(".")); + std::fs::create_dir_all(parent)?; + let filename = path + .file_name() + .ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, "Invalid settings filename"))?; + + // A sibling temp file guarantees the final rename stays on one volume. + // create_new prevents accidental reuse of another process's pending write. + for _ in 0..100 { + let mut temporary_name = std::ffi::OsString::from("."); + temporary_name.push(filename); + temporary_name.push(format!( + ".{}-{}.tmp", + std::process::id(), + NEXT_TEMP.fetch_add(1, Ordering::Relaxed) + )); + let temporary = parent.join(temporary_name); + let mut file = match std::fs::OpenOptions::new() + .write(true) + .create_new(true) + .open(&temporary) + { + Ok(file) => file, + Err(err) if err.kind() == io::ErrorKind::AlreadyExists => continue, + Err(err) => return Err(err), + }; + + let result = (|| { + file.write_all(data)?; + file.sync_all()?; + drop(file); + replace_file(&temporary, path) + })(); + if result.is_err() { + let _ = std::fs::remove_file(&temporary); + } + return result; + } - pub fn replace(&mut self, c: Config) { - self.config = c; + Err(io::Error::new( + io::ErrorKind::AlreadyExists, + "Unable to create a temporary settings file", + )) +} + +#[cfg(windows)] +fn replace_file(source: &Path, destination: &Path) -> io::Result<()> { + use std::os::windows::ffi::OsStrExt; + use winapi::um::winbase::{MoveFileExW, MOVEFILE_REPLACE_EXISTING, MOVEFILE_WRITE_THROUGH}; + + let source: Vec = source.as_os_str().encode_wide().chain(Some(0)).collect(); + let destination: Vec = destination + .as_os_str() + .encode_wide() + .chain(Some(0)) + .collect(); + let succeeded = unsafe { + MoveFileExW( + source.as_ptr(), + destination.as_ptr(), + MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH, + ) + }; + if succeeded == 0 { + Err(io::Error::last_os_error()) + } else { + Ok(()) } } +#[cfg(not(windows))] +fn replace_file(source: &Path, destination: &Path) -> io::Result<()> { + std::fs::rename(source, destination) +} + impl Config { pub fn ratio_limit(&self) -> f32 { 1.0 - (self.min_savings_percent.clamp(0.0, 100.0) / 100.0) @@ -161,7 +296,7 @@ impl Config { || self.min_savings_percent < 0.0 || self.min_savings_percent > 100.0 { - return Err("Minimum estimated savings must be between 0 and 100%.".to_string()); + return Err("Minimum savings must be between 0 and 100%.".to_string()); } if self.max_threads > 16 { @@ -174,9 +309,15 @@ impl Config { pub fn globset(&self) -> Result { let mut globs = GlobSetBuilder::new(); - for pattern in self.excludes.iter().map(|s| s.trim()).filter(|s| !s.is_empty()) { + for pattern in self + .excludes + .iter() + .map(|s| s.trim()) + .filter(|s| !s.is_empty()) + { let glob = GlobBuilder::new(pattern) .case_insensitive(true) + .backslash_escape(false) .build() .map_err(|e| e.to_string())?; globs.add(glob); @@ -192,6 +333,7 @@ fn test_config() { assert!(s.globset().is_ok()); assert_eq!(s.compression, Compression::Lzx); + assert_eq!(s.analysis_mode, AnalysisMode::Sampled); assert_eq!(s.min_savings_percent, 1.0); assert_eq!(s.max_threads, 0); assert!(s.hdd_single_thread); @@ -247,3 +389,110 @@ fn invalid_thread_limit_is_rejected() { s.max_threads = 17; assert!(s.validate().is_err()); } + +#[test] +fn legacy_settings_keep_sampled_analysis() { + let legacy = r#"{"decimal":false,"compression":"Xpress8k","excludes":[]}"#; + let settings: Config = serde_json::from_str(legacy).unwrap(); + assert_eq!(settings.analysis_mode, AnalysisMode::Sampled); + assert_eq!(settings.compression, Compression::Xpress8k); + assert!(settings.validate().is_ok()); +} + +#[test] +fn analysis_modes_round_trip_without_changing_the_algorithm() { + let mut settings = Config::default(); + settings.analysis_mode = "Thorough".parse().unwrap(); + let json = serde_json::to_string(&settings).unwrap(); + let restored: Config = serde_json::from_str(&json).unwrap(); + assert_eq!(restored.analysis_mode, AnalysisMode::Thorough); + assert_eq!(restored.analysis_mode.to_string(), "Thorough"); + assert_eq!(restored.compression, Compression::Lzx); + assert!("Automatic".parse::().is_err()); +} + +#[test] +fn invalid_settings_on_disk_are_reported_and_left_unchanged() { + let directory = tempdir::TempDir::new("compactor-config-invalid").unwrap(); + let path = directory.path().join("config.json"); + let invalid = r#"{"decimal":false,"compression":"Lzx","max_threads":17,"excludes":[]}"#; + std::fs::write(&path, invalid).unwrap(); + + let settings = ConfigFile::new(&path); + assert!(settings.load_error().is_some()); + assert_eq!(settings.current().max_threads, 0); + assert_eq!(std::fs::read_to_string(&path).unwrap(), invalid); +} + +#[test] +fn malformed_exclusion_on_disk_does_not_reach_the_scanner() { + let directory = tempdir::TempDir::new("compactor-config-glob").unwrap(); + let path = directory.path().join("config.json"); + let invalid = r#"{"decimal":false,"compression":"Lzx","excludes":["["]}"#; + std::fs::write(&path, invalid).unwrap(); + + let settings = ConfigFile::new(&path); + assert!(settings.load_error().is_some()); + assert!(settings.current().globset().is_ok()); + assert_eq!(std::fs::read_to_string(&path).unwrap(), invalid); +} + +#[test] +fn settings_update_persists_before_changing_memory() { + let directory = tempdir::TempDir::new("compactor-config-update").unwrap(); + let path = directory.path().join("config.json"); + let mut file = ConfigFile::new(&path); + assert!(file.load_error().is_none()); + file.update(Config::default()).unwrap(); + + let mut updated = file.current(); + updated.analysis_mode = AnalysisMode::Thorough; + updated.min_savings_percent = 7.5; + file.update(updated).unwrap(); + + let restored = ConfigFile::new(&path); + assert!(restored.load_error().is_none()); + assert_eq!(restored.current().analysis_mode, AnalysisMode::Thorough); + assert_eq!(restored.current().min_savings_percent, 7.5); + assert_eq!(std::fs::read_dir(directory.path()).unwrap().count(), 1); +} + +#[test] +fn failed_settings_update_preserves_the_previous_file_and_memory() { + let directory = tempdir::TempDir::new("compactor-config-failed").unwrap(); + let path = directory.path().join("config.json"); + let mut file = ConfigFile::new(&path); + file.update(Config::default()).unwrap(); + let original = std::fs::read(&path).unwrap(); + + let mut invalid = file.current(); + invalid.min_savings_percent = f32::NAN; + assert!(file.update(invalid).is_err()); + assert_eq!(file.current().min_savings_percent, 1.0); + assert_eq!(std::fs::read(&path).unwrap(), original); + + // Force a rename failure without relying on permissions (tests may run as + // administrator/root). A destination directory must remain untouched. + let blocked_path = directory.path().join("blocked.json"); + std::fs::create_dir(&blocked_path).unwrap(); + std::fs::write(blocked_path.join("sentinel"), b"keep").unwrap(); + let mut blocked = ConfigFile::new(&blocked_path); + let mut candidate = blocked.current(); + candidate.analysis_mode = AnalysisMode::Thorough; + assert!(blocked.update(candidate).is_err()); + assert_eq!(blocked.current().analysis_mode, AnalysisMode::Sampled); + assert_eq!( + std::fs::read(blocked_path.join("sentinel")).unwrap(), + b"keep" + ); + assert_eq!(std::fs::read_dir(directory.path()).unwrap().count(), 2); +} + +#[test] +fn windows_path_separators_do_not_escape_glob_characters() { + let mut settings = Config::default(); + settings.excludes = vec![r"C:\Games\*\cache\*".to_string()]; + let exclusions = settings.globset().unwrap(); + assert!(exclusions.is_match(r"C:\Games\Example\cache\data.bin")); + assert!(!exclusions.is_match(r"C:\Games\Example\content\data.bin")); +} diff --git a/src/directstorage.rs b/src/directstorage.rs index 7908b01..ae3d1ae 100644 --- a/src/directstorage.rs +++ b/src/directstorage.rs @@ -1,4 +1,6 @@ +use crate::background::{Background, ControlToken}; use std::collections::HashSet; +use std::io; use std::path::{Path, PathBuf}; use walkdir::WalkDir; @@ -47,6 +49,7 @@ fn lower_name(path: &Path) -> String { fn normalized(path: &Path) -> String { let value = path .to_string_lossy() + .trim_start_matches(r"\\?\") .replace('/', "\\") .trim_end_matches('\\') .to_ascii_lowercase(); @@ -66,6 +69,10 @@ fn normalized(path: &Path) -> String { } } +pub fn same_path(left: &Path, right: &Path) -> bool { + normalized(left) == normalized(right) +} + pub fn is_under(path: &Path, root: &Path) -> bool { let path = normalized(path); let root = normalized(root); @@ -78,7 +85,9 @@ pub fn is_under(path: &Path, root: &Path) -> bool { pub fn is_direct_storage_runtime(path: &Path) -> bool { let name = lower_name(path); - DIRECT_STORAGE_DLLS.iter().any(|candidate| *candidate == name) + DIRECT_STORAGE_DLLS + .iter() + .any(|candidate| *candidate == name) } fn is_drive_root(path: &Path) -> bool { @@ -87,13 +96,15 @@ fn is_drive_root(path: &Path) -> bool { fn is_library_container(path: &Path) -> bool { let name = lower_name(path); - if LIBRARY_CONTAINERS.iter().any(|candidate| *candidate == name) { + if LIBRARY_CONTAINERS + .iter() + .any(|candidate| *candidate == name) + { return true; } let parent = path.parent().map(lower_name).unwrap_or_default(); - (name == "common" && parent == "steamapps") - || (name == "library" && parent == "amazon games") + (name == "common" && parent == "steamapps") || (name == "library" && parent == "amazon games") } fn too_wide_to_skip(path: &Path) -> bool { @@ -138,11 +149,7 @@ fn safe_root(candidate: PathBuf, dll_path: &Path, scan_root: &Path) -> PathBuf { candidate } -fn infer_game_root( - dll_path: &Path, - scan_root: &Path, - exe_dirs: &HashSet, -) -> PathBuf { +fn infer_game_root(dll_path: &Path, scan_root: &Path, exe_dirs: &HashSet) -> PathBuf { let dll_parent = dll_path.parent().unwrap_or(scan_root); if let Some(root) = unreal_project_root(dll_parent) { @@ -216,20 +223,45 @@ fn collapse_roots(mut roots: Vec) -> Vec { kept } -pub fn discover_direct_storage_roots(scan_root: &Path) -> Vec { +pub struct DirectStorageScan { + pub path: PathBuf, +} + +impl Background for DirectStorageScan { + type Output = io::Result>; + type Status = (); + + fn run(self, control: &ControlToken<()>) -> Self::Output { + discover_direct_storage_roots(&self.path, || control.is_cancelled_with_pause()) + } +} + +fn discover_direct_storage_roots( + scan_root: &Path, + mut cancelled: impl FnMut() -> bool, +) -> io::Result> { let mut dlls = Vec::new(); let mut exe_dirs = HashSet::new(); - for entry in WalkDir::new(scan_root) - .follow_links(false) - .into_iter() - .filter_map(Result::ok) - .filter(|entry| entry.file_type().is_file()) - { + for entry in WalkDir::new(scan_root).follow_links(false).into_iter() { + if cancelled() { + return Err(io::Error::new( + io::ErrorKind::Interrupted, + "DirectStorage check stopped", + )); + } + // An incomplete detection cannot establish that an unreadable subtree + // is safe. Report the failure before transforming any files. + let entry = entry.map_err(|error| io::Error::new(io::ErrorKind::Other, error))?; let path = entry.path(); + // A named runtime link is still evidence of DirectStorage. Record its + // name without following it into an unselected tree. if is_direct_storage_runtime(path) { dlls.push(path.to_path_buf()); } + if !entry.file_type().is_file() { + continue; + } if path .extension() @@ -242,18 +274,35 @@ pub fn discover_direct_storage_roots(scan_root: &Path) -> Vec { } } - collapse_roots( - dlls - .iter() + Ok(collapse_roots( + dlls.iter() .map(|dll| infer_game_root(dll, scan_root, &exe_dirs)) .collect(), - ) + )) } #[cfg(test)] mod tests { use super::*; + #[test] + fn detection_is_cancellable_and_does_not_use_compression_exclusions() { + let dir = tempdir::TempDir::new("compactor-directstorage").unwrap(); + let bin = dir.path().join("bin"); + std::fs::create_dir(&bin).unwrap(); + std::fs::write(bin.join("dstorage.dll"), []).unwrap(); + assert_eq!( + vec![dir.path().to_path_buf()], + discover_direct_storage_roots(dir.path(), || false).unwrap() + ); + assert_eq!( + io::ErrorKind::Interrupted, + discover_direct_storage_roots(dir.path(), || true) + .unwrap_err() + .kind() + ); + } + #[test] fn steam_unreal_runtime_maps_to_game_root() { let scan = Path::new(r"D:\SteamLibrary\steamapps\common"); @@ -286,6 +335,22 @@ mod tests { assert_eq!(normalized(&root), normalized(scan)); } + #[test] + fn scope_comparison_accepts_verbatim_prefix_but_respects_directory_boundaries() { + assert!(is_under( + Path::new(r"\\?\C:\Games\A\data.bin"), + Path::new(r"c:\games\a") + )); + assert!(!is_under( + Path::new(r"C:\Games\AB\data.bin"), + Path::new(r"C:\Games\A") + )); + assert!(!is_under( + Path::new(r"D:\Games\A\data.bin"), + Path::new(r"C:\Games\A") + )); + } + #[test] fn nested_roots_are_collapsed() { let roots = collapse_roots(vec![ diff --git a/src/folder.rs b/src/folder.rs index 745d32c..12e7cab 100644 --- a/src/folder.rs +++ b/src/folder.rs @@ -19,19 +19,21 @@ use winapi::um::fileapi::{GetDiskFreeSpaceW, GetVolumeInformationW}; use winapi::um::ioapiset::DeviceIoControl; use winapi::um::sysinfoapi::GetLogicalProcessorInformation; use winapi::um::winioctl::{ - IOCTL_STORAGE_QUERY_PROPERTY, PropertyStandardQuery, StorageDeviceSeekPenaltyProperty, + PropertyStandardQuery, StorageDeviceSeekPenaltyProperty, IOCTL_STORAGE_QUERY_PROPERTY, STORAGE_PROPERTY_QUERY, }; use winapi::um::winnt::{ - BOOLEAN, FILE_ATTRIBUTE_COMPRESSED, FILE_ATTRIBUTE_ENCRYPTED, FILE_ATTRIBUTE_OFFLINE, - FILE_ATTRIBUTE_READONLY, FILE_ATTRIBUTE_REPARSE_POINT, FILE_ATTRIBUTE_SPARSE_FILE, - FILE_ATTRIBUTE_SYSTEM, FILE_ATTRIBUTE_TEMPORARY, FILE_SHARE_DELETE, FILE_SHARE_READ, - FILE_SHARE_WRITE, HANDLE, RelationProcessorCore, SYSTEM_LOGICAL_PROCESSOR_INFORMATION, + RelationProcessorCore, BOOLEAN, FILE_ATTRIBUTE_COMPRESSED, FILE_ATTRIBUTE_ENCRYPTED, + FILE_ATTRIBUTE_OFFLINE, FILE_ATTRIBUTE_READONLY, FILE_ATTRIBUTE_REPARSE_POINT, + FILE_ATTRIBUTE_SPARSE_FILE, FILE_ATTRIBUTE_SYSTEM, FILE_ATTRIBUTE_TEMPORARY, FILE_SHARE_DELETE, + FILE_SHARE_READ, FILE_SHARE_WRITE, HANDLE, SYSTEM_LOGICAL_PROCESSOR_INFORMATION, }; use crate::background::{Background, ControlToken}; -use crate::compact::Compression; +use crate::compact::{self, Compression}; +use crate::config::{AnalysisMode, Config}; use crate::persistence::{incompressible_key, pathdb}; +use crate::policy::{estimated_allocation, sample_is_candidate}; const AUTO_MAX_ANALYSIS_THREADS: usize = 8; const AUTO_MAX_COMPRESSION_THREADS: usize = 16; @@ -53,6 +55,7 @@ pub struct FileInfo { pub logical_size: u64, pub physical_size: u64, pub estimated_physical_size: u64, + pub compression: Option, } #[derive(Debug, Clone, Serialize, Default)] @@ -67,12 +70,15 @@ pub struct GroupInfo { #[derive(Debug, Clone, Serialize)] pub struct FolderInfo { pub path: PathBuf, + pub canonical_root: PathBuf, pub logical_size: u64, pub physical_size: u64, pub compressible: GroupInfo, pub compressed: GroupInfo, pub skipped: GroupInfo, pub direct_storage: bool, + pub cluster_size: u64, + pub scan_errors: usize, } #[derive(Debug, Clone, Serialize, Default)] @@ -104,12 +110,15 @@ impl FolderInfo { pub fn new>(path: P) -> Self { Self { path: path.as_ref().to_owned(), + canonical_root: path.as_ref().to_owned(), logical_size: 0, physical_size: 0, compressible: GroupInfo::default(), compressed: GroupInfo::default(), skipped: GroupInfo::default(), direct_storage: false, + cluster_size: FALLBACK_CLUSTER_SIZE, + scan_errors: 0, } } @@ -205,30 +214,21 @@ impl GroupInfo { #[derive(Debug)] pub struct FolderScan { path: PathBuf, + canonical_root: PathBuf, excludes: GlobSet, - ratio_limit: f32, - compression: Compression, - max_threads: usize, - hdd_single_thread: bool, + config: Config, } impl FolderScan { - pub fn new>( - path: P, - excludes: GlobSet, - ratio_limit: f32, - compression: Compression, - max_threads: usize, - hdd_single_thread: bool, - ) -> Self { - Self { + pub fn new>(path: P, config: &Config) -> Result { + config.validate()?; + Ok(Self { path: path.as_ref().to_path_buf(), - excludes, - ratio_limit, - compression, - max_threads, - hdd_single_thread, - } + canonical_root: std::fs::canonicalize(path.as_ref()) + .map_err(|error| format!("Unable to resolve scan root: {}", error))?, + excludes: config.globset()?, + config: config.clone(), + }) } } @@ -266,6 +266,7 @@ fn volume_root_path(path: &Path) -> Option { fn normalized_path(path: &Path) -> String { path.to_string_lossy() + .trim_start_matches(r"\\?\") .replace('/', "\\") .trim_end_matches('\\') .to_ascii_lowercase() @@ -341,6 +342,21 @@ fn cluster_size_for_path(path: &Path) -> u64 { } pub fn validate_target_path(path: &Path) -> Result<(), String> { + // Refuse aliases through junctions/mount points, including ancestor aliases. + // A textual C:\Games path must not redirect to Windows or another volume. + if !path.is_absolute() { + return Err("Select an absolute local folder path.".to_string()); + } + for ancestor in path.ancestors() { + if let Ok(metadata) = std::fs::symlink_metadata(ancestor) { + if metadata.file_attributes() & FILE_ATTRIBUTE_REPARSE_POINT != 0 { + return Err("Select the actual folder instead of a junction, symbolic link or mounted-folder alias.".to_string()); + } + } + } + let canonical = std::fs::canonicalize(path) + .map_err(|error| format!("Unable to resolve the selected folder: {}", error))?; + let path = canonical.as_path(); if !path.exists() { return Err("The selected folder no longer exists.".to_string()); } @@ -403,40 +419,6 @@ pub fn validate_target_path(path: &Path) -> Result<(), String> { Ok(()) } -fn projection_factor(compression: Compression) -> f32 { - match compression { - Compression::Xpress4k => 1.05, - Compression::Xpress8k => 1.02, - Compression::Xpress16k => 1.00, - Compression::Lzx => 0.90, - } -} - -fn round_up_to_cluster(size: u64, cluster_size: u64) -> u64 { - let cluster_size = cluster_size.max(1); - if size == 0 { - 0 - } else { - size.saturating_add(cluster_size - 1) / cluster_size * cluster_size - } -} - -fn estimate_physical_size( - logical_size: u64, - ratio: f32, - compression: Compression, - cluster_size: u64, - current_physical_size: u64, -) -> u64 { - if !ratio.is_finite() { - return current_physical_size; - } - - let adjusted_ratio = (ratio.clamp(0.0, 1.0) * projection_factor(compression)).clamp(0.0, 1.0); - let estimated = ((logical_size as f64) * adjusted_ratio as f64).round() as u64; - round_up_to_cluster(estimated, cluster_size).min(current_physical_size) -} - fn volume_device_path(path: &Path) -> Option { match path.components().next()? { Component::Prefix(prefix) => match prefix.kind() { @@ -510,9 +492,8 @@ fn physical_core_count() -> Option { let mut entries: Vec = Vec::with_capacity(capacity); let mut buffer_bytes = (capacity * entry_size) as DWORD; - let ret = unsafe { - GetLogicalProcessorInformation(entries.as_mut_ptr(), &mut buffer_bytes) - }; + let ret = + unsafe { GetLogicalProcessorInformation(entries.as_mut_ptr(), &mut buffer_bytes) }; if ret != 0 { let len = (buffer_bytes as usize / entry_size).min(capacity); @@ -616,7 +597,7 @@ fn compresstimate_hdd( len: u64, buffer: &mut Vec, ) -> io::Result { - let chunk = HDD_SAMPLE_CHUNK.min(len as usize); + let chunk = len.min(HDD_SAMPLE_CHUNK as u64) as usize; if chunk == 0 { return Ok(1.0); @@ -671,23 +652,31 @@ fn apply_estimate( mut fi: FileInfo, result: io::Result, ratio_limit: f32, - compression: Compression, + analysis_mode: AnalysisMode, cluster_size: u64, ) { match result { - Ok(ratio) if ratio < ratio_limit => { - fi.estimated_physical_size = estimate_physical_size( - fi.logical_size, - ratio, - compression, - cluster_size, - fi.physical_size, - ); - fi.estimate_valid = true; - fi.estimated_ratio = ratio; + Ok(ratio) => { + fi.estimate_valid = ratio.is_finite() && (0.0..=1.0).contains(&ratio); + fi.estimated_ratio = if fi.estimate_valid { ratio } else { 1.0 }; + fi.estimated_physical_size = + estimated_allocation(fi.logical_size, ratio, cluster_size, fi.physical_size); + if analysis_mode == AnalysisMode::Thorough || sample_is_candidate(ratio, ratio_limit) { + ds.push(FileKind::Compressible, fi); + } else { + ds.push(FileKind::Skipped, fi); + } + } + Err(_) if analysis_mode == AnalysisMode::Thorough => { + // Analysis is read-only and sampled; a transient read error is not + // proof of incompressibility. The protected worker will retry once. + ds.scan_errors += 1; ds.push(FileKind::Compressible, fi); } - Ok(_) | Err(_) => ds.push(FileKind::Skipped, fi), + Err(_) => { + ds.scan_errors += 1; + ds.push(FileKind::Skipped, fi); + } } } @@ -697,7 +686,7 @@ fn estimate_candidates( workers: usize, hdd: bool, ratio_limit: f32, - compression: Compression, + analysis_mode: AnalysisMode, cluster_size: u64, control: &ControlToken<(PathBuf, FolderSummary)>, ds: &mut FolderInfo, @@ -763,14 +752,7 @@ fn estimate_candidates( Ok((fi, result)) => { in_flight -= 1; let status_path = fi.path.clone(); - apply_estimate( - ds, - fi, - result, - ratio_limit, - compression, - cluster_size, - ); + apply_estimate(ds, fi, result, ratio_limit, analysis_mode, cluster_size); if last_status.elapsed() >= Duration::from_millis(50) { *last_status = Instant::now(); @@ -802,14 +784,7 @@ fn estimate_candidates( if cancelled { for (fi, result) in result_rx.try_iter() { - apply_estimate( - ds, - fi, - result, - ratio_limit, - compression, - cluster_size, - ); + apply_estimate(ds, fi, result, ratio_limit, analysis_mode, cluster_size); } for candidate in candidates { @@ -839,13 +814,14 @@ impl Background for FolderScan { fn run(self, control: &ControlToken) -> Self::Output { let FolderScan { path, + canonical_root, excludes, - ratio_limit, - compression, - max_threads, - hdd_single_thread, + config, } = self; + let ratio_limit = config.ratio_limit(); + let analysis_mode = config.analysis_mode; let mut ds = FolderInfo::new(&path); + ds.canonical_root = canonical_root; let cpus = thread::available_parallelism() .map(|count| count.get()) .unwrap_or(1); @@ -853,12 +829,13 @@ impl Background for FolderScan { let analysis_workers = worker_count_for_storage( cpus, seek_penalty, - max_threads, - hdd_single_thread, + config.max_threads, + config.hdd_single_thread, AUTO_MAX_ANALYSIS_THREADS, ); let is_hdd = matches!(seek_penalty, Some(true)); let cluster_size = cluster_size_for_path(&path); + ds.cluster_size = cluster_size; let mut candidates: VecDeque = VecDeque::new(); let inline_estimator = if analysis_workers == 1 { Some(Compresstimator::with_block_size(ESTIMATOR_BLOCK_SIZE)) @@ -873,15 +850,52 @@ impl Background for FolderScan { let mut last_status = Instant::now(); let walker = WalkDir::new(&path) + .follow_links(false) .into_iter() - .filter_entry(|e| e.file_type().is_file() || !excludes.is_match(e.path())) - .filter_map(|e| e.map_err(|e| eprintln!("Error: {:?}", e)).ok()) - .filter(|e| e.file_type().is_file()) - .filter_map(|e| e.metadata().map(|md| (e, md)).ok()) - .filter_map(|(e, md)| e.path().size_on_disk().map(|s| (e, md, s)).ok()) - .enumerate(); - - for (count, (entry, metadata, physical)) in walker { + .filter_entry(|e| { + // Reparse directories can redirect an otherwise safe target to + // another volume or protected tree. Never descend into them. + if e.file_type().is_dir() { + return e + .metadata() + .map(|md| { + md.file_attributes() & FILE_ATTRIBUTE_REPARSE_POINT == 0 + && !excludes.is_match(e.path()) + }) + .unwrap_or(false); + } + true + }); + + for (count, result) in walker.enumerate() { + if control.is_cancelled_with_pause() { + for candidate in candidates { + ds.push(FileKind::Skipped, candidate.file); + } + return Err(ds); + } + let entry = match result { + Ok(entry) if entry.file_type().is_file() => entry, + Ok(_) => continue, + Err(_) => { + ds.scan_errors += 1; + continue; + } + }; + let metadata = match entry.metadata() { + Ok(metadata) => metadata, + Err(_) => { + ds.scan_errors += 1; + continue; + } + }; + let physical = match entry.path().size_on_disk() { + Ok(size) => size, + Err(_) => { + ds.scan_errors += 1; + continue; + } + }; let shortname = entry .path() .strip_prefix(&path) @@ -893,7 +907,7 @@ impl Background for FolderScan { } let logical_size = metadata.len(); - let fi = FileInfo { + let mut fi = FileInfo { path: shortname, content_len: metadata.len(), modified_time: metadata.last_write_time(), @@ -902,6 +916,7 @@ impl Background for FolderScan { logical_size, physical_size: physical, estimated_physical_size: physical, + compression: None, }; if count % 8 == 0 { @@ -919,21 +934,46 @@ impl Background for FolderScan { } let attributes = metadata.file_attributes(); - let special_attributes = FILE_ATTRIBUTE_COMPRESSED + let forbidden = FILE_ATTRIBUTE_COMPRESSED | FILE_ATTRIBUTE_ENCRYPTED - | FILE_ATTRIBUTE_SPARSE_FILE - | FILE_ATTRIBUTE_REPARSE_POINT - | FILE_ATTRIBUTE_OFFLINE; - - if attributes & special_attributes != 0 { + | FILE_ATTRIBUTE_OFFLINE + | FILE_ATTRIBUTE_SYSTEM + | FILE_ATTRIBUTE_TEMPORARY; + if attributes & forbidden != 0 { ds.push(FileKind::Skipped, fi); - } else if fi.physical_size < fi.logical_size { - ds.push(FileKind::Compressed, fi); - } else if fi.content_len <= cluster_size + continue; + } + // WOF itself uses sparse/reparse metadata. Detect the actual provider + // before excluding these flags; size_on_disk < len is not a format. + let backing = compact::detect_compression(entry.path()); + match backing { + Ok(Some(compression)) => { + fi.compression = Some(compression); + ds.push(FileKind::Compressed, fi); + continue; + } + Err(_) => { + ds.scan_errors += 1; + ds.push(FileKind::Skipped, fi); + continue; + } + Ok(None) => {} + } + if fi.content_len <= cluster_size || attributes - & (FILE_ATTRIBUTE_READONLY | FILE_ATTRIBUTE_SYSTEM | FILE_ATTRIBUTE_TEMPORARY) + & (FILE_ATTRIBUTE_READONLY + | FILE_ATTRIBUTE_SPARSE_FILE + | FILE_ATTRIBUTE_REPARSE_POINT) != 0 - || incompressible.contains(incompressible_key(entry.path(), &metadata)) + || incompressible.contains(incompressible_key( + entry.path(), + metadata.len(), + metadata.last_write_time(), + config.compression, + config.analysis_mode, + config.min_savings_percent, + cluster_size, + )) || excludes.is_match(entry.path()) { ds.push(FileKind::Skipped, fi); @@ -950,7 +990,7 @@ impl Background for FolderScan { fi, result, ratio_limit, - compression, + analysis_mode, cluster_size, ); } else { @@ -967,7 +1007,7 @@ impl Background for FolderScan { analysis_workers, is_hdd, ratio_limit, - compression, + analysis_mode, cluster_size, control, &mut ds, @@ -988,7 +1028,7 @@ impl Background for FolderScan { analysis_workers, is_hdd, ratio_limit, - compression, + analysis_mode, cluster_size, control, &mut ds, @@ -1071,21 +1111,39 @@ fn lzx_auto_is_conservatively_capped_and_manual_is_respected() { } #[test] -fn projection_is_algorithm_and_cluster_aware() { - let logical = 1024 * 1024; - let physical = logical; - let xpress = estimate_physical_size( - logical, - 0.50, - Compression::Xpress16k, +fn thorough_analysis_keeps_candidates_rejected_by_a_generic_sample() { + let file = || FileInfo { + path: PathBuf::from("fixture.bin"), + content_len: 65536, + modified_time: 0, + estimate_valid: false, + estimated_ratio: 1.0, + logical_size: 65536, + physical_size: 65536, + estimated_physical_size: 65536, + compression: None, + }; + let mut sampled = FolderInfo::new("fixture"); + apply_estimate( + &mut sampled, + file(), + Ok(1.0), + 0.99, + AnalysisMode::Sampled, 4096, - physical, ); - let lzx = estimate_physical_size(logical, 0.50, Compression::Lzx, 4096, physical); - - assert!(lzx < xpress); - assert_eq!(0, lzx % 4096); - assert_eq!(0, xpress % 4096); + assert_eq!(1, sampled.skipped.count); + let mut thorough = FolderInfo::new("fixture"); + apply_estimate( + &mut thorough, + file(), + Ok(1.0), + 0.99, + AnalysisMode::Thorough, + 4096, + ); + assert_eq!(1, thorough.compressible.count); + assert_eq!(65536, thorough.compressible.estimated_physical_size); } #[test] @@ -1102,6 +1160,7 @@ fn skipped_files_keep_totals_without_retaining_paths() { logical_size: 8192, physical_size: 8192, estimated_physical_size: 8192, + compression: None, }, ); @@ -1111,37 +1170,12 @@ fn skipped_files_keep_totals_without_retaining_paths() { } #[test] -fn it_walks() { - use crate::background::BackgroundHandle; - use crate::config::Config; - - let config = Config::default(); - let gs = config.globset().unwrap(); - let scanner = FolderScan::new( - "C:\\Games", - gs, - config.ratio_limit(), - config.compression, - config.max_threads, - config.hdd_single_thread, - ); - - let task = BackgroundHandle::spawn(scanner); - - let deadline = Instant::now() + Duration::from_millis(2000); - - loop { - let ret = task.wait_timeout(Duration::from_millis(100)); - - if ret.is_some() { - println!("Scanned: {:?}", ret); - break; - } else { - println!("Status: {:?}", task.status()); - } - - if Instant::now() > deadline { - task.cancel(); - } - } +fn scan_uses_an_isolated_fixture_and_accounts_for_empty_files() { + let dir = tempdir::TempDir::new("compactor-scan").unwrap(); + std::fs::write(dir.path().join("empty.bin"), []).unwrap(); + let scanner = FolderScan::new(dir.path(), &Config::default()).unwrap(); + let result = scanner.run(&ControlToken::new()).unwrap(); + assert_eq!(1, result.skipped.count); + assert_eq!(0, result.logical_size); + assert_eq!(0, result.compressible.count); } diff --git a/src/gui.rs b/src/gui.rs index c129d3d..0925c09 100644 --- a/src/gui.rs +++ b/src/gui.rs @@ -2,7 +2,7 @@ use std::path::{Path, PathBuf}; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::Arc; -use crossbeam_channel::{bounded, Receiver}; +use crossbeam_channel::{bounded, unbounded, Receiver, Sender}; use dirs_sys::known_folder; use serde_derive::{Deserialize, Serialize}; use web_view::*; @@ -22,6 +22,7 @@ pub enum GuiRequest { SaveConfig { decimal: bool, compression: String, + analysis_mode: String, min_savings_percent: f32, max_threads: usize, hdd_single_thread: bool, @@ -30,6 +31,7 @@ pub enum GuiRequest { excludes: String, }, ResetConfig, + SettingsChanged, ChooseFolder, Compress, Decompress, @@ -72,6 +74,7 @@ pub enum GuiResponse { Config { decimal: bool, compression: String, + analysis_mode: String, min_savings_percent: f32, max_threads: usize, hdd_single_thread: bool, @@ -105,6 +108,15 @@ pub enum GuiResponse { physical_size: u64, items: Vec, }, + AnalysisInvalidated, + OperationSummary { + operation: String, + changed: usize, + not_beneficial: usize, + skipped: usize, + failed: usize, + errors: Vec, + }, Paused, Resumed, Scanned, @@ -119,6 +131,15 @@ impl GuiWrapper { let gui = Self(handle); gui.version(); gui.config(); + if let Some(error) = config().read().unwrap().load_error() { + gui.error( + "Settings could not be loaded", + format!( + "Compactor is using defaults for this session. The original settings file was left unchanged.\n\n{}", + error + ), + ); + } gui } @@ -142,16 +163,7 @@ impl GuiWrapper { pub fn config(&self) { let s = config().read().unwrap().current(); - self.send(&GuiResponse::Config { - decimal: s.decimal, - compression: s.compression.to_string(), - min_savings_percent: s.min_savings_percent, - max_threads: s.max_threads, - hdd_single_thread: s.hdd_single_thread, - protect_direct_storage: s.protect_direct_storage, - compression_priority: s.compression_priority.to_string(), - excludes: s.excludes.join("\n"), - }); + self.send(&config_response(&s)); } pub fn summary(&self, info: FolderSummary) { @@ -241,7 +253,9 @@ pub fn spawn_gui() { ) ); - let (from_gui, from_gui_rx) = bounded::(128); + // Never block the webview thread on a busy backend. UI state prevents new + // operation requests while one is active, and shutdown drops this sender. + let (from_gui, from_gui_rx) = unbounded::(); let mut webview = web_view::builder() .title("Compactor") @@ -258,6 +272,7 @@ pub fn spawn_gui() { Ok(GuiRequest::SaveConfig { decimal, compression, + analysis_mode, min_savings_percent, max_threads, hdd_single_thread, @@ -265,81 +280,56 @@ pub fn spawn_gui() { compression_priority, excludes, }) => { - let s = Config { - decimal, - compression: compression.parse().unwrap_or_default(), - min_savings_percent, - max_threads, - hdd_single_thread, - protect_direct_storage, - compression_priority: compression_priority.parse().unwrap_or_default(), - excludes: excludes.split('\n').map(str::to_owned).collect(), - }; - - if let Err(msg) = s.validate() { - tinyfiledialogs::message_box_ok( - "Settings Error", - &msg, - tinyfiledialogs::MessageBoxIcon::Error, - ); - } else { + let candidate = (|| { + let s = Config { + decimal, + compression: compression + .parse() + .map_err(|_| "Choose a supported compression algorithm.".to_string())?, + analysis_mode: analysis_mode + .parse() + .map_err(|_| "Choose a supported analysis mode.".to_string())?, + min_savings_percent, + max_threads, + hdd_single_thread, + protect_direct_storage, + compression_priority: compression_priority + .parse() + .map_err(|_| "Choose a supported worker priority.".to_string())?, + excludes: excludes.split('\n').map(str::to_owned).collect(), + }; + s.validate()?; + Ok::(s) + })(); + + match candidate { + Ok(s) => update_config(&mut webview, &from_gui, s), + Err(message) => settings_error(&message), + } + } + Ok(GuiRequest::ResetConfig) => { + update_config(&mut webview, &from_gui, Config::default()); + } + Ok(msg) => { + if from_gui.send(msg).is_err() { message_dispatch( &mut webview, - &GuiResponse::Config { - decimal: s.decimal, - compression: s.compression.to_string(), - min_savings_percent: s.min_savings_percent, - max_threads: s.max_threads, - hdd_single_thread: s.hdd_single_thread, - protect_direct_storage: s.protect_direct_storage, - compression_priority: s.compression_priority.to_string(), - excludes: s.excludes.join("\n"), + &GuiResponse::Error { + title: "Operation unavailable".to_string(), + message: "The background worker has stopped. Restart Compactor before continuing.".to_string(), }, ); - let c = config(); - let mut c = c.write().unwrap(); - c.replace(s); - if let Err(e) = c.save() { - tinyfiledialogs::message_box_ok( - "Settings Error", - &format!("Error saving settings: {:?}", e), - tinyfiledialogs::MessageBoxIcon::Error, - ); - } } } - Ok(GuiRequest::ResetConfig) => { - let s = Config::default(); - + Err(err) => { + eprintln!("Unhandled message {:?}: {:?}", arg, err); message_dispatch( &mut webview, - &GuiResponse::Config { - decimal: s.decimal, - compression: s.compression.to_string(), - min_savings_percent: s.min_savings_percent, - max_threads: s.max_threads, - hdd_single_thread: s.hdd_single_thread, - protect_direct_storage: s.protect_direct_storage, - compression_priority: s.compression_priority.to_string(), - excludes: s.excludes.join("\n"), + &GuiResponse::Error { + title: "Invalid request".to_string(), + message: "The request could not be read. Check the settings values and try again.".to_string(), }, ); - let c = config(); - let mut c = c.write().unwrap(); - c.replace(s); - if let Err(e) = c.save() { - tinyfiledialogs::message_box_ok( - "Settings Error", - &format!("Error saving settings: {:?}", e), - tinyfiledialogs::MessageBoxIcon::Error, - ); - } - } - Ok(msg) => { - from_gui.send(msg).expect("GUI message queue"); - } - Err(err) => { - eprintln!("Unhandled message {:?}: {:?}", arg, err); } } @@ -373,6 +363,55 @@ pub fn spawn_gui() { bg.join().expect("background thread"); } +fn config_response(s: &Config) -> GuiResponse { + GuiResponse::Config { + decimal: s.decimal, + compression: s.compression.to_string(), + analysis_mode: s.analysis_mode.to_string(), + min_savings_percent: s.min_savings_percent, + max_threads: s.max_threads, + hdd_single_thread: s.hdd_single_thread, + protect_direct_storage: s.protect_direct_storage, + compression_priority: s.compression_priority.to_string(), + excludes: s.excludes.join("\n"), + } +} + +fn settings_error(message: &str) { + tinyfiledialogs::message_box_ok( + "Settings Error", + message, + tinyfiledialogs::MessageBoxIcon::Error, + ); +} + +fn update_config( + webview: &mut web_view::WebView<'_, T>, + backend: &Sender, + settings: Config, +) { + let response = config_response(&settings); + let result = config().write().unwrap().update(settings); + match result { + Ok(()) => { + message_dispatch(webview, &response); + if backend.send(GuiRequest::SettingsChanged).is_err() { + message_dispatch( + webview, + &GuiResponse::Error { + title: "Settings saved".to_string(), + message: "The background worker has stopped. Restart Compactor to use the saved settings.".to_string(), + }, + ); + } + } + Err(err) => settings_error(&format!( + "Unable to save settings: {}\n\nThe previous settings are still active.", + err + )), + } +} + fn message_dispatch(wv: &mut web_view::WebView<'_, T>, msg: &GuiResponse) { let js = format!( "Response.dispatch({})", diff --git a/src/main.rs b/src/main.rs index 1ab64ce..bf2aa45 100644 --- a/src/main.rs +++ b/src/main.rs @@ -12,6 +12,7 @@ mod directstorage; mod folder; mod gui; mod persistence; +mod policy; fn setup_panic() { std::panic::set_hook(Box::new(|e| { diff --git a/src/persistence.rs b/src/persistence.rs index edc5425..95c2768 100644 --- a/src/persistence.rs +++ b/src/persistence.rs @@ -1,12 +1,11 @@ use directories::ProjectDirs; use hashfilter::HashFilter; use lazy_static::lazy_static; -use std::fs::Metadata; use std::path::{Path, PathBuf}; use std::sync::RwLock; -use std::time::UNIX_EPOCH; -use crate::config::ConfigFile; +use crate::compact::Compression; +use crate::config::{AnalysisMode, ConfigFile}; lazy_static! { static ref PATHDB: RwLock = RwLock::new(HashFilter::default()); @@ -15,28 +14,33 @@ lazy_static! { pub fn init() { if let Some(dirs) = ProjectDirs::from("", "Freaky", "Compactor") { - // V2 keys include file identity (size + modification time), so files that - // are replaced or updated are automatically reconsidered for compression. + // V3 keys also include algorithm, analysis mode, threshold and allocation + // unit. A rejected XPRESS attempt must not suppress a later LZX attempt. pathdb() .write() .unwrap() - .set_backing(dirs.cache_dir().join("incompressible-v2.dat")); + .set_backing(dirs.cache_dir().join("incompressible-v3.dat")); *config().write().unwrap() = ConfigFile::new(dirs.config_dir().join("config.json")); } } -pub fn incompressible_key(path: &Path, metadata: &Metadata) -> (PathBuf, u64, u64, u32) { - let modified = metadata - .modified() - .ok() - .and_then(|time| time.duration_since(UNIX_EPOCH).ok()) - .unwrap_or_default(); - +pub fn incompressible_key( + path: &Path, + content_len: u64, + modified_time: u64, + compression: Compression, + analysis_mode: AnalysisMode, + min_savings_percent: f32, + cluster_size: u64, +) -> (PathBuf, u64, u64, Compression, AnalysisMode, u32, u64) { ( path.to_path_buf(), - metadata.len(), - modified.as_secs(), - modified.subsec_nanos(), + content_len, + modified_time, + compression, + analysis_mode, + min_savings_percent.to_bits(), + cluster_size, ) } @@ -47,3 +51,75 @@ pub fn config() -> &'static RwLock { pub fn pathdb() -> &'static RwLock { &PATHDB } + +#[test] +fn cached_results_are_scoped_to_the_operation_that_measured_them() { + let path = Path::new(r"C:\Games\data.bin"); + let key = |len, modified, algorithm, mode, minimum, cluster| { + incompressible_key(path, len, modified, algorithm, mode, minimum, cluster) + }; + let original = key( + 8192, + 12, + Compression::Xpress4k, + AnalysisMode::Sampled, + 1.0, + 4096, + ); + assert_eq!( + original, + key( + 8192, + 12, + Compression::Xpress4k, + AnalysisMode::Sampled, + 1.0, + 4096 + ) + ); + for changed in [ + key( + 8192, + 13, + Compression::Xpress4k, + AnalysisMode::Sampled, + 1.0, + 4096, + ), + key( + 16384, + 12, + Compression::Xpress4k, + AnalysisMode::Sampled, + 1.0, + 4096, + ), + key(8192, 12, Compression::Lzx, AnalysisMode::Sampled, 1.0, 4096), + key( + 8192, + 12, + Compression::Xpress4k, + AnalysisMode::Thorough, + 1.0, + 4096, + ), + key( + 8192, + 12, + Compression::Xpress4k, + AnalysisMode::Sampled, + 0.0, + 4096, + ), + key( + 8192, + 12, + Compression::Xpress4k, + AnalysisMode::Sampled, + 1.0, + 65536, + ), + ] { + assert_ne!(original, changed); + } +} diff --git a/src/policy.rs b/src/policy.rs new file mode 100644 index 0000000..e5fa837 --- /dev/null +++ b/src/policy.rs @@ -0,0 +1,127 @@ +//! Pure decisions shared by analysis and the Windows compression worker. +//! +//! An estimate is advisory. Only allocated bytes measured around a WOF operation +//! can satisfy the retention threshold. + +pub fn sample_is_candidate(ratio: f32, ratio_limit: f32) -> bool { + ratio.is_finite() + && ratio_limit.is_finite() + && (0.0..1.0).contains(&ratio) + && (0.0..=1.0).contains(&ratio_limit) + && ratio <= ratio_limit +} + +pub fn savings_worthwhile( + before: u64, + after: u64, + min_savings_percent: f32, + cluster_size: u64, +) -> bool { + if before == 0 + || after >= before + || !min_savings_percent.is_finite() + || !(0.0..=100.0).contains(&min_savings_percent) + { + return false; + } + + // Round the requirement up: a fraction of a byte is not a saving. f64 + // avoids the much coarser f32 conversion of large file sizes. Always demand + // at least one allocation unit, even when the percentage is set to zero. + let minimum_bytes = ((before as f64 * min_savings_percent as f64 / 100.0).ceil() as u64) + .max(cluster_size.max(1)); + before - after >= minimum_bytes +} + +pub fn round_up_to_cluster(size: u64, cluster_size: u64) -> u64 { + let cluster = cluster_size.max(1); + let remainder = size % cluster; + if remainder == 0 { + size + } else { + size.saturating_add(cluster - remainder) + } +} + +/// A generic sample projection, not an algorithm-specific benchmark. +pub fn estimated_allocation( + logical_size: u64, + ratio: f32, + cluster_size: u64, + current_allocation: u64, +) -> u64 { + if !ratio.is_finite() || !(0.0..=1.0).contains(&ratio) { + return current_allocation; + } + let sample_bytes = (logical_size as f64 * ratio as f64).ceil() as u64; + // A nonempty WOF stream needs storage even if the sample is all zeros. + let minimum = if logical_size == 0 { + 0 + } else { + cluster_size.max(1) + }; + round_up_to_cluster(sample_bytes.max(minimum), cluster_size).min(current_allocation) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn retained_files_must_save_an_allocation_unit_and_the_requested_percentage() { + assert!(savings_worthwhile(409_600, 405_504, 1.0, 4096)); + assert!(!savings_worthwhile(409_600, 405_505, 1.0, 4096)); + assert!(!savings_worthwhile(8192, 8191, 0.0, 4096)); + assert!(savings_worthwhile(8192, 4096, 0.0, 4096)); + assert!(!savings_worthwhile(131_072, 126_976, 1.0, 65_536)); + assert!(savings_worthwhile(131_072, 65_536, 50.0, 65_536)); + } + + #[test] + fn invalid_and_non_beneficial_results_are_never_retained() { + for threshold in [f32::NAN, f32::INFINITY, -1.0, 101.0] { + assert!(!savings_worthwhile(8192, 4096, threshold, 4096)); + } + assert!(!savings_worthwhile(0, 0, 0.0, 4096)); + assert!(!savings_worthwhile(8192, 8192, 0.0, 4096)); + assert!(!savings_worthwhile(8192, 16384, 0.0, 4096)); + assert!(!savings_worthwhile(8192, 4096, 100.0, 4096)); + } + + #[test] + fn zero_threshold_does_not_admit_negative_or_incompressible_samples() { + for ratio in [f32::NAN, f32::INFINITY, -0.1, 1.0, 1.1] { + assert!(!sample_is_candidate(ratio, 1.0)); + } + assert!(sample_is_candidate(0.5, 0.5)); + assert!(!sample_is_candidate(0.6, 0.5)); + assert!(!sample_is_candidate(0.5, f32::NAN)); + } + + #[test] + fn allocation_rounding_is_zero_safe_and_never_wraps() { + assert_eq!(0, round_up_to_cluster(0, 4096)); + assert_eq!(4096, round_up_to_cluster(4096, 4096)); + assert_eq!(8192, round_up_to_cluster(4097, 4096)); + assert_eq!(42, round_up_to_cluster(42, 0)); + assert_eq!(u64::MAX, round_up_to_cluster(u64::MAX, 4096)); + } + + #[test] + fn generic_estimates_do_not_invent_algorithm_gains_or_zero_cost_files() { + assert_eq!( + 524_288, + estimated_allocation(1_048_576, 0.5, 4096, 1_048_576) + ); + assert_eq!(4096, estimated_allocation(1_048_576, 0.0, 4096, 1_048_576)); + assert_eq!(8192, estimated_allocation(8192, f32::NAN, 4096, 8192)); + assert_eq!(0, estimated_allocation(0, 0.0, 4096, 0)); + assert_eq!(1024, estimated_allocation(1024, 0.5, 4096, 1024)); + } + + #[test] + fn large_file_thresholds_do_not_overflow() { + assert!(savings_worthwhile(u64::MAX, u64::MAX / 2, 49.0, 4096)); + assert!(!savings_worthwhile(u64::MAX, u64::MAX / 2, 51.0, 4096)); + } +} diff --git a/src/ui/app.js b/src/ui/app.js index 3e242d1..f6d311a 100644 --- a/src/ui/app.js +++ b/src/ui/app.js @@ -63,6 +63,15 @@ var Util = (function() { return number.toLocaleString("en", {minimumFractionDigits: digits, maximumFractionDigits: digits}); }, + setting_number: function(value, minimum, maximum, integer) { + var text = String(value).replace(/^\s+|\s+$/g, ""); + if (!/^[-+]?(?:\d+(?:\.\d*)?|\.\d+)(?:e[-+]?\d+)?$/i.test(text)) return null; + var number = Number(text); + if (!isFinite(number) || number < minimum || number > maximum) return null; + if (integer && Math.floor(number) !== number) return null; + return number; + }, + bytes_to_human_dec: function(bytes) { for (var i = powers.length - 1; i > 0; i--) { var div = Math.pow(10, 3 * i); @@ -150,31 +159,42 @@ var Action = (function() { }, reset_config: function() { + if (Gui.is_busy()) return; external.invoke(JSON.stringify({ type: 'ResetConfig' })); }, save_config: function(config) { + if (Gui.is_busy()) return; config.type = 'SaveConfig'; external.invoke(JSON.stringify(config)); }, choose_folder: function() { + if (Gui.is_busy()) return; + Gui.operation_requested(); external.invoke(JSON.stringify({ type: 'ChooseFolder' })); }, compress: function() { + if (Gui.is_busy() || Gui.needs_analysis()) return; + Gui.operation_requested(); external.invoke(JSON.stringify({ type: 'Compress' })); }, decompress: function() { + if (Gui.is_busy()) return; + Gui.operation_requested(); external.invoke(JSON.stringify({ type: 'Decompress' })); }, decompress_and_exclude: function() { + if (Gui.is_busy()) return; + Gui.operation_requested(); external.invoke(JSON.stringify({ type: 'DecompressAndExclude' })); }, view_compressed: function(view, query, page) { + if (Gui.is_busy()) return; external.invoke(JSON.stringify({ type: 'ViewCompressed', view: view, @@ -192,6 +212,8 @@ var Action = (function() { }, analyse: function() { + if (Gui.is_busy()) return; + Gui.operation_requested(); external.invoke(JSON.stringify({ type: 'Analyse' })); }, @@ -217,6 +239,7 @@ var Response = (function() { case "Config": Gui.set_decimal(msg.decimal); Gui.set_compression(msg.compression); + Gui.set_analysis_mode(msg.analysis_mode || "Sampled"); Gui.set_min_savings(msg.min_savings_percent); Gui.set_max_threads(msg.max_threads); Gui.set_compression_priority(msg.compression_priority); @@ -238,6 +261,7 @@ var Response = (function() { break; case "Error": + Gui.operation_start_failed(); window.alert(msg.title + "\n\n" + msg.message); break; @@ -256,6 +280,14 @@ var Response = (function() { case "CompressedView": Gui.set_compressed_view(msg); break; + + case "AnalysisInvalidated": + Gui.analysis_invalidated(); + break; + + case "OperationSummary": + Gui.set_operation_summary(msg); + break; } }; @@ -299,6 +331,13 @@ var Response = (function() { var Gui = (function() { "use strict"; + var busy = false; + var awaitingOperation = false; + var analysisDirty = false; + var analysisMode = "Sampled"; + var lastFolderSummary = null; + var lastCompressedView = null; + var compressedView = { view: "folders", page: 0, @@ -309,12 +348,27 @@ var Gui = (function() { Gui.request_compressed(0); }, 200); - var addTableCell = function(row, value, className) { - var cell = $("").text(value); + var addTableCell = function(row, value, className, header) { + var cell = $(header ? "" : "").text(value); + if (header) cell.attr("scope", "col"); if (className) cell.addClass(className); row.append(cell); }; + var setBusy = function(active) { + busy = active; + $("#Button_Folder, #Button_Save, #Button_Reset, #Button_Analyse, #Button_Compress, #Button_Decompress, #Button_Decompress_Exclude, #Button_View_Compressed, #Settings input, #Settings select, #Settings textarea") + .prop("disabled", active); + $("#Settings_Busy").toggle(active); + }; + + var updateEstimateDisplay = function() { + $("#Estimated_Sampled").toggle(!analysisDirty && analysisMode === "Sampled"); + $("#Estimated_Thorough").toggle(!analysisDirty && analysisMode === "Thorough"); + $("#Estimated_Stale").toggle(analysisDirty); + $("#Analysis_Invalidated").toggle(analysisDirty); + }; + return { boot: function() { $("a[href]").on("click", function(e) { @@ -323,29 +377,63 @@ var Gui = (function() { return false; }); - $("#Button_Save").on("click", function() { - var minSavings = parseFloat($("#Min_Savings").val()); - if (isNaN(minSavings)) minSavings = 1; - var maxThreads = parseInt($("#Max_Threads").val(), 10); - if (isNaN(maxThreads)) maxThreads = 0; - - Action.save_config({ - decimal: $("#SI_Units").val() == "D", - compression: $("#Compression_Mode").val(), - min_savings_percent: minSavings, - max_threads: maxThreads, - compression_priority: $("#Compression_Priority").val(), - hdd_single_thread: $("#HDD_Single_Thread").prop("checked"), - protect_direct_storage: $("#Protect_DirectStorage").prop("checked"), - excludes: $("#Excludes").val() - }); - }); + $("#Button_Save").on("click", Gui.save_settings); $("#Button_Reset").on("click", function() { Action.reset_config(); }); $("#Compressed_View_Search").on("input", compressedSearch); + $("#Compressed_View_Mode").on("change", function() { + Gui.set_compressed_mode($(this).val()); + }); + $("#Analysis_Mode").on("change", function() { + Gui.update_analysis_help($(this).val()); + }); + Gui.update_analysis_help("Sampled"); + }, + + is_busy: function() { + return busy; + }, + + needs_analysis: function() { + return analysisDirty; + }, + + operation_requested: function() { + awaitingOperation = true; + setBusy(true); + }, + + operation_start_failed: function() { + if (awaitingOperation) Gui.scanned(); + }, + + save_settings: function() { + if (busy) return; + var minSavings = Util.setting_number($("#Min_Savings").val(), 0, 100, false); + if (minSavings === null) { + window.alert("Minimum savings must be a number between 0 and 100%."); + return; + } + var maxThreads = Util.setting_number($("#Max_Threads").val(), 0, 16, true); + if (maxThreads === null) { + window.alert("Maximum worker threads must be a whole number from 0 (Auto) to 16."); + return; + } + + Action.save_config({ + decimal: $("#SI_Units").val() == "D", + compression: $("#Compression_Mode").val(), + analysis_mode: $("#Analysis_Mode").val(), + min_savings_percent: minSavings, + max_threads: maxThreads, + compression_priority: $("#Compression_Priority").val(), + hdd_single_thread: $("#HDD_Single_Thread").prop("checked"), + protect_direct_storage: $("#Protect_DirectStorage").prop("checked"), + excludes: $("#Excludes").val() + }); }, page: function(page) { @@ -356,14 +444,24 @@ var Gui = (function() { }, open_compressed_view: function() { - compressedView.view = "folders"; + if (busy) return; + compressedSearch.clear(); compressedView.page = 0; compressedView.pages = 1; + $("#Compressed_View_Mode").val(compressedView.view); $("#Compressed_View_Search").val(""); Gui.page("CompressedFiles"); Gui.request_compressed(0); }, + set_compressed_mode: function(view) { + if (busy) return; + compressedSearch.clear(); + compressedView.view = view === "files" ? "files" : "folders"; + $("#Compressed_View_Mode").val(compressedView.view); + Gui.request_compressed(0); + }, + request_compressed: function(page) { var query = $("#Compressed_View_Search").val() || ""; var requestedPage = parseInt(page, 10); @@ -376,10 +474,20 @@ var Gui = (function() { }, set_compressed_view: function(data) { - compressedView.view = "folders"; + // A search/mode can change while an earlier request is in flight. + // Keep that earlier response from replacing the user's latest view. + var view = data.view === "files" ? "files" : "folders"; + var query = String($("#Compressed_View_Search").val() || "").replace(/^\s+|\s+$/g, ""); + if (view !== compressedView.view || data.query !== query) return; + lastCompressedView = data; compressedView.page = data.page; compressedView.pages = data.pages; + var folders = view === "folders"; + var itemName = folders ? "folders" : "files"; + var columns = folders ? 5 : 4; + $("#Compressed_View_Title").text(folders ? "Compressed Folders" : "Compressed Files"); + $("#Compressed_View_Search").attr("placeholder", "Filter " + itemName + " by path"); $("#Compressed_View_Root").text(data.root); $("#Compressed_View_Summary").text( Util.format_number(data.compressed_count, 0) + " compressed files - " + @@ -392,16 +500,16 @@ var Gui = (function() { var body = $("#Compressed_View_Body").empty(); var header = $(""); - addTableCell(header, "Files"); - addTableCell(header, "Logical"); - addTableCell(header, "On-disk"); - addTableCell(header, "Saved"); - addTableCell(header, "Folder", "path"); + if (folders) addTableCell(header, "Files", null, true); + addTableCell(header, "Logical", null, true); + addTableCell(header, "On-disk", null, true); + addTableCell(header, "Saved", null, true); + addTableCell(header, folders ? "Folder" : "File", "path", true); head.append(header); data.items.forEach(function(item) { var row = $(""); - addTableCell(row, Util.format_number(item.count, 0)); + if (folders) addTableCell(row, Util.format_number(item.count, 0)); addTableCell(row, Util.bytes_to_human(item.logical_size)); addTableCell(row, Util.bytes_to_human(item.physical_size)); addTableCell(row, Util.bytes_to_human(Math.max(0, item.logical_size - item.physical_size))); @@ -413,9 +521,9 @@ var Gui = (function() { var empty = $(""); empty.append( $("") - .attr("colspan", 5) + .attr("colspan", columns) .addClass("empty") - .text("No matching compressed folders") + .text("No matching compressed " + itemName) ); body.append(empty); } @@ -423,7 +531,7 @@ var Gui = (function() { $("#Compressed_View_Page").text( "Page " + Util.format_number(data.page + 1, 0) + " of " + Util.format_number(data.pages, 0) + " - " + - Util.format_number(data.total, 0) + " folders" + Util.format_number(data.total, 0) + " " + itemName ); $("#Button_Compressed_Previous").prop("disabled", data.page <= 0); $("#Button_Compressed_Next").prop("disabled", data.page + 1 >= data.pages); @@ -443,10 +551,25 @@ var Gui = (function() { field.val("I"); Util.bytes_to_human = Util.bytes_to_human_bin; } + if (lastFolderSummary) Gui.set_folder_summary(lastFolderSummary); + if (lastCompressedView) Gui.set_compressed_view(lastCompressedView); }, set_compression: function(compression) { - $("#Compression_Mode").val(compression); + $("#Compression_Mode").val(String(compression).toUpperCase()); + }, + + set_analysis_mode: function(mode) { + analysisMode = mode === "Thorough" ? "Thorough" : "Sampled"; + $("#Analysis_Mode").val(analysisMode); + Gui.update_analysis_help(analysisMode); + updateEstimateDisplay(); + }, + + update_analysis_help: function(mode) { + $("#Analysis_Mode_Help").text(mode === "Thorough" + ? "Tries every eligible file without the sampling filter. This can find extra savings, but takes longer and may perform more writes." + : "Uses a quick sample to skip files unlikely to benefit. Some files that would compress well may be missed."); }, set_min_savings: function(percent) { @@ -489,15 +612,21 @@ var Gui = (function() { }, set_status: function(status, pct) { - $("#Activity_Text").text(status); - if (pct != null) { - $("#Activity_Progress").val(pct); + $("#Activity_Text").text(status).attr("title", status); + if (typeof pct === "number" && isFinite(pct)) { + $("#Activity_Progress").val(Math.max(0, Math.min(1, pct))); } else { $("#Activity_Progress").removeAttr("value"); } }, scanning: function() { + awaitingOperation = false; + setBusy(true); + analysisDirty = false; + lastCompressedView = null; + compressedSearch.clear(); + Gui.clear_operation_summary(); Gui.reset_folder_summary(); $("#Activity").show(); $("#Analysis").show(); @@ -513,6 +642,10 @@ var Gui = (function() { }, compacting: function() { + awaitingOperation = false; + setBusy(true); + Gui.clear_operation_summary(); + $("#Activity").show(); $("#Button_Pause").show(); $("#Button_Resume").hide(); $("#Button_Stop").show(); @@ -538,18 +671,20 @@ var Gui = (function() { }, scanned: function() { + awaitingOperation = false; + setBusy(false); $("#Button_Pause").hide(); $("#Button_Resume").hide(); $("#Button_Stop").hide(); $("#Button_Analyse").show(); - if ($("#File_Count_Compressible").text() != "0") { + if (!analysisDirty && lastFolderSummary && lastFolderSummary.compressible.count > 0) { $("#Button_Compress").show(); } else { $("#Button_Compress").hide(); } - if ($("#File_Count_Compressed").text() != "0") { + if (lastFolderSummary && lastFolderSummary.compressed.count > 0) { $("#Button_Decompress").show(); $("#Button_Decompress_Exclude").show(); $("#Button_View_Compressed").show(); @@ -560,6 +695,35 @@ var Gui = (function() { } }, + analysis_invalidated: function() { + analysisDirty = true; + $("#Button_Compress").hide(); + updateEstimateDisplay(); + }, + + clear_operation_summary: function() { + $("#Operation_Report").hide(); + $("#Operation_Errors").empty(); + }, + + set_operation_summary: function(data) { + $("#Operation_Title").text(data.operation + " results"); + $("#Operation_Changed").text(Util.format_number(data.changed, 0)); + $("#Operation_Not_Beneficial").text(Util.format_number(data.not_beneficial, 0)); + $("#Operation_Skipped").text(Util.format_number(data.skipped, 0)); + $("#Operation_Failed").text(Util.format_number(data.failed, 0)); + var errors = data.errors || []; + var list = $("#Operation_Errors").empty(); + errors.forEach(function(error) { + list.append($("
  • ").text(error)); + }); + $("#Operation_Error_Heading").text(data.failed > errors.length + ? "Errors (showing " + Util.format_number(errors.length, 0) + " of " + Util.format_number(data.failed, 0) + ")" + : "Errors"); + $("#Operation_Error_Details").toggle(errors.length > 0); + $("#Operation_Report").show(); + }, + reset_folder_summary: function() { Gui.set_folder_summary({ logical_size: 0, @@ -572,6 +736,7 @@ var Gui = (function() { }, set_folder_summary: function(data) { + lastFolderSummary = data; $("#Size_Logical").text(Util.bytes_to_human(data.logical_size)); $("#Size_Physical").text(Util.bytes_to_human(data.physical_size)); @@ -586,12 +751,14 @@ var Gui = (function() { $("#Compressible_Size").text(Util.bytes_to_human(data.compressible.physical_size)); $("#Skipped_Size").text(Util.bytes_to_human(data.skipped.physical_size)); - if (data.physical_size > 0) { - var total = data.physical_size; - document.getElementById("Breakdown_Compressed").style.width = "" + 100 * (data.compressed.physical_size / total).toFixed(2) + "%"; - document.getElementById("Breakdown_Compressible").style.width = "" + 100 * (data.compressible.physical_size / total).toFixed(2) + "%"; - document.getElementById("Breakdown_Skipped").style.width = "" + 100 * (data.skipped.physical_size / total).toFixed(2) + "%"; - } + var total = data.physical_size; + var width = function(size) { + return (total > 0 ? Math.max(0, Math.min(100, 100 * size / total)) : 0).toFixed(2) + "%"; + }; + document.getElementById("Breakdown_Compressed").style.width = width(data.compressed.physical_size); + document.getElementById("Breakdown_Compressible").style.width = width(data.compressible.physical_size); + document.getElementById("Breakdown_Skipped").style.width = width(data.skipped.physical_size); + $("#File_Count_Breakdown").toggle(total > 0); var estimatedCandidateSize = data.compressible.estimated_physical_size; if (estimatedCandidateSize === undefined || estimatedCandidateSize === null) { @@ -608,6 +775,7 @@ var Gui = (function() { $("#File_Count_Compressible").text(Util.format_number(data.compressible.count, 0)); $("#File_Count_Skipped").text(Util.format_number(data.skipped.count, 0)); $("#DirectStorage_Warning").toggle(!!data.direct_storage); + updateEstimateDisplay(); }, analysis_complete: function() { diff --git a/src/ui/index.html b/src/ui/index.html index a0aed23..3c11be7 100644 --- a/src/ui/index.html +++ b/src/ui/index.html @@ -1,6 +1,7 @@ - + + @@ -31,7 +32,7 @@

    Comp @@ -48,11 +49,18 @@

    Comp + +